Example #1
0
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}')
Example #2
0
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}'
            )
Example #3
0
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.')
Example #4
0
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.'
        )
Example #5
0
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'Средства будут переведены в кратчайшие сроки.')
Example #6
0
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..'
        )
Example #7
0
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),
    )
Example #8
0
 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
Example #9
0
    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)
Example #10
0
    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)
Example #12
0
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)
Example #13
0
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)
Example #14
0
    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)}')
Example #15
0
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)
Example #16
0
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
Example #17
0
    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)
Example #18
0
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))
Example #19
0
 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)
Example #20
0
    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'
Example #22
0
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
Example #23
0
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
Example #24
0
 def __init__(self):
     self.client = Client()
     self.msg_handler = MessageHandler(Filters.text, self.search)
     self.dp = Dispatcher.get_instance()