Switch кнопки telegram python

telegram.InlineKeyboardButton¶

This object represents one button of an inline keyboard.

You must use exactly one of the optional fields. Mind that callback_game is not working as expected. Putting a game short name in it might, but is not guaranteed to work.

str – Label text on the button.

str – Optional. HTTP url to be opened when button is pressed.

str – Optional. Data to be sent in a callback query to the bot when button is pressed, 1-64 bytes.

str – Optional. Will prompt the user to select one of their chats, open that chat and insert the bot’s username and the specified inline query in the input field.

str – Optional. Will insert the bot’s username and the specified inline query in the current chat’s input field.

telegram.CallbackGame – Optional. Description of the game that will be launched when the user presses the button.

bool – Optional. Specify True, to send a Pay button.

  • text ( str ) – Label text on the button.
  • url ( str ) – HTTP url to be opened when button is pressed.
  • callback_data ( str , optional) – Data to be sent in a callback query to the bot when button is pressed, 1-64 bytes.
  • switch_inline_query ( str , optional) – If set, pressing the button will prompt the user to select one of their chats, open that chat and insert the bot’s username and the specified inline query in the input field. Can be empty, in which case just the bot’s username will be inserted. This offers an easy way for users to start using your bot in inline mode when they are currently in a private chat with it. Especially useful when combined with switch_pm* actions — in this case the user will be automatically returned to the chat they switched from, skipping the chat selection screen.
  • switch_inline_query_current_chat ( str , optional) – If set, pressing the button will insert the bot’s username and the specified inline query in the current chat’s input field. Can be empty, in which case only the bot’s username will be inserted. This offers a quick way for the user to open your bot in inline mode in the same chat — good for selecting something from multiple options.
  • callback_game ( telegram.CallbackGame , optional) – Description of the game that will be launched when the user presses the button. This type of button must always be the first button in the first row.
  • pay ( bool , optional) – Specify True, to send a Pay button. This type of button must always be the first button in the first row.
  • **kwargs ( dict ) – Arbitrary keyword arguments.
Читайте также:  Php file list server

© Copyright 2015-2018, Leandro Toledo Revision 7eeb670a .

Versions latest stable Downloads pdf On Read the Docs Project Home Builds Free document hosting provided by Read the Docs.

Источник

InlineKeyboardButton¶

class telegram. InlineKeyboardButton ( text , url = None , callback_data = None , switch_inline_query = None , switch_inline_query_current_chat = None , callback_game = None , pay = None , login_url = None , web_app = None , switch_inline_query_chosen_chat = None , * , api_kwargs = None ) [source] ¶ Bases: telegram.TelegramObject This object represents one button of an inline keyboard. Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if their text , url , login_url , callback_data , switch_inline_query , switch_inline_query_current_chat , callback_game , web_app and pay are equal.

  • You must use exactly one of the optional fields. Mind that callback_game is not working as expected. Putting a game short name in it might, but is not guaranteed to work.
  • If your bot allows for arbitrary callback data, in keyboards returned in a response from telegram, callback_data maybe be an instance of telegram.ext.InvalidCallbackData . This will be the case, if the data associated with the button was already deleted.

    If your bot allows your arbitrary callback data, buttons whose callback data is a non-hashable object will become unhashable. Trying to evaluate hash(button) will result in a TypeError .

Changed in version 20.0: web_app is considered as well when comparing objects of this type in terms of equality.

  • text ( str ) – Label text on the button.
  • url ( str , optional) – HTTP or tg:// url to be opened when the button is pressed. Links tg://user?id= can be used to mention a user by their ID without using a username, if this is allowed by their privacy settings.

Tip This is similar to the new parameter switch_inline_query_chosen_chat , but gives no control over which chats can be selected.

Caution The PTB team has discovered that this field works correctly only if your Telegram client is released after April 20th 2023.

Optional. HTTP or tg:// url to be opened when the button is pressed. Links tg://user?id= can be used to mention a user by their ID without using a username, if this is allowed by their privacy settings.

Changed in version 13.9: You can now mention a user using tg://user?id= .

Optional. An HTTPS URL used to automatically authorize the user. Can be used as a replacement for the Telegram Login Widget.

Only HTTPS links are allowed after Bot API 6.1.

Optional. Data to be sent in a callback query to the bot when button is pressed, UTF-8 1 — 64 bytes.

Optional. Description of the Web App that will be launched when the user presses the button. The Web App will be able to send an arbitrary message on behalf of the user using the method answer_web_app_query() . Available only in private chats between a user and the bot.

Читайте также:  Selenium python get innerhtml

Optional. If set, pressing the button will prompt the user to select one of their chats, open that chat and insert the bot’s username and the specified inline query in the input field. Can be empty, in which case just the bot’s username will be inserted. This offers an easy way for users to start using your bot in inline mode when they are currently in a private chat with it. Especially useful when combined with switch_pm* actions — in this case the user will be automatically returned to the chat they switched from, skipping the chat selection screen.

This is similar to the new parameter switch_inline_query_chosen_chat , but gives no control over which chats can be selected.

Optional. If set, pressing the button will insert the bot’s username and the specified inline query in the current chat’s input field. Can be empty, in which case only the bot’s username will be inserted. This offers a quick way for the user to open your bot in inline mode in the same chat — good for selecting something from multiple options.

