示例#1
0
def create_type_of_question_markup(vale_name, false):
    type_of_question_markup = InlineKeyboardMarkup()
    types = db_request(vale_name, False)
    for typeQ in types:
        type_of_question_markup.add(InlineKeyboardButton(typeQ['type_name'],
                                 callback_data='type_name_'+typeQ['type_name']))
    return type_of_question_markup
示例#2
0
async def sum_handler(call: types.CallbackQuery):
    """Ask for sum currency."""
    order = await database.creation.find_one_and_update(
        {"user_id": call.from_user.id}, {"$unset": {
            "price_currency": True
        }})

    if not order:
        await call.answer(i18n("no_creation"))
        return True

    keyboard = InlineKeyboardMarkup()
    keyboard.add(
        InlineKeyboardButton(order["buy"], callback_data="sum buy"),
        InlineKeyboardButton(order["sell"], callback_data="sum sell"),
    )
    for row in await inline_control_buttons():
        keyboard.row(*row)

    await tg.edit_message_text(
        i18n("ask_sum_currency"),
        call.message.chat.id,
        call.message.message_id,
        reply_markup=keyboard,
    )
def add_reminder_markup():
    markup = InlineKeyboardMarkup()
    markup.row_width = 1
    markup.one_time_keyboard=True
    markup.add(InlineKeyboardButton("Добавити повторююче нагадування", callback_data="add_reminder_simple"),
                InlineKeyboardButton("Добавити повторююче нагадування з данними", callback_data="add_reminder_with_bd"))
    return markup
示例#4
0
async def additional_information(query: callback_query, state: FSMContext):
    keyboard = InlineKeyboardMarkup()
    keyboard.add(
        InlineKeyboardButton(buttons.back,
                             callback_data='additional_information_back'))
    await query.message.answer(messages.additional_information,
                               reply_markup=keyboard)
示例#5
0
def build_vacancies_buttons(vacancies):
    kb_full = InlineKeyboardMarkup(row_width=1)
    keys_list = (
        KeyboardButton(vacancy['title'], url=vacancy['url']) for vacancy in vacancies
    )
    kb_full.add(*keys_list)
    return kb_full
示例#6
0
async def ans_1(callback: CallbackQuery, state: FSMContext):
    markup = InlineKeyboardMarkup()
    yes_butt = InlineKeyboardButton('Да', callback_data='да')
    no_butt = InlineKeyboardButton('Нет', callback_data='нет')
    markup.add(yes_butt, no_butt)
    await callback.message.answer(text="Запрос 1", reply_markup=markup)
    await UserState.next()
示例#7
0
async def vacancy_specialization_handler(message: types.Message,
                                         state: FSMContext):
    await state.update_data(specialization=message.text)
    await VacancyState.next()
    keyboard = InlineKeyboardMarkup()
    keyboard.add(InlineKeyboardButton(buttons.menu, callback_data='menu'))
    await message.answer(messages.enter_description, reply_markup=keyboard)
示例#8
0
async def support_keyboard(messages, user_id=None):
    if user_id:
        contact_id = int(user_id)
        as_user = "******"
        text = "Ответить пользователю"
    else:
        contact_id = get_support_manager()
        as_user = "******"
        if messages == "many" and contact_id is None:
            return False
        elif messages == "one" and contact_id is None:
            contact_id = random.choice(support_ids)

        if messages == "one":
            text = "Написать 1 сообщение в техподдержку"
    keyboard = InlineKeyboardMarkup()

    keyboard.add(
        InlineKeyboardButton(text=text,
                             callback_data=support_callback.new(
                                 messages=messages,
                                 user_id=contact_id,
                                 as_user=as_user)))

    if messages == "many":
        keyboard.add(
            InlineKeyboardButton(
                text="Завершить сеанс",
                callback_data=cancel_support.new(user_id=contact_id)))
    return keyboard
