def __ProcessChangeBank(self, msg: str):
        if msg == ld.CancelKey or msg == "/start":
            print(self.username +
                  " has been cancelled changing request process")
            self.__deleteProcessMessage()
            self.Start()
            return
        if not (msg == ld.SkipKey):
            self.__bank = self.__StripTagsRegex(msg)

        self.currentStep = RequestSteps.ChangeEndDate
        keyboard = InlineKeyboardMarkup(row_width=1)
        keyboard.row(
            InlineKeyboardButton(ld.get_translate(self.__db, self.username,
                                                  ld.CancelKey),
                                 callback_data=ld.CancelKey),
            InlineKeyboardButton(ld.get_translate(self.__db, self.username,
                                                  ld.SkipKey),
                                 callback_data=ld.SkipKey))
        reply = self.__bot.send_message(self.__chatId,
                                        ld.get_translate(
                                            self.__db, self.username,
                                            ld.EnterReqDurationKey),
                                        reply_markup=keyboard)
        self.__processMsgId = reply.message_id
Пример #2
0
def lobbies_menu(user):
    keyboard = InlineKeyboardMarkup()
    for lobby in Lobby.lobbies:
        keyboard.row(InlineKeyboardButton(str(lobby),
                                          callback_data=lobby.name))
    keyboard.row(InlineKeyboardButton('назад', callback_data='back'))
    user.resend_message('--= Лобби =--', keyboard)
Пример #3
0
 def __ProcessFee(self, msg: str):
     if msg == ld.CancelKey or msg == "/start":
         log.info(
             self.username +
             " has been cancelled {0} process".format(self.__reqType.name))
         self.__deleteProcessMessage()
         self.Start()
         return
     try:
         self.__fee = float(msg)
         self.currentStep = RequestSteps.EnterBank
         keyboard = InlineKeyboardMarkup(row_width=1)
         keyboard.row(
             InlineKeyboardButton(ld.get_translate(self.__db, self.username,
                                                   ld.CancelKey),
                                  callback_data=ld.CancelKey))
         reply = self.__bot.send_message(self.__chatId,
                                         ld.get_translate(
                                             self.__db, self.username,
                                             ld.EnterBankNameKey),
                                         reply_markup=keyboard)
         self.__processMsgId = reply.message_id
     except Exception:
         self.__bot.send_message(
             self.__chatId,
             ld.get_translate(self.__db, self.username, ld.WrongInputKey))
    def __ProcessChangeCurrency(self, msg: str):
        if msg == ld.CancelKey or msg == "/start":
            print(self.username +
                  " has been cancelled changing request process")
            self.__deleteProcessMessage()
            self.Start()
            return
        if not (msg == ld.SkipKey):
            assets = self.__db.GetAssetsList()
            if msg not in assets:
                self.__bot.send_message(
                    self.__chatId,
                    ld.get_translate(self.__db, self.username,
                                     ld.WrongInputKey))
                return
            self.__currency = msg

        self.__deleteProcessMessage()
        self.currentStep = RequestSteps.ChangeQuantity
        keyboard = InlineKeyboardMarkup(row_width=1)
        keyboard.row(
            InlineKeyboardButton(ld.get_translate(self.__db, self.username,
                                                  ld.CancelKey),
                                 callback_data=ld.CancelKey),
            InlineKeyboardButton(ld.get_translate(self.__db, self.username,
                                                  ld.SkipKey),
                                 callback_data=ld.SkipKey))
        reply = self.__bot.send_message(self.__chatId,
                                        ld.get_translate(
                                            self.__db, self.username,
                                            ld.EnterQuantityMsgKey),
                                        reply_markup=keyboard)
        self.__processMsgId = reply.message_id
