базовый пример бота телеграммы - PullRequest
0 голосов
/ 07 июля 2019

Я воссоздаю базовый пример бота-телеграммы из здесь , но у меня небольшая проблема.

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'

Ответы [ 2 ]

1 голос
/ 07 июля 2019

use_context доступно начиная с версии 12 python-telegram-bot.Вы можете узнать версию, которую вы установили через pip show python-telegram-bot.

Самое простое решение - просто удалить параметр use_context, то есть заменить

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

на

updater = Updater("YOUR TOKEN HERE")
0 голосов
/ 07 июля 2019

Ошибка говорит вам, что use_context не является допустимым аргументом ключевого слова для инициализатора Updater.Этот аргумент больше не поддерживается в 12-й версии Python Telegram Bot .

Я полагаю, вы сделали 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, выможно просто удалить аргумент use_context из экземпляра класса Updater.

Эта строка:

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

станет:

updater = Updater("YOUR TOKEN HERE")
...