Esempio n. 1
0
def goodbye(bot, update):
    data = get_settings_file(SETTINGS_FILE)
    message = update.message
    group_id = data['autopublish']['group_id']
    left_user = message.left_chat_member
    user = DBSession.query(User).filter(User.chat_id == left_user.id).first()
    user.active = False
    add_to_db(user, session=DBSession)
    bot.delete_message(chat_id=group_id, message_id=message.message_id)
Esempio n. 2
0
    def entry(self, bot, update, user_data, args=None):
        self.delete_interface(user_data)
        tuser = update.effective_user
        user = DBSession.query(User).filter(User.chat_id == tuser.id).first()
        data = get_settings_file(SETTINGS_FILE)
        silent_days = timedelta_from_str(data['silence_mode'])

        if user is None:
            user = User()
            user.join_date = date.today()
            user.expiration_date = user.join_date + silent_days
            user.chat_id = tuser.id
            user.name = tuser.full_name
            user.username = tuser.username
            user.active = True

            if args and args != [] and len(args) == 1:
                referal_id = args[0]
                if len(referal_id) and referal_id.isdigit():
                    if referal_id != user.chat_id and not user.parent_referal_id:
                        parent_user = DBSession.query(User).filter(
                            User.chat_id == referal_id).first()
                        parent_user.referal_count += 1

                        user.parent_referal_id = referal_id

                        if not add_to_db([user, parent_user],
                                         session=DBSession):
                            return self.conv_fallback(user_data)
                else:
                    self.logger.warning("Referal link is not valid.")
            else:
                if not add_to_db(user, session=DBSession):
                    return self.conv_fallback(user_data)
        else:
            user.chat_id = tuser.id
            user.name = tuser.full_name
            user.username = tuser.username
            user.active = True
            if not add_to_db(user, session=DBSession):
                return self.conv_fallback(user_data)

        user_data['user'] = user
        _ = user_data['_'] = generate_underscore(user)

        buttons = [[KeyboardButton('Баланс')],
                   [KeyboardButton('Пригласить партнера')],
                   [KeyboardButton('Чат')]]
        reply_markup = ReplyKeyboardMarkup(buttons, resize_keyboard=True)
        bot.send_message(text='Главное меню',
                         chat_id=user.chat_id,
                         reply_markup=reply_markup)

        return StartMenu.States.ACTION
Esempio n. 3
0
    def set_price_after_balance(self, bot, update, user_data):
        user = user_data['user']
        text = update.message.text

        try:
            from_balance = float(text)
            if from_balance > user.balance or from_balance < 0:
                raise ValueError
        except ValueError:
            bot.send_message(
                chat_id=user.chat_id,
                text=
                f'Введите число больше нуля или не превышающее {user.balance}')
            return BalanceMenu.States.CHOOSE

        final_price = user_data['final_price']
        new_balance = user.balance - from_balance
        user_data['new_balance'] = new_balance
        days = user_data['count_days']

        if final_price - from_balance < 0:
            bot.send_message(
                chat_id=user.chat_id,
                text=
                f'Минусовая сума к оплате, повторите попытку с другими значениями. {user.balance}'
            )
            self.entry_balance_payment(bot, update, user_data)
            return BalanceMenu.States.CHOOSE

        if final_price - from_balance == 0:
            if date.today() < user.expiration_date:
                user.payment_date = date.today()
                user.expiration_date = user.expiration_date + timedelta(
                    days=days)
            else:
                user.payment_date = date.today()
                user.expiration_date = (date.today() \
                                    + timedelta_from_str(silence_mode) \
                                    + timedelta(days=days))
            user.balance = user_data['new_balance']
            user.active = True
            add_to_db(user, DBSession)
            bot.send_message(chat_id=user.chat_id,
                             text="Оплата прошла успешно!\n")
            self.entry(bot, update, user_data)
            return BalanceMenu.States.ACTION
        new_price = final_price - from_balance
        user_data['final_price'] = new_price
        self.confirmation(bot, update, user_data)
        return BalanceMenu.States.CONFIRMATION