Пример #5
0
def show_equipments(found_items, bot, message):
    if len(found_items) != 0:
        users[f'{message.chat.id}']['invent_num_for_show_again'] = found_items[0].invent_num
        movement = None
        for item in found_items:
            temp_movements = item.movements
            if temp_movements.count() > 0:
                for temp in temp_movements:
                    movement = temp
            else:
                movement = Movement.create(it_id=item,
                                           korpus='N/A',
                                           room='N/A')
            item_inline_keyboard = InlineKeyboardMarkup()
            item_inline_keyboard.row(
                InlineKeyboardButton(text=bot_messages_text.get('change_values'),
                                     callback_data=callbacks.get('main_edit').format(it_id=item.it_id)))
            item_inline_keyboard.row(
                InlineKeyboardButton(text=bot_messages_text.get('move'),
                                     callback_data=callbacks.get('main_move').format(it_id=item.it_id)))
            bot.send_message(chat_id=message.chat.id, text=found_item_template(item, movement),
                             reply_markup=item_inline_keyboard)
    else:
        bot.send_message(chat_id=message.chat.id,
                         text=bot_messages_text.get('item_not_found'))
Пример #6
0
def post_markup(message):
    post = post_dict[message.chat.id]
    word = post.words[-1]
    definition_number = len(word.definitions) + 1
    markup = InlineKeyboardMarkup()
    add_definition_button = InlineKeyboardButton(
        "Add definition #{0}".format(definition_number),
        callback_data="add_definition")
    add_tags_button = InlineKeyboardButton("Add tags",
                                           callback_data="add_tags")
    add_links_button = InlineKeyboardButton("Add dictionary links",
                                            callback_data="add_links")
    add_synonyms_button = InlineKeyboardButton("Add synonyms",
                                               callback_data="add_synonyms")
    add_new_word_button = InlineKeyboardButton("Add new word",
                                               callback_data="add_new_word")
    cancel_button = InlineKeyboardButton("Cancel", callback_data="cancel")
    finish_button = InlineKeyboardButton("Finish", callback_data="finish")

    markup.add(add_definition_button)
    if not word.synonyms:
        markup.add(add_synonyms_button)
    if word.definitions:
        markup.add(add_new_word_button)
    if not post.hashTags:
        markup.add(add_tags_button)
    if not post.oxford and not post.cambridge and not post.context:
        markup.add(add_links_button)

    markup.row(cancel_button, finish_button)

    return markup
Пример #7
0
def next_block_handler(call_back):
    data = func.get_current_block(call_back.message.text,
                                  call_back.message.chat.id)
    answer, events = data[0], data[1]
    events_keyboard = InlineKeyboardMarkup(True)
    for event in events:
        event_name = event.strip(" {0}".format(
            emoji["cross_mark"]))[3:-4].split(" - ")
        button_text = "{0} - {1}".format(event_name[0],
                                         event_name[1].split(". ")[-1])
        events_keyboard.row(*[
            InlineKeyboardButton(
                text=name, callback_data=name[:max_inline_button_text_len])
            for name in [button_text]
        ])
    events_keyboard.row(*[
        InlineKeyboardButton(text=emoji[name], callback_data=name)
        for name in ["prev_block", "Отмена", "next_block"]
    ])
    try:
        bot.edit_message_text(text=answer,
                              chat_id=call_back.message.chat.id,
                              message_id=call_back.message.message_id,
                              parse_mode="HTML",
                              reply_markup=events_keyboard)
    except ApiException:
        pass
Пример #8
0
def make_keyboard(keyboard_to_user):
    """Генерирует клавиатуру для отправки пользователю. Распределяет кнопки по страницам, если кнопок много"""
    # buttons - массив с текстом кнопок
    buttons = keyboard_to_user.get('buttons', [])
    row_width = keyboard_to_user.get('row_width', 2)
    page = keyboard_to_user.get('page', 0)
    addition_buttons = keyboard_to_user.get('addition_buttons', [])
    page_len = 10
    # if buttons:
    markup = InlineKeyboardMarkup(row_width=row_width)
    markup.add(*[
        InlineKeyboardButton(text=text, callback_data=call)
        for text, call in buttons[page_len * page:page_len * page + page_len]
    ])
    pages = len(buttons) // page_len + (1 if len(buttons) % page_len != 0 else
                                        0)  # По page_len элементов на страницу
    if pages > 1:
        markup.row(
            InlineKeyboardButton(text=f'Страница {page + 1} из {pages}',
                                 callback_data='none'))
        markup.add(*[
            InlineKeyboardButton(text=i + 1, callback_data=f'page_{i}')
            for i in range(pages)
        ])

    markup.add(*[
        InlineKeyboardButton(text=btn[0],
                             callback_data=btn[1],
                             url=btn[2] if len(btn) == 3 else None)
        for btn in addition_buttons
    ])
    return markup
