基本电报机器人示例

basic telegram bot example

我正在重新创建 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'

错误告诉您 use_context 不是 Updater 初始值设定项的有效关键字参数。 Python Telegram Bot.

的第 12 版不再支持该参数

我猜你 pip install python-telegram-bot==12.0.0b1 --upgrade 安装了库,它正在安装版本 12.0.0b1。

您可以通过运行以下命令再次安装:

  1. 卸载当前版本python-telegram-bot:pip uninstall python-telegram-bot

  2. 安装11版本库:pip install python-telegram-bot==11

此外,如果您不想更改您的库版本并继续使用 python-telegram-bot 12.0.0,您可以从更新程序 [=42] 的实例化中删除 use_context 参数=].

这一行:

updater = Updater("YOUR TOKEN HERE",use_context=True)

会变成:

updater = Updater("YOUR TOKEN HERE")

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")