How to send Keyboard In Telegram Bot using pyTelegramBotApi (telebot)

How to send Keyboard In Telegram Bot using pyTelegramBotApi (telebot)

In this tutorial, we'll guide you through creating a Telegram bot using Python and the Telebot library. Learn how to send a custom keyboard to users and process their responses.

Prerequisites

  • Telegram Account: You need a Telegram account to create a bot and obtain its token.

  • Python Installed: Ensure Python is installed on your system.

Step 1: Getting Your Bot Token

  1. Open the Telegram app and search for BotFather.

  2. Start a chat with BotFather using the /start command.

  3. Create a new bot with the /newbot command. Set a name and username.

  4. Copy the token provided by BotFather and replace 'bot_token' in the Python code with this token.

  5. Full Explanation On Getting Your Bot Token ki

Step 2: Writing the Python Code

import telebot
from telebot import types

bot_token = "bot_token"  # Replace with your actual token

bot = telebot.TeleBot(bot_token)

@bot.message_handler(commands=['start'])
def send_keyboard(message):
    keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True)
    button1 = types.KeyboardButton('Button 1')
    button2 = types.KeyboardButton('Button 2')
    keyboard.row(button1)
    keyboard.row(button2)
    bot.send_message(message.chat.id, "Choose an option:", reply_markup=keyboard)

@bot.message_handler()
def message_handler(message):
    if message.text == 'Button 1':
        bot.send_message(message.chat.id, 'Button 1 was pressed!')

    if message.text == 'Button 2':
        bot.send_message(message.chat.id, 'Button 2 was pressed!')

bot.polling()

Step 3: Running the Bot

  1. Save the Python code in a .py file.
  2. Open your terminal or command prompt and navigate to the directory containing the .py file.
  3. Run the bot script by executing the command: python filename.py.

Step 4: Interacting with Your Bot

  1. Open your Telegram app and search for your bot's username.
  2. Start a chat with your bot.
  3. Send the /start command to initiate the keyboard.
  4. You will receive a custom keyboard with "Button 1" and "Button 2".
  5. Pressing any button will trigger a response from the bot.

Conclusion

Congratulations! You've successfully created a Telegram bot that sends a custom keyboard to users and responds to their selections. This is a basic example, but you can build more advanced interactions using the Telebot library. Remember to refer to the official Telebot documentation for more advanced features and options. Happy bot building! ```

Did you find this article valuable?

Support Karan Coder by becoming a sponsor. Any amount is appreciated!