Пример #9
0
def types_selected_handler(call_back):
    message_text_data = call_back.message.text.split("\n\n")
    answer = "{0}\n\n{1}\n<b>{2}</b>\n{3}\n\nТипы: <b>{4}</b>\n\n".format(
        message_text_data[0], message_text_data[1].split("\n")[0],
        message_text_data[1].split("\n")[1],
        "\n".join(message_text_data[1].split("\n")[2:]),
        message_text_data[2].split(": ")[1])
    days_keyboard = InlineKeyboardMarkup(True)
    day_title = message_text_data[0].split(" ")[-1][1:-1]
    if day_title == "Понедельник" or day_title == "Вторник" or \
                    day_title == "Четверг":
        day_title += "и"
    else:
        day_title = day_title[:-1] + "ы"
    days_keyboard.row(*[
        InlineKeyboardButton(text=name, callback_data=name)
        for name in ["Все {0}".format(day_title.lower())]
    ])
    days_keyboard.row(*[
        InlineKeyboardButton(text=name, callback_data=name)
        for name in ["Отмена", "Все дни"]
    ])
    answer += "Выбери дни для скрытия занятия:"
    bot.edit_message_text(text=answer,
                          chat_id=call_back.message.chat.id,
                          message_id=call_back.message.message_id,
                          parse_mode="HTML",
                          reply_markup=days_keyboard)
Пример #10
0
def select_place_educator_handler(call_back):
    message_text_data = call_back.message.text.split("\n\n")
    answer = "{0}\n\n{1}\n<b>{2}</b>\n{3}\n\nТипы: <b>{4}</b>\n\n" \
             "Дни: <b>{5}</b>\n\nВремя: <b>{6}</b>\n\n" \
             "Выбери, у каких преподавателей скрывать занятие:".format(
                      message_text_data[0], message_text_data[1].split("\n")[0],
                      message_text_data[1].split("\n")[1],
                      "\n".join(message_text_data[1].split("\n")[2:]),
                      message_text_data[2].split(": ")[1],
                      message_text_data[3].split(": ")[1],
                      call_back.data)
    place_educator_keyboard = InlineKeyboardMarkup(True)
    place_educator_keyboard.row(*[
        InlineKeyboardButton(text=name, callback_data=name)
        for name in ["Данные преподаватели"]
    ])
    place_educator_keyboard.row(*[
        InlineKeyboardButton(text=name, callback_data=name)
        for name in ["Отмена", "Любые"]
    ])
    bot.edit_message_text(text=answer,
                          chat_id=call_back.message.chat.id,
                          message_id=call_back.message.message_id,
                          parse_mode="HTML",
                          reply_markup=place_educator_keyboard)
Пример #11
0
def switch_session_type_handler(call_back):
    bot_msg = bot.edit_message_text(
        text="{0}\U00002026".format(choice(loading_text["schedule"])),
        chat_id=call_back.message.chat.id,
        message_id=call_back.message.message_id
    )
    month = func.get_available_months(call_back.message.chat.id)
    if len(month) == 0:
        bot.send_message(call_back.message.chat.id, "<i>Нет событий</i>",
                         parse_mode="HTML")
        return
    inline_keyboard = InlineKeyboardMarkup()
    for key in month.keys():
        inline_keyboard.row(
            *[InlineKeyboardButton(text=month[key], callback_data=str(key))]
        )
    if call_back.data == "Сессия":
        answer = "Выбери месяц:"
        switch_button = "Допса"
    else:
        answer = "Выбери месяц для <b>допсы</b>:"
        switch_button = "Сессия"

    inline_keyboard.row(
        *[InlineKeyboardButton(text=switch_button, callback_data=switch_button)]
    )

    bot.edit_message_text(text=answer,
                          chat_id=call_back.message.chat.id,
                          message_id=bot_msg.message_id,
                          parse_mode="HTML",
                          reply_markup=inline_keyboard)
