From 70e6016b09d1fb91dd45e3cf2dc8fd8e82dbc824 Mon Sep 17 00:00:00 2001 From: autoantwort <41973254+autoantwort@users.noreply.github.com> Date: Mon, 2 Aug 2021 11:54:16 +0200 Subject: [PATCH] Only set webhook and load handlers when we want to receive updates (#19) Co-authored-by: Lukas --- django_telegrambot/apps.py | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/django_telegrambot/apps.py b/django_telegrambot/apps.py index 4f1f821..a34c00e 100644 --- a/django_telegrambot/apps.py +++ b/django_telegrambot/apps.py @@ -2,6 +2,7 @@ # django_telegram_bot/apps.py import os.path import importlib +import sys from collections import OrderedDict from typing import List @@ -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') @@ -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) @@ -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() @@ -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):