Skip to content

Commit

Permalink
Supporting Django 3+ and Telegrambot in 2020 (#2)
Browse files Browse the repository at this point in the history
* Showing more informative TelegramError

* Fixing example and adding a handlers file option

* Update package version

* Adding RetryError handling
  • Loading branch information
leikoilja authored Apr 14, 2020
1 parent 4c191c5 commit 5f07ec5
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 23 deletions.
4 changes: 3 additions & 1 deletion README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
41 changes: 33 additions & 8 deletions django_telegrambot/apps.py
Original file line number Diff line number Diff line change
@@ -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)
Expand All @@ -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'
Expand Down Expand Up @@ -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:
Expand All @@ -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)
Expand Down
6 changes: 3 additions & 3 deletions django_telegrambot/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
20 changes: 10 additions & 10 deletions example/telegrambot.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
2 changes: 1 addition & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[bumpversion]
current_version = 0.1.0
current_version = 0.1.2
commit = True
tag = True

Expand Down

0 comments on commit 5f07ec5

Please sign in to comment.