Skip to content

Production-ready Telegram bot template using python-telegram-bot. Includes commands, inline keyboards, callback handlers, MongoDB integration, and Docker support.

License

Notifications You must be signed in to change notification settings

botdev-community/telegram-bot-starter

Repository files navigation

Telegram Bot Starter 🤖

BotDev Community Python python-telegram-bot License

Production-ready Telegram bot template using python-telegram-bot

A complete, production-ready starter template for building Telegram bots using the official python-telegram-bot library. Built with async/await, this template includes command handlers, inline keyboards, callback handling, and database integration.

✨ Features

  • python-telegram-bot v20+ - Latest async library
  • Command Handlers - /start, /help, custom commands
  • Inline Keyboards - Interactive buttons
  • Callback Handlers - Button press handling
  • Conversation Handler - Multi-step interactions
  • Media Support - Send/receive images, documents, audio
  • MongoDB Integration - Store user data and conversations
  • Error Handling - Comprehensive error management
  • Logging - Structured logging system
  • Docker Support - Easy deployment
  • Production Ready - Battle-tested patterns

📋 Prerequisites

  • Python 3.9 or higher
  • Telegram Bot Token (from @BotFather)
  • MongoDB (local or cloud)

🚀 Quick Start

1. Clone the Repository

git clone https://github.com/botdev-community/telegram-bot-starter.git
cd telegram-bot-starter

2. Install Dependencies

# Create virtual environment
python -m venv venv

# Activate virtual environment
# On Windows:
venv\Scripts\activate
# On macOS/Linux:
source venv/bin/activate

# Install dependencies
pip install -r requirements.txt

3. Get Your Bot Token

  1. Open Telegram and search for @BotFather
  2. Send /newbot command
  3. Follow the prompts to create your bot
  4. Copy the bot token provided

4. Configure Environment Variables

Create a .env file:

# Telegram Bot Configuration
TELEGRAM_BOT_TOKEN=your_bot_token_here

# MongoDB Configuration
MONGODB_URL=mongodb://localhost:27017
MONGODB_DB_NAME=telegram_bot

# Application Configuration
ENVIRONMENT=development
LOG_LEVEL=INFO

# Optional
ADMIN_USER_IDS=123456789,987654321

5. Run the Bot

python bot.py

Your bot is now running! Open Telegram and send /start to your bot.

📁 Project Structure

telegram-bot-starter/
├── bot.py                      # Main bot file
├── config.py                   # Configuration management
├── handlers/
│   ├── __init__.py
│   ├── start.py                # /start command
│   ├── help.py                 # /help command
│   ├── commands.py             # Custom commands
│   ├── callbacks.py            # Button callbacks
│   └── conversation.py         # Multi-step conversations
├── services/
│   ├── __init__.py
│   ├── database.py             # Database operations
│   └── message_builder.py     # Message formatting
├── utils/
│   ├── __init__.py
│   ├── logger.py               # Logging configuration
│   └── decorators.py           # Helper decorators
├── deployment/
│   ├── Dockerfile
│   └── docker-compose.yml
├── .env.example
├── .gitignore
├── requirements.txt
└── README.md

🎮 Bot Commands

Default Commands

  • /start - Start the bot and see welcome message
  • /help - Display help information
  • /menu - Show interactive menu
  • /settings - User settings
  • /stats - Bot statistics
  • /about - About the bot

Custom Commands (Examples)

  • /echo <text> - Echo back your message
  • /poll - Create a quick poll
  • /reminder - Set a reminder

💡 Usage Examples

Basic Command Handler

from telegram import Update
from telegram.ext import ContextTypes

async def hello_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Handle /hello command"""
    await update.message.reply_text("Hello! 👋")

Inline Keyboard

from telegram import InlineKeyboardButton, InlineKeyboardMarkup

keyboard = [
    [
        InlineKeyboardButton("Option 1", callback_data="opt_1"),
        InlineKeyboardButton("Option 2", callback_data="opt_2")
    ],
    [InlineKeyboardButton("Cancel", callback_data="cancel")]
]
reply_markup = InlineKeyboardMarkup(keyboard)

await update.message.reply_text(
    "Choose an option:",
    reply_markup=reply_markup
)

Callback Handler

async def button_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Handle button presses"""
    query = update.callback_query
    await query.answer()
    
    if query.data == "opt_1":
        await query.edit_message_text("You chose Option 1!")

Send Photo

await update.message.reply_photo(
    photo="https://example.com/image.jpg",
    caption="Here's your image!"
)

Send Document

await update.message.reply_document(
    document=open("file.pdf", "rb"),
    filename="document.pdf"
)

