You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Pyrogram让机器人回复其他带inline keyboard的机器人消息

Pyrogram操作对方机器人返回的Inline Keyboard实现方案

你需要先捕获目标机器人返回的带Inline Keyboard的消息,提取对应按钮的回调数据,再调用Pyrogram内置的回调请求方法触发按钮点击效果,具体实现步骤和代码如下:

  • 第一步:主动发消息后,等待目标机器人返回的响应消息,需过滤发送方为对方机器人ID/用户名的新消息,避免匹配到其他无关消息
  • 第二步:从返回消息的reply_markup属性中提取Inline Keyboard对应按钮的callback_data参数
  • 第三步:调用request_callback_query方法触发回调请求,完成模拟点击操作
from pyrogram import Client
from pyrogram.errors import RPCError

api_id = 12345
api_hash = "hash123"
target_bot_username = "otherbot"

with Client("my_account", api_id, api_hash) as app:
    # 1. 主动向目标机器人发送消息
    app.send_message(target_bot_username, "Hello")
    
    # 2. 获取目标机器人最新返回的消息,验证是否携带Inline Keyboard
    for message in app.get_chat_history(target_bot_username, limit=1):
        if message.from_user.is_bot and message.reply_markup and hasattr(message.reply_markup, 'inline_keyboard'):
            target_msg = message
            break
    else:
        print("未收到目标机器人返回的带Inline Keyboard的消息")
        exit()

    # 3. 匹配需要点击的Inline按钮,可根据实际需求修改匹配规则(比如按钮文本)
    target_button = None
    for row in target_msg.reply_markup.inline_keyboard:
        for button in row:
            # 示例匹配文本为"确认"的按钮,可自行调整
            if button.text == "确认":
                target_button = button
                break
        if target_button:
            break
    
    if not target_button or not hasattr(target_button, 'callback_data'):
        print("未找到符合要求的带回调数据的Inline按钮")
        exit()

    try:
        # 4. 触发回调请求,模拟点击Inline按钮
        app.request_callback_query(
            chat_id=target_msg.chat.id,
            message_id=target_msg.id,
            callback_data=target_button.callback_data
        )
        print("Inline按钮点击操作完成")
    except RPCError as e:
        print(f"触发回调失败,错误信息:{e}")

注意:如果对方机器人的Inline按钮是跳转链接类型(url属性而非callback_data),则不需要触发回调,直接提取url属性访问即可。

内容的提问来源于stack exchange,提问作者JChris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 18:15:05