使用Telethon解析按钮及确认消息中的URL
解析Telegram两类Web应用按钮的目标URL(Telethon实现)
一、直接打开Web应用的按钮
这类按钮对应Telethon中的WebAppButton对象,直接读取其url属性即可获取目标链接。
示例代码:
从消息的回复按钮中提取:
from telethon import events from telethon.tl.types import WebAppButton @client.on(events.NewMessage(chats='fueljetton_bot')) async def handle_new_message(event): if event.message.reply_markup: for row in event.message.reply_markup.rows: for button in row.buttons: if isinstance(button, WebAppButton): print(f"直接打开的WebApp URL: {button.url}")
二、需确认窗口的按钮及确认消息解析
这类按钮点击后会弹出确认窗口,窗口内的按钮才是真正触发Web应用的入口。你需要监听按钮点击事件,并从弹出的确认消息中提取WebApp链接:
步骤1:监听按钮点击事件
触发确认窗口的按钮通常是CallbackButton,点击后会产生CallbackQuery事件,响应后可获取后续弹出的确认消息:
from telethon import events from telethon.tl.types import CallbackButton, WebAppButton @client.on(events.CallbackQuery(chats='fueljetton_bot')) async def handle_callback_query(event): await event.answer() # 响应回调,避免按钮处于加载状态 # 获取最新的确认消息(可根据文本特征进一步过滤) confirm_msg = await client.get_messages('fueljetton_bot', limit=1) if confirm_msg and confirm_msg[0].reply_markup: for row in confirm_msg[0].reply_markup.rows: for button in row.buttons: if isinstance(button, WebAppButton): print(f"确认窗口中的WebApp URL: {button.url}")
补充:通过Raw事件直接获取
如果是作为机器人接收用户的WebApp请求,可监听UpdateBotWebAppQuery原始事件,直接从事件对象中提取URL:
from telethon import events from telethon.tl.types import UpdateBotWebAppQuery @client.on(events.Raw(UpdateBotWebAppQuery)) async def handle_webapp_query(event): webapp_url = event.query.url print(f"WebApp请求对应的URL: {webapp_url}")
关键说明
- 按钮类型区分:通过
isinstance()判断按钮是WebAppButton还是CallbackButton,前者直接取URL,后者需触发后续确认消息解析。 - 确认消息过滤:实际场景中可结合消息文本、发送者ID等特征精准定位确认消息,避免误匹配。
内容的提问来源于stack exchange,提问作者SokKi
相关产品推荐
相关产品推荐

