如何使用Telethon提取Telegram消息中内联按钮的链接?
提取Telegram频道消息中的内联按钮链接方法
方法一:使用Pyrogram库(推荐)
这是最便捷的实现方式,适合Python开发者快速上手:
前置准备
- 前往 my.telegram.org 注册你的应用,获取
API ID和API Hash - 通过@BotFather创建机器人,拿到
Bot Token - 安装依赖库:
pip install pyrogram tgcrypto - 将机器人添加到目标频道,并赋予读取消息的权限(私有频道需确保机器人已加入)
- 前往 my.telegram.org 注册你的应用,获取
提取链接的代码示例
from pyrogram import Client # 替换为你的实际参数 API_ID = 123456 API_HASH = "abcdef1234567890abcdef1234567890" BOT_TOKEN = "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11" CHANNEL_USERNAME = "@your_target_channel" app = Client("link_extractor_bot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN) async def get_inline_links(): # 遍历频道历史消息 async for msg in app.get_chat_history(CHANNEL_USERNAME): # 检查消息是否包含内联键盘 if msg.reply_markup and msg.reply_markup.inline_keyboard: # 遍历键盘的每一行和每个按钮 for row in msg.reply_markup.inline_keyboard: for btn in row: # 提取带URL的按钮链接 if btn.url: print(f"消息ID {msg.id} | 链接: {btn.url}") with app: app.run(get_inline_links())
方法二:使用python-telegram-bot库
如果你更熟悉这个库,也可以用类似逻辑实现:
from telegram import Update from telegram.ext import ApplicationBuilder, ContextTypes, MessageHandler, filters async def extract_links(update: Update, context: ContextTypes.DEFAULT_TYPE): msg = update.effective_message if msg.reply_markup and msg.reply_markup.inline_keyboard: for row in msg.reply_markup.inline_keyboard: for btn in row: if btn.url: print(f"链接: {btn.url}") if __name__ == '__main__': application = ApplicationBuilder().token("你的BOT_TOKEN").build() # 监听频道消息 application.add_handler(MessageHandler(filters.ChatType.CHANNEL, extract_links)) application.run_polling()
注意事项
- 机器人必须有权限访问目标频道,私有频道需要先邀请机器人加入
- 如果需要提取历史消息,Pyrogram的
get_chat_history方法更高效;python-telegram-bot默认监听实时消息,如需历史消息需额外处理 - 内联按钮分为带外部URL的按钮和回调按钮,上述代码只提取带有
url字段的外部链接,回调按钮(仅含callback_data)不属于外部链接范畴
内容的提问来源于stack exchange,提问作者ehsan mohseni
相关产品推荐
相关产品推荐

