基于python-telegram-bot实现提及机器人触发菜单及按键输入功能
解决方案
1. 实现提及机器人触发菜单
通过MessageHandler监听文本消息,过滤包含机器人用户名的内容,匹配成功后触发菜单发送逻辑即可实现该功能。
关键代码实现
先把菜单发送逻辑抽为独立函数,方便复用:
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup from telegram.ext import CallbackContext, MessageHandler, Filters, CommandHandler import re def show_menu(update: Update, context: CallbackContext): # 兼容不同类型的更新(命令、回调、提及消息) if update.callback_query: query = update.callback_query query.answer() chat_id = query.message.chat.id else: query = update.effective_message chat_id = update.effective_chat.id bot_username = context.bot.username # 构建按钮(下文会修改按钮类型) keyboard = [ [InlineKeyboardButton("Open Search Menu", switch_inline_query="")] ] reply_markup = InlineKeyboardMarkup(keyboard) context.bot.send_photo( chat_id=chat_id, photo=returnConfig()["General_Config"]["Image"], caption=f"Hey @{query.from_user.username}! Welcome back, how can I help you today?\n\nCheck out {returnConfig()['General_Config']['UpdatesGroup']} for instant updates, and {returnConfig()['General_Config']['ServicesList']} for all our services.", reply_markup=reply_markup, ) # 原/start命令直接调用菜单函数 def start(update: Update, context: CallbackContext): show_menu(update, context) # 处理提及机器人的消息 def handle_bot_mention(update: Update, context: CallbackContext): bot_username = context.bot.username # 匹配包含@机器人用户名的消息 # 若要精确匹配(仅单独提及机器人),改用正则:rf"^\s*@{re.escape(bot_username)}\s*$" if f"@{bot_username}" in update.effective_message.text: show_menu(update, context)
然后在机器人的处理器注册中添加:
# 注册命令和消息处理器 application.add_handler(CommandHandler("start", start)) application.add_handler(MessageHandler(Filters.text & ~Filters.command, handle_bot_mention))
2. 制作点击后输入@bot_username的按钮
利用Telegram内联按钮的switch_inline_query参数,点击后会自动在聊天输入框填入@机器人用户名 + 设定参数,将参数设为空字符串即可满足需求。
修改按钮代码
把原代码中的callback_data="???"替换为switch_inline_query="":
keyboard = [ [InlineKeyboardButton("Open Search Menu", switch_inline_query="")] ]
点击该按钮后,Telegram客户端会自动在输入框中填入@bot_username (末尾带空格),用户可直接输入内容触发机器人的内联菜单。
若要限定在当前聊天中触发内联查询,可改用switch_inline_query_current_chat="",效果一致但范围更明确。
内容的提问来源于stack exchange,提问作者Rehan
相关产品推荐
相关产品推荐

