python - 我收到错误 AttributeError : 'Updater' object has no attribute 'dispatcher'

标签 python bots telegram openai-api

运行 python 脚本以将 openai 与 Telegram Bot 集成时出现错误。这是我的代码:

# Import the necessary modules
import telegram
import openai
from telegram.ext import CommandHandler, MessageHandler, Updater
from queue import Queue

# Initialize the Telegram bot
bot = telegram.Bot(token='')

# Initialize the OpenAI API
openai.api_key = ''

# Define a function to handle /start command
def start(bot, update):
    bot.send_message(chat_id=update.message.chat_id, text="Hi! I'm a ChatGPT bot. Send me a message and I'll try to respond to it.")

# Define a function to handle messages
def message(bot, update):
    # Get the message text
    message_text = update.message.text

    # Call the OpenAI API to generate a response
    response = openai.Completion.create(
        engine="davinci",
        prompt=message_text,
        max_tokens=1024,
        n=1,
        stop=None,
        temperature=0.5,
    )

    # Get the response text from the API
    response_text = response.choices[0].text.strip()

    # Send the response back to the user
    bot.send_message(chat_id=update.message.chat_id, text=response_text)

# Initialize the Telegram bot updater and dispatcher
update_queue = Queue()
updater = Updater(bot=bot, update_queue=update_queue)
dispatcher = updater.dispatcher

# Add command handlers
start_handler = CommandHandler('start', start)
dispatcher.add_handler(start_handler)

# Add message handler
message_handler = MessageHandler(None, message)
dispatcher.add_handler(message_handler)

# Start the Telegram bot
updater.start_polling()

错误:

dispatcher = updater.dispatcher
                 ^^^^^^^^^^^^^^^^^^
AttributeError: 'Updater' object has no attribute 'dispatcher'

我不知道如何解决这个问题,因为我已经看到很多解决方案,但它告诉我更新 Telegram Bot 。 有什么解决办法吗?我已经升级了 telegram-bot,但仍然出错。

最佳答案

我认为 'dispatcher'20.0a0 版本中不再使用

如果你想使用你的代码,那么你可以降级为:

pip install python-telegram-bot==13.3

如果您使用的是 v20,那么您必须以不同的方式构建您的应用程序,并且您必须使用 async 函数。

关于python - 我收到错误 AttributeError : 'Updater' object has no attribute 'dispatcher' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75455878/

相关文章:

javascript - 需要帮助制作 Java 脚本 Discord 音乐机器人

java - 尝试在 VPS 上启动 JDA Discord 机器人时出错

python - 使用python在MySQL中添加数据

python - Tkinter 网格布局不会扩展

java - Java 的 Facebook Messenger bot 对象结构

python - 如何定期在 Telegram Bot 中发送 InlineKeyboardButton?

python - 使用 Telegram-InlineKeyboardMarkup,我可以在按下按钮时向用户提供反馈吗?

Go Telegram Bot API 从本地文件上传照片

python - 如何删除或替换 zip 存档中的文件?

python - `/bin/sh` 在 docker 内的 Jenkins 内的 tox 中未找到