使用Telethon调用Telegram inline bot时如何选择返回菜单选项
解决Telethon调用Inline Bot无法选中返回选项的方案
核心逻辑说明
你需要的两个调用参数全部来自GetInlineBotResultsRequest的返回结果,不需要额外调用其他接口。
完整实现代码
from telethon import TelegramClient from telethon.tl.functions.messages import GetInlineBotResultsRequest from telethon.tl.functions.messages import SendInlineBotResultRequest # 替换为你自己的API参数 api_id = 替换为你的API ID api_hash = '替换为你的API HASH' client = TelegramClient('session_name', api_id, api_hash) async def main(): # 会话初始化、登录逻辑请自行补充 await client.start() # 1. 获取inline bot返回的结果列表,必须加await关键字 bot_results = await client(GetInlineBotResultsRequest( bot=colorbot, # 目标inline bot的Peer对象 peer=colorgroup, # 调用bot所在的群/频道Peer对象 query='favorite color poll', offset='' )) # 2. 提取公共参数query_id obtained_query_id = bot_results.query_id # 3. 遍历结果列表匹配目标选项 target_result_id = None target_color = "Red" # 替换为你要选择的颜色选项文本 for result in bot_results.results: # 如需确认所有选项的对应关系,可放开下方打印逻辑 # print(f"选项ID: {result.id}, 选项标题: {result.title}, 选项描述: {result.description}") if result.title.strip() == target_color: target_result_id = result.id break if not target_result_id: print("未找到匹配的选项") return # 4. 发送选中的inline结果 await client(SendInlineBotResultRequest( peer=colorgroup, # 此处为消息接收方的会话Peer,不是bot的Peer query_id=obtained_query_id, id=target_result_id, random_id=client.rnd_id() # 必须传入随机ID避免重复发送 )) with client: client.loop.run_until_complete(main())
注意事项
- 所有Telethon的API调用都是异步方法,必须加
await关键字,否则拿到的是协程对象而非实际返回结果 - 若选项匹配失败,可以先打印所有result的title、description字段,确认目标选项的展示文本后再调整匹配逻辑
- 部分特殊inline bot的选项标识可能存储在
result.send_message字段中,用title匹配不到时可以打印完整的result对象查看字段结构
内容的提问来源于stack exchange,提问作者Exosylver
相关产品推荐
相关产品推荐

