async def process_waypoints(message: types.Message, state: FSMContext):
    content = message.text
    user_data = await state.get_data()

    if content == 'skip':
        # Finishing adding waypoints
        waypoints_str = ' through <b>{}</b>'.format(", ".join(
            user_data['waypoints'])) if user_data['waypoints'] else ''

        await message.answer(messages.CONFIRMATION_MESSAGE.format(
            user_data['mode'], user_data['origin'], user_data['destination'],
            waypoints_str),
                             reply_markup=keyboard.create_keyboard(
                                 keyboard.PATHFINDER_BUTTONS['start']),
                             parse_mode='HTML')

        await UserStates.CONFIRMATION.set()

    else:
        # Adding waypoint
        user_data['waypoints'].append(process_location(message))
        await state.update_data(waypoints=user_data['waypoints'])
        await message.answer(messages.WAYPOINT_REQUEST_MESSAGE,
                             reply_markup=keyboard.create_keyboard(
                                 keyboard.PATHFINDER_BUTTONS['waypoint'],
                                 row_len=2),
                             parse_mode='HTML')
async def process_restart(message: types.Message, state: FSMContext):
    """
    Finish navigation processing
    """
    content = message.text

    if content == 'finish':
        # Finish pathfinder and go to main
        await state.update_data(**config.DEFAULT_GEO_DATA)
        await message.answer(messages.FINISH_MESSAGE,
                             reply_markup=keyboard.create_keyboard(
                                 keyboard.COMMANDS, one_time_keyboard=False),
                             parse_mode='HTML')
        await UserStates.START.set()

    elif content == 'restart':
        # Start pathfinder from beginning
        await message.answer(messages.RESTART_MESSAGE, parse_mode='HTML')
        await state.update_data(step=0)

        await message.answer(messages.reply_message(await state.get_data()),
                             reply_markup=keyboard.create_keyboard(
                                 keyboard.PATHFINDER_BUTTONS['navigation']),
                             parse_mode='HTML')
        await UserStates.BUILDING.set()
async def process_confirmation(message: types.Message, state: FSMContext):
    """
    Confirmation processing
    """
    user_data = await state.get_data()

    payload_maps = {
        'origin':
        user_data['origin'],
        'destination':
        user_data['destination'],
        'mode':
        user_data['mode'],
        'waypoints':
        '|'.join(user_data['waypoints']),
        'units':
        user_data['units'],
        'avoid':
        '|'.join(messages.multi_selection_setting_format(user_data, 'avoid')),
        'traffic_model':
        user_data['traffic_model'],
        'transit_mode':
        '|'.join(
            messages.multi_selection_setting_format(user_data,
                                                    'transit_mode')),
        'departure_time':
        user_data['departure_time'],
        'transit_routing_preference':
        user_data['transit_routing_preference'],
        'key':
        config.GMAPS_TOKEN
    }
    # Getting google maps data
    gmaps_data = requests.get(config.GMAPS_DIRECTIONS_URL,
                              params=payload_maps).json()

    if gmaps_data['status'] != 'OK':
        # Path not found
        await message.answer(messages.NOT_FOUND_MESSAGE,
                             reply_markup=keyboard.create_keyboard(
                                 keyboard.COMMANDS, one_time_keyboard=False),
                             parse_mode='HTML')
        await UserStates.START.set()

    else:
        # Path found
        await state.update_data(directions=functools.reduce(
            operator.iconcat,
            [leg["steps"] for leg in gmaps_data["routes"][0]["legs"]], []))
        await message.answer(messages.reply_message(await state.get_data()),
                             reply_markup=keyboard.create_keyboard(
                                 keyboard.PATHFINDER_BUTTONS['navigation']),
                             parse_mode='HTML')
        await UserStates.BUILDING.set()
async def process_cancel(message: types.Message, state: FSMContext):
    await state.update_data(**config.DEFAULT_GEO_DATA)
    await message.answer(messages.CANCEL_MESSAGE,
                         reply_markup=keyboard.create_keyboard(
                             keyboard.COMMANDS, one_time_keyboard=False),
                         parse_mode='HTML')
    await UserStates.START.set()
async def process_multi_selection(message: types.Message, state: FSMContext,
                                  parameter_name):
    """
    Changing multiple selection (e.g. avoidance) parameter
    :param message: incoming message
    :param state: current state context
    :param parameter_name: parameter name to be changed
    """
    content = message.text
    user_data = await state.get_data()
    if content == 'back':
        await process_selection_back(message, state)
    else:
        user_data[parameter_name][
            content] = not user_data[parameter_name][content]
        await state.update_data(**{parameter_name: user_data[parameter_name]})

        selected = messages.multi_selection_setting_format(
            user_data, parameter_name)

        await message.answer(messages.CHANGED_PARAMETER_MESSAGE.format(
            parameters.PARAMETER_NAMES[parameter_name], ', '.join(selected)),
                             reply_markup=keyboard.create_keyboard(
                                 keyboard.OPTION_BUTTONS[parameter_name],
                                 one_time_keyboard=False,
                                 row_len=3),
                             parse_mode='HTML')
Beispiel #6
0
def handle_asking_tutorial(user, text):
    if text.lower() == 'да':
        return handle_tutorial(user, text)
    elif text.lower() == 'нет':
        user.action = ACTION.Empty
        return 'Ну ладно. Посмотри /help для ознакомления с командами', False
    return 'Я тебя не понял. Cкажи НЕТ если не хочешь :)', kb.create_keyboard(
        'Да', 'Нет')
async def process_go_command(message: types.Message):
    """
    Go command processing
    """
    await message.answer(messages.ORIGIN_REQUEST_MESSAGE,
                         reply_markup=keyboard.create_keyboard(
                             keyboard.PATHFINDER_BUTTONS['cancel'],
                             one_time_keyboard=False),
                         parse_mode='HTML')
    await UserStates.SET_ORIGIN.set()
