|
| 1 | +import logging |
| 2 | + |
| 3 | +from telegram import Update |
| 4 | +from telegram.ext import CommandHandler, CallbackContext |
| 5 | +from mongoengine.errors import DoesNotExist, MultipleObjectsReturned |
| 6 | + |
| 7 | +from bot.core import BotTelegramCore |
| 8 | +from db.subject import Subject |
| 9 | +from db.observer import UserObserver |
| 10 | +from db.update_message import UpdateMessage |
| 11 | + |
| 12 | + |
| 13 | +logging.basicConfig( |
| 14 | + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', |
| 15 | + level=logging.INFO) |
| 16 | + |
| 17 | +logger = logging.getLogger(__name__) |
| 18 | + |
| 19 | + |
| 20 | +def now(update: Update, context: CallbackContext): |
| 21 | + chat = update.effective_chat |
| 22 | + message = update.effective_message |
| 23 | + |
| 24 | + try: |
| 25 | + observer = UserObserver.objects.get(chat_id=f"{chat.id}") |
| 26 | + except DoesNotExist: |
| 27 | + observer = UserObserver(f"{chat.username}", |
| 28 | + f"{chat.id}").save() |
| 29 | + |
| 30 | + subject_names = context.args |
| 31 | + subjects = [] |
| 32 | + errors = [] |
| 33 | + |
| 34 | + if subject_names: |
| 35 | + for name in subject_names: |
| 36 | + try: |
| 37 | + subject = Subject.objects.get(name__icontains=name) |
| 38 | + subjects.append(subject) |
| 39 | + except DoesNotExist as e: |
| 40 | + errors.append(f"{name}: {e}") |
| 41 | + except MultipleObjectsReturned as e: |
| 42 | + errors.append(f"{e}\n" |
| 43 | + f"The value {name} returned more than " |
| 44 | + f"one subject. Please be more specific!") |
| 45 | + else: |
| 46 | + subjects = Subject.objects.all() |
| 47 | + |
| 48 | + update_messages = [] |
| 49 | + |
| 50 | + for subject in subjects: |
| 51 | + update_messages.append(UpdateMessage.get_last_by_subject(subject)) |
| 52 | + |
| 53 | + if errors: |
| 54 | + error_message = "\n".join(errors) |
| 55 | + message.reply_text(error_message) |
| 56 | + |
| 57 | + for msg in update_messages: |
| 58 | + observer.notify(msg) |
| 59 | + |
| 60 | + |
| 61 | +def config_handlers(instance: BotTelegramCore): |
| 62 | + logger.info('Setting subject commands...') |
| 63 | + |
| 64 | + instance.add_handler(CommandHandler("now", now)) |
0 commit comments