示例#9
0
async def send_find(message: types.Message):
    file_name = message.text.split(" ", 1)[-1]
    #print(file_name)
    if file_name != "/find":
        if len(file_name) >= 3:
            files = await loop.create_task(db.find_file_by_name(file_name))
            if len(files) > 0:
                files_kb = InlineKeyboardMarkup()
                for n, i in enumerate(files):
                    if n < 5:
                        files_kb.add(
                            InlineKeyboardButton(i['file_name'],
                                                 callback_data="file=" +
                                                 i['file_id']))
                if len(files) > 5:
                    files_kb.row(
                        InlineKeyboardButton("1", callback_data="page=1"),
                        InlineKeyboardButton(_("Дальше >>"),
                                             callback_data="next_all=" +
                                             file_name + "=" + str(5)))
                await message.reply(_("Документы"), reply_markup=files_kb)
            else:
                await message.reply(_("Ничего не нашел :("))
        else:
            await message.reply(_("Минимум 3 буквы для поиска"))
    else:
        await message.reply(
            _("Чтобы воспользоваться командой напиши /find имя_файла"))
示例#10
0
async def getCustomKeyboard(**kwargs):
    keyboard = InlineKeyboardMarkup()
    for arg, text in kwargs.items():
        keyboard.add(
            InlineKeyboardButton(
                text=text, callback_data=confirmation_callback.new(bool=arg)))
    return keyboard
示例#11
0
async def manager_kb(manager_data):
    markup = InlineKeyboardMarkup()
    markup.add(InlineKeyboardButton(text="🗑️ Удалить менеджера",
                                    callback_data=manager.new(manager_id=manager_data['userid'], action="delete")))
    markup.add(InlineKeyboardButton(text="👨‍💼 К списку менеджеров",
                                    callback_data=manager.new(manager_id="to_managers", action="to_managers")))
    return markup
示例#12
0
def only_back_button():
    back_button = InlineKeyboardMarkup(row_width=2)
    button = InlineKeyboardButton('Back',
                                  callback_data=data.new(action='back_to_main',
                                                         button_name='back'))
    back_button.add(button)
    return back_button
示例#13
0
async def select_payer_simple(callback_query: types.CallbackQuery):
    global cost
    global individual_products

    individual_products = []

    await callback_query.message.delete_reply_markup()

    cost['плательщик'] = callback_query.data[7:]

    await bot.send_message(
        callback_query.message.chat.id,
        "🆚 Для каждого товара выберите покупателя.\n"
        "💤 Если товар общий, то ничего не нажимайте.\n"
        "Когда закончите, то нажмите кнопку в самом конце списка ✅")

    # Выводим все товары отдельно с кнопками выбора плательщика.
    # В callback_data делаем префикс с номером товара.
    for index, product in enumerate(products):
        name, sum = product
        await bot.send_message(callback_query.message.chat.id,
                               f"{sum} - {name}",
                               reply_markup=await
                               get_keyboard_payers(alias=f'{index}_',
                                                   need_cancel=False))

    ending_keyboard = InlineKeyboardMarkup(row_width=1)
    button = InlineKeyboardButton('✅ Заврешить уточнение',
                                  callback_data='Заврешить уточнение')
    ending_keyboard.add(button)
    await bot.send_message(
        callback_query.message.chat.id,
        "Если все товары определены, то нажмите кнопку ниже",
        reply_markup=ending_keyboard)
示例#14
0
async def post_keyboard(name, link):
    inline_kb = InlineKeyboardMarkup()
    inline_kb.add(InlineKeyboardButton(name, url=link))
    return inline_kb


#some
示例#15
0
文件: bot.py 项目: PhySci/cinemaBot
async def show_one_day_schedule(query: CallbackQuery):
    """
    Shows schedule for one day

    :param query:
    :return:
    """
    _, _, date = parse_callback(query)
    # @TODO: need to validate date here
    try:
        date = datetime.fromtimestamp(float(date))
    except:
        return None
    db = DBDriver()
    shows = db.get_schedule(date)

    keyboard = InlineKeyboardMarkup()
    for i, show in enumerate(shows):
        item_text = show.get('datetime').strftime("%H:%M") + ' -> ' + show.get(
            'title') + '  (' + show.get('genre') + ')'
        callback = date_cb.new(action='show_movie_info',
                               date=show.get('movie_id'))
        keyboard.add(
            InlineKeyboardButton(text=item_text, callback_data=callback))
    date_str = format_date(date)
    await bot.send_message(
        query.from_user.id,
        text='Расписание кинотеатра на {:s}'.format(date_str),
        reply_markup=keyboard)