async def process_transport_command(message: types.Message, state: FSMContext):
    """
    Setting travel mode command processing
    """
    user_data = await state.get_data()
    await message.answer(
        messages.TRAVEL_MODE_MESSAGE.format(user_data['mode']),
        reply_markup=keyboard.create_keyboard(keyboard.OPTION_BUTTONS['mode']),
        parse_mode='HTML')
    await UserStates.TRAVEL_MODE.set()
async def process_start_command(message: types.Message, state: FSMContext):
    """
    Start command processing: set start state and send welcome message
    """
    await UserStates.START.set()
    await state.update_data(**config.DEFAULT_USER_DATA)
    await message.answer(messages.WELCOME_MESSAGE,
                         reply_markup=keyboard.create_keyboard(
                             keyboard.COMMANDS, one_time_keyboard=False),
                         parse_mode='HTML')
async def process_selection_back(message: types.Message, state: FSMContext):
    user_data = await state.get_data()

    await message.answer(messages.reply_current_options(user_data),
                         reply_markup=keyboard.create_keyboard(
                             keyboard.OPTION_BUTTONS['options'],
                             one_time_keyboard=False,
                             row_len=3),
                         parse_mode='HTML')
    await UserStates.OPTIONS.set()
Beispiel #11
0
async def generate_button(header, message: types.Message):
    subheaders = header.subheaders
    if len(subheaders) > 0:
        stack_store.clear()
        stack_store.extend(subheaders)
        keyboard = kb.create_keyboard(subheaders)
        await message.reply("Выберите из перечня нужный раздел", reply_markup=keyboard)
    else:
        action_list.pop()
        await bot.send_message(message.from_user.id,
                               "Ссылки, содержащиеся в %s:\n %s" % (header.get_name(), header.links))
async def process_options_command(message: types.Message, state: FSMContext):
    """
    Options command processing
    """
    user_data = await state.get_data()

    await message.answer(messages.reply_current_options(user_data),
                         reply_markup=keyboard.create_keyboard(
                             keyboard.OPTION_BUTTONS['options'], row_len=3),
                         parse_mode='HTML')
    await UserStates.OPTIONS.set()
async def process_path(message: types.Message, state: FSMContext):
    """
    Path processing
    """
    content = message.text
    user_data = await state.get_data()
    steps_number = len(user_data['directions'])

    if content == 'target location image':
        # Getting target location image
        await message.answer_photo(
            messages.reply_image(await state.get_data()),
            reply_markup=keyboard.create_keyboard(
                keyboard.PATHFINDER_BUTTONS['navigation']),
            parse_mode='HTML')
    else:
        if content == 'next':
            # Next step
            await state.update_data(step=user_data['step'] + 1)
        elif content == 'previous' and user_data['step'] > 0:
            # Previous step
            await state.update_data(step=user_data['step'] - 1)

        user_data = await state.get_data()

        if user_data['step'] >= steps_number:
            # Destination reached
            await message.answer(messages.REACH_MESSAGE,
                                 reply_markup=keyboard.create_keyboard(
                                     keyboard.PATHFINDER_BUTTONS['finish']),
                                 parse_mode='HTML')
            await UserStates.FINISH.set()

        else:
            # Still going
            await message.answer(
                messages.reply_message(await state.get_data()),
                reply_markup=keyboard.create_keyboard(
                    keyboard.PATHFINDER_BUTTONS['navigation']),
                parse_mode='HTML')
async def process_destination(message: types.Message, state: FSMContext):
    """
    Setting destination point processing
    """

    await state.update_data(destination=process_location(message))

    await message.answer(messages.WAYPOINT_REQUEST_MESSAGE,
                         reply_markup=keyboard.create_keyboard(
                             keyboard.PATHFINDER_BUTTONS['waypoint'],
                             row_len=1),
                         parse_mode='HTML')
    await UserStates.SET_WAYPOINTS.set()
Beispiel #15
0
def search(update: Update, context: CallbackContext):
    message = update.message.text
    serials = sub_service.search_serial(message)
    if len(serials) == 0:
        update.message.reply_text("Nothing not found...")
    else:
        context.user_data["SERIALS"] = serials
        context.user_data["STATE"] = Step.SELECT_SERIAL
        buttons = buttons_from_serials(serials)
        keyboard_markup = create_keyboard(buttons)
        update.message.reply_text('Select serial:',
                                  reply_markup=keyboard_markup)
    context.bot.delete_message(update.message.chat.id,
                               update.message.message_id)
async def process_origin(message: types.Message, state: FSMContext):
    """
    Setting origin point processing
    """

    await state.update_data(origin=process_location(message))

    await message.answer(messages.DESTINATION_REQUEST_MESSAGE,
                         reply_markup=keyboard.create_keyboard(
                             keyboard.PATHFINDER_BUTTONS['cancel'],
                             one_time_keyboard=False),
                         parse_mode='HTML')

    await UserStates.SET_DESTINATION.set()
async def process_transport_selection(message: types.Message,
                                      state: FSMContext):
    """
    Setting travel mode input processing
    """
    await process_selection(message=message,
                            state=state,
                            parameter_name='mode')
    await message.answer(messages.WAITING_MESSAGE,
                         reply_markup=keyboard.create_keyboard(
                             keyboard.COMMANDS,
                             one_time_keyboard=False,
                             row_len=2),
                         parse_mode='HTML')
    await UserStates.START.set()
Beispiel #18
0
"""Copyright 2020 Alex Malkhasov, Nikita Vronski, Vadim Kholodilo
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE."""

import keyboard
yes_no = keyboard.create_keyboard(buttons={
    '0': 'Нет',
    '1': 'Да'
},
                                  num_buttons_per_row=2)