Пример #12
0
def attestation_handler(message):
    bot.send_chat_action(message.chat.id, "typing")
    month = func.get_available_months(message.chat.id)
    if len(month) == 0:
        bot.send_message(message.chat.id, "<i>Нет событий</i>",
                         parse_mode="HTML")
        return
    inline_keyboard = InlineKeyboardMarkup()
    for key in month.keys():
        inline_keyboard.row(
            *[InlineKeyboardButton(text=month[key], callback_data=str(key))]
        )
    if message.text == "Сессия":
        answer = "Выбери месяц:"
        switch_button = "Допса"
    else:
        answer = "Выбери месяц для <b>допсы</b>:"
        switch_button = "Сессия"

    inline_keyboard.row(
        *[InlineKeyboardButton(text=switch_button, callback_data=switch_button)]
    )

    bot.send_message(message.chat.id, answer, reply_markup=inline_keyboard,
                     parse_mode="HTML")
Пример #13
0
def get_ask_decline_book_keyboard(data):
    keyboard = InlineKeyboardMarkup()

    no = InlineKeyboardButton("Ні", callback_data=f"back")
    yes = InlineKeyboardButton("Так", callback_data=f"decline_{data}")
    keyboard.row(no, yes)
    return keyboard
Пример #14
0
def group_templates_handler(message):
    bot.send_chat_action(message.chat.id, "typing")
    answer = ""
    groups = func.get_templates(message.chat.id)
    group_title = func.get_current_group(message.chat.id)[1]
    answer += "Текущая группа: <b>{0}</b>\n".format(group_title)
    last_row = ["Отмена", "Сохранить"]
    inline_keyboard = InlineKeyboardMarkup(row_width=2)
    if len(groups) == 0:
        answer += "Нет шаблонов групп, но ты можешь сохранить текущую\n"
    else:
        answer += "Выбери группу:"
        inline_keyboard.add(*[
            InlineKeyboardButton(text=name, callback_data=str(groups[name]))
            for name in groups.keys()
        ])
        if group_title in groups.keys():
            last_row = ["Отмена", "Удалить"]
    inline_keyboard.row(*[
        InlineKeyboardButton(text=name, callback_data=name)
        for name in last_row
    ])
    inline_keyboard.row(*[
        InlineKeyboardButton(text=name, callback_data=name)
        for name in ["Сменить группу"]
    ])
    bot.send_message(message.chat.id,
                     answer,
                     reply_markup=inline_keyboard,
                     parse_mode="HTML")
Пример #15
0
def pagination_orders(paginator: Paginator, page):
    markup = InlineKeyboardMarkup()
    page = paginator.page(page)
    text_prev_page = '⬅'
    text_next_page = '➡'
    if paginator.num_pages <= 1:
        text_next_page = text_prev_page = '⏺'
        prev_page = paginator.num_pages
        next_page = paginator.num_pages
    else:
        try:
            next_page = page.next_page_number()
        except EmptyPage:
            next_page = 1
            text_next_page = '↩'
        try:
            prev_page = page.previous_page_number()
        except EmptyPage:
            prev_page = paginator.num_pages
            text_prev_page = '↪'
    prev_btn = InlineKeyboardButton(
        text_prev_page, callback_data=f'pagination_orders-{prev_page}')
    next_btn = InlineKeyboardButton(
        text_next_page, callback_data=f'pagination_orders-{next_page}')
    markup.row(prev_btn, next_btn)
    order = page[0]
    if order.product.category.doc:
        show_doc = InlineKeyboardButton(
            'Get document', callback_data=f'get_document-{order.product.id}')
        markup.row(show_doc)
    return markup
Пример #16
0
def unsub(subscribes):
    markup = InlineKeyboardMarkup()
    for sub in subscribes:
        markup.row(
            InlineKeyboardButton("Отписаться от %s" % sub.name,
                                 callback_data='unsub/' + str(sub.id_)))
    return markup
