如何发送本地照片在电报机器人为java

xzlaal3s  于 2023-01-29  发布在  Java
关注(0)|答案(3)|浏览(148)

我有个任务:需要发送一张照片与我的本地文件夹在电报机器人。
预处理:
我使用这个库https://github.com/rubenlagus/TelegramBots
在Pom文件中:

<repositories>
    <repository>
        <id>jitpack.io</id>
        <url>https://jitpack.io</url>
    </repository>
</repositories>

<dependencies>
    <dependency>
        <groupId>com.github.rubenlagus</groupId>
        <artifactId>TelegramBots</artifactId>
        <version>4.1</version>
    </dependency>

如何创建发送方法?
我试着这么做:

public void sendInTelegram() {
    try {
        TelegramLongPollingBot telegramLongPollingBot = new TelegramLongPollingBot() {
            @Override
            public String getBotToken() {
                return "My_Token";
            }

            @Override
            public void onUpdateReceived(Update update) {
                try {
                    SendPhoto message = new SendPhoto().setPhoto("SomeText", new FileInputStream(new File("/root/index.png")));
                    this.sendPhoto(message);

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public String getBotUsername() {
                return "my_bot";
            }
        };
    } catch (Exception e) {
        logger.error("Send in Telegram fail");
        Assert.fail("Send in Telegram fail");
    }

而是他的. sendPhoto(消息);sendPhoto无法解析enter image description here
请告诉我什么是不够的,我可以发送照片?

ax6ht2ek

ax6ht2ek1#

使用execute,而不是sendPhoto

SendPhoto message = new SendPhoto().setPhoto("SomeText", new FileInputStream(new File("/root/index.png")));
this.execute(message);
6ie5vjzr

6ie5vjzr2#

您还必须设置chatID:

try {
     SendPhoto sendPhoto = new SendPhoto()
           .setChatId(update.getMessage().getChatId())
           .setPhoto("Photo", new FileInputStream(new File("/root/index.png")));
     execute(sendPhoto);
} catch (FileNotFoundException e) {
     e.printStackTrace();
} catch (TelegramApiException e) {
     e.printStackTrace();
}
9vw9lbht

9vw9lbht3#

我用这个例子:

public void sendPhotoMessage(long chatId, UserContent content) {

        String caption = getCaption(content);

        SendPhoto sendPhoto = SendPhoto.builder()
            .chatId(chatId)
            .photo(new InputFile(new File(content.getMediaUrl())))
            .caption(caption)
            .parseMode(ParseMode.HTML)
            .build();

        try {
            chronologyBot.execute(sendPhoto);
        } catch (TelegramApiException e) {
            log.error("Can't send photo message", e);
        }
    }

此外,如果我们想在一条消息中发送多张照片,我们可以使用SendMediaGroup。使用MediaGroup发送多个图像

相关问题