Skip to content

Commit

Permalink
Only set webhook and load handlers when we want to receive updates (#19)
Browse files Browse the repository at this point in the history
Co-authored-by: Lukas <[email protected]>
  • Loading branch information
autoantwort and lukruh authored Aug 2, 2021
1 parent 3a9da9c commit 70e6016
Showing 1 changed file with 17 additions and 4 deletions.
21 changes: 17 additions & 4 deletions django_telegrambot/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
# django_telegram_bot/apps.py
import os.path
import importlib
import sys
from collections import OrderedDict
from typing import List

Expand Down Expand Up @@ -149,9 +150,18 @@ def ready(self):
modes = ['WEBHOOK','POLLING']
logger.info('Django Telegram Bot <{} mode>'.format(modes[self.mode]))

receive_updates = True
args = [arg.casefold() for arg in sys.argv]
is_manage_py = any(arg.endswith("manage.py") for arg in args)
if is_manage_py:
if self.mode == WEBHOOK_MODE:
receive_updates = "runserver" in args
else:
receive_updates = "botpolling" in args

bots_list = settings.DJANGO_TELEGRAMBOT.get('BOTS', [])

if self.mode == WEBHOOK_MODE:
if self.mode == WEBHOOK_MODE and receive_updates:
webhook_site = settings.DJANGO_TELEGRAMBOT.get('WEBHOOK_SITE', None)
if not webhook_site:
logger.warn('Required TELEGRAM_WEBHOOK_SITE missing in settings')
Expand Down Expand Up @@ -199,8 +209,8 @@ def ready(self):
request = Request(proxy_url=bot.proxy['proxy_url'], urllib3_proxy_kwargs=bot.proxy['urllib3_proxy_kwargs'])
bot.instance = telegram.Bot(token=bot.token, request=request)

bot.dispatcher = Dispatcher(bot.instance, None, use_context=bot.use_context)
if not settings.DJANGO_TELEGRAMBOT.get('DISABLE_SETUP', False):
bot.dispatcher = Dispatcher(bot.instance, None, workers=0, use_context=bot.use_context)
if not settings.DJANGO_TELEGRAMBOT.get('DISABLE_SETUP', False) and receive_updates:
hookurl = '{}/{}/{}/'.format(webhook_site, webhook_base, bot.token)
max_connections = b.get('WEBHOOK_MAX_CONNECTIONS', 40)
setted = bot.instance.setWebhook(hookurl, certificate=certificate, timeout=bot.timeout, max_connections=max_connections, allowed_updates=bot.allowed_updates)
Expand All @@ -227,7 +237,7 @@ def ready(self):

else:
try:
if not settings.DJANGO_TELEGRAMBOT.get('DISABLE_SETUP', False):
if not settings.DJANGO_TELEGRAMBOT.get('DISABLE_SETUP', False) and receive_updates:
bot.updater = Updater(token=bot.token, request_kwargs=bot.proxy, use_context=bot.use_context)
bot.instance = bot.updater.bot
bot.instance.delete_webhook()
Expand Down Expand Up @@ -280,6 +290,9 @@ def module_imported(module_name, method_name, execute):

return True

if not receive_updates:
return

# import telegram bot handlers for all INSTALLED_APPS
for app_config in apps.get_app_configs():
if module_has_submodule(app_config.module, TELEGRAM_BOT_MODULE_NAME):
Expand Down

0 comments on commit 70e6016

Please sign in to comment.