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

如何让Python Telegram Bot命令触发后等待并处理后续消息

实现Telegram Bot命令等待后续消息的功能

需求说明

当前你的Telegram Bot支持发送/musica + YouTube链接来获取对应MP3文件,现在需要优化:当用户仅发送/musica命令时,Bot先回复「请发送YouTube链接」,随后自动处理用户发送的下一条消息作为链接来生成MP3。

修改后的完整代码

from telegram import Update
from telegram.ext import Application, CommandHandler, filters, ContextTypes, MessageHandler
from download import ottieniMp3

token = "MYTOKEN"
username= "USERNAME"

# commands
async def musica(update: Update, context: ContextTypes.DEFAULT_TYPE):
    # 提取命令后的文本内容
    command_text = update.message.text.split("/musica", 1)[-1].strip()
    if command_text:
        # 如果命令后直接带了链接,直接处理
        try:
            await update.message.reply_audio(open(ottieniMp3(command_text), "rb"))
        except Exception as e:
            await update.message.reply_text(f"处理链接时出错:{str(e)}")
    else:
        # 如果没有附带链接,设置用户状态并提示
        context.user_data['awaiting_youtube_link'] = True
        await update.message.reply_text("请发送YouTube链接")

# 消息处理
async def gestisciMessaggio(update: Update, context: ContextTypes.DEFAULT_TYPE):
    # 先检查用户是否处于等待YouTube链接的状态
    if context.user_data.get('awaiting_youtube_link'):
        youtube_link = update.message.text.strip()
        try:
            # 处理链接并发送MP3
            await update.message.reply_audio(open(ottieniMp3(youtube_link), "rb"))
            # 处理完成后清除状态
            del context.user_data['awaiting_youtube_link']
        except Exception as e:
            await update.message.reply_text(f"链接无效或处理出错:{str(e)}")
            # 出错后也清除状态,避免一直卡住
            del context.user_data['awaiting_youtube_link']
    else:
        # 非等待状态下的默认回复
        await update.message.reply_text("i do not understand")

async def gestisciErrore(update: Update, context: ContextTypes.DEFAULT_TYPE):
    print(f"Update {update} caused the error {context.error}")

if __name__ == '__main__':
    print('the bot is starting')
    bot = Application.builder().token(token).build()
    # 添加命令处理器
    bot.add_handler(CommandHandler('musica', musica))
    # 添加消息处理器(注意顺序:命令处理器优先于消息处理器)
    bot.add_handler(MessageHandler(filters.TEXT, gestisciMessaggio))
    # 错误处理器
    bot.add_error_handler(gestisciErrore)

    print('Polling')
    bot.run_polling(poll_interval=3)

关键逻辑说明

  1. 用户状态跟踪:使用context.user_data存储用户的会话状态,这是每个用户独立的字典,用来标记当前是否需要等待YouTube链接。
  2. 命令分支处理:
    • 当用户发送/musica附带链接时,直接调用ottieniMp3处理并返回音频
    • 当用户仅发送/musica时,设置awaiting_youtube_link状态为True,并提示用户发送链接
  3. 消息优先处理:在gestisciMessaggio中先检查用户状态,如果处于等待链接状态,就把当前消息当作YouTube链接处理,完成后删除状态;否则返回默认的不理解回复。
  4. 错误处理:添加try-except捕获处理链接时的异常,避免Bot崩溃,同时出错后清除状态,防止用户一直处于等待状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 18:23:41