Telegram bot api模拟用户交互

时间:2018-01-30 20:41:40

标签: telegram telegram-bot

我正在使用电报bot api,我想在确定的时间内向用户发送消息,但机器人需要收到一条消息""发送一些东西,我的问题是: 是否可以发送模拟用户互动的更新?

我的意思是这样的: 在这里,我创建了模拟用户交互的更新(sendUpdate)  是一种自定义方法,例如,这实际上并不起作用

public void sendUpdate() {
    //sending the update to simulate user interaction
    Update upd = new Update();

    //method that telegram bot api uses to reply when you send a message to the bot
    onUpdateReceived(upd);
}

@Override
//Here I want to recipt my update to simulate the user interaction, and send a message witout user input
public void onUpdateReceived(Update update) {
    System.out.println(update);
    LOGGER.setLevel(Level.ALL);
    LOGGER.addHandler(new ConsoleHandler());

    LOGGER.info("2");
    if (update.hasMessage() && update.getMessage().hasText()) {
        // Set variables
        String message_text = "Message";
        long chat_id = update.getMessage().getChatId();
        SendMessage message = new SendMessage() 
                .setChatId(chat_id)
                .setText(message_text);
        try {
            this.sendMessage(message); 
        } catch (TelegramApiException e) {
            e.printStackTrace();
        }
    }
}

1 个答案:

答案 0 :(得分:3)

如果你想测试你的API webhook并模拟用户交互,我更喜欢模拟你的webhook URI的整个POST请求(URI,你的Telegram Bot监听,以及从Telegram接收更新)。

您可以使用任何您想要的工具,例如 Fiddler (选项卡编辑器)。在你体内,你将把JSON(它将被转换为你的Update对象)

方法类型:POST

域:https://whereyourwebhookislistening.com

标题:content-type: application/json

请求Body例如:

{
   "update_id":123456789,
   "message":{
      "message_id":123,
      "from":{
         "id":123456789,
         "is_bot":false,
         "first_name":"Test",
         "language_code":"ru-RU"
      },
      "date":1517384207,
      "chat":{
         "id":123456789,
         "type":"private",
         "first_name":"Testr",
         "all_members_are_administrators":false,
      },
      "forward_from_message_id":0,
      "text":"Test text",
      "delete_chat_photo":false,
      "group_chat_created":false,
      "supergroup_chat_created":false,
      "channel_chat_created":false,
      "migrate_to_chat_id":0,
      "migrate_from_chat_id":0,
   },
}

通过这种方法,您可以模拟来自Telegram Bot的真实webhook调用。添加示例请求的屏幕截图:

Fiddler composed POST request to webhook

相关问题