You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Telegram Bot开发:如何通过switch_pm实现选聊天发消息后返回Bot会话

解决Telegram Bot引导用户跳转聊天撰写消息后返回的问题

嘿,我刚好踩过这个坑!你说的switch_pm确实是实现这个需求的正确方案,我来给你讲清楚它的用法,再帮你调整代码。

首先先区分下你原来用的switch_inline_query和switch_pm的核心区别:

  • switch_inline_query是让用户在当前聊天窗口发起inline query
  • 而switch_pm才是你需要的:它会引导用户离开Bot聊天窗口,选择其他目标聊天,在那个聊天里发起你的Bot的inline query,完成输入后会自动跳回和Bot的聊天界面,完美匹配你的需求。

switch_pm的核心参数说明

在创建InlineKeyboardButton时,你需要用到两个关键参数:

  • switch_pm_text:按钮上显示的文字,比如“去其他窗口写消息”
  • switch_pm_parameter(可选):自定义标记参数,用来识别用户是从哪个入口跳转过来的,方便后续处理inline请求时做区分

修改后的完整代码示例

我直接给你调整好可运行的代码,加上详细注释:

from telegram import InlineKeyboardButton, InlineKeyboardMarkup, InlineQueryResultArticle, InputTextMessageContent
from telegram.ext import CommandHandler, CallbackQueryHandler, InlineQueryHandler, Updater

def inlineKeyboard(update, context):
    # 创建带switch_pm参数的按钮,引导用户跳转至其他聊天窗口
    keyboard = [[InlineKeyboardButton(
        "点击去其他窗口写消息", 
        switch_pm_text="开始撰写", 
        switch_pm_parameter="from_test_command"  # 标记跳转来源,后续可识别
    )]]
    reply_markup = InlineKeyboardMarkup(keyboard)
    update.message.reply_text('请点击下方按钮开始撰写消息:', reply_markup=reply_markup)

# 注意:switch_pm类型的按钮不会触发CallbackQuery,这个handler是处理普通按钮的,可按需保留或删除
def button(update, context):
    query = update.callback_query
    query.answer()
    query.edit_message_text(text="Selected option: {}".format(query.data))

# 处理用户跳转后发起的inline query请求
def handle_inline_query(update, context):
    user_input_content = update.inline_query.query
    source_tag = update.inline_query.switch_pm_parameter  # 获取之前设置的来源标记
    
    # 这里可以根据需求处理用户输入的内容,比如保存到数据库、返回自定义结果等
    # 示例:返回一个确认选项,用户选择后消息会发送到目标聊天,同时自动回到Bot界面
    results = [
        InlineQueryResultArticle(
            id='1',
            title='确认发送这条消息',
            input_message_content=InputTextMessageContent(message_text=user_input_content)
        )
    ]
    update.inline_query.answer(results)

# 初始化Bot并注册处理器
updater = Updater("你的Bot令牌")
updater.dispatcher.add_handler(CommandHandler('test', inlineKeyboard))
updater.dispatcher.add_handler(CallbackQueryHandler(button))
updater.dispatcher.add_handler(InlineQueryHandler(handle_inline_query))

updater.start_polling()
updater.idle()

完整流程说明

  1. 用户发送/test命令,Bot回复带跳转按钮的消息
  2. 用户点击按钮,Telegram自动弹出聊天选择界面
  3. 用户选择目标聊天后,输入框会自动关联你的Bot(格式为@你的Bot名 + 输入内容)
  4. 用户输入内容后,Bot通过InlineQueryHandler收到请求并返回处理结果
  5. 用户选择结果后,消息会发送到目标聊天,同时Telegram自动将用户带回Bot的聊天界面

这样就完全实现了你想要的功能啦!

内容的提问来源于stack exchange,提问作者Ralstonnn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 15:32:53