async def debug_logger( message: types.Message, exception: Exception = None, descriptions: list = 'error', ): dispatcher = Dispatcher.get_current() bot = dispatcher.bot url = '' if hasattr(message, 'chat') and message.chat.type != "private": # ~ url = message.url url = message.link('link', as_html = False) text = list() text.append( u" ".join([ u" ".join([escape_md("#" + d) for d in descriptions]), url, ]) ) text.append('') text.append('```') text.append(json.dumps(message.to_python(), indent=2)) text.append('```') text.append('') text.append('```') text.append(json.dumps(repr(exception), indent=2)) text.append('```') try: await bot.send_message( chat_id = bot.users['special']['debug'], text = '\n'.join(text), disable_notification = True, parse_mode = "MarkdownV2", ) except KeyError: logging.debug(key_error)
async def message_throttled(self, message: types.Message, throttled: Throttled): """ Notify user only on first exceed and notify about unlocking only on last exceed :param message: :param throttled: """ handler = current_handler.get() dispatcher = Dispatcher.get_current() if handler: key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}") else: key = f"{self.prefix}_message" # Calculate how many time is left till the block ends delta = throttled.rate - throttled.delta # Prevent flooding if throttled.exceeded_count <= 10: await message.reply( '�е по�пішай, не в�тигаю читати 😔') # Sleep. await asyncio.sleep(delta) # Check lock status thr = await dispatcher.check_key(key) # If current message is not last with current key - do not send message if thr.exceeded_count == throttled.exceeded_count: await message.reply('В�е, дочитав')
async def on_process_message(self, message: types.Message, data: dict): """ This handler is called when dispatcher receives a message :param message: :param data: """ # Get current handler handler = current_handler.get() # Get dispatcher from context dispatcher = Dispatcher.get_current() # If handler was configured, get rate limit and key from handler if handler: limit = getattr(handler, "throttling_rate_limit", self.rate_limit) key = getattr(handler, "throttling_key", f"{self.prefix}_{handler.__name__}") else: limit = self.rate_limit key = f"{self.prefix}_message" # Use Dispatcher.throttle method. try: await dispatcher.throttle(key, rate=limit) except Throttled as t: # Execute action await self.message_throttled(message, t) # Cancel current handler raise CancelHandler()
async def show(cls, data: Union[types.CallbackQuery, types.Message] = None, chat: str = None, user: str = None, dispatcher: Dispatcher = None): dispatcher = dispatcher or cls.dispatcher if dispatcher is None: raise Exception("dispatcher not set") if data is not None: if isinstance(data, types.CallbackQuery): await data.answer(cache_time=0) chat, user = data.message.chat.id, data.from_user.id if cls.save_data: name = await dispatcher.storage.get_state(chat=chat, user=user) await cls.save_callback_data(call=data, name=name) elif isinstance(data, types.Message): chat, user = data.chat.id, data.from_user.id await cls.default_text_save(message=data, state=Dispatcher.get_current().current_state()) else: raise Exception("UNKNOWN") elif chat is None or user is None: raise Exception("need chat and/or user") await dispatcher.storage.set_state(chat=chat, user=user, state=cls.state) keyboard = await cls.build_buttons() await dispatcher.bot.send_message( chat_id=chat, text=cls.text(chat=chat, user=user, dispatcher=dispatcher) if callable(cls.text) else cls.text, reply_markup=keyboard )
async def update_logger( update: types.Update, descriptions: list = ['none'], ): dispatcher = Dispatcher.get_current() bot = dispatcher.bot url = '' if hasattr(update, 'chat') and update.chat.type != "private": # ~ url = update.url url = update.link('link', as_html=False) text = list() text.append(u" ".join([ u" ".join([ "\#" + d.replace('_', '\_').replace('.', '\.').replace('*', '\*') for d in descriptions ]), url, ])) text.append('```') text.append(json.dumps(update.to_python(), indent=2)) text.append('```') await bot.send_message( bot.users['special']['log'], '\n'.join(text), disable_notification=True, parse_mode="MarkdownV2", )
async def message_throttled(self, message: types.Message, throttled: Throttled): """ Notify user only on first exceed and notify about unlocking only on last exceed :param message: :param throttled: """ handler = current_handler.get() dispatcher = Dispatcher.get_current() if handler: key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}") else: key = f"{self.prefix}_message" # Calculate how many time is left till the block ends delta = throttled.rate - throttled.delta # Prevent flooding if throttled.exceeded_count <= 2: await message.reply('❗️Слишком много запросов. ' 'Подождите еще несколько секунд перед отправкой следующего сообщения.' '\nВ целях предотвращения флуда, бот перестанет отвечать на ваши сообщения ' 'на некоторое время.') # Sleep. await asyncio.sleep(delta) # Check lock status thr = await dispatcher.check_key(key) # If current message is not last with current key - do not send message if thr.exceeded_count == throttled.exceeded_count: await message.reply('Unlocked.')
async def execute(cls, c: CallbackQuery, state=None, **kwargs): data = c.data.split() user = int(data[-2]) second_user = int(data[-1]) action_type = data[1] player = Player(tg_id=user) second_player = Player( tg_id=second_user) if user != second_user else player dp = Dispatcher.get_current() for u in {user, second_user}: state = await dp.current_state(chat=u, user=u).get_state() if state == ActionForm.busy.state: await c.answer("%s занят." % player.name, show_alert=True) return dt = dp.actions_storage action = dt.get(c.message.chat.id, user, 'action') if not action: Action = ActionsFactory.get(action_type) action = Action(5, player, second_player, c.message.chat.id) await action.complete() try: await c.message.delete() except: pass await Game.process_accepted_action(action, dp, c.message.chat.id, player, second_player)
async def message_throttled(self, message: types.Message, throttled: Throttled): """ Notify user only on first exceed and notify about unlocking only on last exceed """ handler = current_handler.get() dispatcher = Dispatcher.get_current() if handler: key = getattr(handler, THROTTLING_KEY, f"{self.prefix}_{handler.__name__}") else: key = f"{self.prefix}_message" delta = throttled.rate - throttled.delta if throttled.exceeded_count <= 2: await message.reply('Too many requests! Don`t flood, please!') await asyncio.sleep(delta) thr = await dispatcher.check_key(key) if thr.exceeded_count == throttled.exceeded_count: await message.reply('Unlocked. You can continue!')
async def message_throttled(self, message: types.Message, throttled: Throttled): handler = current_handler.get() dispatcher = Dispatcher.get_current() if handler: key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}") else: key = f"{self.prefix}_message" # Calculate how many time is left till the block ends delta = throttled.rate - throttled.delta # # Prevent flooding if throttled.exceeded_count <= 2: await bot.send_message( chat_id=message.chat.id, text= f'Команда {message.text} работает 1 раз в {throttled.rate} секунд' ) await message.delete() # Sleep. await asyncio.sleep(delta) # # Check lock status thr = await dispatcher.check_key(key) # If current message is not last with current key - do not send message if thr.exceeded_count == throttled.exceeded_count: await message.reply('Unlocked.')
def __init__( self, dispatcher: Optional[Dispatcher] = None, routers: Optional[Union[List[BaseStateRouter], Set[BaseStateRouter]]] = None, ) -> None: super().__init__(routers=routers) self.dispatcher = dispatcher or Dispatcher.get_current()
async def exception_logger( exception: Exception = None, descriptions: list = 'error', ): dispatcher = Dispatcher.get_current() bot = dispatcher.bot text = list() text.append( u" ".join([ u" ".join([escape_md("#" + d) for d in descriptions]), ]) ) text.append('') text.append('```') text.append(json.dumps(repr(exception), indent=2)) text.append('```') try: await bot.send_message( chat_id = bot.users['special']['debug'], text = '\n'.join(text), disable_notification = True, parse_mode = "MarkdownV2", ) except KeyError: logging.debug(key_error)
async def message_throttled(self, message: types.Message, throttled: Throttled): """ Notify user only on first exceed and notify about unlocking only on last exceed :param message: :param throttled: """ handler = current_handler.get() dispatcher = Dispatcher.get_current() if handler: key = getattr(handler, "throttling_key", f"{self.prefix}_{handler.__name__}") else: key = f"{self.prefix}_message" # Calculate how many time is left till the block ends delta = throttled.rate - throttled.delta # Prevent flooding if throttled.exceeded_count <= 2: await message.reply("Too many requests! ") # Sleep. await asyncio.sleep(delta) # Check lock status thr = await dispatcher.check_key(key) # If current message is not last with current key - do not send message if thr.exceeded_count == throttled.exceeded_count: await message.reply("Unlocked.")
async def execute_action(cls, m: Message): try: await m.delete() except: pass if 'xbet' in m.text.lower(): await m.answer('Идите нахуй со своим 1xbet, забаню щас блять') return action_split = m.text.split('|', maxsplit=1) description = action_split[0].split(maxsplit=1)[1].strip() action_type = 'custom' if 'type:' in description: action_type = description.split('type:')[1].split()[0] description = description.replace(f'type:{action_type} ', '') user = m.from_user second_user = m.reply_to_message.from_user player = Player(tg_id=user.id) second_player = Player(tg_id=second_user.id) Action = ActionsFactory.get(action_type) action = Action(cls.needs_satiety_level, player, second_player, m.chat.id) delay = random.randint(config.SEX_DELAY_INTERVAL[0], config.SEX_DELAY_INTERVAL[1]) custom_data = action_split[1].strip() if len(action_split) > 1 else "" await action.complete(custom_data=custom_data, delay=delay) dp = Dispatcher.get_current() if user.id == second_user.id or not second_player.alive: await Game.process_accepted_action(action, dp, m.chat.id, player, second_player) return dt = dp.actions_storage dt.update(m.chat.id, m.from_user.id, {'action': action}) kb = InlineKeyboardMarkup() accept = InlineKeyboardButton( 'Го', callback_data= f'action {action_type} accept {player.tg_id} {second_player.tg_id}' ) decline = InlineKeyboardButton( 'Нее', callback_data= f'action {action_type} decline {player.tg_id} {second_player.tg_id}' ) kb.add(accept, decline) await m.answer('%s, %s предлагает %s' % (second_user.get_mention( second_player.name), user.get_mention(player.name), description), reply_markup=kb)
async def get_current_state() -> Optional[State]: """Search current State(...) in all StatesGroups.""" try: state_ctx = Dispatcher.get_current().current_state() state_name = await state_ctx.get_state() state = _get_state_by_name(state_name) return state except AttributeError: return None
async def on_process_message(self, message: types.Message, _: dict): if await is_admin.IsAdmin(False).check(message): dispatcher = Dispatcher.get_current() limit = self.rate_limit key = f"{self.prefix}_message" try: await dispatcher.throttle(key, rate=limit) except Throttled as t: await self.message_throttled(message, t) raise CancelHandler()
def register_all(dp = None): if dp is None: dp = Dispatcher.get_current() handlers_module = importlib.import_module('.handlers_bot', package='bot.handlers') for handler in handlers_module.__all__: logger.debug(f"loading {handler}") handler = getattr(handlers_module, handler) handler_ = handler(dp) handler_.register()
def __init__(self, storage: BaseStorage, dispatcher: Optional[Dispatcher] = None) -> None: self.dispatcher = dispatcher or Dispatcher.get_current() self.storage = storage if self.dispatcher is None: bot = None else: bot = self.dispatcher.bot self.bot = bot
async def welcome(message): bot = Dispatcher.get_current().bot admin = message.from_user.first_name count = await bot.get_chat_members_count(message.chat.id) if message.chat.type in ['group', 'supergroup']: admin = [ member.user for member in await bot.get_chat_administrators(message.chat.id) if member.status == 'creator' ][0].first_name or u"@admin" return random_texts.welcome(message, count, admin)
def __getattribute__(self, name: str): attr = super().__getattribute__(name) if name == "bot" and attr is None: bot = Bot.get_current() super().__setattr__(name, bot) return bot if name == "dispatcher" and attr is None: dispatcher = Dispatcher.get_current() super().__setattr__(name, dispatcher) return dispatcher return attr
async def edit_name(callback: CallbackQuery, category, cat_name, item_id, new): if str(callback.message.chat.id) in admins: await callback.message.edit_text(text="Введите новое имя:") await EditState.name.set() state = Dispatcher.get_current().current_state() await state.update_data(category=category, cat_name=cat_name, item_id=item_id, new=new) else: await callback.message.edit_text(text="Недостаточно прав")
async def message_throttled(self, message: types.Message, throttled: Throttled): handler = current_handler.get() dispatcher = Dispatcher.get_current() if handler: key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}") else: key = f"{self.prefix}_message" delta = throttled.rate - throttled.delta if throttled.exceeded_count <= 2: await message.reply('Too many requests! ') await asyncio.sleep(delta) thr = await dispatcher.check_key(key) if thr.exceeded_count == throttled.exceeded_count: await message.reply('Unlocked.')
async def on_process_message(self, message: types.Message, data: dict): handler = current_handler.get() dispatcher = Dispatcher.get_current() if handler: limit = getattr(handler, "throttling_rate_limit", self.rate_limit) key = getattr(handler, "throttling_key", f"{self.prefix}_{handler.__name__}") else: limit = self.rate_limit key = f"{self.prefix}_message" try: await dispatcher.throttle(key, rate=limit) except Throttled as t: await self.message_throttled(message, t) raise CancelHandler()
async def pre_execute(cls, m: Message): if cls.needs_reply_auth and not m.reply_to_message: try: await m.answer('Команда должна быть реплаем') except: pass raise CancelHandler users_to_auth = [] if cls.needs_auth: users_to_auth.append(m.from_user) if cls.needs_reply_auth and m.reply_to_message: users_to_auth.append(m.reply_to_message.from_user) dp = Dispatcher.get_current() for user in users_to_auth: player = Player(tg_id=user.id) mention_url = f"https://t.me/{user.username}" if user.username else user.url mention = f'<a href="{mention_url}">{player.name}</a>' if not player.exists: try: await m.answer('%s не играет.' % mention) except: pass raise CancelHandler if m.chat.type in ['group', 'supergroup' ] and m.chat.id not in player.chats: await player.join_chat(m.chat.id) if not player.alive and not cls.dead_allowed: try: await m.answer('%s мёртв.' % mention) except: pass raise CancelHandler if player.alive and player.satiety is not None and player.satiety < cls.needs_satiety_level: await m.answer( '%s слишком голоден! Нужный уровень сытости - %s, уровень сытости - %s.' % (mention, cls.needs_satiety_level, round(player.satiety)) ) raise CancelHandler state = await dp.current_state(chat=user.id, user=user.id).get_state() if state == ActionForm.busy.state and not cls.ignore_busy: await m.answer("%s занят." % mention, disable_web_page_preview=True) raise CancelHandler
async def next(cls, data: Union[types.CallbackQuery, types.Message] = None): state = Dispatcher.get_current().current_state() state_name = await state.get_state() cur_state = cls.get_window(state_name) try: next_step = cls.__subclasses__().index(cur_state) + 1 except ValueError: next_step = 0 try: next_state = cls.__subclasses__()[next_step] except IndexError: return await next_state.show(chat=state.chat, user=state.user)
async def message_throttled(self, query: CallbackQuery, throttled: Throttled): handler = current_handler.get() dispatcher = Dispatcher.get_current() if handler: key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}") else: key = f"{self.prefix}_message" delta = throttled.rate - throttled.delta if throttled.exceeded_count <= 25: await query.answer('Слишком быстрые клики!') thr = await dispatcher.check_key(key)
async def message_filter(msg: atp.Message): _ = Dispatcher.get_current().get("i18n").gettext if msg.via_bot and msg.via_bot.id == msg.bot.id: await send_auto_delete(msg, _("I ignore my messages")) elif msg.audio and not msg.audio.title: await send_auto_delete(msg, _("I can't save audio without title field")) elif msg.video and msg.video.mime_type != "video/mp4": await send_auto_delete(msg, _("Video mime type not valid")) else: file = get_file(msg) return dict( file_id=file.file_id if file else "", file_uid=file.file_unique_id if file else "", ) return False
async def _throttle(self, message: Message, data: dict[str]): handler = current_handler.get() dispatcher = Dispatcher.get_current() if handler: limit = getattr(handler, 'throttling_rate_limit', self.rate_limit) key = getattr(handler, 'throttling_key', f'{self.prefix}_{handler.__name__}') else: limit = self.rate_limit key = f'{self.prefix}_message' try: await dispatcher.throttle(key, rate=limit) except Throttled as throttled: if throttled.exceeded_count <= 2: await message.reply(_('Too many requests!')) raise CancelHandler()
async def message_throttled(self, message: types.Message, throttled: Throttled): handler = current_handler.get() dispatcher = Dispatcher.get_current() if handler: key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}") else: key = f"{self.prefix}_message" delta = throttled.rate - throttled.delta if throttled.exceeded_count == 2: await message.reply('Слишком часто! Давай не так быстро') elif throttled.exceeded_count == 2: await message.reply('Все. Больше не отвечу, пока не пройдет 10 сек') await asyncio.sleep(delta) thr = await dispatcher.check_key(key) if thr.exceeded_count == throttled.exceeded_count: await message.reply('Unlocked.')
async def message_throttled(self, message: types.Message, throttled: Throttled): handler = current_handler.get() dispatcher = Dispatcher.get_current() if handler: key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}") else: key = f"{self.prefix}_message" delta = throttled.rate - throttled.delta if throttled.exceeded_count <= 2: await message.reply('Занадто багато запитів. Зачекайте..') await asyncio.sleep(delta) thr = await dispatcher.check_key(key) if thr.exceeded_count == throttled.exceeded_count: await message.reply('Розблоковано.')
async def message_throttled(self, message: types.Message, throttled: Throttled): handler = current_handler.get() dispatcher = Dispatcher.get_current() if handler: key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}") else: key = f"{self.prefix}_message" delta = throttled.rate - throttled.delta if throttled.exceeded_count <= 2: await message.reply('Слишком много запросов! ') await asyncio.sleep(delta) thr = await dispatcher.check_key(key) if thr.exceeded_count == throttled.exceeded_count: await message.reply(f'Заблокировано на {throttled.rate}')