Creating Telegram Bot Commands
Building a Telegram Bot - Step by Step
Responding to Commands
Welcome to the second part of our Telegram bot development series. In this tutorial, we'll learn how to make your bot respond to specific commands.
Step 1: Import the Telebot Library
Start by importing the Telebot library in your Python code:
import telebot
Step 2: Initialize Your Bot
Initialize your bot using the bot token you obtained from BotFather:
bot = telebot.TeleBot("YOUR_BOT_TOKEN")
Step 3: Create a Command Handler
To respond to commands, create a handler function. For example, let's create a handler for the "/start" command:
/div> @bot.message_handler(commands=['start']) def handle_start(message): bot.send_message(message.chat.id, "Welcome to our Telegram bot! Type /help for assistance.")
Step 4: Poll for Updates
Finally, add the code to continuously poll for updates:
if __name__ == "__main__": bot.polling(none_stop=True)
Now, your bot will respond with a welcome message when someone uses the "/start" command.
Summary
In this part, we learned how to respond to commands in Telegram bots. You can create additional command handlers to make your bot do more tasks based on user commands.
Stay tuned for the next part of our series where we'll explore more advanced bot features!
Join the conversation