Exemplo n.º 1
0
def _create_withdrawal(bot, update):
    text = update.message.text

    try:
        amount = _validate_transaction(bot.user, text)
    except ValueError:
        bot.send_message(chat_id=bot.chat_id, text=lang.invalid_input())
        return bot_states.CREATE_WITHDRAWAL
    except LessThanMinimalWithdraw:
        bot.send_message(chat_id=bot.chat_id,
                         text=lang.minimal_withdraw_amount())
        return bot_states.CREATE_WITHDRAWAL
    except NotEnoughBalance:
        bot.send_message(chat_id=bot.chat_id, text=lang.not_enough_eth())
        return bot_states.CREATE_WITHDRAWAL

    try:
        not_approved_withdrawal = Withdrawal.get(approved=False)
        bot.send_message(chat_id=bot.chat_id,
                         text=lang.not_approved_previous(
                             not_approved_withdrawal.amount),
                         reply_markup=keyboards.main_keyboard())
        return bot_states.MAIN
    except DoesNotExist:
        pass

    Withdrawal.create(user=bot.user, amount=amount)

    bot.send_message(chat_id=bot.chat_id,
                     text=lang.withdrawal_created(bot.user.wallet),
                     reply_markup=keyboards.main_keyboard())

    return bot_states.MAIN
Exemplo n.º 2
0
def _start_command(bot, update, args):
    chat_id = update.message.chat_id
    first_name = update.message.chat.first_name
    username = update.message.from_user.username

    try:
        user = User.get(chat_id=chat_id)
        text = f'{first_name}, You are already registered in the system. Welcome home!'
    except DoesNotExist:
        referral = None
        try:
            if len(args) > 0:
                referred_by = args[0]
                referral = User.get(chat_id=referred_by)
        except DoesNotExist:
            pass

        user = User.create(chat_id=chat_id,
                           username=username,
                           first_name=update.message.from_user.first_name,
                           last_name=update.message.from_user.last_name,
                           referral=referral)

        text = f'{first_name}, You have been successfully registered in the system!'

    bot.send_message(chat_id=user.chat_id,
                     text=text,
                     reply_markup=keyboards.main_keyboard())
    return bot_states.MAIN
Exemplo n.º 3
0
def _start_command(bot, update, args):
    chat_id = update.message.chat_id
    first_name = update.message.chat.first_name
    username = update.message.from_user.username

    try:
        user = User.get(chat_id=chat_id)
        text = f'{first_name}, вы уже зарегистрированны в системе. Добро пожаловать домой!'
    except DoesNotExist:
        referral = None
        try:
            if len(args) > 0:
                referred_by = args[0]
                referral = User.get(chat_id=referred_by)
        except DoesNotExist:
            pass

        user = User.create(
            chat_id=chat_id,
            username=username,
            first_name=update.message.from_user.first_name,
            last_name=update.message.from_user.last_name,
            referral=referral
        )

        text = f'{first_name}, вы были успешно зарегистрированны в системе!'

    bot.send_message(chat_id=user.chat_id, text=text, reply_markup=keyboards.main_keyboard())
    return bot_states.MAIN
Exemplo n.º 4
0
def helm_direction(update, context):
    query = update.callback_query
    chat_id = query.message.chat_id
    params = parameters_db.find_one({'_id': chat_id})
    sub_params = sub_param_db.find_one({'_id': chat_id})
    params['helm_dir'] = int(update.callback_query.data[-1:])
    keyboard = main_keyboard()
    msg = ''
    if sub_params['helm'] == 1:
        keyboard = num_keyboard()
        msg = 'Enter Wrap Coefficient'
        sub_param_db.update_one({'_id': chat_id}, {"$set": {'helm': 0}}, upsert=True)
    elif sub_params['torpedoes'] == 1:
        sub_param_db.update_one({'_id': chat_id}, {"$set": {'torpedoes': 0}}, upsert=True)
        params = torpedoes_compute(params)
        params['input'] = 0
        msg = params['msg'] + params['attack_msg_out']
        params['msg'] = ''
    parameters_db.update_one({'_id': chat_id}, {"$set": params}, upsert=True)
    if params['klingons'] == 0:
        victory(update, context)
        params['msg'] = ''
    else:
        context.bot.edit_message_text(chat_id=query.message.chat_id,
                                      message_id=query.message.message_id,
                                      text=main_message(update, context, msg),
                                      reply_markup=keyboard,
                                      parse_mode=telegram.ParseMode.MARKDOWN)