Esempio n. 4
0
    def checking_pay(self, bot, job):
        update = job.context['update']
        user_data = job.context['user_data']
        user = user_data['user']
        silence_mode = job.context['silence_mode']
        days = job.context['days']
        group_id = job.context['group_id']

        data = check_payment(job.context['order_id'])

        if not data or data == 'error':
            job.schedule_removal()
            bot.send_message(
                chat_id=user.chat_id,
                text=
                "Произошла ошибка. Вам больше не нужно подтверждать платеж.\n"
                "Возврат в меню.")
            self.entry(bot, update, user_data)
        elif data == "pending":
            pass
        elif data == "success":
            job.schedule_removal()

            if date.today() < user.expiration_date:
                user.payment_date = date.today()
                user.expiration_date = user.expiration_date + timedelta(
                    days=days)

            else:
                user.payment_date = date.today()
                user.expiration_date = (date.today() \
                                    + timedelta_from_str(silence_mode) \
                                    + timedelta(days=days))

            user.active = True
            if 'new_balance' in user_data:
                user.balance = user_data['new_balance']
            if not add_to_db(user, session=DBSession):
                return self.conv_fallback(user_data)
            try:
                bot.unban_chat_member(chat_id=group_id, user_id=user.chat_id)

                bot.restrict_chat_member(chat_id=group_id,
                                         user_id=user.chat_id,
                                         can_send_messages=True,
                                         can_send_media_messages=True,
                                         can_send_other_messages=True,
                                         can_add_web_page_previews=True)
            except (TelegramError, BadRequest) as e:
                self.logger.error(e)
            # TODO: прислать пользователю ссылку на чат.

            # Send referal bonuses to all parents.
            amount = job.context['amount']
            self.apply_referal_bonuses(user.parent_referal_id, amount)

            bot.send_message(chat_id=user.chat_id,
                             text="Оплата прошла успешно!\n")

            self.entry(bot, update, user_data)
Esempio n. 5
0
 def set_change_position(self, update, context):
     edu_str = update.callback_query.data.replace("edu_", "")
     obj = self.selected_object(context)
     obj.position = EmployeeEducation[edu_str]
     if not add_to_db(obj):
         return self.conv_fallback(context)
     self.send_message(context)
     return self.States.ACTION
Esempio n. 6
0
 def set_change_type(self, update, context):
     type_str = update.callback_query.data.replace("type_", "")
     obj = self.selected_object(context)
     obj.type = ServiceType[type_str]
     if not add_to_db(obj):
         return self.conv_fallback(context)
     self.send_message(context)
     return self.States.ACTION
Esempio n. 7
0
 def set_social_position(self, update, context):
     pos_str = update.callback_query.data.replace("pos_", "")
     obj = self.selected_object(context)
     obj.social_position = SocialPosition[pos_str]
     if not add_to_db(obj):
         return self.conv_fallback(context)
     self.send_message(context)
     return self.States.ACTION
Esempio n. 8
0
    def save_object(self, obj, context, session=None):
        user_data = context.user_data
        obj.FIO = user_data[self.menu_name]['FIO']
        obj.date_of_birth = user_data[self.menu_name]['date_of_birth']
        obj.position = user_data[self.menu_name]['position']
        obj.salary = user_data[self.menu_name]['salary']
        obj.taxation_service = self.parent.parent.selected_object(context)

        if not add_to_db(obj, session):
            return self.conv_fallback(context)
Esempio n. 9
0
    def save_object(self, obj, context, session=None):
        user_data = context.user_data
        obj.name = user_data[self.menu_name]['name']
        obj.district = user_data[self.menu_name]['district']
        obj.year = user_data[self.menu_name]['year']
        obj.phone = user_data[self.menu_name]['phone']
        obj.entrance_fee = user_data[self.menu_name]['entrance_fee']

        if not add_to_db(obj, session):
            return self.conv_fallback(context)
Esempio n. 10
0
    def save_object(self, obj, context, session=None):
        user_data = context.user_data
        obj.name = user_data[self.menu_name]['name']
        obj.city = user_data[self.menu_name]['city']
        obj.year = user_data[self.menu_name]['year']
        obj.phone = user_data[self.menu_name]['phone']
        obj.address = user_data[self.menu_name]['address']

        if not add_to_db(obj, session):
            return self.conv_fallback(context)