Optional. Description of the game that will be launched when the user presses the button. This type of button must always be the first button in the first row.

Optional. Specify True , to send a Pay button. This type of button must always be the first button in the first row and can only be used in invoice messages.

Optional. If set, pressing the button will prompt the user to select one of their chats of the specified type, open that chat and insert the bot’s username and the specified inline query in the input field.

This is similar to switch_inline_query , but gives more control on which chats can be selected.

The PTB team has discovered that this field works correctly only if your Telegram client is released after April 20th 2023.

Sets callback_data to the passed object. Intended to be used by telegram.ext.CallbackDataCache .

Источник

Встроенные кнопки в Telegram Bot API — pyTelegramBotAPI

Добрый день уважаемые читатели, давайте рассмотрим, какие основные типы встроенных кнопок предлагают чат-боты telegram и в чем их особенности. Статья будет полезна всем, кто хочет разобраться в возможностях взаимодействия с пользователями telegram в версии bot API 2.0.

Для обзора возможностей нам понадобится установить 3 целых 2 десятых Python`a и пару ложек pyTelegramBotAPI. Особенности настройки и регистрации чат-бота мы рассматривать не будем, т.к. есть множество статей на эту тему.

Читайте также:  Css image width device width

И так, что же такое встроенные кнопки(клавиатура) в мессенджере Telegram? Это кнопки которые выводятся во внутренней области чата и привязываются к конкретному сообщению. Они жестко связаны с сообщением(если удалить сообщение, внутренние кнопки так же удаляются вместе с ним.). Они дают возможность динамически видоизменять его.

В данный момент есть три типа встроенных кнопок:

URL-кнопки

Для создания кнопки используется тип InlineKeyboardMarkup, давайте создадим кнопку «Наш сайт»:

@bot.message_handler(commands = ['url']) def url(message): markup = types.InlineKeyboardMarkup() btn_my_site= types.InlineKeyboardButton(text='Наш сайт', url='https://habrahabr.ru') markup.add(btn_my_site) bot.send_message(message.chat.id, "Нажми на кнопку и перейди на наш сайт.", reply_markup = markup) 

Тут название говорит само за себя, это тип кнопок предназначен для перенаправления пользователя по ссылке, с соответствующим предупреждением. Кнопка имеет соответствующий ярлычок в правом верхнем углу, чтобы дать понять пользователю, что это ссылка.

Switch-кнопки

Этот тип кнопок предназначен для перенаправления пользователя в какой либо чат, с последующей активацией (встроенного) inline-режима общения с ботом. Данный режим можно активировать вручную: в чате, вводим: «@название бота», но switch-кнопки позволяют это сделать автоматически (помогая знакомиться с inline-режимом новичкам).

Для того что-бы создать подобный переключатель, необходимо указать аргумент switch_inline_query либо пустой, либо с каким-либо текстом.

@bot.message_handler(commands = ['switch']) def switch(message): markup = types.InlineKeyboardMarkup() switch_button = types.InlineKeyboardButton(text='Try', switch_inline_query="Telegram") markup.add(switch_button) bot.send_message(message.chat.id, "Выбрать чат", reply_markup = markup) 

Теперь, если мы нажмем на кнопку и выберем чат, вот что получится:
Шаг 1:

Нажимаем на кнопку.

Шаг 2:

Выбираем чат.

Шаг 3:

Активировался встроенный inline-режим.

Callback-кнопки

Ну и наконец самое интересное — это кнопки с обратной связью: позволяют динамически обновлять сообщение/встроенные кнопки (не засоряя при этом ленту), а так же отображать уведомление в верху чат-бота или модальном окне.

Например, их можно использовать для просмотра длинного сообщения, аналогично пагинации страниц на сайтах, или например сделать календарь. Я не стану изобретать велосипед, а через поиск по GitHub, найду готовую библиотеку calendar-telegram. Выполнив указанные инструкции, получаем готовый календарь, который можно динамически изменять по нажатию на соответствующие кнопки:

@bot.message_handler(commands=['calendar']) def get_calendar(message): now = datetime.datetime.now() #Текущая дата chat_id = message.chat.id date = (now.year,now.month) current_shown_dates[chat_id] = date #Сохраним текущую дату в словарь markup = create_calendar(now.year,now.month) bot.send_message(message.chat.id, "Пожалйста, выберите дату", reply_markup=markup)

Так же можно добавить уведомление по нажатию на дату, для этого достаточно указать сообщение в ответе:

bot.answer_callback_query(call.id, text="Дата выбрана")

(Пример в десктопной версии)

(Пример в мобильной версии)

Если изменить show_alert на True, то мы получим модальное окно:

bot.answer_callback_query(call.id, show_alert=True, text="Дата выбрана")

Заключение

По последним данным, в нашумевшем мессенджере Telegram регистрируются больше 600к пользователей ежедневно. Именно поэтому важно подхватить тренд и разобраться с его основными особенностями, т.к. различные методы взаимодействия с ботами существенно облегчает жизнь разработчиков и пользователей.

Cпасибо за Ваш интерес к данной теме.

Источник

Оцените статью