Exemplo n.º 5
0
def bot_helm(update, context):
    chat_id = update.effective_chat.id
    drop_subparams_flag(chat_id)
    sub_param_db.update_one({'_id': chat_id}, {"$set": {'helm': 1}}, upsert=True)
    context.bot.send_message(chat_id=update.effective_chat.id,
                             text='``` \nCourse direction(1-4,5-9)? ```',
                             parse_mode=telegram.ParseMode.MARKDOWN)
    update.message.reply_text(main_message(update, context), reply_markup=main_keyboard())
Exemplo n.º 6
0
def restart(update, context):
    query = update.callback_query
    start_game(update, context)
    context.bot.edit_message_text(chat_id=query.message.chat_id,
                                  message_id=query.message.message_id,
                                  text='',
                                  reply_markup=main_keyboard(),
                                  parse_mode=telegram.ParseMode.MARKDOWN)
def quize_message(user_id):
    text = "Пройди, пожалуйста, опрос. Чтобы мы имели понятие о твоих интересах https://forms.gle/JHAZeEMjcrcNaUjY8"
    vk.method(
        "messages.send", {
            "peer_id": user_id,
            "message": text,
            "random_id": int(r.uniform(0, 2**32)),
            "keyboard": keyboards.main_keyboard()
        })
def error_message(user_id):
    text = "Ты написал что-то не то. Вернись к предыдущему шагу, пожалуйста"
    vk.method(
        "messages.send", {
            "peer_id": user_id,
            "message": text,
            "random_id": int(r.uniform(0, 2**32)),
            "keyboard": keyboards.main_keyboard()
        })
Exemplo n.º 9
0
def booze(update, context):
    query = update.callback_query
    start_text = '''```
tst
```'''
    context.bot.send_message_text(chat_id=query.message.chat_id,
                                  message_id=query.message.message_id,
                                  text=start_text,
                                  reply_markup=main_keyboard(),
                                  parse_mode=telegram.ParseMode.MARKDOWN)
Exemplo n.º 10
0
    def inner(bot, update, *args, **kwargs):
        import keyboards
        text = update.message.text
        chat_id = update.message.chat_id

        if text == keyboards.MAIN_BUTTONS['back']:
            bot.send_message(chat_id=chat_id,
                             text=lang.back_to_main_menu(),
                             reply_markup=keyboards.main_keyboard())
            return bot_states.MAIN
        return func(bot, update, *args, **kwargs)
Exemplo n.º 11
0
def back2main(update, context):
    query = update.callback_query
    drop_subparams_flag(query.message.chat_id)
    chat_id = update.effective_chat.id
    params = parameters_db.find_one({'_id': chat_id})
    params['num_input'] = ''
    parameters_db.update_one({'_id': chat_id}, {"$set": params}, upsert=True)
    context.bot.edit_message_text(chat_id=query.message.chat_id,
                                  message_id=update.callback_query.message.message_id,
                                  text=main_message(update, context, ''),
                                  reply_markup=main_keyboard(),
                                  parse_mode=telegram.ParseMode.MARKDOWN)
Exemplo n.º 12
0
def bot_srs(update, context):
    chat_id = update.effective_chat.id
    drop_subparams_flag(chat_id)
    params = parameters_db.find_one({'_id': chat_id})
    params['condition'], params['srs_map'] = srs(params['current_sector'], params['ent_position'])
    params['status_msg'] = status(params)
    srs_ = f"{params['srs_map']}{params['status_msg']}"
    context.bot.edit_message_text(chat_id=update.effective_chat.id,
                                  message_id=update.callback_query.message.message_id,
                                  text=main_message(update, context, srs_),
                                  reply_markup=main_keyboard(),
                                  parse_mode=telegram.ParseMode.MARKDOWN)
Exemplo n.º 13
0
def bot_lrs(update, context):
    chat_id = update.effective_chat.id
    drop_subparams_flag(chat_id)
    params = parameters_db.find_one({'_id': chat_id})
    sector = params['sector']
    galaxy = params['galaxy']
    lrs_out = lrs(galaxy, sector)
    context.bot.edit_message_text(chat_id=update.effective_chat.id,
                                  message_id=update.callback_query.message.message_id,
                                  text=main_message(update, context, lrs_out),
                                  reply_markup=main_keyboard(),
                                  parse_mode=telegram.ParseMode.MARKDOWN)
def meeting_message(user_id, day_of_week):
    text = "Хорошо. Скоро мы найдём тебе пару."

    with open("days.txt", 'a') as f:
        f.write(str(user_id) + ' ' + str(day_of_week + 1) + "\n")
    vk.method(
        "messages.send", {
            "peer_id": user_id,
            "message": text,
            "random_id": int(r.uniform(0, 2**32)),
            "keyboard": keyboards.main_keyboard()
        })