Пример #17
0
def wallet():
    markup = InlineKeyboardMarkup()
    load_btn = InlineKeyboardButton('📤 LOAD', callback_data='wallet_upload')
    history_btn = InlineKeyboardButton('⏳ HISTORY',
                                       callback_data='wallet_history')
    markup.row(load_btn, history_btn)
    return markup
Пример #18
0
    def se_categories(self,
                      buttons: List[InlineKeyboardButton],
                      chat_id: int,
                      text: str,
                      back_button: InlineKeyboardButton = None,
                      message_id: int = None,
                      delete_message_id: int = None,
                      **kwargs):

        kb = InlineKeyboardMarkup(row_width=3)

        if back_button:
            kb.row(back_button)

        kb.add(*buttons)

        params = dict(chat_id=chat_id, text=text, reply_markup=kb, **kwargs)

        if message_id:
            params['message_id'] = message_id
            self.edit_message_text(**params)
        else:
            self.send_message(**params)
            if delete_message_id:
                self.delete_message(chat_id=chat_id,
                                    message_id=delete_message_id)
Пример #19
0
def return_educator(call_back):
    data = func.get_hide_lessons_data(call_back.message.chat.id,
                                      is_educator=True)
    ids_keyboard = InlineKeyboardMarkup(True)
    if len(data):
        answer = "Вот список занятий с выбранными преподавателями:\n\n"
        for lesson in data:
            answer += "<b>id: {0}</b>\n<b>Название</b>: {1}\n" \
                      "<b>Преподаватель</b>: {2}\n\n".format(
                                    lesson[0], lesson[1], lesson[5])
            ids_keyboard.row(
                *[InlineKeyboardButton(
                    text=name, callback_data=name[:max_inline_button_text_len]
                ) for name in ["{0} - {1}".format(lesson[0], lesson[1])]]
            )
        ids_keyboard.row(
            *[InlineKeyboardButton(text=name, callback_data=name)
              for name in ["Отмена", "Вернуть всех"]]
        )
        answer += "Выбери связь, которую хочешь убрать:"
    else:
        answer = "Скрытых преподавателей нет"
    if len(answer) >= 3000:
        answers = answer.split("\n\n")
        for answer in answers[:-1]:
            bot.send_message(call_back.message.chat.id, answer,
                             parse_mode="HTML")
        answer = answers[-1]
        bot.send_message(call_back.message.chat.id, answer,
                         reply_markup=ids_keyboard, parse_mode="HTML")
    else:
        bot.edit_message_text(text=answer, chat_id=call_back.message.chat.id,
                              message_id=call_back.message.message_id,
                              parse_mode="HTML", reply_markup=ids_keyboard)
Пример #20
0
def departments(message):
    response = requests.get(
        "https://www.amazon.es/gp/site-directory?ref=nav_shopall_btn",
        allow_redirects=True)
    soup = BeautifulSoup(response.content)
    categories = soup.findAll("h2", {"class": "popover-category-name"})
    click_kb = InlineKeyboardMarkup()
    list_categories = []
    i = 0
    for category in categories:
        i += 1
        name_category = category.get_text()
        click_button = InlineKeyboardButton(name_category,
                                            callback_data='parent_' +
                                            name_category)
        list_categories.append(click_button)
        if i % 2 == 0:
            click_kb.row(*list_categories)
            list_categories = []
    bot.send_message(
        message.chat.id,
        "<b>Aquí se muestran todos los departamentos de Amazon...</b>",
        parse_mode="HTML",
        reply_markup=click_kb,
        disable_web_page_preview=True)
