Клавиатуры telegram bot python

ReplyKeyboardMarkup¶

https://core.telegram.org/file/464001950/1191a/2RwpmgU-swU.123554/b50478c124d5914c23

class telegram. ReplyKeyboardMarkup ( keyboard , resize_keyboard = None , one_time_keyboard = None , selective = None , input_field_placeholder = None , is_persistent = None , * , api_kwargs = None ) [source] ¶ Bases: telegram.TelegramObject This object represents a custom keyboard with reply options. Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if their size of keyboard and all the buttons are equal.

  • telegram.Bot.copy_message()
  • telegram.Bot.send_animation()
  • telegram.Bot.send_audio()
  • telegram.Bot.send_contact()
  • telegram.Bot.send_dice()
  • telegram.Bot.send_document()
  • telegram.Bot.send_location()
  • telegram.Bot.send_message()
  • telegram.Bot.send_photo()
  • telegram.Bot.send_poll()
  • telegram.Bot.send_sticker()
  • telegram.Bot.send_venue()
  • telegram.Bot.send_video_note()
  • telegram.Bot.send_video()
  • telegram.Bot.send_voice()

An another kind of keyboard would be the telegram.InlineKeyboardMarkup .

  • Example usage: A user requests to change the bot’s language, bot replies to the request with a keyboard to select the new language. Other users in the group don’t see the keyboard.
  • Conversation Bot
  • Conversation Bot 2
  • keyboard (Sequence[Sequence[ str | telegram.KeyboardButton ]]) – Array of button rows, each represented by an Array of telegram.KeyboardButton objects.
  • resize_keyboard ( bool , optional) – Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard smaller if there are just two rows of buttons). Defaults to False , in which case the custom keyboard is always of the same height as the app’s standard keyboard.
  • one_time_keyboard ( bool , optional) – Requests clients to hide the keyboard as soon as it’s been used. The keyboard will still be available, but clients will automatically display the usual letter-keyboard in the chat — the user can press a special button in the input field to see the custom keyboard again. Defaults to False .
  • selective ( bool , optional) – Use this parameter if you want to show the keyboard to specific users only. Targets:
    1. Users that are @mentioned in the text of the telegram.Message object.
    2. If the bot’s message is a reply (has reply_to_message_id ), sender of the original message.

Array of button rows, each represented by an Array of telegram.KeyboardButton objects.

Optional. Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard smaller if there are just two rows of buttons). Defaults to False , in which case the custom keyboard is always of the same height as the app’s standard keyboard.

Читайте также:  Using mysql with python

Optional. Requests clients to hide the keyboard as soon as it’s been used. The keyboard will still be available, but clients will automatically display the usual letter-keyboard in the chat — the user can press a special button in the input field to see the custom keyboard again. Defaults to False .

Optional. Show the keyboard to specific users only. Targets:

  1. Users that are @mentioned in the text of the telegram.Message object.
  2. If the bot’s message is a reply (has reply_to_message_id ), sender of the original message.

Optional. The placeholder to be shown in the input field when the keyboard is active; 1 — 64 characters.

Optional. Requests clients to always show the keyboard when the regular keyboard is hidden. If False , the custom keyboard can be hidden and opened with a keyboard icon.

classmethod from_button ( button , resize_keyboard = False , one_time_keyboard = False , selective = False , input_field_placeholder = None , is_persistent = None , ** kwargs ) [source] ¶

ReplyKeyboardMarkup([[button]], **kwargs) 

Return a ReplyKeyboardMarkup from a single KeyboardButton.

  • button ( telegram.KeyboardButton | str ) – The button to use in the markup.
  • resize_keyboard ( bool , optional) – Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard smaller if there are just two rows of buttons). Defaults to False , in which case the custom keyboard is always of the same height as the app’s standard keyboard.
  • one_time_keyboard ( bool , optional) – Requests clients to hide the keyboard as soon as it’s been used. The keyboard will still be available, but clients will automatically display the usual letter-keyboard in the chat — the user can press a special button in the input field to see the custom keyboard again. Defaults to False .
  • selective ( bool , optional) – Use this parameter if you want to show the keyboard to specific users only. Targets:
    1. Users that are @mentioned in the text of the Message object.
    2. If the bot’s message is a reply (has reply_to_message_id ), sender of the original message.
ReplyKeyboardMarkup([[button] for button in button_column], **kwargs) 

Return a ReplyKeyboardMarkup from a single column of KeyboardButtons.

  1. Users that are @mentioned in the text of the Message object.
  2. If the bot’s message is a reply (has reply_to_message_id ), sender of the original message.
ReplyKeyboardMarkup([button_row], **kwargs) 

Return a ReplyKeyboardMarkup from a single row of KeyboardButtons.

  1. Users that are @mentioned in the text of the Message object.
  2. If the bot’s message is a reply (has reply_to_message_id ), sender of the original message.

Источник

Создание кнопок для телеграмм бота с использованием библиотеки pyTelegramBotAPI

