Python Telethon实现Telegram机器人按钮点击失败,求助解决方案
解决Telethon中点击按钮失败的问题
我看了你的代码和按钮结构,问题出在你用错了方法处理KeyboardButtonUrl类型的按钮。
先理清两种按钮的区别:
KeyboardButtonUrl:这种按钮本质是跳转链接,用户点击后直接打开URL,不需要向机器人发送任何回调请求。所以你用GetBotCallbackAnswerRequest来处理它完全不对,这个方法是专门给**KeyboardButtonCallback(带回调数据的交互按钮,比如你的Report和Skip按钮)**用的。KeyboardButtonCallback:点击这类按钮时,客户端会向机器人发送携带data字段的请求,这时候才需要调用GetBotCallbackAnswerRequest。
针对你的需求修改代码:
如果你要处理「Go to website」这个Url按钮:
不需要调用任何Telegram API来模拟点击,直接提取它的URL即可(如果需要打开链接,用系统浏览器就行):
from telethon import TelegramClient, sync from telethon.tl.functions.messages import GetHistoryRequest from telethon.tl.types import KeyboardButtonUrl api_id = 974119 api_hash = 'a483ea002564cdaa0499a08126abe4a3' client = TelegramClient('session_name', api_id, api_hash) client.start() channel_username = 'GOOGLE' channel_entity = client.get_entity(channel_username) # 获取最新一条消息 posts = client(GetHistoryRequest( peer=channel_entity, limit=1, offset_date=None, offset_id=0, max_id=0, min_id=0, add_offset=0, hash=0 )) message = posts.messages[0] # 检查按钮类型并提取URL first_button = message.reply_markup.rows[0].buttons[0] if isinstance(first_button, KeyboardButtonUrl): target_url = first_button.url print(f"提取到Url按钮的链接:{target_url}") # 如果你需要自动打开链接,可以用webbrowser模块 # import webbrowser # webbrowser.open(target_url) client.disconnect()
如果你要处理「Report」或「Skip」这类回调按钮:
这时候才需要用GetBotCallbackAnswerRequest,注意要传入正确的peer(实体对象)和按钮的data字段:
from telethon import TelegramClient, sync from telethon.tl.functions.messages import GetHistoryRequest, GetBotCallbackAnswerRequest from telethon.tl.types import KeyboardButtonCallback api_id = 974119 api_hash = 'a483ea002564cdaa0499a08126abe4a3' client = TelegramClient('session_name', api_id, api_hash) client.start() channel_username = 'GOOGLE' channel_entity = client.get_entity(channel_username) posts = client(GetHistoryRequest( peer=channel_entity, limit=1, offset_date=None, offset_id=0, max_id=0, min_id=0, add_offset=0, hash=0 )) message = posts.messages[0] # 找到Report按钮(第二行第一个按钮) report_button = message.reply_markup.rows[1].buttons[0] if isinstance(report_button, KeyboardButtonCallback): # 发送回调请求,注意peer传channel_entity,不是username callback_result = client(GetBotCallbackAnswerRequest( peer=channel_entity, msg_id=message.id, data=report_button.data )) print("回调请求已发送,返回结果:", callback_result) client.disconnect()
额外注意点:
- 调用
GetBotCallbackAnswerRequest时,peer参数最好传入channel_entity而不是字符串用户名,避免Telethon解析出错。 - 一定要先判断按钮的类型,防止因按钮类型不匹配导致的报错。
内容的提问来源于stack exchange,提问作者Agum Yudhistira