Пример #21
0
def titulo(message: Message):
    if message.text == boton_cancelar:
        introducc(message.chat.id, message.chat.first_name)
    else:
        temp: Temp = db.get_temp(message.chat.id)
        if temp:
            temp.titulo = (message.text[:150] +
                           ('...' if len(message.text) > 150 else '')) if message.text else None
            temp.username = message.chat.username
            temp.id_user = message.chat.id
            temp.name = message.chat.first_name
            temp.hidden_name = None
            temp.post = P_Anime()
            log(temp, 'titulo')
            db.set_temp(message.chat.id, temp)

            markup = InlineKeyboardMarkup()
            markup.row(InlineKeyboardButton('Anime', callback_data='a'))
            markup.row(InlineKeyboardButton('Manga', callback_data='m'))
            markup.row(InlineKeyboardButton(
                'Novela Visual', callback_data='vn'))
            if twitch_client_id and twitch_client_secret:
                markup.row(InlineKeyboardButton('Juego', callback_data='j'))
            markup.row(InlineKeyboardButton(
                'Otro contenido', callback_data='o'))
            markup.row(InlineKeyboardButton(salir_menu, callback_data='s'))
            try:
                bot.send_message(message.chat.id, t_ty, reply_markup=markup)
            except:
                print(traceback.format_exc())
        else:
            introducc(message.chat.id, message.chat.first_name)
Пример #22
0
 def __ProcessEnterCurrency(self, msg: str):
     if msg == ld.CancelKey or msg == "/start":
         log.info(
             self.username +
             " has been cancelled {0} process".format(self.__reqType.name))
         self.__deleteProcessMessage()
         self.Start()
         return
     assets = self.__db.GetAssetsList()
     if msg not in assets:
         self.__bot.send_message(
             self.__chatId,
             ld.get_translate(self.__db, self.username, ld.WrongInputKey))
         return
     self.__currency = msg
     self.currentStep = RequestSteps.EnterQuantity
     self.__deleteProcessMessage()
     keyboard = InlineKeyboardMarkup(row_width=1)
     keyboard.row(
         InlineKeyboardButton(ld.get_translate(self.__db, self.username,
                                               ld.CancelKey),
                              callback_data=ld.CancelKey))
     reply = self.__bot.send_message(self.__chatId,
                                     ld.get_translate(
                                         self.__db, self.username,
                                         ld.EnterQuantityMsgKey),
                                     reply_markup=keyboard)
     self.__processMsgId = reply.message_id
Пример #23
0
 def __base_keyboard(self, **kwargs):
     keyboard = InlineKeyboardMarkup(row_width=1)
     for name, id_ in kwargs.get('names', []):
         keyboard.add(
             InlineKeyboardButton(name,
                                  callback_data=f'challenge_to_user={id_}'))
     if kwargs.get('has_pages', None) and kwargs.get('cur_page', None):
         end_row = [
             InlineKeyboardButton(
                 '<',
                 callback_data=
                 f'challenge_to_paginate={kwargs["cur_page"] - 1}'
                 if kwargs.get('has_prev', None) else 'challenge_to_none'),
             InlineKeyboardButton(
                 f'{kwargs["cur_page"]}{(" / " + str(kwargs["pages"]) if kwargs.get("pages", None) else "")}',
                 callback_data='challenge_to_none'),
             InlineKeyboardButton(
                 '>',
                 callback_data=
                 f'challenge_to_paginate={kwargs["cur_page"] + 1}'
                 if kwargs.get('has_next', None) else 'challenge_to_none')
         ]
         keyboard.row(*end_row)
     keyboard.row(
         InlineKeyboardButton(get_translation_for('back_btn'),
                              callback_data='challenge_to_back'),
         InlineKeyboardButton('🔄', callback_data='challenge_to_refresh'))
     return keyboard
Пример #24
0
def endboard(size, field):
    keyboard = Mark(size)
    for i in range(size):
        rows = []
        for j in range(size):
            if field[i * size + j]["mine"] == 1:
                text = "💣"
            else:
                if field[i * size + j]["around"] == 0:
                    text = "0️⃣"
                elif field[i * size + j]["around"] == 1:
                    text = "1️⃣"
                elif field[i * size + j]["around"] == 2:
                    text = "2⃣"
                elif field[i * size + j]["around"] == 3:
                    text = "3⃣"
                elif field[i * size + j]["around"] == 4:
                    text = "4⃣"
                elif field[i * size + j]["around"] == 5:
                    text = "5⃣"
                elif field[i * size + j]["around"] == 6:
                    text = "6⃣"
                elif field[i * size + j]["around"] == 7:
                    text = "7⃣"
                elif field[i * size + j]["around"] == 8:
                    text = "8⃣"
            rows.append(MARKUP.GAME("OK", text))
        keyboard.row(*rows)
    return keyboard
