如何在Telegram Bot中通过文本超链接获取回调?
Telegram Bot实现文本链接点击回调(无需按钮)
Telegram的普通外部链接无法直接触发Bot回调,但可以通过Deep Linking机制实现需求:把列表项做成指向Bot的专属链接,用户点击后会唤起Bot并携带参数,Bot解析参数后返回对应详细信息。具体步骤如下:
实现思路
- 构造Deep Link链接:格式为
t.me/你的Bot用户名?start=自定义标识,比如针对Alex,链接可以是t.me/MyListBot?start=alex(标识建议用用户ID等唯一值,避免冲突和参数篡改)。 - 生成带链接的列表消息:在
/list命令的返回消息中,将每个名称用HTML或Markdown格式包裹为上述Deep Link。 - Bot端处理参数:监听
/start命令,解析携带的参数,根据参数返回对应用户的详细信息。
代码示例(Python + python-telegram-bot v20)
from telegram import Update from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes # 模拟用户详细信息数据 USER_DETAILS = { "alex": "Alex:25岁,后端工程师,擅长Python和Go", "ivan": "Ivan:30岁,UI设计师,专注于移动端界面设计", "pier": "Pier:28岁,产品经理,主导过3个SaaS项目" } async def handle_start(update: Update, context: ContextTypes.DEFAULT_TYPE): if context.args: user_key = context.args[0] # 根据参数查询并返回详细信息 detail = USER_DETAILS.get(user_key, "未找到该用户的详细信息") await update.message.reply_text(detail) else: await update.message.reply_text("欢迎使用列表Bot!发送/list查看用户列表。") async def handle_list(update: Update, context: ContextTypes.DEFAULT_TYPE): # 构造带Deep Link的HTML格式消息 bot_username = "MyListBot" # 替换成你的Bot用户名 list_content = f"""现有部分列表: <a href="t.me/{bot_username}?start=alex">Alex</a> <a href="t.me/{bot_username}?start=ivan">Ivan</a> <a href="t.me/{bot_username}?start=pier">Pier</a> """ # 禁用网页预览,让消息更整洁 await update.message.reply_text(list_content, parse_mode="HTML", disable_web_page_preview=True) if __name__ == "__main__": # 替换成你的Bot Token app = ApplicationBuilder().token("YOUR_BOT_TOKEN").build() app.add_handler(CommandHandler("start", handle_start)) app.add_handler(CommandHandler("list", handle_list)) app.run_polling()
注意事项
- 参数安全性:优先用用户ID而非明文名称作为参数,避免用户手动修改链接参数查询其他用户信息(比如
start=12345对应ID为12345的用户)。 - 消息格式:如果使用Markdown格式,链接写法为
[Alex](t.me/MyListBot?start=alex),需设置parse_mode="MarkdownV2"并转义特殊字符。 - 网页预览:务必添加
disable_web_page_preview=True,否则Telegram会显示链接预览卡片,影响列表展示效果。
内容的提问来源于stack exchange,提问作者english_wife
相关产品推荐
相关产品推荐