Exemplo n.º 15
0
def start_work(message):
    # Вот здесь происходит запись username (message.from_user.username) пользователя, если его нет, то записывает айдишник(message.from_user.id)
    try:
        if message.from_user.username is not None:
            interaction.insert_into_user_table(message.from_user.username, 0)
        else:
            interaction.insert_into_user_table(str(message.from_user.id), 0)
    except:
        pass
    bot.send_message(message.chat.id,
                     "Обращаем ваше внимание на то, что ссылки, который вы подаете боту, должны быть в следующем формате:"
                     "\nВидео: https://www.youtube.com/watch?v***"
                     "\nКанал: https://www.youtube.com/channel/***  или \nhttps://www.youtube.com/user/***",
                     reply_markup=keyboards.main_keyboard(message))
Exemplo n.º 16
0
def _demo_top_up(bot, update):
    from models import TopUp
    chat_id = bot.chat_id
    text = update.message.text
    user = bot.user
    try:
        amount = _validate_transaction(user, text, demo=True)
    except ValueError:
        bot.send_message(chat_id=chat_id, text='Инпут ерор)))))00')
        return bot_states.DEMO_TOP_UP

    top_up = TopUp.create(user=user, amount=amount, from_wallet=user.wallet)
    bot.send_message(chat_id=chat_id,
                     text=lang.back_to_main_menu(),
                     reply_markup=keyboards.main_keyboard())
    return bot_states.MAIN
def sit_message(user_id, table_number, partner_id):
    print(user_id)
    string = ''
    for index in same_answers.compare(
            spreadsheets.people_answers()[user_id],
            spreadsheets.people_answers()[partner_id]):
        print(index, "index", type(index))
        string += str(spreadsheets.text_of_question()[3 + index])
        string += '  '
    text = "Привет. Номер твоего стола " + str(
        table_number) + ". Твой собеседник " + "https://vk.com/id" + str(
            partner_id
        ) + ". " + "У вас совпали ответы на такие вопросы: " + string
    vk.method(
        "messages.send", {
            "peer_id": user_id,
            "message": text,
            "random_id": int(r.uniform(0, 2**32)),
            "keyboard": keyboards.main_keyboard()
        })
Exemplo n.º 18
0
def _transfer_balance_to_user(bot, update):
    text = update.message.text

    transfer_data = text.split(' ')

    if len(transfer_data) != 2:
        bot.send_message(chat_id=bot.chat_id, text=lang.invalid_input())
        return bot_states.TRANSFER_BALANCE_TO_USER

    username = transfer_data[0].lower()

    try:
        user_to_transfer = User.get(fn.Lower(User.username) == username)
        amount = _validate_transaction(bot.user, transfer_data[1])
    except ValueError:
        bot.send_message(chat_id=bot.chat_id, text=lang.invalid_input())
        return bot_states.TRANSFER_BALANCE_TO_USER
    except LessThanMinimalWithdraw:
        bot.send_message(chat_id=bot.chat_id,
                         text=lang.minimal_withdraw_amount())
        return bot_states.TRANSFER_BALANCE_TO_USER
    except NotEnoughBalance:
        bot.send_message(chat_id=bot.chat_id, text=lang.not_enough_eth())
        return bot_states.TRANSFER_BALANCE_TO_USER
    except DoesNotExist:
        bot.send_message(chat_id=bot.chat_id, text=lang.user_not_registered())
        return bot_states.TRANSFER_BALANCE_TO_USER

    UserTransfer.create(
        from_user=bot.user,
        to_user=user_to_transfer,
        amount=amount,
    )

    bot.send_message(chat_id=bot.chat_id,
                     text=lang.balance_transferred_to_user(
                         amount, user_to_transfer.username),
                     reply_markup=keyboards.main_keyboard())

    return bot_states.MAIN
Exemplo n.º 19
0
def _change_wallet(bot, update):
    wallet = update.message.text.lower()
    if wallet[0:2] != '0x':
        wallet = f'0x{wallet}'

    if not is_eth_address(wallet):
        bot.send_message(chat_id=bot.chat_id, text=lang.invalid_input())
        return bot_states.WALLET_CHANGE
    try:
        User.get(wallet=wallet)
        bot.send_message(chat_id=bot.chat_id, text=lang.eth_address_taken())
        return bot_states.WALLET_CHANGE
    except DoesNotExist:
        pass

    user = bot.user
    user.wallet = wallet.lower()
    user.save()
    bot.send_message(chat_id=bot.chat_id,
                     text=lang.wallet_successfully_set(wallet),
                     reply_markup=keyboards.main_keyboard())
    return bot_states.MAIN
