我正在从here重新创建基本的电报机器人示例,但是我遇到了一个小问题。
import logging
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',level=logging.INFO)
logger = logging.getLogger(__name__)
# Define a few command handlers. These usually take the two arguments bot and
# update. Error handlers also receive the raised TelegramError object in error.
def start(update, context):
"""Send a message when the command /start is issued."""
update.message.reply_text('Hi!')
def help(update, context):
"""Send a message when the command /help is issued."""
update.message.reply_text('Help!')
def echo(update, context):
"""Echo the user message."""
update.message.reply_text(update.message.text)
def error(update, context):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, context.error)
def main():
"""Start the bot."""
# Create the Updater and pass it your bot's token.
# Make sure to set use_context=True to use the new context based callbacks
# Post version 12 this will no longer be necessary
updater = Updater("YOUR TOKEN HERE",use_context=True)
# Get the dispatcher to register handlers
dp = updater.dispatcher
# on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help))
# on noncommand i.e message - echo the message on Telegram
dp.add_handler(MessageHandler(Filters.text, echo))
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.start_polling()
# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
if __name__ == '__main__':
main()
执行脚本后出现以下错误:
$ python test1.py
Traceback (most recent call last):
File "test1.py", line 64, in <module>
main()
File "test1.py", line 39, in main
updater = Updater(TOKEN,use_context=True)
TypeError: __init__() got an unexpected keyword argument 'use_context'
答案 0 :(得分:1)
use_context
自python-telegram-bot版本12起可用。您可以通过pip show python-telegram-bot
来找到已安装的版本。
最简单的解决方案是仅删除参数use_context
,即替换
updater = Updater("YOUR TOKEN HERE",use_context=True)
使用
updater = Updater("YOUR TOKEN HERE")
答案 1 :(得分:0)
该错误告诉您use_context
不是Updater初始化程序的有效关键字参数。 Python Telegram Bot的第12版不再支持该参数。
我想您已经pip install python-telegram-bot==12.0.0b1 --upgrade
安装了该库,并且正在安装版本12.0.0b1。
您可以通过运行以下命令来再次进行安装:
卸载当前版本的python-telegram-bot:pip uninstall python-telegram-bot
安装库的11版本:pip install python-telegram-bot==11
此外,如果您不想更改库版本并继续使用python-telegram-bot
12.0.0,则只需从Updater类的实例中删除use_context
参数。
此行:
updater = Updater("YOUR TOKEN HERE",use_context=True)
将成为:
updater = Updater("YOUR TOKEN HERE")