Пример #1
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
Пример #2
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
Пример #3
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       
Пример #4
0
def send_welcome(message):
    usr = message.from_user
    user = DBSession.query(User).filter(User.chat_id == usr.id).first()
    if user is None:
        user = User()
        user.chat_id = message.chat.id
        user.name = usr.first_name + usr.last_name
        user.username = usr.username
        user.active = True
        user.state = 'start_menu_state'
        if not add_to_db(user, DBSession):
            bot.send_message(
                user.chat_id,
                "Неможливо добавити користувача, проблеми з БД, спробуйте пізніше."
            )
    else:
        add_to_db(user)
        bot.send_message(
            user.chat_id,
            "Вітаю!, Даний бот створений для легкого бронювання квитків.",
            reply_markup=get_send_welcome_keyboard())
Пример #5
0
def users_from_chat(bot=None, job=None):

    data = get_settings_file(SETTINGS_FILE)
    day, month, year = data['transition'].split('.')
    transition = date(int(year), int(month), int(day))

    with client:
        entity = client.get_entity(data['chat_link'])
        users_in_chat = client.get_participants(entity)
        for user_chat in users_in_chat:
            user = DBSession.query(User).filter(User.chat_id == user_chat.id).first()
            if user is None:
                user = User()
                user.chat_id = user_chat.id
                user.name = user_chat.first_name
                user.username = user_chat.username
                user.active = True
                user.join_date = date.today()
                user.expiration_date = transition

                DBSession.add(user)
                DBSession.commit()
                logger.info(f"Added {user.username}")
            else: pass