Telegram bot api 模拟用户交互

标签 telegram telegram-bot

我正在使用 Telegram 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();
        }
    }
}

最佳答案

如果您想测试您的 API Webhook 并模拟用户交互,我更喜欢模拟对您的 Webhook URI 的整个 POST 请求(该 URI,您的 Telegram Bot 正在监听并从 Telegram 接收更新)。

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

方法类型:POST

域名:https://whereyourwebhookislistening.com

header :内容类型:application/json

请求正文例如:

{
   "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

关于Telegram bot api 模拟用户交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48530174/

相关文章:

telegram - 如何在我的 Telegram Bot 中读取/接收 Telegram channel 消息?

Python - Telethon 搜索(Python 的 Telegram API)

javascript - 在返回 promise 中执行 .then()

Telegram Bot 有时需要用户身份验证

api - Telegram channel 的帖子观看次数

api - 使用 Telegram Bot 向电话号码而非@用户名发送消息

python - 我编写了我的 Telegram Bot (用Python)提示用户发送图像。如何确保用户只发送图像而不发送其他内容?

c# - 保存发送给机器人的用户消息并将完成的表格发送给其他用户

c# - 如何使用 C# 使键盘按钮消息文本与其在 Telegram bot API 中的标题不同

node.js - 如何添加后 react 电报机器人node.js