Пример #25
0
def to_university_handler(message):
    bot.send_chat_action(message.chat.id, "typing")

    if message.text.title() == "В Универ":
        from_station = func.get_station_code(message.chat.id, is_home=True)
        to_station = func.get_station_code(message.chat.id, is_home=False)
    else:
        from_station = func.get_station_code(message.chat.id, is_home=False)
        to_station = func.get_station_code(message.chat.id, is_home=True)

    server_datetime = datetime.today() + server_timedelta
    data = get_yandex_timetable_data(from_station, to_station, server_datetime)
    answer = data["answer"]

    update_keyboard = InlineKeyboardMarkup(True)
    if data["is_OK"]:
        if data["is_tomorrow"]:
            bot.send_message(message.chat.id,
                             emoji["warning"] + " На сегодня нет электричек")
            update_keyboard.row(*[
                InlineKeyboardButton(text=name, callback_data=name)
                for name in ["Все на завтра"]
            ])
        else:
            update_keyboard.row(*[
                InlineKeyboardButton(text=name, callback_data=name)
                for name in ["Оставшиеся", "Обновить"]
            ])

    bot.send_message(message.chat.id,
                     answer,
                     reply_markup=update_keyboard,
                     parse_mode='HTML',
                     disable_web_page_preview=True)
    def __ProcessChangeFee(self, msg: str):
        if msg == ld.CancelKey or msg == "/start":
            print(self.username +
                  " has been cancelled changing request process")
            self.__deleteProcessMessage()
            self.Start()
            return
        if not (msg == ld.SkipKey):
            try:
                self.__fee = float(msg)
            except:
                self.__bot.send_message(
                    self.__chatId,
                    ld.get_translate(self.__db, self.username,
                                     ld.WrongInputKey))
                return

        self.__deleteProcessMessage()
        self.currentStep = RequestSteps.ChangeBank
        keyboard = InlineKeyboardMarkup(row_width=1)
        keyboard.row(
            InlineKeyboardButton(ld.get_translate(self.__db, self.username,
                                                  ld.CancelKey),
                                 callback_data=ld.CancelKey),
            InlineKeyboardButton(ld.get_translate(self.__db, self.username,
                                                  ld.SkipKey),
                                 callback_data=ld.SkipKey))
        reply = self.__bot.send_message(self.__chatId,
                                        ld.get_translate(
                                            self.__db, self.username,
                                            ld.EnterBankNameKey),
                                        reply_markup=keyboard)
        self.__processMsgId = reply.message_id
Пример #27
0
def list_mp(list_id):
    list_ = List.get_by_id(list_id)
    list_ = List.get_by_id(list_.subscribed_by_id)

    mp = InlineKeyboardMarkup(row_width=1)
    for item in list_.items:
        if item.tag:
            s = "🔘 %s" % item.name
        else:
            s = "⚪ %s" % item.name
        mp.add(
            InlineKeyboardButton(s,
                                 callback_data="upd_list" + str(list_id) +
                                 "." + str(item.id)))
    if len(list_.items) > 0:
        mp.row(
            InlineKeyboardButton(_("➕ Add item"),
                                 callback_data="add_item_%i" % list_id),
            InlineKeyboardButton(_("🔗 Share"), switch_inline_query=list_.name),
            InlineKeyboardButton(_("❌ Delete item"),
                                 callback_data="delete_items_%i" % list_id),
        )
    else:
        mp.row(
            InlineKeyboardButton(_("➕ Add item"),
                                 callback_data="add_item_%i" % list_id),
            InlineKeyboardButton(_("🔗 Share"), switch_inline_query=list_.name),
        )
    return mp
 def __ProcessShowMy(self):
     myReqs = self.__db.GetRequestsFor(self.username, self.username)
     if len(myReqs) == 0:
         self.__bot.send_message(
             self.__chatId,
             ld.get_translate(self.__db, self.username, ld.EmptyKey))
         return
     for req in myReqs:
         idx1 = req.find('(')
         idx2 = req.find(')')
         if idx1 < 0 or idx2 < 0:
             continue
         reqId = req[idx1:idx2 + 1]
         keyboard = InlineKeyboardMarkup(row_width=1)
         keyboard.row(
             InlineKeyboardButton("{0} {1}".format(
                 ld.get_translate(self.__db, self.username, ld.RemoveKey),
                 reqId),
                                  callback_data="{0} {1}".format(
                                      ld.RemoveKey, reqId)),
             InlineKeyboardButton("{0} {1}".format(
                 ld.get_translate(self.__db, self.username, ld.ChangeKey),
                 reqId),
                                  callback_data="{0} {1}".format(
                                      ld.ChangeKey, reqId)))
         self.__bot.send_message(self.__chatId,
                                 req,
                                 parse_mode="HTML",
                                 reply_markup=keyboard)
