如何通过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
相关产品推荐
相关产品推荐