示例#16
0
async def process_file_name(message: types.Message, state: FSMContext):
    """
    Process file name
    """
    if message.text != "/cancel":
        files = await loop.create_task(db.find_file_by_name(message.text))
        #print(files)
        if len(files) > 0:
            files_kb = InlineKeyboardMarkup()
            for n, i in enumerate(files):
                if n < 5:
                    files_kb.add(
                        InlineKeyboardButton(i['file_name'],
                                             callback_data="file=" +
                                             i['file_id']))
            if len(files) > 5:
                files_kb.row(
                    InlineKeyboardButton("1", callback_data="page=1"),
                    InlineKeyboardButton("Дальше >>",
                                         callback_data="next_all=" +
                                         message.text + "=" + str(5)))
            await message.reply(_("Документы"), reply_markup=files_kb)
        else:
            await message.reply(_("Ничего не нашел :("))
        await state.finish()
    else:
        await message.reply(_("Отмена поиска."))
        await state.finish()
示例#17
0
    async def execute(cls, c: CallbackQuery):
        offset = int(c.data.split()[-2])

        player = Player(tg_id=c.from_user.id)
        items = list(player.backpack.items())
        kb = InlineKeyboardMarkup(row_width=2)
        n = 0
        for item_id, item_quantity in items[offset:]:
            if item_quantity <= 0:
                continue
            item = Item(id=ObjectId(item_id))
            item.update_from_db()
            button = InlineKeyboardButton(f'{item.emoji or ""} {item.name} {item_quantity}',
                                          callback_data=f'item observe backpack {item_id} {c.from_user.id}')
            kb.add(button)
            n += 1
            if n == PAGE_OFFSET:
                break
        close = InlineKeyboardButton('✖', callback_data=f"close_menu {c.from_user.id}")
        backward = InlineKeyboardButton('<-', callback_data=f"backpack offset {offset - PAGE_OFFSET} {c.from_user.id}")
        forward = InlineKeyboardButton('->', callback_data=f"backpack offset {offset + PAGE_OFFSET} {c.from_user.id}")
        buttons = [close]
        if offset > 0:
            buttons.insert(0, backward)
        if len(items) > offset + PAGE_OFFSET:
            buttons.append(forward)
        kb.row(*buttons)

        await c.message.edit_reply_markup(reply_markup=kb)
def create_kb_plus_or_minus_sum():
    keyboard = InlineKeyboardMarkup()

    keyboard.add(InlineKeyboardButton(text='+', callback_data='plus'))
    keyboard.add(InlineKeyboardButton(text='-', callback_data='minus'))

    return keyboard
示例#19
0
async def create_vacancy_handler(query: callback_query):
    await VacancyState.name.set()
    keyboard = InlineKeyboardMarkup()
    keyboard.add(InlineKeyboardButton(buttons.menu, callback_data='menu'))
    await bot.send_message(query.message.chat.id,
                           messages.enter_name_vacancy,
                           reply_markup=keyboard)
示例#20
0
async def choice_method(call: CallbackQuery):
    """
    Стартовый экран при заходе в бота. Выводи список доступных клубов из джейсон файла.
    :param call:
    :return:
    """
    try:
        await call.message.edit_reply_markup()
    except MessageNotModified:
        pass

    keyboard_markup = InlineKeyboardMarkup(inline_keyboard=[[
        InlineKeyboardButton(text='Contacts', callback_data='contacts')
    ]])

    data = read_json_data(JSON_DATA_FILENAME)
    if data != 'File not read' and data.get('Clubs'):
        for club in data.get('Clubs'):
            keyboard_markup.add(
                InlineKeyboardButton(
                    text=f'{club.get("Club_name")}',
                    callback_data=club_cb.new(club=club.get('Club_name'))))
        reply = f'Choice the Club.'
        await call.message.answer(text=reply, reply_markup=keyboard_markup)
    else:
        await service_unavailable(call.from_user.id)
