Slide 8
Slide 8 text
BOT API CODE
IMPLEMENTATION
Webhook Setup: Configure your bot to receive updates via HTTPS callbacks
# Set up webhook using requests library
import requests
TOKEN = "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11"
WEBHOOK_URL = "https://your-domain.com/webhook"
api_url = f"https://api.telegram.org/bot{TOKEN}/setWebhook"
params = {
"url": WEBHOOK_URL,
"allowed_updates": ["channel_post"],
}
response = requests.post(api_url, json=params)
print(response.json())
Benefits of Webhook Approach:
Immediate update delivery (no polling delay)
More efficient than long polling for high-traffic bots
Can be deployed on serverless platforms
WEBHOOK HANDLER EXAMPLE
# Flask webhook handler example
from flask import Flask, request, jsonify
import json
app = Flask(__name__)
BOT_TOKEN = "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11"
@app.route(f"/webhook", methods=['POST'])
def webhook_handler():
# Parse incoming update
update = request.get_json()
# Check if update contains channel post
if 'channel_post' in update:
channel_post = update['channel_post']
chat_id = channel_post['chat']['id']
message_id = channel_post['message_id']
message_text = channel_post.get('text', "")
# Process channel post
process_channel_post(chat_id, message_id, message_text)
return jsonify({'ok': True})
def process_channel_post(chat_id, message_id, text):
# Your processing logic here
print(f"New post in {chat_id}: {text[:30]}...")
# Save to database, trigger notifications, etc.
Deployment: Host on HTTPS-enabled server (Cloudflare Workers, Vercel, etc.)
Security: Optionally add secret_token parameter to setWebhook for request
validation
8