gender_selector = keyboard.create_keyboard(buttons={
    '0': 'Женский',
    '1': 'Мужской'
},
                                           num_buttons_per_row=2)
range_selector = keyboard.create_keyboard(buttons={
    '0': '0',
    '1': '1',
    '2': '2',
    '3': '3',
    '4': '4',
    '5': '5',
    '6': '6',
    '7': '7',
    '8': '8',
    '9': '9',
    '10': '10'
},
Beispiel #19
0
def button(update: Update, context: CallbackContext):
    bot = context.bot
    query = update.callback_query
    data = query.data
    chat_id = query.message.chat.id

    if data == 'export_event':
        print("Export calling...")

    if data == 'edit_event':
        print("Edit calling...")

    if context.user_data["STATE"] != Step.NEW:
        if context.user_data["STATE"] == Step.SELECT_SERIAL:
            context.user_data["SERIAL"] = context.user_data["SERIALS"][int(
                data)]
            context.user_data["STATE"] = Step.SELECT_SEASON
            serial = context.user_data["SERIAL"]
            buttons = buttons_from_seasons(serial.seasons)
            keyboard_markup = create_keyboard(buttons)
            message = "Select season:"
        else:
            if context.user_data["STATE"] == Step.SELECT_SEASON:
                season = context.user_data["SERIAL"].seasons[int(data)]
                context.user_data["SEASON_NUMBER"] = data
                context.user_data["SEASON"] = season
                context.user_data["STATE"] = Step.SELECT_EPISODE

                buttons = buttons_from_episodes(season.episodes)
                keyboard_markup = create_keyboard(buttons)
                message = "Select episode:"
            else:
                if context.user_data["STATE"] == Step.SELECT_EPISODE:
                    season = context.user_data["SEASON"]
                    episode = season.episodes[int(data)]
                    context.user_data["EPISODE"] = episode
                    context.user_data["STATE"] = Step.GET_WORDS
                    season_number = str(season.title).lower().replace(
                        "season ", "")
                    serial = context.user_data["SERIAL"]
                    subtitle = sub_service.get_subtitle(
                        serial.id, serial.title, season_number, episode.number)
                    print(subtitle)
                    sub_text = sub_service.get_subtitle_text(subtitle)
                    if len(sub_text) != 0:
                        buttons = buttons_for_footer()
                        keyboard_markup = create_keyboard(buttons)
                        user = User(chat_id)
                        dictionary = DictionaryService(
                            config).create_user_dictionary(sub_text, user)
                        message = f"You select {serial.title} {context.user_data['SEASON'].title} episode {episode.number}, words count: {len(dictionary)}"
                        text = str()
                        for i, line in enumerate(dictionary):
                            if i % 150 == 0 and i > 0:
                                bot.send_message(chat_id, text)
                                text = line + "\r\n"
                            else:
                                text += line + "\r\n"
                        bot.send_message(chat_id, text)
                    else:
                        keyboard_markup = None
                        message = "Sorry, subtitles is empty..."
                else:
                    keyboard_markup = None
                    message = "Sorry, please repeat your search..."
        query.answer()
        query.edit_message_text(text=message, reply_markup=keyboard_markup)
Beispiel #20
0
def handle_empty(user, text: str):
    answer, keyboard = False, False
    if text is None:
        return "Я могу отвечать только на текст.", False

    elif is_command(text, '/start'):
        answer = 'Привет! Я снова живу!\n\n' \
                 '/help для списка команд\n' \
                 'Я создан что бы помочь тебе следить за твоими средствами.\n' \
                 f'Хочешь начать с обучения, {user.name}?'
        user.action = ACTION.AskingTutorial
        return answer, kb.create_keyboard('Да', 'Нет')
    elif is_command(text, '/tutorial'):
        return handle_tutorial(user, text)
    elif is_command(text, '/total'):
        records = journal.show(user)
        if len(records):
            filename = f"{IMAGE_PATH}/{user.id}-total.png"
            draw.drawCircle(filename,
                            datetime.datetime.now().strftime("%B"), records)
            file_info = tel.InputFileInfo(filename, open(filename, "rb"),
                                          "image/png")
            return tel.InputFile("photo", file_info), False
        else:
            return "Слишком мало данных для статистики", False
    elif is_command(text, '/balance'):
        answer = 'Текущий баланс %d%s\n' % (user.balance, user.currency)

    elif is_command(text, '/setbalance'):
        user.action = ACTION.Balance
        answer = 'Текущий баланс - %d%s.\n/setbalance для отмены.\nВведите новое значение - ' \
                 % (user.balance, user.currency)
    elif is_command(text, '/history'):
        answer = journal.get_history(user)
        return answer, False
    elif is_command(text, '/stats'):
        records = journal.show(user)
        if len(records):
            filename = f"{IMAGE_PATH}/{user.id}-stats.png"
            draw.drawLines(filename,
                           datetime.datetime.now().strftime("%B"), records)
            file_info = tel.InputFileInfo(filename, open(filename, "rb"),
                                          "image/png")
            return tel.InputFile("photo", file_info), False
        else:
            return "Слишком мало данных для статистики", False
    elif is_command(text, '/cancel'):
        user.action = ACTION.Empty
        journal.cancel_last_transaction(user)
        return "Последняя транзакция отменена.", False
    elif is_command(text, '/help'):
        return '''
        Введите любое число, чтобы начать транзакцию.
        /start - начни обучение здесь
        /setbalance - установить баланс
        /total - показать суммарный баланс за месяц
        /history - показать историю транзакций
        /balance - проверить баланс
        /stats - показать статистику за месяц
        /cancel - отмена операции
        /tutorial - начать обучение
        /help - подсказка
        /f - [debug] установить демо транзакции (стирает ваши транзакции, осторожно!)
        ''', False
    elif is_command(text, '/f'):
        journal.fill(user)
        answer = "Готово"
    elif is_command(text, '/save'):
        from storage import save_pool
        save_pool(journal.pool)
        from users import User
        User.save()
        return 'Сохранил', False
    else:
        value = get_number(text, user)
        if value < 0 or value > VERY_BIG_NUMBER:
            return "Введите положительное разумное число!", False

        if value:
            answer = 'На что ты потратил %d%s?\nЕсли это заработанные средства - Жми "➕Доход"' % (
                value, user.currency)
            keyboard = kb.create_keyboard_with_tags(journal.get_tags(user))
            user.action = ACTION.Spend
            user.value = value
    return answer, keyboard
Beispiel #21
0
def monitor_msg(vk_session, session_api, members):
    longpoll = VkLongPoll(vk_session)
    # users_not_msg = 0
    while True:
        try:
            for event in longpoll.listen():
                # Вывод сообщение по ивенту: НОВОЕ СООБЩЕНИЕ
                if event.type == VkEventType.MESSAGE_NEW:
                    print("Время сообщения: " + str(event.datetime))
                    print("Сообщение: " + str(event.text))
                    # Преобразование всего текста в нижний регистр
                    response = event.text.lower()
                    # Присоеденение к БД
                    # 0 - участник группы
                    # 1 - админ группы
                    # 2 - админ админов группы
                    if event.from_user and not event.from_me:
                        db = sqlite3.connect('server.db')
                        sql = db.cursor()
                        dataCopy = sql.execute(
                            f"SELECT permession  FROM users WHERE idlogin = '******' AND permession = '{1}'"
                        )
                        if dataCopy.fetchone() is None:
                            values = 0
                        else:
                            values = 1
                        db.close()
                        if event.user_id == my_id:
                            values = 2
                        new_keyboard = keyboard.create_keyboard(
                            response, values)
                        # Если нажимают: "1"
                        if (response == 'рассылка') and (values == 1
                                                         or values == 2):
                            print("Ввели команду: рассылка")
                            with open("buff_text\Инструкция.txt",
                                      'r',
                                      encoding="utf-8") as f:
                                message_main = f.read()
                            send_message(vk_session,
                                         id_type='user_id',
                                         id_user=event.user_id,
                                         message=f"{message_main}",
                                         keyboard=new_keyboard,
                                         attachment=None)
                        elif response == 'начать' or response == 'вернуться назад':
                            with open("buff_text\Приветствие.txt",
                                      'r',
                                      encoding="utf-8") as f:
                                message_main = f.read()
                            with open("buff_text\hello_for_users.txt",
                                      'r',
                                      encoding="utf-8") as f:
                                hello_users = f.read()
                            name = session_api.users.get(
                                user_ids=event.user_id)[0]["first_name"]
                            print("Ввели команду: начать")
                            if values == 1 or values == 2:
                                send_message(
                                    vk_session,
                                    id_type='user_id',
                                    id_user=event.user_id,
                                    message=
                                    f"Привет, {name}! &#128127; {message_main}",
                                    keyboard=new_keyboard,
                                    attachment=None)
                            else:
                                send_message(
                                    vk_session,
                                    id_type='user_id',
                                    id_user=event.user_id,
                                    message=f"Привет, {name}! {hello_users}",
                                    keyboard=new_keyboard,
                                    attachment=None)
                        elif response == 'о нас':
                            print("Ввели команду: о нас")
                            text_final = open("buff_text\аbout_text.txt",
                                              'r',
                                              encoding="utf-8")
                            attach_final = open("buff_text\аbout_attach.txt",
                                                'r',
                                                encoding="utf-8")
                            send_text_final = text_final.read()
                            send_attach_final = attach_final.read()
                            text_final.close()
                            attach_final.close()
                            send_message(vk_session,
                                         id_type='user_id',
                                         id_user=event.user_id,
                                         message=f"{send_text_final}",
                                         keyboard=None,
                                         attachment=f"{send_attach_final}")
                        elif response == 'закрыть клавиатуру':
                            print("Ввели команду: закрыть клавиатуру")
                            send_message(vk_session,
                                         id_type='user_id',
                                         id_user=event.user_id,
                                         message="Вы закрыли клавиатуру",
                                         keyboard=new_keyboard,
                                         attachment=None)
                        elif (response
                              == 'создать рассылку') and (values == 1
                                                          or values == 2):
                            print("Ввели команду: создать рассылку")
                            send_message(
                                vk_session,
                                id_type='user_id',
                                id_user=event.user_id,
                                message=
                                "Введите сообщение и прекрипите вложение!",
                                keyboard=None,
                                attachment=None)
                            text_send_in = open('buff_text\Текст рассылки.txt',
                                                'w',
                                                encoding='utf-8')
                            attach_send_in = open(
                                'buff_text\Вложение рассылки.txt',
                                'w',
                                encoding='utf-8')
                            text_send_in.truncate()
                            attach_send_in.truncate()
                        elif (response
                              == 'отправить рассылку') and (values == 1
                                                            or values == 2):
                            text_final = open("buff_text\Текст рассылки.txt",
                                              'r',
                                              encoding="utf-8")
                            attach_final = open(
                                "buff_text\Вложение рассылки.txt",
                                'r',
                                encoding="utf-8")
                            send_text_final = text_final.read()
                            send_attach_final = attach_final.read()
                            text_final.close()
                            attach_final.close()
                            print("Список id участников группы: " +
                                  str(members))
                            print("Сообщение доставляется: " +
                                  str(len(members)) + " пользовтелям...")
                            # Цикл в котором будет происходить рассылка сообщения участникам группы
                            # Кол-во участников регулируется переменной count_users_items
                            for i in range(len(members)):
                                # users_not_msg += 1
                                # Блок try catch, если по каким то причинам невозможна отправка сообщения участнику,
                                # то добавляем к итератору 1 и продолжаем цикл for
                                try:
                                    send_message(
                                        vk_session,
                                        id_type='user_id',
                                        id_user=members[i],
                                        message=f"{send_text_final}",
                                        keyboard=None,
                                        attachment=f"{str(send_attach_final)}")
                                except vk_api.exceptions.ApiError:
                                    i += 1
                                    print(
                                        "Пользователю не отправилось сообщение!"
                                    )
                                    continue
                        elif (response
                              == 'посмотреть рассылку') and (values == 1
                                                             or values == 2):
                            print("Ввели команду: посмотреть рассылку")
                            text_final = open("buff_text\Текст рассылки.txt",
                                              'r',
                                              encoding="utf-8")
                            attach_final = open(
                                "buff_text\Вложение рассылки.txt",
                                'r',
                                encoding="utf-8")
                            send_text_final = text_final.read()
                            send_attach_final = attach_final.read()
                            send_message(
                                vk_session,
                                id_type='user_id',
                                id_user=event.user_id,
                                message=
                                f"Обычная рассылка сообщений пользователям выглядит таким образом: \n\n\n {send_text_final}",
                                keyboard=None,
                                attachment=f"{send_attach_final}")
                        elif (response
                              == 'управление админами') and (values == 1
                                                             or values == 2):
                            print("Ввели команду: управление админами")
                            with open("buff_text\control_admin.txt",
                                      'r',
                                      encoding="utf-8") as f:
                                message_main = f.read()
                            send_message(vk_session,
                                         id_type='user_id',
                                         id_user=event.user_id,
                                         message=f"{message_main}",
                                         keyboard=new_keyboard,
                                         attachment=None)
                            text_final = open("buff_text\Текст рассылки.txt",
                                              'w',
                                              encoding="utf-8")
                            text_final.truncate()
                        elif (response == 'список админов') and (values == 1 or
                                                                 values == 2):
                            print("Ввели команду: список админов")
                            db = sqlite3.connect('server.db')
                            sql = db.cursor()
                            dataCount = sql.execute(
                                f"SELECT COUNT(idlogin)  FROM users WHERE permession = '{1}' OR permession = '{2}'"
                            )
                            numberOfRows = dataCount.fetchone()[0]
                            # reg = re.compile('[^a-zA-Z ]')
                            dataCopy = sql.execute(
                                f"SELECT idlogin  FROM users WHERE permession = '{1}' OR permession = '{2}'"
                            )
                            values = dataCopy.fetchmany(size=numberOfRows)
                            print("Кол во:" + str(numberOfRows))
                            print(type(values))
                            for i in range(0, numberOfRows):
                                send_message(
                                    vk_session,
                                    id_type='user_id',
                                    id_user=event.user_id,
                                    message=f"Админ группы: id{values[i]}",
                                    keyboard=None,
                                    attachment=None)
                            text_final = open("buff_text\Текст рассылки.txt",
                                              'w',
                                              encoding="utf-8")
                            text_final.truncate()
                        elif (response == 'добавить админа') and (values == 2):
                            print("Ввели команду: добавить админа")
                            send_message(
                                vk_session,
                                id_type='user_id',
                                id_user=event.user_id,
                                message=
                                f"Для того, чтобы добавить/удалить админа введите его id в формате: "
                                f"111111111 и отправьте его боту.\n А затем нажмите на кнопку "
                                f"сохранить добавление/удаление.",
                                keyboard=None,
                                attachment=None)
                            text_final = open("buff_text\id админа.txt",
                                              'w',
                                              encoding="utf-8")
                            text_final.truncate()
                        elif (response == 'удалить админа') and (values == 2):
                            print("Ввели команду: удалить админа")
                            send_message(
                                vk_session,
                                id_type='user_id',
                                id_user=event.user_id,
                                message=
                                f"Для того, чтобы добавить/удалить админа введите его id в формате: "
                                f"111111111 и отправьте его боту.\n А затем нажмите на кнопку "
                                f"сохранить добавление/удаление.",
                                keyboard=None,
                                attachment=None)
                            text_final = open("buff_text\id админа.txt",
                                              'w',
                                              encoding="utf-8")
                            text_final.truncate()
                        elif response == 'узнать id':
                            print("Ввели команду: узнать свой id")
                            send_message(vk_session,
                                         id_type='user_id',
                                         id_user=event.user_id,
                                         message=f"Ваш id: {event.user_id}",
                                         keyboard=None,
                                         attachment=None)
                        elif response == 'сохранить добавление':
                            print("Ввели команду: Сохранить добавление")
                            text_final = open("buff_text\id админа.txt",
                                              'r',
                                              encoding="utf-8")
                            send_text_final = text_final.read()
                            text_final.close()
                            db = sqlite3.connect('server.db')
                            sql = db.cursor()
                            sql.execute(
                                f'UPDATE users SET permession = {1} WHERE idlogin = "******"'
                            )
                            db.commit()
                            db.close()
                            send_message(vk_session,
                                         id_type='user_id',
                                         id_user=event.user_id,
                                         message=f"Права обновлены!",
                                         keyboard=None,
                                         attachment=None)
                            text_final = open("buff_text\id админа.txt",
                                              'w',
                                              encoding="utf-8")
                            text_final.truncate()
                        elif response == 'сохранить удаление':
                            print("Ввели команду: Сохранить удаление")
                            text_final = open("buff_text\id админа.txt",
                                              'r',
                                              encoding="utf-8")
                            send_text_final = text_final.read()
                            text_final.close()
                            db = sqlite3.connect('server.db')
                            sql = db.cursor()
                            sql.execute(
                                f'UPDATE users SET permession = {0} WHERE idlogin = "******"'
                            )
                            db.commit()
                            db.close()
                            send_message(vk_session,
                                         id_type='user_id',
                                         id_user=event.user_id,
                                         message=f"Права обновлены!",
                                         keyboard=None,
                                         attachment=None)
                            text_final = open("buff_text\id админа.txt",
                                              'w',
                                              encoding="utf-8")
                            text_final.truncate()
                        elif (response == 'рассылкаопрос') and (values == 1 or
                                                                values == 2):
                            print("Ввели команду: рассылкаопрос")
                            with open("buff_text\poll_msg.txt",
                                      'r',
                                      encoding="utf-8") as f:
                                message_main = f.read()
                            send_message(vk_session,
                                         id_type='user_id',
                                         id_user=event.user_id,
                                         message=f"{message_main}",
                                         keyboard=new_keyboard,
                                         attachment=None)
                        elif (response == 'посмотреть рассылку опроса') and (
                                values == 1 or values == 2):
                            print("Ввели команду: посмотреть рассылку")
                            text_final = open("buff_text\Текст опрос.txt",
                                              'r',
                                              encoding="utf-8")
                            attach_final = open("buff_text\Вложение опрос.txt",
                                                'r',
                                                encoding="utf-8")
                            send_text_final = text_final.read()
                            send_attach_final = attach_final.read()
                            send_message(
                                vk_session,
                                id_type='user_id',
                                id_user=event.user_id,
                                message=
                                f"Рассылка для проголосовавших в опросе выглядит таким образом: \n\n\n{send_text_final}",
                                keyboard=None,
                                attachment=f"{send_attach_final}")
                        elif (response
                              == 'создать сообщение') and (values == 1
                                                           or values == 2):
                            print("Ввели команду: создать сообщение")
                            send_message(
                                vk_session,
                                id_type='user_id',
                                id_user=event.user_id,
                                message=
                                f"Введите текст рассылки для проголосовавших в опросе и можете прикрепить "
                                f"вложения...",
                                keyboard=None,
                                attachment=None)
                            text_send_in = open('buff_text\Текст опрос.txt',
                                                'w',
                                                encoding='utf-8')
                            attach_send_in = open(
                                'buff_text\Вложение опрос.txt',
                                'w',
                                encoding='utf-8')
                            text_send_in.truncate()
                            attach_send_in.truncate()
                        elif (response
                              == 'сохранить сообщение') and (values == 1
                                                             or values == 2):
                            print("Ввели команду: сохранить сообщение")
                            send_message(
                                vk_session,
                                id_type='user_id',
                                id_user=event.user_id,
                                message=
                                f"Текст рассылки для опроса успешно сохранен!",
                                keyboard=None,
                                attachment=None)
                        elif (response
                              == 'создать id опроса') and (values == 1
                                                           or values == 2):
                            print("Ввели команду: создать id опроса")
                            send_message(
                                vk_session,
                                id_type='user_id',
                                id_user=event.user_id,
                                message=
                                f"Введите id опроса в формате: 111111111",
                                keyboard=None,
                                attachment=None)
                            text_send_in = open('buff_text\id опрос.txt',
                                                'w',
                                                encoding='utf-8')
                            text_send_in.truncate()
                        elif (response
                              == 'сохранить id опроса') and (values == 1
                                                             or values == 2):
                            print("Ввели команду: сохранить id опроса")
                            send_message(
                                vk_session,
                                id_type='user_id',
                                id_user=event.user_id,
                                message=f"Id опроса успешно сохранен!",
                                keyboard=None,
                                attachment=None)
                        elif (response == "создать о нас") and (values == 1 or
                                                                values == 2):
                            print("Ввели команду: создать о нас")
                            with open("buff_text\create_about.txt",
                                      'r',
                                      encoding="utf-8") as f:
                                message_main = f.read()
                            send_message(vk_session,
                                         id_type='user_id',
                                         id_user=event.user_id,
                                         message=f"{message_main}",
                                         keyboard=new_keyboard,
                                         attachment=None)
                        elif (response == 'создать текст') and (values == 1 or
                                                                values == 2):
                            print("Ввели команду: создать текст")
                            send_message(
                                vk_session,
                                id_type='user_id',
                                id_user=event.user_id,
                                message=
                                f"Введите текст и прекрепите вложение, а потом отправьте это "
                                f"сообщение боту. \n Затем, нажмите кнопку: сохранить текст",
                                keyboard=None,
                                attachment=None)
                            text_send_in = open('buff_text\аbout_text.txt',
                                                'w',
                                                encoding='utf-8')
                            attach_send_in = open('buff_text\аbout_attach.txt',
                                                  'w',
                                                  encoding='utf-8')
                            text_send_in.truncate()
                            attach_send_in.truncate()
                        elif (response
                              == 'сохранить текст') and (values == 1
                                                         or values == 2):
                            print("Ввели команду: сохранить текст")
                            send_message(
                                vk_session,
                                id_type='user_id',
                                id_user=event.user_id,
                                message=
                                f"Ваш текст сохранен! Проверьте кнопку: О нас",
                                keyboard=None,
                                attachment=None)
                        elif (response
                              == 'посмотреть о нас') and (values == 1
                                                          or values == 2):
                            print("Ввели команду: Посмотреть о нас")
                            text_send_in = open('buff_text\аbout_text.txt',
                                                'r',
                                                encoding='utf-8')
                            attach_send_in = open('buff_text\аbout_attach.txt',
                                                  'r',
                                                  encoding='utf-8')
                            send_text_final = text_send_in.read()
                            send_attach_final = attach_send_in.read()

                            send_message(
                                vk_session,
                                id_type='user_id',
                                id_user=event.user_id,
                                message=
                                f"Пункт меню О нас - выглядит таким образом: \n\n\n{send_text_final}",
                                keyboard=None,
                                attachment=f"{send_attach_final}")
                        elif values == 1 or values == 2:
                            msg_history = vk_session.method(
                                'messages.getHistory', {
                                    'offset': 2,
                                    'count': 1,
                                    'user_id': event.user_id,
                                    'group_id': vk_id_group
                                })
                            msg_text = msg_history["items"][0]["text"]
                            print("ОБРАТИ НА МЕНЯ ВНИМАНИЕ: " + str(msg_text))
                            if msg_text == 'создать рассылку' or msg_text == 'Создать рассылку':
                                buff_type = []
                                buff_id = []
                                for i in range(1, 10):
                                    try:
                                        id_attach = event.attachments["attach"
                                                                      + str(i)]
                                        buff_id.append(id_attach)
                                        type_attach = event.attachments[
                                            "attach" + str(i) + "_type"]
                                        buff_type.append(type_attach)
                                    except KeyError:
                                        pass
                                buff = []
                                for i in range(0, len(buff_type)):
                                    buff.append(
                                        str(buff_type[i]) + str(buff_id[i]))
                                final_buff = []
                                for items in buff:
                                    final_buff.append(items)
                                attach_list = ','.join(final_buff)
                                text_final = open(
                                    "buff_text\Текст рассылки.txt",
                                    'r+',
                                    encoding="utf-8")
                                attach_final = open(
                                    "buff_text\Вложение рассылки.txt",
                                    'r+',
                                    encoding="utf-8")
                                new_text_send = text_final.read()
                                new_attach_send = attach_final.read()
                                new_text_send = re.sub(new_text_send,
                                                       str(event.text),
                                                       new_text_send)
                                new_attach_send = re.sub(
                                    new_attach_send, str(attach_list),
                                    new_attach_send)
                                text_final.write(new_text_send)
                                attach_final.write(new_attach_send)
                                text_final.close()
                                attach_final.close()
                            elif msg_text == 'создать сообщение' or msg_text == 'Создать сообщение':
                                buff_type = []
                                buff_id = []
                                for i in range(1, 10):
                                    try:
                                        id_attach = event.attachments["attach"
                                                                      + str(i)]
                                        buff_id.append(id_attach)
                                        type_attach = event.attachments[
                                            "attach" + str(i) + "_type"]
                                        buff_type.append(type_attach)
                                    except KeyError:
                                        pass
                                buff = []
                                for i in range(0, len(buff_type)):
                                    buff.append(
                                        str(buff_type[i]) + str(buff_id[i]))
                                final_buff = []
                                for items in buff:
                                    final_buff.append(items)
                                attach_list = ','.join(final_buff)
                                text_final = open("buff_text\Текст опрос.txt",
                                                  'r+',
                                                  encoding="utf-8")
                                attach_final = open(
                                    "buff_text\Вложение опрос.txt",
                                    'r+',
                                    encoding="utf-8")
                                new_text_send = text_final.read()
                                new_attach_send = attach_final.read()
                                new_text_send = re.sub(new_text_send,
                                                       str(event.text),
                                                       new_text_send)
                                new_attach_send = re.sub(
                                    new_attach_send, str(attach_list),
                                    new_attach_send)
                                text_final.write(new_text_send)
                                attach_final.write(new_attach_send)
                                text_final.close()
                                attach_final.close()
                            elif msg_text == 'cоздать id опроса' or msg_text == 'Создать id опроса':
                                text_final = open("buff_text\id опрос.txt",
                                                  'r+',
                                                  encoding="utf-8")
                                new_text_send = text_final.read()
                                new_text_send = re.sub(new_text_send,
                                                       str(event.text),
                                                       new_text_send)
                                text_final.write(new_text_send)
                                text_final.close()
                            elif msg_text == 'добавить админа' or msg_text == 'Добавить админа':
                                text_final = open("buff_text\id админа.txt",
                                                  'r+',
                                                  encoding="utf-8")
                                new_text_send = text_final.read()
                                new_text_send = re.sub(new_text_send,
                                                       str(event.text),
                                                       new_text_send)
                                text_final.write(new_text_send)
                                text_final.close()
                            elif msg_text == 'удалить админа' or msg_text == 'Удалить админа':
                                text_final = open("buff_text\id админа.txt",
                                                  'r+',
                                                  encoding="utf-8")
                                new_text_send = text_final.read()
                                new_text_send = re.sub(new_text_send,
                                                       str(event.text),
                                                       new_text_send)
                                text_final.write(new_text_send)
                                text_final.close()
                            elif msg_text == 'cоздать текст' or msg_text == 'Создать текст':
                                buff_type = []
                                buff_id = []
                                for i in range(1, 10):
                                    try:
                                        id_attach = event.attachments["attach"
                                                                      + str(i)]
                                        buff_id.append(id_attach)
                                        type_attach = event.attachments[
                                            "attach" + str(i) + "_type"]
                                        buff_type.append(type_attach)
                                    except KeyError:
                                        pass
                                buff = []
                                for i in range(0, len(buff_type)):
                                    buff.append(
                                        str(buff_type[i]) + str(buff_id[i]))
                                final_buff = []
                                for items in buff:
                                    final_buff.append(items)
                                attach_list = ','.join(final_buff)
                                text_final = open("buff_text\аbout_text.txt",
                                                  'r+',
                                                  encoding="utf-8")
                                attach_final = open(
                                    "buff_text\аbout_attach.txt",
                                    'r+',
                                    encoding="utf-8")
                                new_text_send = text_final.read()
                                new_attach_send = attach_final.read()
                                new_text_send = re.sub(new_text_send,
                                                       str(event.text),
                                                       new_text_send)
                                new_attach_send = re.sub(
                                    new_attach_send, str(attach_list),
                                    new_attach_send)
                                text_final.write(new_text_send)
                                attach_final.write(new_attach_send)
                                text_final.close()
                                attach_final.close()
                            else:
                                print("Неопозннная команда...")
                                send_message(
                                    vk_session,
                                    id_type='user_id',
                                    id_user=event.user_id,
                                    message=
                                    f"Я тебя не понимаю. \nДля того, чтобы посмотреть мои команды введи: начать",
                                    keyboard=None,
                                    attachment=None)

        except Exception as error:
            print(error)
Beispiel #22
0
def main():
    updates = get_updates()["result"]
    if len(updates):
        first_update_id = updates[0]["update_id"]
        updates = get_updates(first_update_id)
        if len(updates["result"]):
            if "callback_query" in updates["result"][0]:
                data = updates["result"][0]["callback_query"]["data"]
                chat_id = int(updates["result"][0]["callback_query"]["message"]
                              ["chat"]["id"])
                session = sessionManager.get_session(chat_id)

                if session.step != Step.NEW:
                    if session.step == Step.SELECT_SERIAL:
                        serial = session.serials[int(data)]
                        sessionManager.update_session(chat_id,
                                                      Step.SELECT_SEASON,
                                                      serial=serial)
                        buttons = buttons_from_seasons(serial.seasons)
                        keyboard_markup = create_keyboard(buttons)
                        message = "Select season:"
                    else:
                        if session.step == Step.SELECT_SEASON:
                            season = session.serial.seasons[int(data)]
                            sessionManager.update_session(chat_id,
                                                          Step.SELECT_EPISODE,
                                                          season=season,
                                                          season_number=data)
                            buttons = buttons_from_episodes(season.episodes)
                            keyboard_markup = create_keyboard(buttons)
                            message = "Select episode:"
                        else:
                            if session.step == Step.SELECT_EPISODE:
                                episode = session.season.episodes[int(data)]
                                sessionManager.update_session(chat_id,
                                                              Step.GET_WORDS,
                                                              episode=episode)
                                subtitle = sub_service.get_subtitle(
                                    session.serial.id, session.serial.title,
                                    int(session.season_number) + 1,
                                    episode.number)
                                print(subtitle)
                                sub_text = sub_service.get_subtitle_text(
                                    subtitle)
                                if len(sub_text) != 0:
                                    dictionary = DictionaryService(
                                        config).create_dictionary(sub_text)
                                    keyboard_markup = None
                                    text = str()
                                    for i, line in enumerate(dictionary):
                                        if i % 100 == 0:
                                            send_message(
                                                chat_id, text, keyboard_markup)
                                            text = line + "\r\n"
                                        else:
                                            text += line + "\r\n"
                                    message = text
                                else:
                                    keyboard_markup = None
                                    message = "Sorry, subtitles is empty..."
                            else:
                                keyboard_markup = None
                                message = "Sorry, please repeat your search..."
                    send_message(chat_id, message, keyboard_markup)
            else:
                message = updates["result"][0]["message"]["text"]
                chat_id = int(updates["result"][0]["message"]["chat"]["id"])
                serials = sub_service.search_serial(message)
                if len(serials) == 0:
                    send_message(chat_id, "Nothing not found...")
                else:
                    sessionManager.update_session(chat_id, Step.SELECT_SERIAL,
                                                  serials, message)
                    buttons = buttons_from_serials(serials)
                    keyboard_markup = create_keyboard(buttons)
                    send_message(chat_id, "Select serial:", keyboard_markup)
            get_updates(first_update_id + 1)
async def process_options_selection(message: types.Message, state: FSMContext):
    """
    Options selection processing
    """
    content = message.text

    user_data = await state.get_data()

    if content == 'units':
        # Setting units
        await message.answer(messages.UNITS_MESSAGE.format(user_data['units']),
                             reply_markup=keyboard.create_keyboard(
                                 keyboard.OPTION_BUTTONS['units'], row_len=3),
                             parse_mode='HTML')
        await UserStates.SET_UNITS.set()

    elif content == 'avoid':
        # Setting avoidance
        selected = messages.multi_selection_setting_format(user_data, 'avoid')
        await message.answer(messages.AVOID_MESSAGE.format(
            ', '.join(selected)),
                             reply_markup=keyboard.create_keyboard(
                                 keyboard.OPTION_BUTTONS['avoid'],
                                 one_time_keyboard=False,
                                 row_len=3),
                             parse_mode='HTML')
        await UserStates.SET_AVOIDANCE.set()

    elif content == 'traffic model':
        # Setting traffic model
        await message.answer(messages.TRAFFIC_MODEL_MESSAGE.format(
            user_data['traffic_model']),
                             reply_markup=keyboard.create_keyboard(
                                 keyboard.OPTION_BUTTONS['traffic_model'],
                                 row_len=3),
                             parse_mode='HTML')
        await UserStates.SET_TRAFFIC_MODEL.set()

    elif content == 'transit mode':
        # Setting transit mode
        selected = messages.multi_selection_setting_format(
            user_data, 'transit_mode')
        await message.answer(messages.TRANSIT_MODE_MESSAGE.format(
            ', '.join(selected)),
                             reply_markup=keyboard.create_keyboard(
                                 keyboard.OPTION_BUTTONS['transit_mode'],
                                 one_time_keyboard=False,
                                 row_len=3),
                             parse_mode='HTML')
        await UserStates.SET_TRANSIT_MODE.set()

    elif content == 'transit routing preference':
        # Setting transit routing preference
        await message.answer(
            messages.TRANSIT_ROUTING_MESSAGE.format(
                user_data['transit_routing_preference']),
            reply_markup=keyboard.create_keyboard(
                keyboard.OPTION_BUTTONS['transit_routing_preference'],
                row_len=3),
            parse_mode='HTML')
        await UserStates.SET_TRANSIT_ROUTING.set()

    elif content == 'back':
        # Return to main menu
        await message.answer(messages.WAITING_MESSAGE,
                             reply_markup=keyboard.create_keyboard(
                                 keyboard.COMMANDS, one_time_keyboard=False),
                             parse_mode='HTML')
        await UserStates.START.set()