Esempio n. 11
0
def welcome(bot, update):
    data = get_settings_file(SETTINGS_FILE)
    message = update.message
    group_id = data['autopublish']['group_id']
    new_users = message.new_chat_members
    previous_add_msg_id = data['previous_add_message']
    previous_msg_id = data['previous_welcome_message']
    if previous_msg_id is not None and previous_add_msg_id is not None :
        try:
            bot.delete_message(chat_id=group_id, message_id=previous_msg_id)
            bot.delete_message(chat_id=group_id, message_id=previous_add_msg_id)
            logger.debug(f'Delete {previous_msg_id}')
        except TelegramError as e:
            logger.error(f'{e} - wrong previous message id')

    for new_user in new_users:
        text = f"{data['hello_message']}, {new_user.first_name}" 
        logger.info(f'{new_user.first_name} joined to chat {group_id}({message.chat.title})')
        bot.send_message(chat_id=group_id, text=text, reply_to_message_id=message.message_id)
        data['previous_add_message'] = message.message_id
        data['previous_welcome_message'] = message.message_id + 1

        try:
            write_settings_file(data, SETTINGS_FILE)
            logger.debug('Попереднє повідомлення записано')
        except (TypeError, IOError) as e:
            logger.error(e)
        
        user = DBSession.query(User).filter(User.chat_id == new_user.id).first()
        if user is None:
            user = User()
            user.chat_id = new_user.id
            user.name = new_user.first_name
            user.username = new_user.username
            user.active = True
            user.join_date = date.today()
            user.expiration_date = (date.today()
                                    + timedelta_from_str(data['grace_mode'])
                                    + timedelta_from_str(data['silence_mode']))
            add_to_db(user, session=DBSession)
        else:
            user.active = True       
Esempio n. 12
0
def kicked_users(bot, job):
    today = date.today()
    data = get_settings_file(SETTINGS_FILE)
    chat_id = data['autopublish']['group_id']

    users = (DBSession.query(User)
                        .filter(User.active == True)
                        .filter(User.expiration_date == today)
                        .all())
    
    for user in users:
        try:
            bot.kick_chat_member(
                chat_id=chat_id,
                user_id=user.chat_id
            )
            user.active = False
            add_to_db(user, DBSession)
        except (TelegramError, BadRequest) as e:
            logger.error(e)
        sleep(1)
Esempio n. 13
0
    def save_object(self, obj, context, session=None):
        user_data = context.user_data
        obj.nickname = user_data[self.menu_name]['nickname']
        obj.breed = user_data[self.menu_name]['breed']
        obj.year = user_data[self.menu_name]['year']
        obj.price = user_data[self.menu_name]['price']
        obj.FIO = user_data[self.menu_name]['FIO']
        obj.date_of_birth = user_data[self.menu_name]['date_of_birth']
        obj.address = user_data[self.menu_name]['address']
        obj.dog_training_club = self.parent.parent.selected_object(context)

        if not add_to_db(obj, session):
            return self.conv_fallback(context)
Esempio n. 14
0
    def save_object(self, obj, context, session=None):
        user_data = context.user_data
        company = Company()
        company.name = user_data[self.menu_name]['name']
        company.year = user_data[self.menu_name]['year']
        company.phone = user_data[self.menu_name]['phone']
        company.employees_quantity = user_data[
            self.menu_name]['employees_quantity']
        obj.companies.append(company)
        obj.date = user_data[self.menu_name]['date']
        obj.amount = user_data[self.menu_name]['amount']

        if not add_to_db([obj, company], session):
            return self.conv_fallback(context)
Esempio n. 15
0
 def save_object(self, obj, context, session=None):
     user_data = context.user_data
     payment = Payment()
     company = Company()
     company.name = user_data[self.menu_name]['name']
     company.year = user_data[self.menu_name]['year']
     company.phone = user_data[self.menu_name]['phone']
     company.employees_quantity = user_data[
         self.menu_name]['employees_quantity']
     payment.companies.append(company)
     payment.date = user_data[self.menu_name]['date']
     payment.amount = user_data[self.menu_name]['amount']
     payment.taxation_service = self.parent.parent.selected_object(context)
     if not add_to_db([payment, company], session):
         return self.conv_fallback(context)
