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

集成ChatGPT的Telegram代码修复Bot报错:Dispatcher未定义

解决Telegram Bot中的NameError: name 'Dispatcher' is not defined问题

问题原因

  1. 未导入Dispatcher类,且新版python-telegram-bot中无需手动创建Dispatcher——Updater对象已经自带dispatcher属性,手动实例化属于冗余且不符合新版本规范的操作。
  2. 代码中存在大小写错误:导入的是filters(小写),但使用时写成了Filters(大写)。
  3. Flask应用未实例化,会导致后续app.run()报错。

修复方案

直接使用Updater内置的dispatcher,修正大小写错误,并补全Flask实例化代码:

import os

from flask import Flask, request, jsonify 

from telegram import Update, Bot

from telegram.ext import MessageHandler, filters, Updater, CommandHandler, CallbackContext
from queue import Queue

import openai

# 替换为你的OpenAI API密钥
openai.api_key = "openAI_API_KEY_HERE" 

# 替换为你的Telegram Bot令牌
TELEGRAM_API_TOKEN = "bot_Token_here"

# 实例化Flask应用
app = Flask(__name__)

bot = Bot(token=TELEGRAM_API_TOKEN)

update_queue = Queue()
updater = Updater(bot=bot, update_queue=update_queue)

# 直接使用Updater内置的dispatcher,无需手动创建
dispatcher = updater.dispatcher
dispatcher.use_context = True


# 处理Telegram消息的函数
def handle_message(update: Update, context: CallbackContext):
    message_text = update.message.text
    chat_id = update.message.chat_id

    # 判断是否为代码修复请求
    if message_text.startswith("/codefix"):
        # 提取需要修复的代码
        code_to_fix = message_text[8:]

        # 请求ChatGPT修复代码
        response = openai.Completion.create(
            engine="davinci",
            prompt=f"Fix the following code:\n```{code_to_fix}```",
            max_tokens=50
        )

        # 提取修复后的代码
        fixed_code = response.choices[0].text
        
        # 回复用户
        bot.send_message(chat_id=chat_id, text=f"修复后的代码:\n```{fixed_code}```")

    else:
        # 处理非代码修复请求
        bot.send_message(chat_id=chat_id, text="我仅提供代码修复服务,请使用/codefix命令提交需要修复的代码。")

# start命令处理函数
def start(update: Update, context: CallbackContext):
    update.message.reply_text("欢迎使用代码修复Bot!发送/codefix + 你的代码即可获取修复帮助。")

# 设置消息处理器(注意filters是小写)
message_handler = MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message)
dispatcher.add_handler(message_handler)

# 设置命令处理器
dispatcher.add_handler(CommandHandler("start", start))

if __name__ == "__main__":
    # 启动Bot和Flask服务
    updater.start_polling()  
    app.run(debug=True)

额外优化建议

  • 若使用python-telegram-bot v13及以上版本,Updater的update_queue参数已被弃用,建议改用更简洁的初始化方式:updater = Updater(token=TELEGRAM_API_TOKEN, use_context=True),无需手动创建Bot和Queue。
  • OpenAI的Completion接口已逐步被ChatCompletion取代,建议改用gpt-3.5-turbo模型,示例代码如下:
response = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    messages=[{"role": "user", "content": f"Fix the following code:\n```{code_to_fix}```"}],
    max_tokens=50
)
fixed_code = response.choices[0].message['content']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 21:05:07