示例#21
0
async def vacancy_key_skills_handler(message: types.Message,
                                     state: FSMContext):
    await state.update_data(key_skills=message.text)
    await VacancyState.next()
    keyboard = InlineKeyboardMarkup()
    keyboard.add(InlineKeyboardButton(buttons.menu, callback_data='menu'))
    await message.answer(messages.enter_income, reply_markup=keyboard)
示例#22
0
文件: ui.py 项目: ne-bknn/CSSH
async def kb_images_picker(page: int) -> Optional[InlineKeyboardMarkup]:
    keyboard = InlineKeyboardMarkup(row_width=1)
    db = await InterfaceDB.create_tmp(DB_CONN)

    images = await db.get_images()
    images_to_add = images[page * 5:page * 5 + 5]

    if page == 0 and len(images_to_add) == 0:
        await db.close()
        return None

    for image in images_to_add:
        keyboard.add(
            InlineKeyboardButton(image, callback_data=f"picked_image:{image}"))

    none_button = InlineKeyboardButton(" ", callback_data=" ")

    row = [none_button, none_button]

    if page != 0:
        row[0] = InlineKeyboardButton(
            "<", callback_data=f"next_image_list:{page-1}")

    if not (len(images_to_add) < 5
            or len(images[(page + 1) * 5:(page + 1) * 5 + 5]) == 0):
        row[1] = InlineKeyboardButton(
            ">", callback_data=f"next_image_list:{page+1}")

    if any(button != none_button for button in row):
        keyboard.row(*row)

    await db.close()
    return keyboard
示例#23
0
async def echo_product(message):
    global product
    global raw_message

    raw_message = message.text

    try:
        product = DBMS.product_exist(raw_message)
    except Exception as e:
        print("Возникла ошибка: ", e)
        await message.answer(
            f"Что-то пошло не так... Вводите доходы/расходы в виде НАЗВАНИЕ - СТОИМОСТЬ."
        )
    else:
        if product.category:
            await message.answer(
                f"Товар {product.codename} на сумму {product.price} "
                f"добавлен в категорию {product.category}.")
        else:
            # Клавиатура с выбором.
            keyboard = InlineKeyboardMarkup(row_width=2)
            deposit = InlineKeyboardButton("Доход", callback_data="Доход")
            cost = InlineKeyboardButton("Расход", callback_data="Расход")
            keyboard.add(deposit, cost)

            # Далее обработка ответа.
            await message.answer('Это доход или расход', reply_markup=keyboard)
示例#24
0
def generate_choose_day_button() -> InlineKeyboardMarkup:
    '''
    Return buttons for choosing building message in this way:
    [  1st  ] [  2nd  ]
    [  3rd  ] [  4th  ]
    [      CLOSE      ]
    '''
    keyboard = InlineKeyboardMarkup(row_width=2)
    for start_number in [1, 3]:
        row = []
        for number in range(start_number, start_number + 2):
            row.append(
                InlineKeyboardButton(text=f"{ordinal(number)}",
                                     callback_data=':'.join([
                                         constants.INLINE_PREFIX_SETBUILDING,
                                         constants.INLINE_INFIX_CHANGE,
                                         str(number)
                                     ])))
        keyboard.add(*row)

    keyboard.add(
        InlineKeyboardButton(text=messages.BUTTON_EXIT,
                             callback_data=':'.join([
                                 constants.INLINE_PREFIX_SETBUILDING,
                                 constants.INLINE_INFIX_CLOSE, '0'
                             ])))
    return keyboard
示例#25
0
文件: bot.py 项目: f1b/BotPython
async def send_welcome(message: types.Message):
    keybord = InlineKeyboardMarkup()

    button_1 = InlineKeyboardButton(text='ПМИ', callback_data='пми')

    keybord.add(button_1)
    await message.answer("есть", reply_markup=keybord)
