Exemple #1
0
 def get_users_chats_with_bot(self, user_id):
     # type: (int) -> dict
     chats_available = {}
     user, created = TtbUser.update_or_create_by_tt_user(None, user_id)
     if user:
         if not TtbDjChatAvailable.objects.filter(
                 user=user, subscriber__enabled=True).exists():
             self.recreate_cache(user_id)
         for chat_available in TtbDjChatAvailable.objects.filter(
                 user=user, subscriber__enabled=True):
             if isinstance(chat_available, TtbDjChatAvailable):
                 chat = self.deserialize_open_api_object(
                     bytes(chat_available.chat, encoding='utf-8'), 'Chat')
                 if isinstance(chat, Chat):
                     chat_ext = ChatExt(
                         chat,
                         self.get_dialog_name(self.title,
                                              chat=chat,
                                              user_id=user.user_id),
                         json.loads(chat_available.permissions))
                     chats_available[chat.chat_id] = chat_ext
                     self.lgz.debug(
                         'chat => chat_id=%(id)s added into list available chats from cache'
                         % {'id': chat.chat_id})
     else:
         self.lgz.debug(
             f"it can't be, but it happened... user_id={user_id}")
     return chats_available
Exemple #2
0
    def cmd_handler_view_selected_chat_info(self, update):
        # type: (UpdateCmn) -> bool
        if not (update.chat_type in [ChatType.DIALOG]):
            return False

        if not (update.chat_id or update.user_id):
            return False

        if not update.this_cmd_response:  # Обрабатываем только саму команду
            if update.cmd_args:
                is_close = update.cmd_args.get('is_close')
                if is_close:
                    return True
                chat_id = update.cmd_args.get('chat_id')
                if chat_id is None:
                    parts = update.cmd_args.get('c_parts') or []
                    if parts and parts[0]:
                        chat_id = parts[0][0]
                if chat_id:
                    chat_ext = ChatExt(self.chats.get_chat(chat_id),
                                       self.title)
                    chat_type = update.cmd_args.get('type')
                    self.send_notification(
                        update,
                        f'chat_type: {chat_type}; chat_id={chat_id}; подключен/attached? {self.chat_is_attached(chat_ext.chat_id)}; {chat_ext.chat_name_ext}'
                    )
        return False
Exemple #3
0
    def change_subscriber(self,
                          update,
                          enabled,
                          chat_ext=None,
                          api_user=None,
                          recreate_cache=True):
        # type: (UpdateCmn or None, bool or None, ChatExt, User, bool) -> TtbDjSubscriber
        subscriber = None
        defaults = {'updated': now()}
        if enabled is not None:
            defaults['enabled'] = enabled
        if update:
            if not api_user:
                api_user = update.user
                if api_user and not hasattr(api_user, 'disable'):
                    api_user.disable = True
            try:
                chat_ext = chat_ext or ChatExt(
                    self.chats.get_chat(update.chat_id),
                    self.get_dialog_name(self.title, user=api_user))
            except ApiException:
                chat_ext = None

        if chat_ext:
            defaults['chat_name'] = chat_ext.chat_name
            defaults['chat_type'] = chat_ext.chat.type
            defaults['participants_count'] = chat_ext.chat.participants_count
            subscriber, created = TtbDjSubscriber.objects.update_or_create(
                chat_id=chat_ext.chat_id, defaults=defaults)

        db_user = None
        if api_user:
            if api_user.is_bot:
                api_user.disable = True
            db_user, created = TtbUser.update_or_create_by_tt_user(api_user)
            api_user.disable = not db_user.enabled
            if db_user:
                if subscriber:
                    db_user.subscriber.add(subscriber)
                else:
                    subscriber, created = TtbDjSubscriber.objects.update_or_create(
                        chat_id=update.chat_id, defaults=defaults)
                    db_user.subscriber.remove(subscriber)

        if isinstance(subscriber, TtbDjSubscriber) and chat_ext:
            if subscriber.language is None:
                if chat_ext.lang:
                    subscriber.language = chat_ext.lang
                    subscriber.save()
                elif isinstance(db_user, TtbUser) and db_user.language:
                    subscriber.language = db_user.language
                    subscriber.save()

        if api_user:
            if recreate_cache and api_user.user_id:
                self.recreate_cache(api_user.user_id)

        return subscriber
Exemple #4
0
 def handle_bot_added_to_chat_update(self, update):
     # type: (BotAddedToChatUpdate) -> bool
     update = UpdateCmn(update, self)
     chat = self.chats.get_chat(update.chat_id)
     if isinstance(chat, Chat):
         admins_chats = self.admins_contacts.get('chats') or []
         if update.chat_id not in admins_chats:
             chat_ext = self.chat_is_available(chat, update.user.user_id)
             if chat_ext and self.chat_is_allowed_for_add(
                     chat_ext, update.user.user_id):
                 return bool(self.change_subscriber(update, True))
             res = self.chats.leave_chat(update.chat_id)
             if isinstance(
                     res,
                     SimpleQueryResult) and not res.success and isinstance(
                         update.user, User):
                 self.send_admin_message(
                     f'Error leaving chat {chat.chat_id} ({chat.title}/{chat.link}): {res.message}\nTry adding user {update.user.user_id} - {update.user.name}(@{update.user.username})'
                 )
             elif isinstance(
                     res, SimpleQueryResult) and res.success and isinstance(
                         update.user, User):
                 if not chat_ext:
                     chat_ext = ChatExt(chat, self.title)
                 try:
                     # noinspection PyTypeChecker
                     self.send_message(NewMessageBody(
                         _('The bot %(bot_name)s cannot be added to %(chat_name)s, because it cannot work correctly under the current environment (rights, chat type, etc.).'
                           ) % {
                               'bot_name':
                               f'<{self.name} (@{self.username})>',
                               'chat_name': chat_ext.chat_name_ext,
                           }),
                                       user_id=update.user.user_id)
                 except (ApiException, ValueError):
                     pass
     return False