def on_save_handler(model_class, instance, created): if created: if instance.referral: Dispatcher.get_instance().bot.send_message( chat_id=instance.referral.chat_id, text= f'По вашей ссылке зарегистрировался новый партнёр: {instance}')
def on_save_handler(model_class, instance, created): if created: if instance.referral: Dispatcher.get_instance().bot.send_message( chat_id=instance.referral.chat_id, text=f'Your link has registered a new partner: {instance}' )
def on_save_handler(model_class, instance, created): if instance.user: user = instance.user user.deposit += instance.amount user.save() Payments.update_levels_deposit(user, instance.amount) Dispatcher.get_instance().bot.send_message( chat_id=user.chat_id, text=f'Ваш депозит был увеличен на {instance.amount} ETH.')
def on_save_handler(model_class, instance, created): if instance.user: user = instance.user user.deposit += instance.amount user.save() Payments.update_levels_deposit(user, instance.amount) Dispatcher.get_instance().bot.send_message( chat_id=user.chat_id, text=f'Your deposit has been increased by {instance.amount} ETH.' )
def on_save_handler(model_class, instance, created): user = instance.user if created: user.balance -= instance.amount user.save() elif instance.approved: Dispatcher.get_instance().bot.send_message( chat_id=user.chat_id, text=f'Ваш перевод на сумму {instance.amount} ETH был подтвержден. ' f'Средства будут переведены в кратчайшие сроки.')
def on_save_handler(model_class, instance, created): user = instance.user if created: user.balance -= instance.amount user.save() elif instance.approved: Dispatcher.get_instance().bot.send_message( chat_id=user.chat_id, text=f'Your transfer to {Instance.amount} ETH was confirmed. ' f'Funds will be transferred as soon as possible..' )
def on_save_handler(model_class, instance, created): from_user = instance.from_user to_user = instance.to_user amount = instance.amount from_user.balance -= amount from_user.save() to_user.balance += amount to_user.save() Dispatcher.get_instance().bot.send_message( chat_id=to_user.chat_id, text=lang.balance_transferred_from_user(amount, from_user), )
def _data_by_type(cls) -> Dict: dispatcher = Dispatcher.get_instance() if cls.data_type() == DataType.USER: data = dispatcher.user_data elif cls.data_type() == DataType.CHAT: data = dispatcher.chat_data elif cls.data_type() == DataType.BOT: data = dispatcher.bot_data return data
def __call__(self, parser, namespace, values, option_string = None): bot_data = BotData.from_context(self._context) bot = Dispatcher.get_instance().bot text = [] for var_id in bot_data.pending_forms: user_data = UserData.by_id(var_id) text.append(f'{var_id} ({user_data.mention()})') text = 'Список анкет: ' + ', '.join(text) bot.sendMessage(self._update.effective_chat.id, text)
def append(self, value): """Append item to list.""" bot = Dispatcher.get_instance().bot try: var_id = bot.getChat(value).id except TelegramError as exc: raise IncorrectIdError(f'Can\'t get chat: {value}') from exc if var_id not in self._list: logger.info(f'New id added to \'{self._name}\' list: {var_id}') self._list.append(var_id)
def command_delete_confirm(update, context): """ Handle delete confirmation button. Delete the command and return user to commands list. """ command = context.chat_data['cmd_instance'] dp = Dispatcher.get_instance() handlers = dp.handlers[settings.DEFAULT_HANDLER_GROUP] for h in handlers: if getattr(h, 'id', None) == command.id: dp.remove_handler(h, settings.DEFAULT_HANDLER_GROUP) command.delete() update.message.reply_text('The command has disappeared...') return commands.commands_list(update, context)
def loaddata(job_queue): dispatch = Dispatcher.get_instance() try: with open(CHAT_DATA_FILE, "rb") as f: chat_data = pickle.load(f) dispatch.chat_data = chat_data except FileNotFoundError: logging.warning("chat_data file not found") try: with open(USER_DATA_FILE, "rb") as f: user_data = pickle.load(f) dispatch.user_data = user_data except FileNotFoundError: logging.warning("user_data file not found") try: load_jobs(job_queue) except FileNotFoundError: logging.warning("job_data file not found") job_queue.run_repeating(save_data, interval=DEFAULT_CHECK_TIME)
def command_add_complete(update, context): """ Callback function to handle /complete command to finish command adding. """ command = context.chat_data['cmd_instance_edit'] if command.message_set.count() == 0: update.message.reply_text( 'Please, add at least one message before saving the command.', ) return states.SEND_MESSAGE command.status = CommandStatus.DONE command.save() del context.chat_data['cmd_instance_edit'] handler = get_command_handler(command) dp = Dispatcher.get_instance() dp.add_handler(handler) update.message.reply_text( 'Congratulations! The command was added to your bot.', ) return commands.commands_list(update, context)
def __call__(self, parser, namespace, values, option_string = None): user_data = UserData.by_id(int(values[0])) bot_data = BotData.from_context(self._context) bot = Dispatcher.get_instance().bot if not bot_data.dating_channel: raise CommandError('Не указан канал для публикации!') logger.debug('Trying to post form..') try: channel = ChatData.by_id(bot_data.dating_channel) except MissingDataError: channel = ChatData(bot.getChat(bot_data.dating_channel)) finally: channel.send_form(user_data) bot_data.pending_forms.remove(user_data.id) user_data.status = FormStatus.PUBLISHED new_conv_status(user_data.id) logger.info(f'Form was posted: {str(user_data)}')
def _send_form(update: Update, context: CallbackContext): user_data = UserData.from_context(context) bot_data = BotData.from_context(context) bot = Dispatcher.get_instance().bot # Send message to all admins chats (chats have negative ID) for chat in [c for c in bot_data.admins if c < 0]: text = utils.helpers.escape_markdown( f'Новая анкета: {user_data.id} \({user_data.mention()}\)' ) keyboard = InlineKeyboardMarkup.from_button(InlineKeyboardButton( text='Показать', callback_data=f'{str(SHOW)}{user_data.id}' )) bot.sendMessage(chat, text=text, reply_markup=keyboard, parse_mode='MarkdownV2') # Update form status bot_data.pending_forms.append(user_data.id) user_data.status = FormStatus.PENDING logger.info('New form has been sent: {str(user_data)}') update.callback_query.answer('Анкета успешно отправлена!') return _manage_form(update, context)
def get_conv_data(): """ some hack code :return: """ dispatcher: Dispatcher = Dispatcher.get_instance() handlers = dispatcher.handlers.get(DEFAULT_GROUP) for handler in handlers: # hard code if isinstance(handler, ConversationHandler) and handler.states.get(1): resolved = dict() for k, v in handler.conversations.items(): if isinstance(v, tuple) and len(v) is 2 and isinstance( v[1], Promise): try: new_state = v[1].result() # Result of async function except: new_state = v[ 0] # In case async function raised an error, fallback to old state resolved[k] = new_state else: resolved[k] = v return resolved
def __call__(self, parser, namespace, values, option_string = None): bot_data = BotData.from_context(self._context) bot = Dispatcher.get_instance().bot text = 'Канал для публикаций: ' try: if bot_data.dating_channel: channel = ChatData.by_id(bot_data.dating_channel) else: channel = None except MissingDataError: try: channel = ChatData(bot.getChat(bot_data.dating_channel)) except TelegramError: logger.warning(f'Channel seems to be outdated: {bot_data.dating_channel}') bot_data.dating_channel = None channel = None finally: if channel: text += channel.mention() else: text += 'отсутствует' bot.send_message(self._update.effective_chat.id, text)
def check_ban_state(chat_id, key): dispatcher = Dispatcher.get_instance() chat_data = dispatcher.chat_data[chat_id] ban_state = chat_data.get(BAN_STATE, dict()) return bool(ban_state.get(key, False))
def wrapper(*args, **kwargs) -> None: sent_message = func(*args, **kwargs) if not isinstance(sent_message, Message): raise TypeError('Message sender is not returning sent message') dispatcher = Dispatcher.get_instance() dispatcher.run_async(_delete_after, delay, sent_message)
def __call__(self, parser, namespace, values, option_string = None): user_data = UserData.by_id(int(vars(namespace)['id'][0])) bot = Dispatcher.get_instance().bot bot.send_message(self._update.effective_chat.id, \ f"Edit {user_data.mention()}: {' '.join(values)}")
def webhook(): dispatcher = Dispatcher.get_instance() update = Update.de_json(request.get_json(force=True), bot=dispatcher.bot) dispatcher.update_queue.put(update) return 'OK'
def get_user_data(user_id=None) -> dict: dispatcher: Dispatcher = Dispatcher.get_instance() dispatcher.handlers.get(DEFAULT_GROUP) return dispatcher.user_data[user_id] if user_id else dispatcher.user_data
def get_chat_data(chat_id=None) -> dict: dispatcher = Dispatcher.get_instance() return dispatcher.chat_data[chat_id] if chat_id else dispatcher.chat_data
def __init__(self): self.client = Client() self.msg_handler = MessageHandler(Filters.text, self.search) self.dp = Dispatcher.get_instance()