我正在创建一个电报机器人,出现以下错误,如何修复它?

问题描述 投票:0回答:2

我正在创建一个电报机器人,当我运行代码来尝试它时,它显示此错误:发生异常:TypeError Updater.init() 得到了意外的关键字参数“use_context”

import telegram
from telegram.ext import Updater, CommandHandler, MessageHandler, filters

def handle_message(update, context):
    message = update.message.text
    
    # Implement your logic based on the message content
    if message == '/help':
        context.bot.send_message(chat_id=update.effective_chat.id, text="This is the help message.")
    elif message.startswith('/sayhello'):
        name = message.split()[1]  # Extract the name from the command
        context.bot.send_message(chat_id=update.effective_chat.id, text=f"Hello, {name}!")
    else:
        context.bot.send_message(chat_id=update.effective_chat.id, text="Sorry, I didn't understand that command.")


def start_command(update, context):
    # Send a welcome message
    context.bot.send_message(chat_id=update.effective_chat.id, text="Hello! I'm your Telegram bot.")

bot = telegram.Bot(token='blabla')
updater = Updater(bot= bot, use_context=True)
dispatcher = updater.dispatcher
dispatcher.add_handler(CommandHandler('start', start_command))
dispatcher.add_handler(MessageHandler(filters.text, handle_message))

updater.start_polling()



我正在使用 python-telegram-bot 库的 20.3 版本。 我尝试降级到 20.2 和其他版本,但没有任何效果。

python telegram-bot python-telegram-bot py-telegram-bot-api
2个回答
0
投票

错误消息表明您正在使用过时版本的 python-telegram-bot 库。 use_context 参数是在库的 13.0 版本中引入的,看来您的代码正在尝试将它与旧版本一起使用。

要解决此问题,您有几个选择:

升级 python-telegram-bot 库:将 python-telegram-bot 库更新到 13.0 或更高版本,支持 use_context 参数。您可以使用以下命令来升级库:

pip install --upgrade python-telegram-bot

升级后,use_context参数应该被Updater类识别。

修改代码以删除 use_context 参数:如果您不想升级库,可以修改代码以删除 use_context 参数。在该库的早期版本中,不存在 use_context 参数,因此您只需从 Updater.init() 函数调用中将其删除即可。您更新后的代码可能如下所示:

from telegram.ext import Updater, CommandHandler

def start_command(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id, text="Hello, I'm your bot!")

updater = Updater('blabla')
dispatcher = updater.dispatcher
start_handler = CommandHandler('start', start)
dispatcher.add_handler(start_handler)

updater.start_polling()

此修改后的代码应该适用于旧版本的 python-telegram-bot 库。

选择最适合您需求的选项,并确保相应地调整您的代码。


0
投票

要解决此问题,请将“过滤器”替换为“过滤器”并安装旧版本的 python-telegram-bot。 您可以尝试以下命令: pip 安装 python-telegram-bot==13.14

这修复了我的代码,现在运行没有任何问题。 我以前有 python-telegram-bot v20.6,它导致了错误。 安装v13.14后,就没有再出现错误了。

更新的代码: pip 安装 python-telegram-bot==13.14

© www.soinside.com 2019 - 2024. All rights reserved.