Build a Telegram Bot in Python
Chatbots have become an indispensable tool for automating workflows, delivering real-time notifications, providing customer support, and building interactive community interfaces. Among messaging platforms, **Telegram** stands out as a developer favorite due to its exceptionally robust, fast, and free Bot API.
Python is one of the most popular languages for building bots thanks to its clean syntax and powerful wrapper libraries like `python-telegram-bot`. This comprehensive tutorial walks through creating a Telegram bot from scratch, registering commands, handling incoming messages, and deploying your bot code.
1. Creating a Bot via BotFather and Environment Setup
Before writing any code, you must register your bot with Telegram's master bot manager, **BotFather**:
- Open Telegram and search for `@BotFather`.
- Send the command `/newbot` and follow the prompts to choose a display name and a unique username ending in `_bot`.
- BotFather will issue your unique **API Token** (e.g., `123456789:ABCdefGhIJKlmNoPQRsTUVwxyZ`). Keep this token secure.
# Terminal setup and installation commands
mkdir telegram-bot-app
cd telegram-bot-app
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install python-telegram-bot python-dotenv
2. Writing the Bot Script with `python-telegram-bot`
Create a `bot.py` file to handle `/start`, `/help`, and echo text responses using version 20+ of the `python-telegram-bot` asynchronous application builder.
# bot.py
import logging
import os
from telegram import Update
from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler, MessageHandler, filters
from dotenv import load
load_dotenv()
TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "YOUR_BOT_TOKEN_HERE");
# Enable logging
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
);
logger = logging.getLogger(__name__);
async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
user = update.effective_user;
await update.message.reply_text(
f"Hello {user.first_name}! Welcome to your custom CodeCrown Telegram bot. Send any message to get started!"
);
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text(
"Available Commands:\n/start - Initialize bot\n/help - Display help menu"
);
async def echo_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_text = update.message.text;
await update.message.reply_text(f"Echo: {user_text}");
if __name__ == '__main__':
# Build application instance
application = ApplicationBuilder().token(TELEGRAM_BOT_TOKEN).build();
# Register command and message handlers
application.add_handler(CommandHandler("start", start_command));
application.add_handler(CommandHandler("help", help_command));
application.add_handler(MessageHandler(filters.TEXT & (~filters.COMMAND), echo_message));
print("🤖 Telegram Bot is polling for updates...");
application.run_polling();
3. Running and Testing Your Bot
Set your token in a `.env` file or export it as an environment variable, then run your Python script.
# .env configuration file
TELEGRAM_BOT_TOKEN=123456789:ABCdefGhIJKlmNoPQRsTUVwxyZ
# Run bot script
python bot.py
Open Telegram, search for your bot's username, click **Start**, and test sending custom text messages to watch your bot echo responses live.
Conclusion
Building Telegram bots in Python using `python-telegram-bot` is straightforward and powerful. By combining command handlers, message filters, and async event loops, you can scale simple bots into full-fledged automation assistants and web service integrations.