From b0d17fc088b1a1e4a0baa0cc07ff3a26614cdae3 Mon Sep 17 00:00:00 2001 From: Nikita Shamaev Date: Fri, 9 Sep 2022 17:56:14 +0300 Subject: [PATCH 1/3] change structure tgbot with handlers are in separate folder. separate commands, dispatcher in tgbot --- arcgis/migrations/0001_initial.py | 4 +- arcgis/models.py | 2 +- dtb/settings.py | 2 +- dtb/urls.py | 6 +- {tgbot => dtb}/views.py | 23 ++-- run_polling.py | 26 ++++- tgbot/apps.py | 5 - tgbot/commands.py | 55 ++++++++++ tgbot/dispatcher.py | 102 ++---------------- tgbot/handlers/admin/handlers.py | 2 +- tgbot/handlers/broadcast_message/handlers.py | 4 +- tgbot/handlers/broadcast_message/utils.py | 8 +- tgbot/handlers/location/handlers.py | 2 +- tgbot/handlers/onboarding/handlers.py | 2 +- tgbot/handlers/utils/error.py | 2 +- tgbot/handlers/utils/files.py | 2 +- tgbot/handlers/utils/info.py | 5 +- tgbot/main.py | 17 +++ tgbot/urls.py | 10 -- {tgbot/migrations => users}/__init__.py | 0 {tgbot => users}/admin.py | 12 +-- users/apps.py | 5 + {tgbot => users}/forms.py | 0 {tgbot => users}/migrations/0001_initial.py | 2 +- .../migrations/0002_alter_user_user_id.py | 2 +- .../migrations/0003_rm_unused_fields.py | 2 +- users/migrations/__init__.py | 0 {tgbot => users}/models.py | 0 {tgbot => users}/tasks.py | 10 +- .../templates/admin/broadcast_message.html | 0 30 files changed, 161 insertions(+), 151 deletions(-) rename {tgbot => dtb}/views.py (70%) delete mode 100644 tgbot/apps.py create mode 100644 tgbot/commands.py create mode 100644 tgbot/main.py delete mode 100644 tgbot/urls.py rename {tgbot/migrations => users}/__init__.py (100%) rename {tgbot => users}/admin.py (87%) create mode 100644 users/apps.py rename {tgbot => users}/forms.py (100%) rename {tgbot => users}/migrations/0001_initial.py (97%) rename {tgbot => users}/migrations/0002_alter_user_user_id.py (91%) rename {tgbot => users}/migrations/0003_rm_unused_fields.py (89%) create mode 100644 users/migrations/__init__.py rename {tgbot => users}/models.py (100%) rename {tgbot => users}/tasks.py (80%) rename {tgbot => users}/templates/admin/broadcast_message.html (100%) diff --git a/arcgis/migrations/0001_initial.py b/arcgis/migrations/0001_initial.py index a4c0312..da45575 100644 --- a/arcgis/migrations/0001_initial.py +++ b/arcgis/migrations/0001_initial.py @@ -9,7 +9,7 @@ class Migration(migrations.Migration): initial = True dependencies = [ - ('tgbot', '0001_initial'), + ('users', '0001_initial'), ] operations = [ @@ -17,7 +17,7 @@ class Migration(migrations.Migration): name='Arcgis', fields=[ ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)), - ('location', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, primary_key=True, serialize=False, to='tgbot.location')), + ('location', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, primary_key=True, serialize=False, to='users.location')), ('match_addr', models.CharField(max_length=200)), ('long_label', models.CharField(max_length=200)), ('short_label', models.CharField(max_length=128)), diff --git a/arcgis/models.py b/arcgis/models.py index a803369..6548d06 100644 --- a/arcgis/models.py +++ b/arcgis/models.py @@ -4,7 +4,7 @@ from django.db import models # Create your models here. -from tgbot.models import Location +from users.models import Location from utils.models import CreateTracker, GetOrNoneManager diff --git a/dtb/settings.py b/dtb/settings.py index 33b282c..6eb9e03 100644 --- a/dtb/settings.py +++ b/dtb/settings.py @@ -44,7 +44,7 @@ 'debug_toolbar', # local apps - 'tgbot.apps.TgbotConfig', + 'users.apps.UsersConfig', 'arcgis', ] diff --git a/dtb/urls.py b/dtb/urls.py index 4e24179..e1572a4 100644 --- a/dtb/urls.py +++ b/dtb/urls.py @@ -16,9 +16,13 @@ import debug_toolbar from django.contrib import admin from django.urls import path, include +from django.views.decorators.csrf import csrf_exempt + +from . import views urlpatterns = [ path('tgadmin/', admin.site.urls), - path('', include('tgbot.urls')), path('__debug__/', include(debug_toolbar.urls)), + path('', views.index, name="index"), + path('super_secter_webhook/', csrf_exempt(views.TelegramBotWebhookView.as_view())), ] diff --git a/tgbot/views.py b/dtb/views.py similarity index 70% rename from tgbot/views.py rename to dtb/views.py index a06d6fb..5cbc737 100644 --- a/tgbot/views.py +++ b/dtb/views.py @@ -2,33 +2,40 @@ import logging from django.views import View from django.http import JsonResponse +from telegram import Update +from dtb.celery import app from dtb.settings import DEBUG -from tgbot.dispatcher import process_telegram_event +from tgbot.dispatcher import dispatcher +from tgbot.main import bot logger = logging.getLogger(__name__) +@app.task(ignore_result=True) +def process_telegram_event(update_json): + update = Update.de_json(update_json, bot) + dispatcher.process_update(update) + + def index(request): return JsonResponse({"error": "sup hacker"}) class TelegramBotWebhookView(View): - # WARNING: if fail - Telegram webhook will be delivered again. + # WARNING: if fail - Telegram webhook will be delivered again. # Can be fixed with async celery task execution def post(self, request, *args, **kwargs): if DEBUG: process_telegram_event(json.loads(request.body)) - else: + else: # Process Telegram event in Celery worker (async) - # Don't forget to run it and & Redis (message broker for Celery)! - # Read Procfile for details - # You can run all of these services via docker-compose.yml + # Don't forget to run it and & Redis (message broker for Celery)! + # Locally, You can run all of these services via docker-compose.yml process_telegram_event.delay(json.loads(request.body)) - # TODO: there is a great trick to send action in webhook response # e.g. remove buttons, typing event return JsonResponse({"ok": "POST request processed"}) - + def get(self, request, *args, **kwargs): # for debug return JsonResponse({"ok": "Get request received! But nothing done"}) diff --git a/run_polling.py b/run_polling.py index f825107..24ffd94 100644 --- a/run_polling.py +++ b/run_polling.py @@ -3,7 +3,31 @@ os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dtb.settings') django.setup() -from tgbot.dispatcher import run_polling +from telegram import Bot +from telegram.ext import Updater + +from dtb.settings import TELEGRAM_TOKEN +from tgbot.dispatcher import setup_dispatcher + + +def run_polling(tg_token: str = TELEGRAM_TOKEN): + """ Run bot in polling mode """ + updater = Updater(tg_token, use_context=True) + + dp = updater.dispatcher + dp = setup_dispatcher(dp) + + bot_info = Bot(tg_token).get_me() + bot_link = f"https://t.me/{bot_info['username']}" + + print(f"Polling of '{bot_link}' has started") + # it is really useful to send '👋' emoji to developer + # when you run local test + # bot.send_message(text='👋', chat_id=) + + updater.start_polling() + updater.idle() + if __name__ == "__main__": run_polling() diff --git a/tgbot/apps.py b/tgbot/apps.py deleted file mode 100644 index d3ebe59..0000000 --- a/tgbot/apps.py +++ /dev/null @@ -1,5 +0,0 @@ -from django.apps import AppConfig - - -class TgbotConfig(AppConfig): - name = 'tgbot' diff --git a/tgbot/commands.py b/tgbot/commands.py new file mode 100644 index 0000000..8e9908c --- /dev/null +++ b/tgbot/commands.py @@ -0,0 +1,55 @@ +from typing import Dict + +from telegram import Bot, BotCommand + +from tgbot.main import bot + + +def set_up_commands(bot_instance: Bot) -> None: + + langs_with_commands: Dict[str, Dict[str, str]] = { + 'en': { + 'start': 'Start django bot 🚀', + 'stats': 'Statistics of bot 📊', + 'admin': 'Show admin info ℹ️', + 'ask_location': 'Send location 📍', + 'broadcast': 'Broadcast message 📨', + 'export_users': 'Export users.csv 👥', + }, + 'es': { + 'start': 'Iniciar el bot de django 🚀', + 'stats': 'Estadísticas de bot 📊', + 'admin': 'Mostrar información de administrador ℹ️', + 'ask_location': 'Enviar ubicación 📍', + 'broadcast': 'Mensaje de difusión 📨', + 'export_users': 'Exportar users.csv 👥', + }, + 'fr': { + 'start': 'Démarrer le bot Django 🚀', + 'stats': 'Statistiques du bot 📊', + 'admin': "Afficher les informations d'administrateur ℹ️", + 'ask_location': 'Envoyer emplacement 📍', + 'broadcast': 'Message de diffusion 📨', + "export_users": 'Exporter users.csv 👥', + }, + 'ru': { + 'start': 'Запустить django бота 🚀', + 'stats': 'Статистика бота 📊', + 'admin': 'Показать информацию для админов ℹ️', + 'broadcast': 'Отправить сообщение 📨', + 'ask_location': 'Отправить локацию 📍', + 'export_users': 'Экспорт users.csv 👥', + } + } + + bot_instance.delete_my_commands() + for language_code in langs_with_commands: + bot_instance.set_my_commands( + language_code=language_code, + commands=[ + BotCommand(command, description) for command, description in langs_with_commands[language_code].items() + ] + ) + + +set_up_commands(bot) diff --git a/tgbot/dispatcher.py b/tgbot/dispatcher.py index 94fbcdf..3fc1623 100644 --- a/tgbot/dispatcher.py +++ b/tgbot/dispatcher.py @@ -1,29 +1,23 @@ """ Telegram event handlers """ -import sys -import logging -from typing import Dict - -import telegram.error -from telegram import Bot, Update, BotCommand from telegram.ext import ( - Updater, Dispatcher, Filters, + Dispatcher, Filters, CommandHandler, MessageHandler, CallbackQueryHandler, ) -from dtb.celery import app # event processing in async mode -from dtb.settings import TELEGRAM_TOKEN, DEBUG +from dtb.settings import DEBUG +from tgbot.handlers.broadcast_message.manage_data import CONFIRM_DECLINE_BROADCAST +from tgbot.handlers.broadcast_message.static_text import broadcast_command +from tgbot.handlers.onboarding.manage_data import SECRET_LEVEL_BUTTON from tgbot.handlers.utils import files, error from tgbot.handlers.admin import handlers as admin_handlers from tgbot.handlers.location import handlers as location_handlers from tgbot.handlers.onboarding import handlers as onboarding_handlers from tgbot.handlers.broadcast_message import handlers as broadcast_handlers -from tgbot.handlers.onboarding.manage_data import SECRET_LEVEL_BUTTON -from tgbot.handlers.broadcast_message.manage_data import CONFIRM_DECLINE_BROADCAST -from tgbot.handlers.broadcast_message.static_text import broadcast_command +from tgbot.main import bot def setup_dispatcher(dp): @@ -76,89 +70,5 @@ def setup_dispatcher(dp): return dp -def run_polling(): - """ Run bot in polling mode """ - updater = Updater(TELEGRAM_TOKEN, use_context=True) - - dp = updater.dispatcher - dp = setup_dispatcher(dp) - - bot_info = Bot(TELEGRAM_TOKEN).get_me() - bot_link = f"https://t.me/" + bot_info["username"] - - print(f"Polling of '{bot_link}' has started") - # it is really useful to send '👋' emoji to developer - # when you run local test - # bot.send_message(text='👋', chat_id=) - - updater.start_polling() - updater.idle() - - -# Global variable - best way I found to init Telegram bot -bot = Bot(TELEGRAM_TOKEN) -try: - TELEGRAM_BOT_USERNAME = bot.get_me()["username"] -except telegram.error.Unauthorized: - logging.error(f"Invalid TELEGRAM_TOKEN.") - sys.exit(1) - - -@app.task(ignore_result=True) -def process_telegram_event(update_json): - update = Update.de_json(update_json, bot) - dispatcher.process_update(update) - - -def set_up_commands(bot_instance: Bot) -> None: - langs_with_commands: Dict[str, Dict[str, str]] = { - 'en': { - 'start': 'Start django bot 🚀', - 'stats': 'Statistics of bot 📊', - 'admin': 'Show admin info ℹ️', - 'ask_location': 'Send location 📍', - 'broadcast': 'Broadcast message 📨', - 'export_users': 'Export users.csv 👥', - }, - 'es': { - 'start': 'Iniciar el bot de django 🚀', - 'stats': 'Estadísticas de bot 📊', - 'admin': 'Mostrar información de administrador ℹ️', - 'ask_location': 'Enviar ubicación 📍', - 'broadcast': 'Mensaje de difusión 📨', - 'export_users': 'Exportar users.csv 👥', - }, - 'fr': { - 'start': 'Démarrer le bot Django 🚀', - 'stats': 'Statistiques du bot 📊', - 'admin': "Afficher les informations d'administrateur ℹ️", - 'ask_location': 'Envoyer emplacement 📍', - 'broadcast': 'Message de diffusion 📨', - "export_users": 'Exporter users.csv 👥', - }, - 'ru': { - 'start': 'Запустить django бота 🚀', - 'stats': 'Статистика бота 📊', - 'admin': 'Показать информацию для админов ℹ️', - 'broadcast': 'Отправить сообщение 📨', - 'ask_location': 'Отправить локацию 📍', - 'export_users': 'Экспорт users.csv 👥', - } - } - - bot_instance.delete_my_commands() - for language_code in langs_with_commands: - bot_instance.set_my_commands( - language_code=language_code, - commands=[ - BotCommand(command, description) for command, description in langs_with_commands[language_code].items() - ] - ) - - -# WARNING: it's better to comment the line below in DEBUG mode. -# Likely, you'll get a flood limit control error, when restarting bot too often -set_up_commands(bot) - n_workers = 0 if DEBUG else 4 dispatcher = setup_dispatcher(Dispatcher(bot, update_queue=None, workers=n_workers, use_context=True)) diff --git a/tgbot/handlers/admin/handlers.py b/tgbot/handlers/admin/handlers.py index 13f3d61..5e6fafe 100644 --- a/tgbot/handlers/admin/handlers.py +++ b/tgbot/handlers/admin/handlers.py @@ -6,7 +6,7 @@ from tgbot.handlers.admin import static_text from tgbot.handlers.admin.utils import _get_csv_from_qs_values -from tgbot.models import User +from users.models import User def admin(update: Update, context: CallbackContext) -> None: diff --git a/tgbot/handlers/broadcast_message/handlers.py b/tgbot/handlers/broadcast_message/handlers.py index 0b52706..98ca359 100644 --- a/tgbot/handlers/broadcast_message/handlers.py +++ b/tgbot/handlers/broadcast_message/handlers.py @@ -9,8 +9,8 @@ from .keyboards import keyboard_confirm_decline_broadcasting from .static_text import broadcast_command, broadcast_wrong_format, broadcast_no_access, error_with_html, \ message_is_sent, declined_message_broadcasting -from tgbot.models import User -from tgbot.tasks import broadcast_message +from users.models import User +from users.tasks import broadcast_message def broadcast_command_with_message(update: Update, context: CallbackContext): diff --git a/tgbot/handlers/broadcast_message/utils.py b/tgbot/handlers/broadcast_message/utils.py index 2a98c5b..76cc1ca 100644 --- a/tgbot/handlers/broadcast_message/utils.py +++ b/tgbot/handlers/broadcast_message/utils.py @@ -4,10 +4,10 @@ from telegram import MessageEntity, InlineKeyboardButton, InlineKeyboardMarkup from dtb.settings import TELEGRAM_TOKEN -from tgbot.models import User +from users.models import User -def _from_celery_markup_to_markup(celery_markup: Optional[List[List[Dict]]]) -> Optional[InlineKeyboardMarkup]: +def from_celery_markup_to_markup(celery_markup: Optional[List[List[Dict]]]) -> Optional[InlineKeyboardMarkup]: markup = None if celery_markup: markup = [] @@ -26,7 +26,7 @@ def _from_celery_markup_to_markup(celery_markup: Optional[List[List[Dict]]]) -> return markup -def _from_celery_entities_to_entities(celery_entities: Optional[List[Dict]] = None) -> Optional[List[MessageEntity]]: +def from_celery_entities_to_entities(celery_entities: Optional[List[Dict]] = None) -> Optional[List[MessageEntity]]: entities = None if celery_entities: entities = [ @@ -42,7 +42,7 @@ def _from_celery_entities_to_entities(celery_entities: Optional[List[Dict]] = No return entities -def _send_message( +def send_one_message( user_id: Union[str, int], text: str, parse_mode: Optional[str] = telegram.ParseMode.HTML, diff --git a/tgbot/handlers/location/handlers.py b/tgbot/handlers/location/handlers.py index 7be7518..9e73ba7 100644 --- a/tgbot/handlers/location/handlers.py +++ b/tgbot/handlers/location/handlers.py @@ -4,7 +4,7 @@ from tgbot.handlers.location.static_text import share_location, thanks_for_location from tgbot.handlers.location.keyboards import send_location_keyboard -from tgbot.models import User, Location +from users.models import User, Location def ask_for_location(update: Update, context: CallbackContext) -> None: diff --git a/tgbot/handlers/onboarding/handlers.py b/tgbot/handlers/onboarding/handlers.py index e82be4d..069807c 100644 --- a/tgbot/handlers/onboarding/handlers.py +++ b/tgbot/handlers/onboarding/handlers.py @@ -6,7 +6,7 @@ from tgbot.handlers.onboarding import static_text from tgbot.handlers.utils.info import extract_user_data_from_update -from tgbot.models import User +from users.models import User from tgbot.handlers.onboarding.keyboards import make_keyboard_for_start_command diff --git a/tgbot/handlers/utils/error.py b/tgbot/handlers/utils/error.py index f20c3bf..69a3125 100644 --- a/tgbot/handlers/utils/error.py +++ b/tgbot/handlers/utils/error.py @@ -7,7 +7,7 @@ from telegram.ext import CallbackContext from dtb.settings import TELEGRAM_LOGS_CHAT_ID -from tgbot.models import User +from users.models import User def send_stacktrace_to_tg_chat(update: Update, context: CallbackContext) -> None: diff --git a/tgbot/handlers/utils/files.py b/tgbot/handlers/utils/files.py index ecd8ccb..bd725c5 100644 --- a/tgbot/handlers/utils/files.py +++ b/tgbot/handlers/utils/files.py @@ -39,7 +39,7 @@ from telegram import Update from telegram.ext import CallbackContext -from tgbot.models import User +from users.models import User ALL_TG_FILE_TYPES = ["document", "video_note", "voice", "sticker", "audio", "video", "animation", "photo"] diff --git a/tgbot/handlers/utils/info.py b/tgbot/handlers/utils/info.py index 8bd156f..31520a6 100644 --- a/tgbot/handlers/utils/info.py +++ b/tgbot/handlers/utils/info.py @@ -4,12 +4,15 @@ import telegram from telegram import Update +from tgbot.main import bot + def send_typing_action(func: Callable): """Sends typing action while processing func command.""" @wraps(func) def command_func(update, context, *args, **kwargs): - context.bot.send_chat_action(chat_id=update.effective_message.chat_id, action=telegram.ChatAction.TYPING) + bot.send_chat_action( + chat_id=update.effective_message.chat_id, action=telegram.ChatAction.TYPING) return func(update, context, *args, **kwargs) return command_func diff --git a/tgbot/main.py b/tgbot/main.py new file mode 100644 index 0000000..ef57f3e --- /dev/null +++ b/tgbot/main.py @@ -0,0 +1,17 @@ +import logging +import sys + +import telegram +from telegram import Bot + +from dtb.settings import TELEGRAM_TOKEN + + +bot = Bot(TELEGRAM_TOKEN) +TELEGRAM_BOT_USERNAME = bot.get_me()["username"] +# Global variable - the best way I found to init Telegram bot +try: + pass +except telegram.error.Unauthorized: + logging.error("Invalid TELEGRAM_TOKEN.") + sys.exit(1) diff --git a/tgbot/urls.py b/tgbot/urls.py deleted file mode 100644 index fb28fbc..0000000 --- a/tgbot/urls.py +++ /dev/null @@ -1,10 +0,0 @@ -from django.urls import path, include -from django.views.decorators.csrf import csrf_exempt - -from . import views - -urlpatterns = [ - # TODO: make webhook more secure - path('', views.index, name="index"), - path('super_secter_webhook/', csrf_exempt(views.TelegramBotWebhookView.as_view())), -] \ No newline at end of file diff --git a/tgbot/migrations/__init__.py b/users/__init__.py similarity index 100% rename from tgbot/migrations/__init__.py rename to users/__init__.py diff --git a/tgbot/admin.py b/users/admin.py similarity index 87% rename from tgbot/admin.py rename to users/admin.py index c19432c..db53716 100644 --- a/tgbot/admin.py +++ b/users/admin.py @@ -4,12 +4,12 @@ from dtb.settings import DEBUG -from tgbot.models import Location -from tgbot.models import User -from tgbot.forms import BroadcastForm +from users.models import Location +from users.models import User +from users.forms import BroadcastForm -from tgbot.tasks import broadcast_message -from tgbot.handlers.broadcast_message.utils import _send_message +from users.tasks import broadcast_message +from tgbot.handlers.broadcast_message.utils import send_one_message @admin.register(User) @@ -32,7 +32,7 @@ def broadcast(self, request, queryset): if DEBUG: # for test / debug purposes - run in same thread for user_id in user_ids: - _send_message( + send_one_message( user_id=user_id, text=broadcast_message_text, ) diff --git a/users/apps.py b/users/apps.py new file mode 100644 index 0000000..4ce1fab --- /dev/null +++ b/users/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class UsersConfig(AppConfig): + name = 'users' diff --git a/tgbot/forms.py b/users/forms.py similarity index 100% rename from tgbot/forms.py rename to users/forms.py diff --git a/tgbot/migrations/0001_initial.py b/users/migrations/0001_initial.py similarity index 97% rename from tgbot/migrations/0001_initial.py rename to users/migrations/0001_initial.py index 6696090..1409ca1 100644 --- a/tgbot/migrations/0001_initial.py +++ b/users/migrations/0001_initial.py @@ -40,7 +40,7 @@ class Migration(migrations.Migration): ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)), ('latitude', models.FloatField()), ('longitude', models.FloatField()), - ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='tgbot.user')), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='users.user')), ], options={ 'ordering': ('-created_at',), diff --git a/tgbot/migrations/0002_alter_user_user_id.py b/users/migrations/0002_alter_user_user_id.py similarity index 91% rename from tgbot/migrations/0002_alter_user_user_id.py rename to users/migrations/0002_alter_user_user_id.py index 8834558..1e779d8 100644 --- a/tgbot/migrations/0002_alter_user_user_id.py +++ b/users/migrations/0002_alter_user_user_id.py @@ -6,7 +6,7 @@ class Migration(migrations.Migration): dependencies = [ - ('tgbot', '0001_initial'), + ('users', '0001_initial'), ] operations = [ diff --git a/tgbot/migrations/0003_rm_unused_fields.py b/users/migrations/0003_rm_unused_fields.py similarity index 89% rename from tgbot/migrations/0003_rm_unused_fields.py rename to users/migrations/0003_rm_unused_fields.py index 2a3cd13..f9d2f82 100644 --- a/tgbot/migrations/0003_rm_unused_fields.py +++ b/users/migrations/0003_rm_unused_fields.py @@ -6,7 +6,7 @@ class Migration(migrations.Migration): dependencies = [ - ('tgbot', '0002_alter_user_user_id'), + ('users', '0002_alter_user_user_id'), ] operations = [ diff --git a/users/migrations/__init__.py b/users/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tgbot/models.py b/users/models.py similarity index 100% rename from tgbot/models.py rename to users/models.py diff --git a/tgbot/tasks.py b/users/tasks.py similarity index 80% rename from tgbot/tasks.py rename to users/tasks.py index 5feb9b0..a109b6e 100644 --- a/tgbot/tasks.py +++ b/users/tasks.py @@ -9,8 +9,8 @@ from dtb.celery import app from celery.utils.log import get_task_logger -from tgbot.handlers.broadcast_message.utils import _send_message, _from_celery_entities_to_entities, \ - _from_celery_markup_to_markup +from tgbot.handlers.broadcast_message.utils import send_one_message, from_celery_entities_to_entities, \ + from_celery_markup_to_markup logger = get_task_logger(__name__) @@ -27,11 +27,11 @@ def broadcast_message( """ It's used to broadcast message to big amount of users """ logger.info(f"Going to send message: '{text}' to {len(user_ids)} users") - entities_ = _from_celery_entities_to_entities(entities) - reply_markup_ = _from_celery_markup_to_markup(reply_markup) + entities_ = from_celery_entities_to_entities(entities) + reply_markup_ = from_celery_markup_to_markup(reply_markup) for user_id in user_ids: try: - _send_message( + send_one_message( user_id=user_id, text=text, entities=entities_, diff --git a/tgbot/templates/admin/broadcast_message.html b/users/templates/admin/broadcast_message.html similarity index 100% rename from tgbot/templates/admin/broadcast_message.html rename to users/templates/admin/broadcast_message.html From f890b6245561b319e8810c37794a468e1be44dd6 Mon Sep 17 00:00:00 2001 From: Nikita Shamaev Date: Fri, 9 Sep 2022 18:24:37 +0300 Subject: [PATCH 2/3] add typing while exporting csv users --- tgbot/handlers/admin/handlers.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tgbot/handlers/admin/handlers.py b/tgbot/handlers/admin/handlers.py index 5e6fafe..511cf43 100644 --- a/tgbot/handlers/admin/handlers.py +++ b/tgbot/handlers/admin/handlers.py @@ -6,6 +6,7 @@ from tgbot.handlers.admin import static_text from tgbot.handlers.admin.utils import _get_csv_from_qs_values +from tgbot.handlers.utils.info import send_typing_action from users.models import User @@ -37,6 +38,7 @@ def stats(update: Update, context: CallbackContext) -> None: ) +@send_typing_action def export_users(update: Update, context: CallbackContext) -> None: u = User.get_user(update, context) if not u.is_admin: From ea714a3b2b395635742cbdc5ce78d73f041fb181 Mon Sep 17 00:00:00 2001 From: Nikita Shamaev Date: Mon, 12 Sep 2022 18:21:20 +0300 Subject: [PATCH 3/3] commands -> system_commands --- tgbot/{commands.py => system_commands.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename tgbot/{commands.py => system_commands.py} (100%) diff --git a/tgbot/commands.py b/tgbot/system_commands.py similarity index 100% rename from tgbot/commands.py rename to tgbot/system_commands.py