DEV Community

Apollo
Apollo

Posted on

The fastest way to build a Telegram Bot natively

The Fastest Way to Build a Native Telegram Bot: A Technical Deep Dive

Building a Telegram bot natively (without third-party frameworks) offers maximum control over performance, scalability, and customization. This guide covers the fastest implementation using Python and the python-telegram-bot library while explaining core Telegram Bot API concepts.

Prerequisites

  • Python 3.10+
  • A Telegram account and @BotFather access
  • Basic async/await knowledge

Step 1: Create & Configure Your Bot

  1. Open Telegram, search for @BotFather.
  2. Run /newbot, follow prompts to get your API Token.

Step 2: Native Implementation with python-telegram-bot

This library is the most performant native wrapper for Telegram’s Bot API.

Install the Library

pip install python-telegram-bot --upgrade
Enter fullscreen mode Exit fullscreen mode

Minimal Echo Bot (Async)

from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters

TOKEN = "YOUR_API_TOKEN"

async def start(update: Update, context):
    await update.message.reply_text("Bot activated. Send any message.")

async def echo(update: Update, context):
    await update.message.reply_text(update.message.text)

def main():
    app = Application.builder().token(TOKEN).build()

    # Handlers
    app.add_handler(CommandHandler("start", start))
    app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))

    # Polling
    app.run_polling()

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

Key Components Explained:

  1. Application: Manages bot lifecycle and handlers.
  2. CommandHandler: Processes commands like /start.
  3. MessageHandler: Handles non-command messages.
  4. filters: Conditionally process messages (e.g., text-only).

Step 3: Optimizing for Performance

Webhook vs. Polling

  • Polling: Simple but higher latency. Use for development.
  • Webhook: Production-grade. Requires HTTPS endpoint.

Webhook Setup (FastAPI Example)

from fastapi import FastAPI, Request
from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes

app = FastAPI()
TOKEN = "YOUR_API_TOKEN"
bot_app = Application.builder().token(TOKEN).build()

@app.post("/webhook")
async def webhook(request: Request):
    json_data = await request.json()
    update = Update.de_json(json_data, bot_app.bot)
    await bot_app.process_update(update)
    return {"status": "ok"}

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text("Webhook active!")

def setup():
    bot_app.add_handler(CommandHandler("start", start))
Enter fullscreen mode Exit fullscreen mode

Configure Webhook via API

import requests

url = f"https://api.telegram.org/bot{TOKEN}/setWebhook?url=https://yourdomain.com/webhook"
response = requests.get(url)
print(response.json())  # Expect {"ok": true}
Enter fullscreen mode Exit fullscreen mode

Step 4: Advanced Features

1. Inline Keyboards

from telegram import InlineKeyboardButton, InlineKeyboardMarkup

async def menu(update: Update, context):
    keyboard = [
        [InlineKeyboardButton("Option 1", callback_data="1")],
        [InlineKeyboardButton("Option 2", callback_data="2")]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)
    await update.message.reply_text("Choose:", reply_markup=reply_markup)

async def button_click(update: Update, context):
    query = update.callback_query
    await query.answer(f"You chose {query.data}")

# Add handler in main():
bot_app.add_handler(CallbackQueryHandler(button_click))
Enter fullscreen mode Exit fullscreen mode

2. Rate Limiting

Use @retry and exponential backoff for API calls:

from tenacity import retry, stop_after_attempt, wait_exponential

@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))
async def safe_api_call():
    # Your API logic here
Enter fullscreen mode Exit fullscreen mode

3. Database Integration (PostgreSQL)

import asyncpg

async def save_user(user_id: int):
    conn = await asyncpg.connect("postgresql://user:pass@localhost/db")
    await conn.execute("INSERT INTO users(id) VALUES($1)", user_id)
    await conn.close()
Enter fullscreen mode Exit fullscreen mode

Step 5: Deployment

Option A: Serverless (AWS Lambda)

  1. Package dependencies with pip install -t ./package.
  2. Zip and deploy with:
cd package && zip -r ../lambda.zip . && cd ..
zip -g lambda.zip bot.py
aws lambda create-function --runtime python3.10 --handler bot.handler --zip-file fileb://lambda.zip
Enter fullscreen mode Exit fullscreen mode

Option B: Containerized (Docker)

FROM python:3.10-slim
COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
CMD ["python", "bot.py"]
Enter fullscreen mode Exit fullscreen mode

Benchmarking & Optimization

  • Throughput: A well-optimized bot handles 1K+ RPM (requests per minute).
  • Latency: Webhooks reduce response time to <500ms vs. polling’s 1–5s.
  • Load Testing: Use locust to simulate traffic:
from locust import HttpUser, task

class BotUser(HttpUser):
    @task
    def send_message(self):
        self.client.post("/webhook", json={"message": {"text": "test"}})
Enter fullscreen mode Exit fullscreen mode

Final Notes

  • Avoid Global State: Use ContextTypes for thread-safe data.
  • Error Handling: Wrap handlers in try/except and log errors.
  • Telegram API Limits: 30 messages/second, 20 messages/group/minute.

By leveraging native APIs and async patterns, you achieve sub-100ms response times. For further scaling, consider sharding or Redis-based queues.

Next Steps: Explore Telegram Bot API Docs for advanced features like payments or games.


🚀 Stop Writing Boilerplate Prompts

If you want to skip the setup and code 10x faster with complete AI architecture patterns, grab my Senior React Developer AI Cookbook ($19). It includes Server Action prompt libraries, UI component generation loops, and hydration debugging strategies.

Browse all 10+ developer products at the Apollo AI Store | Or snipe Solana tokens free via @ApolloSniper_Bot.

Top comments (0)