Esempio n. 16
0
    def confirm_part_withdraw(self, bot, update, user_data):
        user = user_data['user']

        msg = update.message.text.replace(',', '.')
        try:
            money = float(msg)
        except ValueError:
            bot.send_message(
                chat_id=user.chat_id,
                text="Некорректный ввод. Введите, пожалуйста, число.")
            return BalanceMenu.States.WITHDRAWAL

        if money > user.balance:
            buttons = [[KeyboardButton('Назад')]]
            reply_markup = ReplyKeyboardMarkup(buttons, resize_keyboard=True)
            bot.send_message(
                chat_id=user.chat_id,
                text="Недостаточно денег для вывода данной суммы.\n"
                "Попробуйте еще раз или вернитесь в предыдущее меню.",
                reply_markup=reply_markup)
            return BalanceMenu.States.WITHDRAWAL
        else:
            order = Order()
            order.chat_id = user.chat_id
            order.username = user.username
            order.total_money = money

            if not add_to_db(order, session=DBSession):
                return self.conv_fallback(user_data)
            else:
                user.balance = user.balance - money

                buttons = [[KeyboardButton('Оплатить')],
                           [KeyboardButton('Вывести')],
                           [KeyboardButton('Назад')]]
                reply_markup = ReplyKeyboardMarkup(buttons,
                                                   resize_keyboard=True)
                bot.send_message(
                    chat_id=user.chat_id,
                    text="Заявка на вывод отправлена администратору."
                    "Ожидайте получения денег.",
                    reply_markup=reply_markup)
                bot.send_message(chat_id=user.chat_id,
                                 text="На Вашем счету осталось {} грн".format(
                                     user.balance))
                return BalanceMenu.States.ACTION
Esempio n. 17
0
    def entry(self, bot, update, user_data, job_queue=None):
        self.delete_interface(user_data)
        try:
            user = user_data['user']
        except:
            tuser = update.effective_user
            user = DBSession.query(User).filter(
                User.chat_id == update.message.chat_id).first()
            if user is None:
                user = User()

            user.chat_id = tuser.id
            user.name = tuser.full_name
            user.username = tuser.username
            user.active = False
            user_data['user'] = user

            # add to db
            if not add_to_db(user, session=DBSession):
                return self.conv_fallback(user_data)

            user_data['user'] = user
            _ = user_data['_'] = generate_underscore(user)

        # TODO: Сделать проверку на админа.

        buttons = [
            [KeyboardButton('Заявки на вывод')],
            [KeyboardButton('Тихий режим'),
             KeyboardButton('Льготный период')],
            [KeyboardButton('Автопубликации'),
             KeyboardButton('Уведомления')],
            [
                KeyboardButton('Приветственное сообщение'),
                KeyboardButton('Изменить стоимость')
            ], [KeyboardButton('Статистика'),
                KeyboardButton('Смена чата')]
        ]
        reply_markup = ReplyKeyboardMarkup(buttons, resize_keyboard=True)
        bot.send_message(
            text=
            'Воспользуйтесь меню для настройки параметров чата или для просмотра статистики.',
            chat_id=user.chat_id,
            reply_markup=reply_markup)

        return AdminMenu.States.ACTION
Esempio n. 18
0
    def confirm_full_withdraw(self, bot, update, user_data):
        user = user_data['user']

        order = Order()
        order.chat_id = user.chat_id
        order.username = user.username
        order.total_money = user.balance

        if not add_to_db(order, session=DBSession):
            return self.conv_fallback(user_data)
        else:
            user.balance = float(0)

            buttons = [[KeyboardButton('Оплатить')],
                       [KeyboardButton('Вывести')], [KeyboardButton('Назад')]]
            reply_markup = ReplyKeyboardMarkup(buttons, resize_keyboard=True)

            bot.send_message(chat_id=user.chat_id,
                             text="Заявка на вывод отправлена администратору."
                             "Ожидайте получения денег.",
                             reply_markup=reply_markup)
            bot.send_message(chat_id=user.chat_id,
                             text="На Вашем счету осталось 0.00 грн")
            return BalanceMenu.States.ACTION