DEV Community

NOSTRA
NOSTRA

Posted on

🐍 Build a Telegram Bot in 24 Hours: Complete Python Guide

Ever wanted to build a Telegram bot but didn't know where to start?

After building 50+ bots for clients, I've distilled everything into a single, practical guide. No fluffβ€”just code that works.
🎯 What You'll Build

A complete Telegram bot for video streaming with:

Multi-admin video upload

Smart search with filters

Role-based access (User, Admin, Owner)

Production-ready deployment
Enter fullscreen mode Exit fullscreen mode

πŸ’» Let's Start Coding
1. Setting Up Your Project

# Create project structure
mkdir my_telegram_bot
cd my_telegram_bot

# Create virtual environment
python -m venv venv
source venv/bin/activate  # Linux/Mac
# or
venv\Scripts\activate  # Windows

# Install dependencies
pip install python-telegram-bot==20.3 supabase python-dotenv

Enter fullscreen mode Exit fullscreen mode

2. Your First Bot
python

# bot.py
import os
import logging
from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes
from dotenv import load_dotenv

load_dotenv()
logging.basicConfig(level=logging.INFO)

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text("πŸ‘‹ Hello! I'm your Telegram bot!")

def main():
    token = os.getenv('TELEGRAM_TOKEN')
    app = Application.builder().token(token).build()
    app.add_handler(CommandHandler("start", start))
    app.run_polling()

if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode

3. Add Async Commands
python

async def search(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = ' '.join(context.args)
    if not query:
        await update.message.reply_text("Usage: /search <keyword>")
        return

    # Simulate async database search
    await asyncio.sleep(0.5)

    await update.message.reply_text(f"πŸ” Searching for: {query}")

Enter fullscreen mode Exit fullscreen mode

πŸ” Security Best Practices
python

# Rate limiting middleware
class RateLimiter:
    def __init__(self, max_requests: int = 30, window: int = 60):
        self.max_requests = max_requests
        self.window = window
        self.requests = {}

    async def is_allowed(self, user_id: int) -> bool:
        now = time.time()
        if user_id in self.requests:
            self.requests[user_id] = [t for t in self.requests[user_id] if now - t < self.window]
        if len(self.requests.get(user_id, [])) >= self.max_requests:
            return False
        self.requests.setdefault(user_id, []).append(now)
        return True
Enter fullscreen mode Exit fullscreen mode

πŸ—„οΈ Database Schema
sql

-- Users table
CREATE TABLE users (
    id BIGSERIAL PRIMARY KEY,
    user_id BIGINT UNIQUE NOT NULL,
    username VARCHAR(255),
    created_at TIMESTAMP DEFAULT NOW()
);

-- Videos table
CREATE TABLE videos (
    id BIGSERIAL PRIMARY KEY,
    file_id VARCHAR(255) NOT NULL,
    caption TEXT,
    tags TEXT[] DEFAULT '{}',
    owner_id BIGINT REFERENCES users(user_id),
    views INTEGER DEFAULT 0,
    upload_date TIMESTAMP DEFAULT NOW()
);

Enter fullscreen mode Exit fullscreen mode

πŸš€ Deployment on Render (Free)
yaml

# render.yaml
services:
  - type: web
    name: telegram-bot
    runtime: python
    buildCommand: pip install -r requirements.txt
    startCommand: python -m src.bot
    envVars:
      - key: TELEGRAM_TOKEN
        sync: false
      - key: SUPABASE_URL
        sync: false
      - key: SUPABASE_KEY
        sync: false
Enter fullscreen mode Exit fullscreen mode

πŸ“š Go Deeper

This tutorial covers the basics. If you want to build a complete production-ready bot with:

βœ… 8 chapters of step-by-step content
βœ… Complete source code on GitHub
βœ… Production-ready deployment
βœ… 1 formats: PDF
βœ… ENGLISH AND FRENCH VERSION
βœ… Lifetime updates
Enter fullscreen mode Exit fullscreen mode

πŸ“– Get the Full Course

"Python Bot Mastery" – Build a Telegram bot from scratch in 24 hours.

 πŸ”₯ Launch price: $10 (regular $14.99 – 33% off)

πŸ‘‰ Get your copy now

What would you build with a Telegram bot? Let me know in the comments! πŸ‘‡

Top comments (0)