When developers first build a Telegram bot in Python using python-telegram-bot or telebot, they almost always start with long polling:
# The traditional polling approach — requires a 24/7 running server
import telebot
bot = telebot.TeleBot("YOUR_BOT_TOKEN")
@bot.message_handler(commands=['start', 'help'])
def send_welcome(message):
bot.reply_to(message, "Hello! I am running on a server.")
bot.infinity_polling() # Keeps an open HTTP socket forever
To run this in production, you have to spin up a VPS (EC2, DigitalOcean, or Hetzner), install Python, write a systemd service unit, configure automatic restarts, and keep the machine running 24 hours a day, 7 days a week.
If your bot handles 100 messages a day, that is approximately 30 seconds of total CPU time per month. Yet you are paying $6 to $15 every month just to keep an idle server listening for connections.
The production-grade alternative is Telegram Webhooks.
Polling vs. Webhooks: Architectural Comparison
| Feature | Long Polling (infinity_polling) |
Telegram Webhook (Serverless) |
|---|---|---|
| Server Requirements | Requires an always-on VPS / server | No server. Runs purely on demand. |
| Idle Cost | $5 – $20 / month for idle compute | $0 when idle (pay only for executions) |
| Network Overhead | Continuously holds an open HTTP socket | Telegram makes an HTTPS POST only when a message arrives |
| Crash Vulnerability | If the script unhandled-exceptions, bot dies | Every request runs in an isolated, fresh sandbox |
| Scaling | Single thread bottlenecks during spikes | Auto-scales to hundreds of concurrent users |
| Security | Hardcoded tokens on VPS | Environment secrets injected at runtime |
How Telegram Webhooks Work
Instead of your code constantly asking Telegram "Do you have new messages yet?", Telegram takes the initiative:
Telegram User Sends Message / Command
│
▼
Telegram Bot API Gateway
│
POST https://run.litelambda.in/w/my-telegram-bot
(Header: X-Telegram-Bot-Api-Secret-Token: secret_123)
│
▼
LiteLambda Micro-Runner
┌──────────────────────────────────────────────────┐
│ 1. Validate Secret Token │
│ 2. Parse Message text, Chat ID, and User ID │
│ 3. Execute logic (query DB, call AI API, etc.) │
│ 4. Reply instantly with Telegram method payload │
└──────────────────────────────────────────────────┘
Telegram also supports a performance feature: Method Responses. When handling a webhook, you can return your response directly in the HTTP 200 JSON payload instead of making a separate outbound HTTP call back to the Telegram API. This cuts roundtrip response latency by half.
The Complete Python Telegram Webhook Handler
Here is a full production-ready handler that verifies Telegram's secret token, handles commands (/start, /quote, /help), and replies with sub-second latency:
import os
import json
import requests
def handler(event, context):
"""
Handles incoming Telegram Bot webhook updates.
Runs in LiteLambda's zero-cold-start Python environment.
"""
headers = event.get("headers", {})
secret_token = headers.get("x-telegram-bot-api-secret-token")
expected_secret = os.environ.get("TELEGRAM_WEBHOOK_SECRET")
# 1. Verify Telegram Secret Token (Prevents spoofed webhooks)
if expected_secret and secret_token != expected_secret:
print("⚠️ Unauthorized request: Invalid Telegram Secret Token")
return {"status": 403, "body": "Forbidden"}
# 2. Parse Incoming Update Payload
payload = event.get("body_json") or {}
message = payload.get("message") or payload.get("edited_message")
# If no message (e.g. channel post or status change), acknowledge and exit
if not message:
return {"status": 200, "received": True}
chat_id = message.get("chat", {}).get("id")
from_user = message.get("from", {}).get("first_name", "there")
text = message.get("text", "").strip()
if not chat_id:
return {"status": 200, "received": True}
print(f"📩 Message from {from_user} ({chat_id}): {text}")
# 3. Handle Commands
if text.startswith("/start"):
reply_text = (
f"👋 Hey {from_user}! I am running serverlessly on LiteLambda.\n\n"
"Try these commands:\n"
"• `/status` - Check system uptime\n"
"• `/ping` - Test latency\n"
"• Send any question to get an instant reply!"
)
return send_telegram_response(chat_id, reply_text)
elif text.startswith("/status"):
reply_text = "🟢 System Status: Operational\n⚡ Engine: LiteLambda Serverless Python\n⏱ Cold Start: 0ms"
return send_telegram_response(chat_id, reply_text)
elif text.startswith("/ping"):
return send_telegram_response(chat_id, "🏓 Pong! Webhook latency < 45ms.")
else:
# Default echo or AI assistant logic
reply_text = f"You said: *{text}*\n\n_Processed via LiteLambda Python Webhook._"
return send_telegram_response(chat_id, reply_text)
def send_telegram_response(chat_id: int, text: str):
"""
Option A: Return method payload directly in HTTP response.
This saves a full HTTP roundtrip!
"""
return {
"status": 200,
"headers": {"Content-Type": "application/json"},
"body_json": {
"method": "sendMessage",
"chat_id": chat_id,
"text": text,
"parse_mode": "Markdown"
}
}
Why Traditional Serverless (AWS Lambda) Is Bad for Telegram Bots
While AWS Lambda eliminates servers, it suffers from 500ms – 2,500ms cold starts if your function hasn't been invoked recently. When a Telegram user sends
/startand waits 3 seconds for a response, the bot feels broken.LiteLambda micro-sandboxes stay warm with near-instant execution (<35ms). Your bot replies instantly, every single time, without paying $15/month for a VPS.
Step-by-Step Deployment Guide
Step 1: Deploy to LiteLambda
Save your script as telegram_bot.py. Deploy it via the LiteLambda CLI:
pip install litelambda-cli
litelambda login
litelambda deploy telegram-bot telegram_bot.py \
--type webhook \
--env TELEGRAM_BOT_TOKEN="123456789:ABCdefGhIJKlmNoPQRsTUVwxyZ" \
--env TELEGRAM_WEBHOOK_SECRET="super_secret_token_12345"
LiteLambda outputs your unique live HTTPS endpoint:
https://run.litelambda.in/w/telegram-bot/live_sec_89df20a
Step 2: Register the Webhook with Telegram
Call Telegram's setWebhook API with your endpoint URL and secret token using curl:
curl -X POST "https://api.telegram.org/bot<YOUR_BOT_TOKEN>/setWebhook" \
-H "Content-Type: application/json" \
-d '{
"url": "https://run.litelambda.in/w/telegram-bot/live_sec_89df20a",
"secret_token": "super_secret_token_12345",
"allowed_updates": ["message", "callback_query"]
}'
Telegram will respond with:
{
"ok": true,
"result": true,
"description": "Webhook was set"
}
Step 3: Test Your Live Bot
Open Telegram on your phone or desktop, search for your bot's username, and send /start.
Your bot will reply within milliseconds. You can inspect every incoming update and check live execution logs directly from your LiteLambda dashboard.
How to Switch Back to Polling for Local Debugging
When testing locally, you can easily remove the webhook so you can run local polling without conflicts:
# Delete webhook
curl "https://api.telegram.org/bot<YOUR_BOT_TOKEN>/deleteWebhook"
Once your changes are committed, re-deploy with litelambda deploy and set the webhook URL again.
Summary
Hosting a Telegram bot shouldn't require managing Linux servers, renewing Let's Encrypt certificates, or paying for idle cloud instances.
Switching to Telegram webhooks on LiteLambda delivers:
- Zero server maintenance: Never log into SSH or configure systemd again.
- Lower cloud bills: Pay $4.99/mo instead of keeping dedicated VPS servers alive.
- Instant response times: Sub-second execution with direct method responses.