Creating a Custom Keyboard for Your Telegram Bot using Python

Creating a Custom Keyboard for Your Telegram Bot using Python

Play this article

In this tutorial, we will guide you through the process of creating a Telegram bot using Python and the Telebot library. We'll focus on how to send a custom keyboard to users and process their responses. Let's get started!

Prerequisites :-

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

  • Python Installed: Make sure you have Python 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 by sending the /start command.

  3. Use the /newbot command to create a new bot. Set a name and username for your bot.

  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

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.

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!