Want complete projects instead of snippets? Download the starter bot templates: ZIPs with README, Dockerfile, tests and MIT license.
Telegram bot in Node.js (grammY, long polling)
Commands, an echo handler and error logging. Run with BOT_TOKEN=... node bot.mjs.
Install: npm i grammy
import { Bot } from "grammy";
const bot = new Bot(process.env.BOT_TOKEN);
bot.command("start", (ctx) =>
ctx.reply("Hello! Send me any text and I will echo it. /help lists commands."));
bot.command("help", (ctx) => ctx.reply("/start - greeting\n/help - this message"));
bot.on("message:text", (ctx) => ctx.reply(ctx.message.text));
bot.catch((err) => console.error("Handler error:", err.error));
// Long polling: no public URL needed. Stops cleanly on Ctrl+C.
bot.start({ onStart: (me) => console.log(`Running as @${me.username}`) });
process.once("SIGINT", () => bot.stop());
process.once("SIGTERM", () => bot.stop());
Telegram bot in Python (python-telegram-bot v21+)
Async handlers for /start and text messages using long polling.
Install: pip install python-telegram-bot
import logging
import os
from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters
logging.basicConfig(level=logging.INFO)
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
await update.message.reply_text("Hello! Send me any text and I will echo it.")
async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
await update.message.reply_text(update.message.text)
def main() -> None:
app = Application.builder().token(os.environ["BOT_TOKEN"]).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))
app.run_polling(allowed_updates=Update.ALL_TYPES)
if __name__ == "__main__":
main()
Telegram webhook bot on Cloudflare Workers
Verifies the secret_token header, answers quickly and calls sendMessage. Set the webhook with setWebhook and the same secret.
Install: npm create cloudflare@latest
export default {
async fetch(request, env, ctx) {
if (request.method !== "POST") return new Response("ok");
// Telegram sends the secret you passed to setWebhook in this header.
if (request.headers.get("X-Telegram-Bot-Api-Secret-Token") !== env.WEBHOOK_SECRET) {
return new Response("forbidden", { status: 403 });
}
const update = await request.json();
const msg = update.message;
if (msg?.text) {
// Reply after returning 200 so Telegram does not retry.
ctx.waitUntil(send(env, msg.chat.id, msg.text === "/start" ? "Hello from a Worker!" : msg.text));
}
return new Response("ok");
},
};
async function send(env, chatId, text) {
const res = await fetch(`https://api.telegram.org/bot${env.BOT_TOKEN}/sendMessage`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ chat_id: chatId, text }),
});
if (!res.ok) console.error("sendMessage failed", res.status, await res.text());
}
Discord slash command bot in Node.js (discord.js v14)
Registers a guild command on startup and replies ephemerally. Needs DISCORD_TOKEN, CLIENT_ID and GUILD_ID.
Install: npm i discord.js
import { Client, Events, GatewayIntentBits, MessageFlags, REST, Routes, SlashCommandBuilder } from "discord.js";
const { DISCORD_TOKEN, CLIENT_ID, GUILD_ID } = process.env;
const commands = [
new SlashCommandBuilder().setName("ping").setDescription("Check that the bot is alive").toJSON(),
];
// Guild commands update instantly; use Routes.applicationCommands for global ones.
await new REST().setToken(DISCORD_TOKEN).put(Routes.applicationGuildCommands(CLIENT_ID, GUILD_ID), { body: commands });
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
client.once(Events.ClientReady, (c) => console.log(`Ready as ${c.user.tag}`));
client.on(Events.InteractionCreate, async (interaction) => {
if (!interaction.isChatInputCommand()) return;
if (interaction.commandName === "ping") {
await interaction.reply({ content: `Pong (${client.ws.ping} ms)`, flags: MessageFlags.Ephemeral });
}
});
client.login(DISCORD_TOKEN);
Discord slash command bot in Python (discord.py 2.x)
Uses an app_commands tree synced to one guild for fast iteration.
Install: pip install discord.py
import os
import discord
from discord import app_commands
intents = discord.Intents.default()
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)
GUILD = discord.Object(id=int(os.environ["GUILD_ID"]))
@tree.command(name="ping", description="Check that the bot is alive", guild=GUILD)
async def ping(interaction: discord.Interaction) -> None:
await interaction.response.send_message(f"Pong ({round(client.latency * 1000)} ms)", ephemeral=True)
@client.event
async def on_ready() -> None:
await tree.sync(guild=GUILD)
print(f"Ready as {client.user}")
client.run(os.environ["DISCORD_TOKEN"])
Slack app in Node.js (Bolt, Socket Mode)
Socket Mode needs no public URL. Requires a bot token (xoxb-) and an app-level token (xapp-) with connections:write.
Install: npm i @slack/bolt
import bolt from "@slack/bolt";
const { App } = bolt;
const app = new App({
token: process.env.SLACK_BOT_TOKEN,
appToken: process.env.SLACK_APP_TOKEN,
socketMode: true,
});
app.message("hello", async ({ message, say }) => {
await say(`Hi <@${message.user}>!`);
});
app.command("/status", async ({ ack, respond }) => {
await ack(); // acknowledge within 3 seconds
await respond("All systems normal.");
});
await app.start();
console.log("Bolt app running in Socket Mode");
Slack app in Python (Bolt, Socket Mode)
Same behavior as the Node.js version.
Install: pip install slack_bolt
import os
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler
app = App(token=os.environ["SLACK_BOT_TOKEN"])
@app.message("hello")
def hello(message, say):
say(f"Hi <@{message['user']}>!")
@app.command("/status")
def status(ack, respond):
ack() # acknowledge within 3 seconds
respond("All systems normal.")
if __name__ == "__main__":
SocketModeHandler(app, os.environ["SLACK_APP_TOKEN"]).start()
WhatsApp Cloud API webhook in Node.js (no dependencies)
Handles the verification handshake, checks X-Hub-Signature-256 against the raw body and replies to text messages.
Install: Node.js 20+
import crypto from "node:crypto";
import http from "node:http";
const { VERIFY_TOKEN, APP_SECRET, WHATSAPP_TOKEN, PHONE_NUMBER_ID, PORT = 3000 } = process.env;
const GRAPH = "https://graph.facebook.com/v21.0"; // use the current Graph API version
http.createServer(async (req, res) => {
const url = new URL(req.url, "http://localhost");
if (url.pathname !== "/webhook") return res.writeHead(404).end();
if (req.method === "GET") {
const ok = url.searchParams.get("hub.mode") === "subscribe" && url.searchParams.get("hub.verify_token") === VERIFY_TOKEN;
return res.writeHead(ok ? 200 : 403).end(ok ? url.searchParams.get("hub.challenge") : "");
}
const chunks = [];
for await (const c of req) chunks.push(c);
const raw = Buffer.concat(chunks);
const expected = "sha256=" + crypto.createHmac("sha256", APP_SECRET).update(raw).digest("hex");
const got = String(req.headers["x-hub-signature-256"] || "");
if (got.length !== expected.length || !crypto.timingSafeEqual(Buffer.from(got), Buffer.from(expected))) {
return res.writeHead(401).end();
}
res.writeHead(200).end(); // acknowledge first
const body = JSON.parse(raw.toString("utf8"));
for (const entry of body.entry ?? []) {
for (const change of entry.changes ?? []) {
for (const msg of change.value?.messages ?? []) {
if (msg.type !== "text") continue;
await fetch(`${GRAPH}/${PHONE_NUMBER_ID}/messages`, {
method: "POST",
headers: { Authorization: `Bearer ${WHATSAPP_TOKEN}`, "Content-Type": "application/json" },
body: JSON.stringify({ messaging_product: "whatsapp", to: msg.from, type: "text", text: { body: `You said: ${msg.text.body}` } }),
});
}
}
}
}).listen(PORT, () => console.log(`Listening on :${PORT}`));
WhatsApp Cloud API webhook in Python (FastAPI)
Run with uvicorn main:app. Replies are sent in a background task after the 200 response.
Install: pip install fastapi uvicorn httpx
import hashlib
import hmac
import os
import httpx
from fastapi import BackgroundTasks, FastAPI, Request, Response
VERIFY_TOKEN = os.environ["VERIFY_TOKEN"]
APP_SECRET = os.environ["APP_SECRET"].encode()
WHATSAPP_TOKEN = os.environ["WHATSAPP_TOKEN"]
PHONE_NUMBER_ID = os.environ["PHONE_NUMBER_ID"]
GRAPH = "https://graph.facebook.com/v21.0" # use the current Graph API version
app = FastAPI()
@app.get("/webhook")
def verify(request: Request) -> Response:
p = request.query_params
if p.get("hub.mode") == "subscribe" and p.get("hub.verify_token") == VERIFY_TOKEN:
return Response(p.get("hub.challenge", ""))
return Response(status_code=403)
async def reply(to: str, text: str) -> None:
async with httpx.AsyncClient(timeout=10) as client:
await client.post(
f"{GRAPH}/{PHONE_NUMBER_ID}/messages",
headers={"Authorization": f"Bearer {WHATSAPP_TOKEN}"},
json={"messaging_product": "whatsapp", "to": to, "type": "text", "text": {"body": f"You said: {text}"}},
)
@app.post("/webhook")
async def receive(request: Request, tasks: BackgroundTasks) -> Response:
raw = await request.body()
expected = "sha256=" + hmac.new(APP_SECRET, raw, hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, request.headers.get("x-hub-signature-256", "")):
return Response(status_code=401)
body = await request.json()
for entry in body.get("entry", []):
for change in entry.get("changes", []):
for msg in change.get("value", {}).get("messages", []):
if msg.get("type") == "text":
tasks.add_task(reply, msg["from"], msg["text"]["body"])
return Response(status_code=200)
.env example for the templates
Copy to .env, fill in values and never commit the real file. Check it with the .env validator tool.
# Telegram
BOT_TOKEN=
WEBHOOK_SECRET=
# Discord
DISCORD_TOKEN=
CLIENT_ID=
GUILD_ID=
# Slack
SLACK_BOT_TOKEN=
SLACK_APP_TOKEN=
# WhatsApp Cloud API
VERIFY_TOKEN=
APP_SECRET=
WHATSAPP_TOKEN=
PHONE_NUMBER_ID=
Telegram setMyCommands JSON
A BotCommand array ready for setMyCommands.
[
{"command": "start", "description": "Start the bot"},
{"command": "help", "description": "Show help"},
{"command": "privacy", "description": "Privacy summary"},
{"command": "stop", "description": "Stop receiving messages"}
]
Register Discord guild commands (fetch)
Minimal guild command registration using fetch (no discord.js required).
Install: node --env-file=.env register.mjs
const token = process.env.DISCORD_TOKEN;
const appId = process.env.CLIENT_ID;
const guildId = process.env.GUILD_ID;
const commands = [{ name: "ping", description: "Replies with pong", type: 1 }];
const res = await fetch(`https://discord.com/api/v10/applications/${appId}/guilds/${guildId}/commands`, {
method: "PUT",
headers: { Authorization: `Bot ${token}`, "Content-Type": "application/json" },
body: JSON.stringify(commands),
});
if (!res.ok) throw new Error(await res.text());
console.log("registered", await res.json());
Verify HMAC-SHA256 in Node.js
Constant-time HMAC compare for webhook bodies.
import { createHmac, timingSafeEqual } from "node:crypto";
export function verify(secret, rawBody, headerHex) {
const dig = createHmac("sha256", secret).update(rawBody).digest("hex");
const a = Buffer.from(dig);
const b = Buffer.from(String(headerHex).replace(/^sha256=/, ""));
return a.length === b.length && timingSafeEqual(a, b);
}
Express /healthz route
Tiny liveness route that checks BOT_TOKEN presence.
Install: npm i express
export function mountHealth(app) {
app.get("/healthz", (_req, res) => {
if (!process.env.BOT_TOKEN) return res.status(500).json({ ok: false });
res.json({ ok: true });
});
}
Telegram setWebhook curl examples
curl examples for setWebhook, deleteWebhook and getWebhookInfo.
#!/usr/bin/env bash
# Replace TOKEN, URL and SECRET.
curl -s "https://api.telegram.org/bot$TOKEN/setWebhook" \
-d "url=$URL" \
-d "secret_token=$SECRET" \
-d 'allowed_updates=["message","callback_query"]'
curl -s "https://api.telegram.org/bot$TOKEN/getWebhookInfo"
In-memory update dedup (TTL)
Simple Map-based dedup for webhook retries with TTL eviction.
const seen = new Map();
export function once(id, ttlMs = 600_000) {
const now = Date.now();
for (const [k, exp] of seen) if (exp < now) seen.delete(k);
if (seen.has(id)) return false;
seen.set(id, now + ttlMs);
return true;
}
Graceful shutdown for Node bots
Stop polling/gateway cleanly on SIGTERM for containers and systemd.
export function onShutdown(stop) {
let stopping = false;
const run = async (sig) => {
if (stopping) return;
stopping = true;
console.log("shutting down on", sig);
try { await stop(); } finally { process.exit(0); }
};
process.once("SIGINT", () => run("SIGINT"));
process.once("SIGTERM", () => run("SIGTERM"));
}
Honor Retry-After helper
Parse Retry-After seconds or HTTP-date and sleep.
export function retryAfterMs(headerValue) {
if (headerValue == null) return 1000;
const s = String(headerValue).trim();
if (/^\d+(\.\d+)?$/.test(s)) return Math.ceil(parseFloat(s) * 1000);
const t = Date.parse(s);
return Number.isFinite(t) ? Math.max(0, t - Date.now()) : 1000;
}
export const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
ACK-first Express handler
Return 200 immediately then continue slow work.
Install: npm i express
app.post("/hook", (req, res) => {
res.status(200).end("ok");
setImmediate(() => doSlowWork(req.body));
});
timingSafeEqual helper
Constant-time string compare for secrets.
import { timingSafeEqual } from "node:crypto";
export function safeEqual(a, b) {
const ba = Buffer.from(String(a));
const bb = Buffer.from(String(b));
if (ba.length !== bb.length) return false;
return timingSafeEqual(ba, bb);
}
Parse Retry-After header
Convert Retry-After seconds or HTTP date to milliseconds.
export function retryAfterMs(res) {
const h = res.headers.get("retry-after");
if (!h) return 1000;
const n = Number(h);
if (!Number.isNaN(n)) return n * 1000;
const when = Date.parse(h);
return Number.isNaN(when) ? 1000 : Math.max(0, when - Date.now());
}
hmac.compare_digest verify
HMAC-SHA256 hex digest compare in Python.
import hmac, hashlib
def verify(secret: str, raw: bytes, header: str) -> bool:
digest = hmac.new(secret.encode(), raw, hashlib.sha256).hexdigest()
return hmac.compare_digest(digest, header.replace("sha256=", ""))
Ephemeral interaction reply
Discord interaction callback with ephemeral flag 64.
{
"type": 4,
"data": { "content": "Only you see this", "flags": 64 }
}
Telegram secret_token header check
Reject requests missing the setWebhook secret.
const ok = req.headers["x-telegram-bot-api-secret-token"] === process.env.WEBHOOK_SECRET;
if (!ok) return res.status(403).end("forbidden");
Minimal /healthz JSON route
Liveness endpoint returning {ok:true}.
app.get("/healthz", (_req, res) => res.json({ ok: true }));
SIGTERM closes HTTP server
Stop accepting connections then exit.
process.on("SIGTERM", () => {
server.close(() => process.exit(0));
});
Require env helper
Throw if a required environment variable is missing.
export function reqEnv(name) {
const v = process.env[name];
if (!v) throw new Error(`Missing ${name}`);
return v;
}
In-memory idempotency Set
Single-process dedupe helper (use Redis in prod).
const seen = new Set();
export function once(id) {
if (seen.has(id)) return false;
seen.add(id);
return true;
}
Slack signature base string
v0:timestamp:rawBody base for HMAC.
const base = `v0:${timestamp}:${rawBody}`;
WhatsApp verify challenge
Return hub.challenge when verify_token matches.
if (mode === "subscribe" && token === process.env.VERIFY_TOKEN) {
return challenge;
}
Next steps
- Generate a Dockerfile, systemd unit or pm2 config: Hosting config generator
- Check your environment file: .env validator
- Read the matching guide: Telegram, Discord, Slack, WhatsApp