Exemplo n.º 20
0
def _transfer_balance_to_deposit(bot, update):
    text = update.message.text
    chat_id = bot.chat_id

    try:
        amount = _validate_transaction(bot.user, text)
    except ValueError:
        bot.send_message(chat_id=chat_id, text=lang.invalid_input())
        return bot_states.TRANSFER_BALANCE_TO_DEPOSIT
    except LessThanMinimalWithdraw:
        bot.send_message(chat_id=chat_id, text=lang.minimal_withdraw_amount())
        return bot_states.TRANSFER_BALANCE_TO_DEPOSIT
    except NotEnoughBalance:
        bot.send_message(chat_id=chat_id, text=lang.not_enough_eth())
        return bot_states.TRANSFER_BALANCE_TO_DEPOSIT

    DepositTransfer.create(user=bot.user, amount=amount)

    bot.send_message(chat_id=chat_id,
                     text=lang.balance_transferred_to_deposit(amount),
                     reply_markup=keyboards.main_keyboard())
    return bot_states.MAIN
Exemplo n.º 21
0
def handle_start(message):
    active_user = ds.find_user_by_id(message.from_user.id)
    if not active_user:
        # collect new user info
        user_info = message.from_user
        telegram_id = user_info.id
        language = user_info.language_code
        username = user_info.username

        active_user = ds.create_user(telegram_id, username, language)

        bot.send_message(
            message.chat.id,
            f"Hello {active_user.username}, welcome to cikpak-weather-bot")
        bot.send_message(message.chat.id,
                         'By default you will receive weather in °C')
        bot.send_message(message.chat.id, 'You can change it in settings')
    else:
        bot.send_message(message.chat.id, f"Hello, {active_user.username}!")

    bot.send_message(message.chat.id,
                     'Choose a option:',
                     reply_markup=main_keyboard())
Exemplo n.º 22
0
def start_game(update, context, restart_msg=''):
    blurb_msg = blurb()
    # Set up a random stardate
    stardate = round(float(random.randrange(1000, 1500, 1)), 2)
    # Enterprise starts with 3,000 units of energy, 15 torpedoes and 1,000
    # units of energy in its shields
    energy = 3000
    torpedoes = 15
    shields = 0
    # No klingons around ... yet!
    klingons = 0
    # The galaxy is divided into 64 sectors. Each sector is represented by one
    # element in the galaxy list. The galaxy list contains a three digit number
    # Hundreds = number of klingons in the sector
    # Tens = number of starbases
    # Units = number of stars
    galaxy = []
    # Initialise the galaxy list
    for i in range(0, 64):
        x = y = 0
        z = random.randint(1, 5)
        if random.randint(1, 10) < 8:
            x = random.randint(1, 3)
        if random.randint(1, 100) > 88:
            y = 1
        # galaxy.append(x * 100 + y * 10 + z)
        galaxy.append([x] + [y] + [z])
        # Keep a record of how many klingons are left to be destroyed
        klingons += x
    # Choose the starting sector and position for the Enterprise
    sector = random.randint(0, 63)
    ent_position = random.randint(0, 63)
    # Set up current sector and decode it
    # x = klingons; y = starbases; z = stars
    x = galaxy[sector][0]
    y = galaxy[sector][1]
    z = galaxy[sector][2]
    # x, y, z = decode(galaxy[sector])
    # Set up the current sector map
    # Each sector has 64 positions in which a klingon, starbase, star
    # or the Enterprise may be located in
    current_sector = init(x, y, z, ent_position)
    # Perform a short range scan
    condition, srs_map = srs(current_sector, ent_position)
    params = {
        'sector': sector,
        'stardate': stardate,
        'condition': condition,
        'energy': energy,
        'torpedoes': torpedoes,
        'shields': shields,
        'klingons': klingons
    }
    status_msg = status(params)
    # Keep going until we have destroyed all the klingons or we run out of
    # energy or we quit
    chat_id = update.effective_chat.id
    username = update.effective_chat.username
    first_name = update.effective_chat.first_name
    last_name = update.effective_chat.last_name
    parameters4db = {'_id': chat_id, 'username': username, 'first_name': first_name, 'last_name': last_name,
                     'galaxy': galaxy, 'klingons': klingons, 'energy': energy, 'torpedoes': torpedoes,
                     'shields': shields, 'stardate': stardate, 'sector': sector,
                     'ent_position': ent_position, 'attack_msg_out': '',
                     'x': x, 'y': y, 'z': z, 'current_sector': current_sector, 'condition': condition,
                     'wrap': 0, 'helm': 0, 'srs_map': srs_map, 'status_msg': status_msg, 'num_input': ''}
    sub_param4db = {'_id': chat_id, 'shields_flag': 0, 'helm': 0, 'phasers_flag': 0, 'lrs_flag': 0,
                    'wrap': 0, 'torpedoes': 0}
    try:
        parameters_db.delete_one({'_id': chat_id})
        sub_param_db.delete_one({'_id': chat_id})
    except Exception as e:
        print('error mongo! chat_id = ', chat_id, '\nerror = ', e)
    parameters_db.update_one({'_id': chat_id}, {"$set": parameters4db}, upsert=True)
    sub_param_db.update_one({'_id': chat_id}, {"$set": sub_param4db}, upsert=True)
    start_msg = restart_msg + blurb_msg
    update.effective_message.reply_text(main_message(update, context, start_msg),
                                        reply_markup=main_keyboard(),
                                        parse_mode=telegram.ParseMode.MARKDOWN)
