From 5f07ec585086eca9f26d10305eca58fe21c67a6d Mon Sep 17 00:00:00 2001 From: Ilja Leiko Date: Tue, 14 Apr 2020 02:52:24 +0200 Subject: [PATCH] Supporting Django 3+ and Telegrambot in 2020 (#2) * Showing more informative TelegramError * Fixing example and adding a handlers file option * Update package version * Adding RetryError handling --- README.rst | 4 +++- django_telegrambot/apps.py | 41 +++++++++++++++++++++++++++++-------- django_telegrambot/views.py | 6 +++--- example/telegrambot.py | 20 +++++++++--------- setup.cfg | 2 +- 5 files changed, 50 insertions(+), 23 deletions(-) diff --git a/README.rst b/README.rst index 111b40b..e9a093c 100644 --- a/README.rst +++ b/README.rst @@ -77,10 +77,12 @@ And set your bots:: # apps contain telegrambot.py files that cannot be successfully # imported. + 'BOT_MODULE_NAME': 'telegrambot_handlers', #(Optional [str]) # The default name for file name containing telegram handlers which has to be placed inside your local app(s). Default is 'telegrambot'. Example is to put "telegrambot_handlers.py" file to local app's folder. + 'BOTS' : [ { 'TOKEN': '123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11', #Your bot token. - + #'CONTEXT': True, # Use context based handler functions #'ALLOWED_UPDATES':(Optional[list[str]]), # List the types of diff --git a/django_telegrambot/apps.py b/django_telegrambot/apps.py index fd37381..5b40d50 100644 --- a/django_telegrambot/apps.py +++ b/django_telegrambot/apps.py @@ -1,26 +1,34 @@ # coding=utf-8 # django_telegram_bot/apps.py +import os.path +import importlib +import telegram +import logging +from time import sleep + from django.apps import AppConfig from django.apps import apps from django.conf import settings -import importlib -import telegram from django.utils.module_loading import module_has_submodule + from telegram.ext import Dispatcher from telegram.ext import Updater -from telegram.error import InvalidToken, TelegramError +from telegram.error import InvalidToken +from telegram.error import RetryAfter +from telegram.error import TelegramError from telegram.utils.request import Request from telegram.ext import messagequeue as mq + from .mqbot import MQBot -import os.path -import logging logger = logging.getLogger(__name__) -TELEGRAM_BOT_MODULE_NAME = 'telegrambot' + +TELEGRAM_BOT_MODULE_NAME = settings.DJANGO_TELEGRAMBOT.get('BOT_MODULE_NAME', 'telegrambot') WEBHOOK_MODE, POLLING_MODE = range(2) + class classproperty(property): def __get__(self, obj, objtype=None): return super(classproperty, self).__get__(objtype) @@ -29,6 +37,7 @@ def __set__(self, obj, value): def __delete__(self, obj): super(classproperty, self).__delete__(type(obj)) + class DjangoTelegramBot(AppConfig): name = 'django_telegrambot' @@ -199,8 +208,16 @@ def ready(self): except InvalidToken: logger.error('Invalid Token : {}'.format(token)) return + except RetryAfter as er: + logger.debug('Error: "{}". Will retry in {} seconds'.format( + er.message, + er.retry_after + ) + ) + sleep(er.retry_after) + self.ready() except TelegramError as er: - logger.error('Error : {}'.format(repr(er))) + logger.error('Error: "{}"'.format(er.message)) return else: @@ -214,8 +231,16 @@ def ready(self): except InvalidToken: logger.error('Invalid Token : {}'.format(token)) return + except RetryAfter as er: + logger.debug('Error: "{}". Will retry in {} seconds'.format( + er.message, + er.retry_after + ) + ) + sleep(er.retry_after) + self.ready() except TelegramError as er: - logger.error('Error : {}'.format(repr(er))) + logger.error('Error: "{}"'.format(er.message)) return DjangoTelegramBot.bots.append(bot) diff --git a/django_telegrambot/views.py b/django_telegrambot/views.py index 37d76e7..44328ae 100644 --- a/django_telegrambot/views.py +++ b/django_telegrambot/views.py @@ -30,19 +30,19 @@ def webhook (request, bot_token): #verifico la validità del token bot = DjangoTelegramBot.getBot(bot_id=bot_token, safe=False) if bot is None: - logger.warn('Request for not found token : {}'.format(bot_token)) + logger.warn('Request for not found token: {}'.format(bot_token)) return JsonResponse({}) try: data = json.loads(request.body.decode("utf-8")) except: - logger.warn('Telegram bot <{}> receive invalid request : {}'.format(bot.username, repr(request))) + logger.warn('Telegram bot <{}> receive invalid request: {}'.format(bot.username, repr(request))) return JsonResponse({}) dispatcher = DjangoTelegramBot.getDispatcher(bot_token, safe=False) if dispatcher is None: - logger.error('Dispatcher for bot <{}> not found : {}'.format(bot.username, bot_token)) + logger.error('Dispatcher for bot <{}> not found: {}'.format(bot.username, bot_token)) return JsonResponse({}) try: diff --git a/example/telegrambot.py b/example/telegrambot.py index 682b75e..e953094 100644 --- a/example/telegrambot.py +++ b/example/telegrambot.py @@ -9,31 +9,31 @@ # 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(bot, update): - bot.sendMessage(update.message.chat_id, text='Hi!') +def start(update, context): + context.bot.sendMessage(update.message.chat_id, text='Hi!') -def help(bot, update): - bot.sendMessage(update.message.chat_id, text='Help!') +def help(update, context): + context.bot.sendMessage(update.message.chat_id, text='Help!') -def echo(bot, update): - bot.sendMessage(update.message.chat_id, text=update.message.text) +def echo(update, context): + context.bot.sendMessage(update.message.chat_id, text=update.message.text) -def error(bot, update, error): +def error(update, context, error): logger.warn('Update "%s" caused error "%s"' % (update, error)) - + def main(): logger.info("Loading handlers for telegram bot") - + # Default dispatcher (this is related to the first bot in settings.TELEGRAM_BOT_TOKENS) dp = DjangoTelegramBot.dispatcher # To get Dispatcher related to a specific bot # dp = DjangoTelegramBot.getDispatcher('BOT_n_token') #get by bot token # dp = DjangoTelegramBot.getDispatcher('BOT_n_username') #get by bot username - + # on different commands - answer in Telegram dp.add_handler(CommandHandler("start", start)) dp.add_handler(CommandHandler("help", help)) diff --git a/setup.cfg b/setup.cfg index bee097a..194b8b4 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 0.1.0 +current_version = 0.1.2 commit = True tag = True