🔧 Configuration

Environment Variables

Variable Description Required Default
TELEGRAM_BOT_TOKEN Bot token from @BotFather Yes -
MONGODB_URL MongoDB connection URL No mongodb://localhost:27017
MONGODB_DB_NAME Database name No telegram_bot
ENVIRONMENT Environment (dev/prod) No development
LOG_LEVEL Logging level No INFO
ADMIN_USER_IDS Admin user IDs (comma-separated) No -

🎨 Customization

Adding New Commands

  1. Create a new handler in handlers/:
# handlers/mycommand.py
from telegram import Update
from telegram.ext import ContextTypes

async def my_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Handle /mycommand"""
    await update.message.reply_text("My custom command!")
  1. Register it in bot.py:
from handlers.mycommand import my_command

application.add_handler(CommandHandler("mycommand", my_command))

Adding Conversation Flow

from telegram.ext import ConversationHandler

# Define states
CHOOSING, TYPING_REPLY = range(2)

# Create conversation handler
conv_handler = ConversationHandler(
    entry_points=[CommandHandler("start", start)],
    states={
        CHOOSING: [MessageHandler(filters.TEXT, regular_choice)],
        TYPING_REPLY: [MessageHandler(filters.TEXT, received_information)]
    },
    fallbacks=[CommandHandler("cancel", cancel)]
)

🐳 Docker Deployment

Using Docker Compose

# Build and run
docker-compose up -d

# View logs
docker-compose logs -f

# Stop
docker-compose down

Using Docker Only

# Build image
docker build -t telegram-bot .

# Run container
docker run -d \
  --name telegram-bot \
  --env-file .env \
  telegram-bot

☁️ Deployment Options

Railway

npm install -g @railway/cli
railway login
railway init
railway up

Heroku

heroku create your-bot-name
heroku config:set TELEGRAM_BOT_TOKEN=your_token
git push heroku main

VPS (Ubuntu)

# Install dependencies
sudo apt update
sudo apt install python3 python3-pip python3-venv

# Clone and setup
git clone your-repo
cd telegram-bot-starter
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt

# Create systemd service
sudo nano /etc/systemd/system/telegram-bot.service

Service file:

[Unit]
Description=Telegram Bot
After=network.target

[Service]
Type=simple
User=your_user
WorkingDirectory=/path/to/bot
ExecStart=/path/to/venv/bin/python bot.py
Restart=always

[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable telegram-bot
sudo systemctl start telegram-bot

🧪 Testing

# Run tests
pytest

# Run with coverage
pytest --cov=. tests/

# Run specific test
pytest tests/test_handlers.py

📊 Features Included

Message Types

  • ✅ Text messages
  • ✅ Photos
  • ✅ Videos
  • ✅ Documents
  • ✅ Audio files
  • ✅ Voice messages
  • ✅ Stickers
  • ✅ Location
  • ✅ Contact

Interactive Elements

  • ✅ Inline keyboards
  • ✅ Reply keyboards
  • ✅ Inline queries
  • ✅ Callback queries
  • ✅ Poll creation

Advanced Features

  • ✅ Multi-step conversations
  • ✅ User state management
  • ✅ Rate limiting
  • ✅ Error handling
  • ✅ Admin commands
  • ✅ Database integration
  • ✅ Scheduled tasks

🔒 Security Best Practices

  1. Never commit your bot token - Use environment variables
  2. Validate user input - Always sanitize inputs
  3. Rate limiting - Prevent spam/abuse
  4. Admin checks - Verify user permissions
  5. Error handling - Don't expose internal errors
  6. HTTPS only - Use webhooks with SSL in production

📖 Resources

Official Documentation

Tutorials

🐛 Troubleshooting

Bot Not Responding

  1. Check bot token is correct
  2. Verify bot is running
  3. Check logs for errors
  4. Ensure network connectivity

Database Connection Issues

  1. Verify MongoDB is running
  2. Check connection string
  3. Ensure database exists
  4. Check user permissions

Commands Not Working

  1. Check handler is registered
  2. Verify command format
  3. Check for errors in logs
  4. Test with simple command first

🤝 Contributing

We welcome contributions! See CONTRIBUTING.md for guidelines.

💬 Community

This project is maintained by BotDev Community.

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments

  • python-telegram-bot library by Leandro Toledo
  • Telegram Bot API by Telegram
  • BotDev Community contributors

About

Production-ready Telegram bot template using python-telegram-bot. Includes commands, inline keyboards, callback handlers, MongoDB integration, and Docker support.

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published