Доброго времени суток. Телеграмм — божественный месседж скаченный у каждого на телефонах/компьютерах и не только. После прочтение этой статьи вы научитесь создавать кнопки для вашего телеграмм бота. Желаю удачи, в прочтении!)

Предупреждение

Забыл предупредить, в этой статье не будет сказано о создание бота, получение токена через BotFather. Для этого прочитайте документацию библиотеки или посмотрите ролики на эту тему в ютубе(Для удобство ссылку на документацию на русском языке библиотеки pyTelegramBotAPI оставлю в описании). И так, вернемся к теме.

Создание url кнопки

Url кнопки используются, когда хотим создать кнопку при клике которой, пользователь переходил на сайт. Пример:

нажима на «перейти», телеграмм перекинет его на сайт, который вы оставили при создание url кнопки, но как же собственно создать? Легко!

import telebot from telebot import types # для указание типов import config bot = telebot.TeleBot(config.token) # токен лежит в файле config.py @bot.message_handler(commands=['start']) #создаем команду def start(message): markup = types.InlineKeyboardMarkup() button1 = types.InlineKeyboardButton("Сайт Хабр", url='https://habr.com/ru/all/') markup.add(button1) bot.send_message(message.chat.id, "Привет, ! Нажми на кнопку и перейди на сайт)".format(message.from_user), reply_markup=markup)kup) bot.polling(none_stop=True)

при создание url-кнопки используется тип InlineKeyboardMarkup, в который мы добавляем кнопку и с помощью reply_markup=markup выводим это в чат(обязательно не забудьте указать это, иначе ваша кнопка просто не будете отображаться).

Создание Reply кнопки

Я не знаю как корректно называются кнопки использующие тип ReplyKeyboardMarkup, но я много практиковался в их создание и покажу вам, как это делается. Вот пример Reply кнопок:

import telebot from telebot import types # для указание типов import config bot = telebot.TeleBot(config.token) @bot.message_handler(commands=['start']) def start(message): markup = types.ReplyKeyboardMarkup(resize_keyboard=True) btn1 = types.KeyboardButton("👋 Поздороваться") btn2 = types.KeyboardButton("❓ Задать вопрос") markup.add(btn1, btn2) bot.send_message(message.chat.id, text="Привет, ! Я тестовый бот для твоей статьи для habr.com".format(message.from_user), reply_markup=markup) @bot.message_handler(content_types=['text']) def func(message): if(message.text == "👋 Поздороваться"): bot.send_message(message.chat.id, text="Привеет.. Спасибо что читаешь статью!)") elif(message.text == "❓ Задать вопрос"): markup = types.ReplyKeyboardMarkup(resize_keyboard=True) btn1 = types.KeyboardButton("Как меня зовут?") btn2 = types.KeyboardButton("Что я могу?") back = types.KeyboardButton("Вернуться в главное меню") markup.add(btn1, btn2, back) bot.send_message(message.chat.id, text="Задай мне вопрос", reply_markup=markup) elif(message.text == "Как меня зовут?"): bot.send_message(message.chat.id, "У меня нет имени..") elif message.text == "Что я могу?": bot.send_message(message.chat.id, text="Поздороваться с читателями") elif (message.text == "Вернуться в главное меню"): markup = types.ReplyKeyboardMarkup(resize_keyboard=True) button1 = types.KeyboardButton("👋 Поздороваться") button2 = types.KeyboardButton("❓ Задать вопрос") markup.add(button1, button2) bot.send_message(message.chat.id, text="Вы вернулись в главное меню", reply_markup=markup) else: bot.send_message(message.chat.id, text="На такую комманду я не запрограммировал..") bot.polling(none_stop=True)

И так. Что бы создать Replay кнопку, нужно создать переменную, я назвал ее markup(9 строчка кода) в нее помещаем types.ReplyKeyboardMarkup(resize_keyboard=True). Resize_keybord=True выполняет функцию адаптации(я всегда указываю и вам советую тоже).После этого мы создаем переменную уже с самими кнопками и их текстом(10, 11 строчка) и затем добавляем эти переменные коммандой markup.add(__имя ваших переменных__). Коммандой bot.send_message(message.chat.id, text=»Привет, ! Я тестовый бот для твоей статьи для habr.com».format(message.from_user), reply_markup=markup) и обязательно не забывайте добавлять reply_markup=markup, иначе просто кнопки не будут отображаться.

Заключение

Большое спасибо вам за прочтение. Не судите строго, это моя первая статья, рассказал я скорее всего не очень, и только поверхностно. Если хотите углубиться в эту тему, почитайте документацию, кстати, вот документация по pyTelegramBotAPI на русском:

  • https://github-com.translate.goog/eternnoir/pyTelegramBotAPI?_x_tr_sl=auto&_x_tr_tl=ru&_x_tr_hl=ru&_x_tr_pto=nui при переходе вниз скролите и вы увидите документацию. пишите комменты с отзывами, буду рад их прочитать.
  • Мой телеграмм канал: https://t.me/it_diaryy

Источник

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