Telegram bot API sendPhoto / Documents | Java的

时间:2017-10-22 14:45:54

标签: java api bots telegram

我想制作一个简单的Telegram Bot。使用方法 - sendPhoto(URL)无法解决问题。使用在线命令时,机器人应该向用户发送图片。图片本身是动态的,所以我使用sendPhoto URL。

代码:

public class SimpleBot extends TelegramLongPollingBot {

public static void main(String[] args) {
    ApiContextInitializer.init();
    TelegramBotsApi telegramBotsApi = new TelegramBotsApi();
    try {
        telegramBotsApi.registerBot(new SimpleBot());
    } catch (TelegramApiException e) {
        e.printStackTrace();
    }
}

@Override
public String getBotUsername() {
    return "SavchukBot";
}

@Override
public String getBotToken() {
    return "TOKEN";
}

@Override
public void onUpdateReceived(Update update) {
    Message message = update.getMessage();
    if (message != null && message.hasText()) {
        if (message.getText().equals("/help"))
            sendMsg(message, "Test");

    }

    if (message != null && message.hasText()) {
        if (message.getText().equals("/команды"))
            sendMsg(message,  "TestV2.0");
    }

    if (message != null && message.hasText()) {
        if (message.getText().equals("/online"))
            sendImageFromUrl("http://samp-stats.ru/web/userbar-15377.png", "@SavchukBot" );


} }

public void sendImageFromUrl(String url, String chatId) {
    SendPhoto sendPhotoRequest = new SendPhoto();
    sendPhotoRequest.setChatId(chatId);
    sendPhotoRequest.setPhoto("http://samp-stats.ru/web/userbar-15377.png");
    try {
        sendPhoto(sendPhotoRequest);
    } catch (TelegramApiException e) {
        e.printStackTrace();
    }
}





private void sendMsg(Message message, String text) {
    SendMessage sendMessage = new SendMessage();
    sendMessage.enableMarkdown(true);
    sendMessage.setChatId(message.getChatId().toString());
    sendMessage.setReplyToMessageId(message.getMessageId());
    sendMessage.setText(text);
    try {
        sendMessage(sendMessage);
    } catch (TelegramApiException e) {
        e.printStackTrace();
    }
}

}

运行命令时出现的错误 - / online:

org.telegram.telegrambots.exceptions.TelegramApiRequestException: Error sending photo: [400] Bad Request: chat not found
    at org.telegram.telegrambots.api.methods.send.SendPhoto.deserializeResponse(SendPhoto.java:153)
    at org.telegram.telegrambots.bots.DefaultAbsSender.sendPhoto(DefaultAbsSender.java:210)
    at SimpleBot.sendImageFromUrl(SimpleBot.java:62)
    at SimpleBot.onUpdateReceived(SimpleBot.java:52)
    at java.util.ArrayList.forEach(ArrayList.java:1249)
    at org.telegram.telegrambots.generics.LongPollingBot.onUpdatesReceived(LongPollingBot.java:27)
    at org.telegram.telegrambots.updatesreceivers.DefaultBotSession$HandlerThread.run(DefaultBotSession.java:301)

任何想法如何解决这个问题。谢谢=)

1 个答案:

答案 0 :(得分:0)

参数二chatId应该是目标聊天ID,而不是机器人名称。

尝试将message.getChatId().toString()作为参数传递。