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 :-
Open the Telegram app and search for BotFather.
Start a chat with BotFather by sending the
/start
command.Use the
/newbot
command to create a new bot. Set a name and username for your bot.Copy the token provided by BotFather and replace
'bot_token'
in the Python code with this 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 :-
Save the Python code in a
.py
file.Open your terminal or command prompt and navigate to the directory containing the
.py
file.Run the bot script by executing the command:
python filename.py
.
Step 4: Interacting with Your Bot
Open your Telegram app and search for your bot's username.
Start a chat with your bot.
Send the
/start
command to initiate the keyboard.You will receive a custom keyboard with "Button 1" and "Button 2".
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!