def main_menu_buttons(self): # type: () -> [] buttons = [ [ CallbackButtonCmd(_('About bot'), 'start', intent=Intent.POSITIVE) ], # [CallbackButton(_('All chat bots'), '/list_all_chats', Intent.POSITIVE)], [ LinkButton(_('Message to the developer'), 'mailto:[email protected]') ], [ LinkButton(_('Chat to discuss the bot'), 'https://tt.me/FileToAudioChat') ], ] if len(self.languages_dict) > 1: buttons.append([ CallbackButtonCmd('Изменить язык / set language', 'set_language', intent=Intent.DEFAULT) ]) return buttons
def main_menu_buttons(self): # type: () -> [] self.lgz.warning( 'The default main menu buttons is used. Maybe is error?') buttons = [ [ CallbackButtonCmd(_('About bot'), 'start', intent=Intent.POSITIVE, bot_username=self.username) ], [ CallbackButtonCmd(_('All chat bots'), 'list_all_chats', intent=Intent.POSITIVE, bot_username=self.username) ], [ CallbackButtonCmd('Доступные чаты | Available chats', 'view_chats_available', intent=Intent.POSITIVE, bot_username=self.username) ], [ CallbackButtonCmd( 'Управление подписками | Managing subscriptions', 'subscriptions_mng', intent=Intent.POSITIVE, bot_username=self.username) ], [ CallbackButtonCmd('Подключенные чаты | Attached chats', 'view_chats_attached', intent=Intent.POSITIVE, bot_username=self.username) ], [ CallbackButtonCmd('Тест кнопок | Buttons test', 'view_buttons_test', intent=Intent.POSITIVE, bot_username=self.username) ], ] if len(self.languages_dict) > 1: buttons.append([ CallbackButtonCmd('Изменить язык / set language', 'set_language', intent=Intent.DEFAULT, bot_username=self.username) ]) return buttons
def cmd_recreate_cache(self, update, user_id=None, dialog_only=True): # type: (UpdateCmn, int, bool) -> bool if dialog_only and not (update.chat_type in [ChatType.DIALOG]): return False if not update.chat_id: return False te = self.recreate_cache(user_id) if isinstance(te, timedelta): msg_text = '@%s: ' % self.username + _( 'Cache recreated.') + ' (%s)' % te else: msg_text = ' (%s)' % te if te else '' msg_text = '@%s: ' % _('Error recreate cache.%s') % msg_text return bool( self.msg.send_message(NewMessageBody(msg_text, link=update.link), chat_id=update.chat_id))
def cmd_handler_subscriptions_mng(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 not update.cmd_args: return bool( self.view_buttons_for_chats_available( _('Select chat to attach/detach your subscription:'), 'subscriptions_mng', update.user_id, update.chat_id, link=update.link, update=update.update_current)) else: 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: update.chat_id = chat_id self.switch_chat_available( False if self.chat_is_attached(chat_id) else True, chat_id) update.cmd_args = None return self.cmd_handler_subscriptions_mng(update) else: # Обработка текстового ответа self.send_message( NewMessageBody(_('Text response is not provided'), link=update.link))
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
def recreate_cache(self, user_id=None): # type: (int) -> timedelta or str tb = now() all_bot_relation = self.get_all_chats_with_bot_admin(True) all_chats_members = all_bot_relation['ChatsMembers'] all_members = all_bot_relation['Members'] all_chats = all_bot_relation['Chats'] proc_user_list = list(all_members.keys()) proc_chat_list = list(all_chats.keys()) if user_id: if user_id not in proc_user_list: return _('Current user (%s) not found.') % user_id api_user = all_members[user_id] TtbUser.update_or_create_by_tt_user(api_user) qs_db_user = TtbUser.objects.filter(user_id=user_id) else: # Синхронизация пользователей proc_user_list = [] c_u = 0 for api_user in all_members.values(): if isinstance(api_user, ChatMember): pass c_u += 1 if api_user.is_bot: api_user.disable = True db_user, created = TtbUser.update_or_create_by_tt_user( api_user) u_i = f'{"bot " if api_user.is_bot else ""}name={api_user.name}; user_id={api_user.user_id}; enabled={db_user.enabled}' if api_user.username: u_i += f'; username={api_user.username}' # if api_user.description: # u_i += f' ({api_user.description[:50]})' self.lgz.debug( f'User synchronization +++++++++++++++> ({c_u} of {len(all_members)}) - {u_i}' ) proc_user_list.append(api_user.user_id) duc = TtbUser.objects.filter(enabled=True).exclude( user_id__in=proc_user_list).update(enabled=False, updated=now()) self.lgz.debug(f'Other users disabled: {duc}') qs_db_user = TtbUser.objects.filter(enabled=True) cnt_u = len(qs_db_user) c_u = 0 for db_user in qs_db_user: c_u += 1 self.lgz.debug( f'+++++++++++++++> ({c_u} of {len(qs_db_user)}) - {db_user}') chat_ext_dict = all_chats_members.get(db_user.user_id) api_user = all_members.get(db_user.user_id) if chat_ext_dict and api_user: cnt_c = len(chat_ext_dict) c_c = 0 for chat_ext in chat_ext_dict.values(): c_c += 1 self.lgz.debug( 'Executing %.4f%% (user %d of %d) -> %.4f%% (chat %d of %d)' % (c_u / cnt_u * 100, c_u, cnt_u, c_c / cnt_c * 100, c_c, cnt_c)) self.change_chat_available(chat_ext, db_user, api_user) if not self.chat_is_allowed( chat_ext, db_user.user_id ) and chat_ext.chat_id in proc_chat_list: proc_chat_list.remove(chat_ext.chat_id) elif not chat_ext_dict: self.lgz.debug( f"do not available chats for user_id={db_user.user_id}") TtbDjChatAvailable.objects.filter(user=db_user).delete() TtbUser.objects.filter(enabled=True, user_id=db_user.user_id).update( enabled=False, updated=now()) # Удаление строк кэша по неактивным подписчикам и пользователям if user_id: TtbDjChatAvailable.objects.filter(user__user_id=user_id).exclude( subscriber__chat_id__in=proc_chat_list).delete() TtbDjChatAvailable.objects.filter( user__user_id=user_id, subscriber__enabled=False).delete() else: dcc = TtbDjSubscriber.objects.filter(enabled=True).exclude( chat_id__in=proc_chat_list).update(enabled=False, updated=now()) self.lgz.debug(f'Other chats disabled: {dcc}') TtbDjChatAvailable.objects.filter( subscriber__enabled=False).delete() TtbDjChatAvailable.objects.filter(user__enabled=False).delete() e_t = now() - tb self.lgz.debug(f'100% executed in {e_t}') return e_t
def about(self): # type: () -> str return _( 'This bot creates, if possible, messages of type "audio" based on new files attached to your chats.\n' 'You need to add the bot to it as an administrator with the "Read all messages" and "Write, edit and delete messages" permissions.\n' 'To open the menu, type /menu.')