Certainly! Below is an example of a simple Python Telegram bot using the telebot library, which you can use to create a bot that responds to basic text commands. Please ensure that you have already created a bot on Telegram and obtained your bot token via BotFather.
First, make sure you have the pytelegrambotapi library installed. You can install it using pip:
pip install pytelegrambotapi
Here's a basic example of a Python script that uses the telebot library:
import telebot
# Replace 'YOUR_BOT_TOKEN' with your bot's token
TOKEN = 'YOUR_BOT_TOKEN'
bot = telebot.TeleBot(TOKEN)
# A handler for the /start command
@bot.message_handler(commands=['start'])
def send_welcome(message):
bot.reply_to(message, "Hello! Welcome to our bot. Type /help to see available commands.")
# A handler for the /help command
@bot.message_handler(commands=['help'])
def send_help(message):
help_text = """
Available commands:
/start - Welcome message
/help - List of commands
/about - Learn more about this bot
"""
bot.reply_to(message, help_text)
# A handler for the /about command
@bot.message_handler(commands=['about'])
def send_about(message):
bot.reply_to(message, "This is a simple bot created using the telebot library.")
# A handler for text messages
@bot.message_handler(func=lambda message: True, content_types=['text'])
def echo_all(message):
bot.reply_to(message, f"You said: {message.text}")
# Polling the Telegram servers
bot.polling()
Explanation:
- Token: Replace
'YOUR_BOT_TOKEN' with your actual Telegram bot token.
- Handlers: We define handlers for specific commands:
/start: Sends a welcome message.
/help: Returns a list of available commands with a brief description.
/about: Provides information about the bot.
- Echo Functionality: For any text message received that doesn't match a command, the bot replies by echoing the message back to the user.
Running the Bot:
To run the bot, save the script to a file, say bot.py, and execute it using Python:
python bot.py
This will start the bot, and it will listen for incoming messages, responding based on the handlers defined in the script.
Important Note:
- Make sure to keep your bot token secure and not share it publicly.
- Ensure your bot is allowed by Telegram to access messages, particularly in groups if needed.
- The method
bot.polling() can be replaced with webhook integration for deploying the bot in a production environment.