Пример #29
0
def currencies_list_keyboard(page_number):
    page_number = int(page_number)
    size = 5
    i = page_number * size + bool(page_number)
    currencies_count = len(market.currencies_list)
    if 0 <= i < currencies_count:
        inline_keyboard = InlineKeyboardMarkup(row_width=1)
        inline_keyboard.add(*[
            InlineKeyboardButton(text=c, callback_data="currency %s" % c)
            for c in market.currencies_list[i:i + size]
        ])

        control_buttons = []
        if page_number != 0:
            control_buttons.append(
                InlineKeyboardButton(text="<<<",
                                     callback_data="page %d" %
                                     (page_number - 1)))
        if i + size < currencies_count:
            control_buttons.append(
                InlineKeyboardButton(text=">>>",
                                     callback_data="page %d" %
                                     (page_number + 1)))

        inline_keyboard.row(*control_buttons)
        return inline_keyboard
Пример #30
0
def set_order(game):
    if not any(p['role'] == 'mafia' for p in game['players']):
        go_to_next_stage(game, inc=2)
        return

    keyboard = InlineKeyboardMarkup(row_width=8)
    keyboard.add(*[
        InlineKeyboardButton(text=f'{i + 1}',
                             callback_data=f'append to order {i + 1}')
        for i, player in enumerate(game['players'])
    ])
    keyboard.row(
        InlineKeyboardButton(text='Познакомиться с командой',
                             callback_data='mafia team'))
    keyboard.row(
        InlineKeyboardButton(text='Закончить выбор',
                             callback_data='end order'))

    message_id = bot.send_message(
        game['chat'],
        f'{role_titles["don"].capitalize()}, тебе предстоит сделать свой выбор и определить порядок выстрелов твоей команды.\nДля этого последовательно нажимай на номера игроков, а после этого нажми на кнопку "Закончить выбор".',
        reply_markup=keyboard).message_id

    database.games.update_one({'_id': game['_id']},
                              {'$set': {
                                  'message_id': message_id
                              }})
Пример #31
0
def get_inline_no_query():
    """Возвращает ответ на пустую строку запроса.

    :rtype: list
    """
    markup = InlineKeyboardMarkup()
    markup.row(InlineKeyboardButton('Бота в другой чат', switch_inline_query=''))
    markup.row(
        InlineKeyboardButton('Дзен', switch_inline_query_current_chat='zen '),
        InlineKeyboardButton('Поиск PEP', switch_inline_query_current_chat='pep '),
    )
    markup.row(
        InlineKeyboardButton('На pythonz.net', url='http://pythonz.net/'),
    )

    results = [
        telebot.types.InlineQueryResultArticle(
            'index',
            'Пульт управления роботом',
            telebot.types.InputTextMessageContent(
                'Нажимайте на кнопки, расположенные ниже, — получайте результат.'),
            description='Нажмите сюда, чтобы вызвать пульт.',
            reply_markup=markup,
        )
    ]
    return results