Exemplo n.º 23
0
def num_command(update, context):
    query = update.callback_query
    chat_id = query.message.chat_id
    params = parameters_db.find_one({'_id': chat_id})
    sub_params = sub_param_db.find_one({'_id': chat_id})
    if sub_params['wrap'] == 1:
        keyboard = main_keyboard()
        sub_param_db.update_one({'_id': chat_id}, {"$set": {'wrap': 0}}, upsert=True)
        params['num_input'] = ''
        params = helm_out(params)
        params['condition'], params['srs_map'] = srs(params['current_sector'], params['ent_position'])
        msg = ''

    elif sub_params['shields_flag'] == 1:
        keyboard = main_keyboard()
        shields_update = params['num_input']
        params['num_input'] = ''
        input = params['input']
        params['input'] = 0
        sub_params['shields_flag'] = 0
        params, sub_params = shields_compute(params, sub_params, input)
        sub_param_db.update_one({'_id': chat_id}, {"$set": sub_params}, upsert=True)
        msg = f'''```
Energy to shields {shields_update}
```'''

    elif sub_params['phasers_flag'] == 1:
        keyboard = main_keyboard()
        sub_param_db.update_one({'_id': chat_id}, {"$set": {'phasers_flag': 0}}, upsert=True)
        params['num_input'] = ''
        input = params['input']
        params['input'] = 0
        params = phasers_compute(update, context, params, input)
        params['condition'], params['srs_map'] = srs(params['current_sector'], params['ent_position'])
        msg = params['msg']
        params['msg'] = ''

    else:
        msg = ''
        keyboard = main_keyboard()

    if params['attack_msg_out'] != '':
        msg += params['attack_msg_out']
        params['attack_msg_out'] = ''

    if params['energy'] == 0:
        gameover(update, context, msg)
        params['msg'] = ''
    elif params['klingons'] == 0:
        victory(update, context)
        params['msg'] = ''
    else:

        params['condition'], params['srs_map'] = srs(params['current_sector'], params['ent_position'])
        params['status_msg'] = status(params)
        parameters_db.update_one({'_id': chat_id}, {"$set": params}, upsert=True)
        context.bot.edit_message_text(chat_id=query.message.chat_id,
                                      message_id=update.callback_query.message.message_id,
                                      text=main_message(update, context, msg),
                                      reply_markup=keyboard,
                                      parse_mode=telegram.ParseMode.MARKDOWN)