示例#26
0
async def get_welcome_message(user, title, join_msg_id):
    emojis = random.sample(EMOJI_DATA, MAX_EMOJIS)
    for emoji in emojis:
        emoji['hash'] = genkey()
    answer = random.sample(emojis, 1)[0]
    sample_welcome_message = 'Привет, {}! Добро пожаловать в <b>{}</b>.\n'.format(
        screen_name(user), title)
    sample_welcome_message += 'Выбери эмодзи по описанию: ' + hitalic(
        answer['description'].capitalize())
    kb = InlineKeyboardMarkup(row_width=MAX_EMOJIS)
    ch = {
        'user_id': user['id'],
        'answer': answer['hash'],
        'join_msg_id': join_msg_id
    }
    challenge = await db.c_challenges.insert_one(ch)

    kb.add(*[
        InlineKeyboardButton(emoji['emoji'],
                             callback_data=captcha_cb.new(
                                 user_id=str(user['id']),
                                 challenge=str(challenge.inserted_id),
                                 answer=emoji['hash'])) for emoji in emojis
    ])
    return sample_welcome_message, kb
示例#27
0
async def new_chat_member(msg: Message):
    if len(msg.new_chat_members
           ) > 0 and msg.new_chat_members[0].id != msg.from_user.id:
        logging.info(
            f'User {msg.from_user.id} added user {msg.new_chat_members[0].id}. Skipping...'
        )
        return

    logging.info(
        f'New chat_member detected! id: {msg.from_user.id}. Restricting...')
    await bot.restrict_chat_member(msg.chat.id,
                                   msg.new_chat_members[0].id,
                                   permissions=RESTRICT_PERMISSIONS)

    kb = InlineKeyboardMarkup()
    kb.add(InlineKeyboardButton(button_text, callback_data=msg.from_user.id))

    answer = await bot.send_message(msg.chat.id,
                                    question_text,
                                    reply_markup=kb)
    create_task(
        init_user_track(user_id=msg.from_user.id,
                        chat_id=msg.chat.id,
                        msg_id=answer.message_id,
                        service_msg_id=msg.message_id))
示例#28
0
def create_kb_groups_users():
    print('function: create_kb_groups_users')
    current_statuses = db.get_all_statuses()

    all_statuses = {
        'admin': 'администраторы',
        'changer': 'чейнджи',
        'operator': 'операторы',
        'secretary': 'секретари',
        'executor': 'исполнители',
        'permit': 'на пропуск',
        'request': 'в статусе "запрос"',
        'block': 'заблокированны'
    }

    kb_groups_users = InlineKeyboardMarkup()

    for status in current_statuses:
        if status in all_statuses.keys():
            text = all_statuses[status]
        else:
            text = 'Тут какая-то хуйня...'

        kb_groups_users.add(
            InlineKeyboardButton(text=text,
                                 callback_data=group_users_data.new(
                                     group=status, handler='statuses')))

    return kb_groups_users
示例#29
0
def yes_no_markup():
    markup = InlineKeyboardMarkup()
    markup.row_width = 1
    markup.one_time_keyboard=True
    markup.add(InlineKeyboardButton("Так", callback_data="answer_yes"),
                InlineKeyboardButton("Ні", callback_data="answer_no"))
    return markup
示例#30
0
def period(period_days_count):
    try:
        connection = psycopg2.connect(user=settings.db_data["user"],
                                      password=settings.db_data["password"],
                                      host=settings.db_data["host"],
                                      port=settings.db_data["port"],
                                      database=settings.db_data["database"])
        connection.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
        cursor = connection.cursor()
        select_query = f"SELECT alias FROM telegram_datas WHERE created_date > (CURRENT_DATE - INTERVAL '{period_days_count} day');"
        cursor.execute(select_query)
        res = cursor.fetchall()

        try:
            btn_group = InlineKeyboardMarkup()
            for alias in res:
                select_query = "SELECT title FROM parsing_datas WHERE alias=%s;"
                cursor.execute(select_query, [alias])
                title = cursor.fetchall()

                btn_group.add(
                    InlineKeyboardButton(
                        f'{title[0][0]} [{str(alias[0])[11:]}]',
                        callback_data=f'link[|]{alias}'))
            return btn_group
        except Exception as error:
            log_handler.write_log([error, "Ошибка при попытке title"],
                                  'bot_buttons.py')
    except Exception as error:
        log_handler.write_log(
            [error, "Ошибка при попытке создать список кнопок"],
            'bot_buttons.py')