Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

A few fixes to support Django 3+ and latest version of TelegramBot #39

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,14 @@ 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
#updates you want your bot to receive. For example, specify
#``["message", "edited_channel_post", "callback_query"]`` to
Expand Down
2 changes: 1 addition & 1 deletion django_telegrambot/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
__version__ = '1.0.1'
__version__ = '1.0.2'
default_app_config = 'django_telegrambot.apps.DjangoTelegramBot'
52 changes: 39 additions & 13 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 @@ -162,15 +171,16 @@ def ready(self):

for b in bots_list:
token = b.get('TOKEN', None)
context = b.get('CONTEXT', False)
if not token:
break

allowed_updates = b.get('ALLOWED_UPDATES', None)
timeout = b.get('TIMEOUT', None)
proxy = b.get('PROXY', None)

if self.mode == WEBHOOK_MODE:
try:
try:
if b.get('MESSAGEQUEUE_ENABLED',False):
q = mq.MessageQueue(all_burst_limit=b.get('MESSAGEQUEUE_ALL_BURST_LIMIT',29),
all_time_limit_ms=b.get('MESSAGEQUEUE_ALL_TIME_LIMIT_MS',1024))
Expand All @@ -184,8 +194,8 @@ def ready(self):
if proxy:
request = Request(proxy_url=proxy['proxy_url'], urllib3_proxy_kwargs=proxy['urllib3_proxy_kwargs'])
bot = telegram.Bot(token=token, request=request)
DjangoTelegramBot.dispatchers.append(Dispatcher(bot, None, workers=0))

DjangoTelegramBot.dispatchers.append(Dispatcher(bot, None, workers=0, use_context=context))
hookurl = '{}/{}/{}/'.format(webhook_site, webhook_base, token)
max_connections = b.get('WEBHOOK_MAX_CONNECTIONS', 40)
setted = bot.setWebhook(hookurl, certificate=certificate, timeout=timeout, max_connections=max_connections, allowed_updates=allowed_updates)
Expand All @@ -198,13 +208,21 @@ 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:
try:
updater = Updater(token=token, request_kwargs=proxy)
updater = Updater(token=token, request_kwargs=proxy, use_context=context)
bot = updater.bot
bot.delete_webhook()
DjangoTelegramBot.updaters.append(updater)
Expand All @@ -213,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