Exemplo n.º 24
0
def processing_message(message):
    if message.text == "Функции администратора":
        bot.send_message(message.chat.id, "Функции администратора", reply_markup=keyboards.admin_keyboard())

    elif message.text == "Добавить нового администратора":
        bot.send_message(message.chat.id, "Введите username пользователя, которого вы хотите сделать администратором")
        SetState(message, 71)


    elif message.text == "Удалить администратора":
        bot.send_message(message.chat.id,
                         "Введите username пользователя, которого вы хотите убрать из списка администраторов")
        SetState(message, 72)

    elif message.text == "Посмотреть статистику":  # новые + за неделю
        bot.send_message(message.chat.id, "Статистика", reply_markup=keyboards.statistics_keyboard())

    elif message.text == "Новые пользователи":  # за день за неделю
        bot.send_message(message.chat.id, "Новые пользователи", reply_markup=keyboards.newusers_keyboard())

    elif message.text == "За день":
        bot.send_message(message.chat.id, "Выводим статистику", reply_markup=keyboards.back_keyboard())
        today_date = dt.date.today()
        data = interaction.check_new_users(today_date)
        if data == []:
            bot.send_message(message.chat.id, f'Количество новых пользователей за день: 0', reply_markup=keyboards.back_keyboard())
        else:
            bot.send_message(message.chat.id, f'Количество новых пользователей за день: {len(data)}', reply_markup=keyboards.back_keyboard())


    elif message.text == "За неделю":
        bot.send_message(message.chat.id, "Выводим статистику", reply_markup=keyboards.back_keyboard())
        today_date = dt.date.today()
        quantity = interaction.check_week_new_users()
        if quantity == []:
            bot.send_message(message.chat.id, f'Количество новых пользователей за неделю: 0', reply_markup=keyboards.back_keyboard())
        else:
            bot.send_message(message.chat.id, f'Количество новых пользователей за неделю: {quantity[0][0]}', reply_markup=keyboards.back_keyboard())

    elif message.text == "Действия пользователей за неделю":  # юзернейм действие по датам (неделя)
        bot.send_message(message.chat.id, "Выводим статистику", reply_markup=keyboards.back_keyboard())
        string = ''
        action_ac = interaction.print_actions_from_statistic_table('ac')
        if action_ac == []:
            string += 'Анализ комментариев под видео: 0 раз\n'
        else:
            string += f'Анализ комментариев под видео: {len(action_ac)} раз' + '\n'

        action_cc = interaction.print_actions_from_statistic_table('cc')
        if action_cc == []:
            string += 'Сравнение двух видео: 0 раз\n'
        else:
            string += f'Сравнение двух видео: {len(action_cc)} раз' + '\n'

        action_ach = interaction.print_actions_from_statistic_table('ach')
        if action_ach == []:
            string += 'Анализ комментариев на канале: 0 раз\n'
        else:
            string += f'Анализ комментариев на канале: {len(action_ach)} раз' + '\n'

        action_wcb = interaction.print_actions_from_statistic_table('wcb')
        if action_wcb == []:
            string += 'Wordcloud речи блогера: 0 раз\n'
        else:
            string += f'Wordcloud речи блогера: {len(action_wcb)} раз' +'\n'

        bot.send_message(message.chat.id, string, reply_markup=keyboards.back_keyboard())


    elif message.text == "Анализ комментариев":
        bot.send_message(message.chat.id, "Проанализировать комментарии...", reply_markup=keyboards.analysis_keyboard())

    elif message.text == "Сравнение комментариев":
        bot.send_message(message.chat.id, "Сравнить комменарии...", reply_markup=keyboards.compare_keyboard())

    elif message.text == "Wordcloud анализ речи блогера":
        bot.send_message(message.chat.id, "Введите ссылку на видео", reply_markup=keyboards.back_keyboard())
        SetState(message, 6)


    elif message.text == "Избранное":
        bot.send_message(message.chat.id, "Выберите действие", reply_markup=keyboards.fav_keyboard())

    elif message.text == "История":
        # выводим список из 10 последний ссылок
        bot.send_message(message.chat.id, "История", reply_markup=keyboards.back_keyboard())
        bot.send_message(message.chat.id, "Список 10 последних ссылок")

    elif message.text == "Назад":
        bot.send_message(message.chat.id, "Что вы хотите сделать?", reply_markup=keyboards.main_keyboard(message))

    elif message.text == "Под видео":
        bot.send_message(message.chat.id, "Введите ссылку на видео", reply_markup=keyboards.back_keyboard())
        SetState(message, 1)


    elif message.text == "На канале":
        bot.send_message(message.chat.id, "Введите ссылку на канал", reply_markup=keyboards.back_keyboard())
        SetState(message, 2)

    elif message.text == "Под двумя видео":
        bot.send_message(message.chat.id, "Введите ссылку на первое видео", reply_markup=keyboards.back_keyboard())
        SetState(message, 31)

    elif message.text == "На двух каналах":
        bot.send_message(message.chat.id, "Введите ссылку на первый канал", reply_markup=keyboards.back_keyboard())
        SetState(message, 41)

    elif message.text == "Посмотреть избранное":
        bot.send_message(message.chat.id, "Выводим список избранных", reply_markup=keyboards.back_keyboard())
        if message.from_user.username is not None:
            favourites = interaction.print_favorites_table(message.from_user.username)
        else:
            favourites = interaction.insert_into_statistic_table(str(message.from_user.id))
        count = 1
        string = ''
        for i in favourites:
            string += f'{count}. i[1]'

        bot.send_message(message.chat.id, string, reply_markup=keyboards.back_keyboard())

    elif message.text == "Добавить в избранное":
        # проверка на количесвто избранных (макс 10)
        bot.send_message(message.chat.id, "Введите ссылку, которую вы хотите добавить в избранное", reply_markup=keyboards.back_keyboard())
        SetState(message, 51)

    elif message.text == "Удалить из избранного":
        bot.send_message(message.chat.id, "Введите ссылку, которую вы хотите удалить из избранного",
                         reply_markup=keyboards.back_keyboard())
        SetState(message, 52)

        # занесение в бд
        # картинка

    elif message.text == "Привет" or message.text == "привет":
        bot.send_message(message.chat.id, "Доброго времени суток! Что вы хотите сделать?",
                         reply_markup=keyboards.main_keyboard(message))

    elif message.text == "/help":
        bot.send_message(message.chat.id,
                         "Если возникла ошибка после ввода ссылки => была введена неверная ссылка. Попробуйте ввести другую "
                         "\nЕсли вы не знаете как начать со мной работать => просто напишите мне 'Привет'"
                         "\nОбращаем ваше внимание на то, что ссылки, который вы подаете боту, должны быть в следующем формате:"
                         "\nВидео: https://www.youtube.com/watch?v***"
                         "\nКанал: https://www.youtube.com/channel/***  или \nhttps://www.youtube.com/user/***")




    elif message.text[0:31] == "https://www.youtube.com/watch?v":
        if GetState(message) == 1:
            try:
                if message.from_user.username is not None:
                    interaction.insert_into_statistic_table(message.from_user.username, "ac")
                else:
                    interaction.insert_into_statistic_table(str(message.from_user.id), "ac")

                bot.link_video1 = message.text
                analysis_a_single_video = AnalysisOfOneVideoActions(bot.link_video1)
                bot.send_message(message.chat.id,
                                 "Анализ комментариев может занять некоторое время, пожалуйста, дождитесь результата.")
                video_info, string = analysis_a_single_video.analysis_of_comments_for_a_single_video()
                bot.send_message(message.chat.id, video_info)
                bot.send_message(message.chat.id, string)

                for i in range(1, 4):
                    photo = open(f'Figures/fig_video_{analysis_a_single_video.id_video}_{i}.png', 'rb')
                    bot.send_photo(message.chat.id, photo)
            except:
                bot.send_message(message.chat.id, "Произошла непредвиденная ошибка, попробуйте еще раз. Если ошибка "
                                                  "не исправляется - попробуйте удалить чат с ботом и попробовать "
                                                  "сначала")
            SetState(message, 0)
        elif GetState(message) == 6:
            try:
                if message.from_user.username is not None:
                    interaction.insert_into_statistic_table(message.from_user.username, "wcb")
                else:
                    interaction.insert_into_statistic_table(str(message.from_user.id), "wcb")
                link_video6 = message.text
                bot.send_message(message.chat.id, "Выводим wordcloud анализ", reply_markup=keyboards.back_keyboard())
                analysis_a_bloger_speech = BlogersWordcloudActions(link_video6)
                analysis_a_bloger_speech.get_wordcloud_picture()
                wphoto = open('Figures/picture_new.png', 'rb')
                bot.send_photo(message.chat.id, wphoto)
            except:
                pass
            SetState(message, 0)

        elif GetState(message) == 31:
            bot.link_video31 = message.text
            SetState(message, 32)
            bot.send_message(message.chat.id, "Введите ссылку на второе видео", reply_markup=keyboards.back_keyboard())

        elif GetState(message) == 32:
            try:
                if message.from_user.username is not None:
                    interaction.insert_into_statistic_table(message.from_user.username, "cc")
                else:
                    interaction.insert_into_statistic_table(str(message.from_user.id), "cc")
                link_video32 = message.text
                bot.send_message(message.chat.id, "Выводим анализ", reply_markup=keyboards.back_keyboard())
                compare_the_two_videos = AnalysisOfTwoVideosActions(bot.link_video31, link_video32)
                compare_the_two_videos.comparative_analysis()
                for i in range(1, 7):
                    photo = open(f'Figures/fig_video_comparison_{i}.png', 'rb')
                    bot.send_photo(message.chat.id, photo)
                SetState(message, 0)
            except:
                bot.send_message(message.chat.id, "Произошла непредвиденная ошибка, попробуйте еще раз. Если ошибка "
                                                  "не исправляется - попробуйте удалить чат с ботом и попробовать "
                                                  "сначала")

        else:
            link_video6 = message.text
            bot.send_message(message.chat.id, "Выводим анализ", reply_markup=keyboards.back_keyboard())
            # картинка
            # занесение в бд действия пользователя
            SetState(message, 0)

    elif message.text[0:28] == "https://www.youtube.com/user" or message.text[
                                                                 0:31] == "https://www.youtube.com/channel":
        if GetState(message) == 2:
            try:
                if message.from_user.username is not None:
                    interaction.insert_into_statistic_table(message.from_user.username, "ach")
                else:
                    interaction.insert_into_statistic_table(str(message.from_user.id), "ach")

                link_channel2 = message.text
                bot.send_message(message.chat.id, "Выводим анализ")  # , reply_markup=keyboards.wordcloud_keyboard()
                analysis_one_channel = AnalysisOfOneChannelActions(link_channel2)
                string = analysis_one_channel.analysis_of_comments_for_a_single_channel()
                bot.send_message(message.chat.id, string)
                photo = open(f'Figures/fig_channel_1.png', 'rb')
                bot.send_photo(message.chat.id, photo)
                SetState(message, 0)
            except:
                bot.send_message(message.chat.id, "Произошла непредвиденная ошибка, попробуйте еще раз. Если ошибка "
                                                  "не исправляется - попробуйте удалить чат с ботом и попробовать "
                                                  "сначала")

        elif GetState(message) == 41:
            link_channel41 = message.text
            bot.send_message(message.chat.id, "Введите ссылку на второй канал", reply_markup=keyboards.back_keyboard())
            SetState(message, 42)

        else:
            link_channel42 = message.text
            bot.send_message(message.chat.id, "Выводим анализ", reply_markup=keyboards.back_keyboard())
            # занесение в бд дей-ия пользователя
            # вывод анализа + картинок
            SetState(message, 0)

    elif message.text[0:23] == "https://www.youtube.com":
        if GetState(message) == 51:  # getstate
            link_fav51 = message.text
            data = interaction.check_in_favourites(link_fav51)
            if data == []:
                bot.send_message(message.chat.id, "Данная ссылка уже существует в Избранном", reply_markup=keyboards.back_keyboard())
            else:
                if message.from_user.username is not None:
                    interaction.insert_into_favourites_table(message.from_user.username,link_fav51)
                else:
                    interaction.insert_into_favourites_table(str(message.from_user.id), link_fav51)
            SetState(message, 0)

        elif states.GetState(message) == 52:
            link_fav52 = message.text
            # удалить из избранного
            bot.send_message(message.chat.id, "Ссылка удалена из избранного",
                             reply_markup=keyboards.back_keyboard())
            SetState(message, 0)

        else:
            bot.send_message(message.chat.id, "Возникла ошибка.")
            SetState(message, 0)

    else:
        if GetState(message) == 71:
            try:
                username71 = message.text #TODO ошибка с админкой
                if interaction.get_user_admin(username71) is None \
                        and interaction.get_user(username71) is not None:
                    interaction.insert_into_admins_table(username71)
                    bot.send_message(message.chat.id, "Новый администратор добавлен",
                                     reply_markup=keyboards.back_keyboard())
                else:
                    bot.send_message(message.chat.id, "Добавление не удалось. Возможно, такого пользователя не "
                                                      "существует, или он уже является администратором",
                                     reply_markup=keyboards.back_keyboard())
            except:
                pass
            SetState(message, 0)

        elif GetState(message) == 72:
            try:
                username72 = message.text
                interaction.delete_from_admins_table(username72)
                bot.send_message(message.chat.id, "Администратор удален", reply_markup=keyboards.back_keyboard())
            except:
                pass
            SetState(message, 0)

        else:
            bot.send_message(message.chat.id, "Возникла ошибка. Была введена неизвестная команда или неверная ссылка"
                                              "\nНапишите /help")
            SetState(message, 0)
Exemplo n.º 25
0
def back_handler(message):
    bot.send_message(message.chat.id,
                     'Main Menu',
                     reply_markup=main_keyboard())
Exemplo n.º 26
0
bot = telebot.TeleBot(TOKEN)


@bot.message_handler(commands=['start'])
def send_welcome(message):
    add_user(message)
    users_massive = get_user_massives()
    bot.send_message(message.chat.id,
                     f'Приветствую тебя, {message.from_user.first_name}!\n'
                     'С моей помощью, ты сможешь следить за фазами Луны,\n'
                     'Для начала работы, выберите МЕНЮ.\n',
                     reply_markup=keyboard)


keyboard = main_keyboard()


@bot.message_handler(content_types=['text'])
def send_answer(message: Message):
    text = message.text
    if text == '❓ Луна сегодня':
        bot.send_message(message.chat.id,
                         '🌖 Сегодня убывающая луна',
                         reply_markup=keyboard)
    elif text == '▶️ В этом месяце':
        bot.send_message(message.chat.id, this_month, reply_markup=keyboard)
    elif text == '⏩ В следующем месяце':
        bot.send_message(message.chat.id, next_m, reply_markup=keyboard)
    elif message.text == 'Статистика':
        answer = read_user_set()