Telegram Bot Builder
Build production-ready Telegram bots for the Israeli market using grammY, Telegraf, or python-telegram-bot. Covers Bot API v10.0 (April 2026), webhooks vs polling, inline keyboards, Hebrew/RTL text, Telegram Stars + Gifts payments, Mini Apps 2.0, Bot Business mode, Managed Bots, and serverless deployment.
Problem
Building Telegram bots for Israeli users involves several challenges that agents consistently get wrong:
- Framework choice confusion - grammY, Telegraf, and python-telegram-bot have different Bot API version support, plugin ecosystems, and deployment models. Agents often mix their APIs or suggest deprecated patterns.
- Webhook vs polling misconfiguration - Agents default to polling (good for development) but fail to set up webhooks correctly for production, missing port restrictions (443, 80, 88, 8443 only), SSL requirements, and secret token verification.
- Hebrew/RTL text corruption - Bidirectional text mixing Hebrew and English (common in Israeli bots) breaks in inline keyboards, callback data, and formatted messages. Agents ignore Unicode control characters and text direction markers.
- Payment integration gaps - Telegram Stars (the in-app currency) has specific invoice creation flows that differ from traditional payment providers. Agents often generate code for deprecated payment APIs.
- Mini App data exchange - The communication protocol between a Telegram Mini App (WebApp) and the bot uses
web_app_dataevents, not regular messages. Agents frequently implement this incorrectly.
Framework Selection
Choose your framework based on your runtime, deployment target, and Bot API version needs:
| Feature | grammY v1.42.0 | Telegraf v4.16.3 | python-telegram-bot v22.7 |
|---------|----------------|-------------------|---------------------------|
| Language | TypeScript/JS | TypeScript/JS | Python 3.10+ |
| Bot API version | Latest (v10.0) | v7.1 | v10.0 |
| Install | npm install grammy | npm install telegraf | pip install python-telegram-bot |
| Plugin ecosystem | Rich (sessions, menus, conversations, i18n) | Moderate (scenes, sessions) | Extensions (JobQueue, persistence) |
| Serverless support | Vercel, CF Workers, Deno Deploy, Supabase Edge, Fly.io | Express/Fastify/Lambda adapters | ASGI adapters, manual webhook handlers |
| Middleware model | Composer-based (like Koa) | Composer-based (like Koa) | Handler groups with filters |
| Long polling | bot.start() | bot.launch() | application.run_polling() |
| Webhook mode | webhookCallback() adapter | bot.launch({ webhook }) or createWebhook() | application.run_webhook() |
| TypeScript types | First-class, auto-generated | Good, manual maintenance | N/A (Python type hints) |
| Recommended for | New projects, serverless, latest API features | Existing Express/Fastify apps | Python shops, data/ML pipelines |
Decision guide:
- Need Bot API v10.0 features (Stars subscriptions, Gifts, Bot Business, Mini Apps 2.0, Managed Bots, guest-bot)? Use grammY or python-telegram-bot.
- Already have an Express/Fastify server? Telegraf integrates cleanly.
- Python team or ML/data pipeline? python-telegram-bot is the only choice.
- Deploying to Vercel/Cloudflare Workers/Deno? grammY has native adapters for all of them.
Bot Creation with BotFather
Every Telegram bot starts with @BotFather. This is not optional, there is no API-only bot creation.
Steps
- Open Telegram, search for
@BotFather, start a chat - Send
/newbot - Provide a display name (e.g., "My Israeli Bot")
- Provide a username ending in
bot(e.g.,my_israeli_bot) - BotFather returns a token in the format:
123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11
Token Security Rules
- Never commit tokens to git. Use environment variables:
BOT_TOKENorTELEGRAM_BOT_TOKEN. - Tokens can be revoked via
/revokentokenin BotFather. - The token format is
{bot_id}:{secret}. The bot_id portion (before the colon) is the bot's numeric user ID. - Store in
.envfile (add to.gitignore) or use your platform's secret management.
BotFather Configuration Commands
/setdescription - Bot bio shown before user starts it
/setabouttext - Shown in bot profile
/setuserpic - Bot avatar
/setcommands - Command menu (critical for UX)
/setprivacy - Group privacy mode (disable to read all group messages)
/setinline - Enable inline mode
/setinlinefeedback - Probability of receiving chosen_inline_result updates
Project Setup
grammY (TypeScript)
mkdir my-telegram-bot && cd my-telegram-bot
npm init -y
npm install grammy dotenv
npm install -D typescript @types/node
npx tsc --init
src/bot.ts:
import { Bot, Context, session, GrammyError, HttpError } from "grammy";
import "dotenv/config";
const token = process.env.BOT_TOKEN;
if (!token) throw new Error("BOT_TOKEN environment variable is required");
const bot = new Bot(token);
// Command handlers
bot.command("start", async (ctx) => {
await ctx.reply("!שלום! אני הבוט שלך");
});
bot.command("help", async (ctx) => {
await ctx.reply(
"הפקודות הזמינות:\n" +
"/start - התחלה\n" +
"/help - עזרה"
);
});
// Message handler
bot.on("message:text", async (ctx) => {
await ctx.reply(`קיבלתי: ${ctx.message.text}`);
});
// Error handling (critical - without this, errors crash the bot silently)
bot.catch((err) => {
const ctx = err.ctx;
console.error(`Error while handling update ${ctx.update.update_id}:`);
const e = err.error;
if (e instanceof GrammyError) {
console.error("Error in request:", e.description);
} else if (e instanceof HttpError) {
console.error("Could not contact Telegram:", e);
} else {
console.error("Unknown error:", e);
}
});
// Start with long polling (development)
bot.start();
console.log("Bot is running...");
Telegraf (TypeScript)
mkdir my-telegram-bot && cd my-telegram-bot
npm init -y
npm install telegraf dotenv
npm install -D typescript @types/node
npx tsc --init
src/bot.ts:
import { Telegraf, Context } from "telegraf";
import "dotenv/config";
const token = process.env.BOT_TOKEN;
if (!token) throw new Error("BOT_TOKEN environment variable is required");
const bot = new Telegraf(token);
bot.start((ctx) => ctx.reply("!שלום! אני הבוט שלך"));
bot.help((ctx) => ctx.reply(
"הפקודות הזמינות:\n" +
"/start - התחלה\n" +
"/help - עזרה"
));
bot.on("text", (ctx) => ctx.reply(`קיבלתי: ${ctx.message.text}`));
// Graceful shutdown
process.once("SIGINT", () => bot.stop("SIGINT"));
process.once("SIGTERM", () => bot.stop("SIGTERM"));
// Start with long polling (development)
bot.launch();
console.log("Bot is running...");
python-telegram-bot (Python)
mkdir my-telegram-bot && cd my-telegram-bot
python -m venv venv
source venv/bin/activate
pip install python-telegram-bot python-dotenv
bot.py:
import os
import logging
from dotenv import load_dotenv
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, filters
load_dotenv()
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
TOKEN = os.getenv("BOT_TOKEN")
if not TOKEN:
raise ValueError("BOT_TOKEN environment variable is required")
async def start(update: Update, context) -> None:
await update.message.reply_text("!שלום! אני הבוט שלך")
async def help_command(update: Update, context) -> None:
await update.message.reply_text(
"הפקודות הזמינות:\n"
"/start - התחלה\n"
"/help - עזרה"
)
async def echo(update: Update, context) -> None:
await update.message.reply_text(f"קיבלתי: {update.message.text}")
def main() -> None:
application = ApplicationBuilder().token(TOKEN).build()
application.add_handler(CommandHandler("start", start))
application.add_handler(CommandHandler("help", help_command))
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))
# Start with long polling (development)
application.run_polling()
if __name__ == "__main__":
main()
Core Patterns
Inline Keyboards
Inline keyboards attach buttons directly to messages. They are the primary interactive UI element in Telegram bots.
grammY:
import { InlineKeyboard } from "grammy";
bot.command("menu", async (ctx) => {
const keyboard = new InlineKeyboard()
.text("אפשרות א׳", "option_a")
.text("אפשרות ב׳", "option_b")
.row()
.text("ביטול", "cancel");
await ctx.reply("בחר אפשרות:", { reply_markup: keyboard });
});
// Handle button presses
bot.callbackQuery("option_a", async (ctx) => {
await ctx.answerCallbackQuery({ text: "בחרת אפשרות א׳!" });
await ctx.editMessageText("בחרת: אפשרות א׳");
});
bot.callbackQuery("option_b", async (ctx) => {
await ctx.answerCallbackQuery({ text: "בחרת אפשרות ב׳!" });
await ctx.editMessageText("בחרת: אפשרות ב׳");
});
bot.callbackQuery("cancel", async (ctx) => {
await ctx.answerCallbackQuery();
await ctx.deleteMessage();
});
Critical: Callback data rules:
- Maximum 64 bytes (not characters). Hebrew uses 2-3 bytes per character in UTF-8, so you get roughly 21-32 Hebrew characters.
- Use short English identifiers for callback data, display Hebrew in button text.
- Pattern:
button text = Hebrew for user,callback data = English identifier for code.
Telegraf:
import { Markup } from "telegraf";
bot.command("menu", (ctx) => {
ctx.reply("בחר אפשרות:", Markup.inlineKeyboard([
[Markup.button.callback("אפשרות א׳", "option_a"),
Markup.button.callback("אפשרות ב׳", "option_b")],
[Markup.button.callback("ביטול", "cancel")]
]));
});
bot.action("option_a", (ctx) => {
ctx.answerCbQuery("בחרת אפשרות א׳!");
ctx.editMessageText("בחרת: אפשרות א׳");
});
python-telegram-bot:
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
async def menu(update: Update, context) -> None:
keyboard = [
[
InlineKeyboardButton("אפשרות א׳", callback_data="option_a"),
InlineKeyboardButton("אפשרות ב׳", callback_data="option_b"),
],
[InlineKeyboardButton("ביטול", callback_data="cancel")],
]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text("בחר אפשרות:", reply_markup=reply_markup)
async def button_handler(update: Update, context) -> None:
query = update.callback_query
await query.answer()
if query.data == "option_a":
await query.edit_message_text("בחרת: אפשרות א׳")
elif query.data == "option_b":
await query.edit_message_text("בחרת: אפשרות ב׳")
elif query.data == "cancel":
await query.delete_message()
# Register handler
application.add_handler(CallbackQueryHandler(button_handler))
Middleware Patterns
Middleware runs before handlers and is essential for logging, authentication, rate limiting, and i18n.
grammY middleware:
// Logging middleware
bot.use(async (ctx, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
console.log(`Update ${ctx.update.update_id} processed in ${ms}ms`);
});
// Auth middleware (restrict to specific users)
function adminOnly(ctx: Context, next: () => Promise<void>) {
const adminIds = [123456789, 987654321]; // Telegram user IDs
if (ctx.from && adminIds.includes(ctx.from.id)) {
return next();
}
return ctx.reply("אין לך הרשאה לפקודה זו.");
}
bot.command("admin", adminOnly, async (ctx) => {
await ctx.reply("פאנל ניהול");
});
python-telegram-bot does not use middleware in the same way. Instead, use handler groups with different priorities:
# Group 0 (default) handlers run first, then group 1, etc.
# Use group -1 for "middleware-like" behavior
async def log_update(update: Update, context) -> None:
logger.info(f"Update from user {update.effective_user.id}")
application.add_handler(MessageHandler(filters.ALL, log_update), group=-1)
Conversation / Multi-Step Flows
For multi-step flows (registration wizards, order forms), each framework has its own pattern: grammY's @grammyjs/conversations plugin (await-style flow), Telegraf's Scenes.WizardScene, and python-telegram-bot's ConversationHandler. Full working snippets in references/conversations.md.
Webhook vs Polling
Polling (Development)
Polling has the bot repeatedly ask Telegram "any new updates?" via getUpdates. Simple to set up, no public URL needed.
Bot --> Telegram: getUpdates?offset=X
Telegram --> Bot: [update1, update2, ...]
Bot --> Telegram: getUpdates?offset=X+2
When to use: Local development, testing, simple bots with low traffic.
All frameworks default to polling (see project setup above).
Webhooks (Production)
Webhooks have Telegram push updates to your server. More efficient, lower latency, required for serverless.
User sends message --> Telegram --> POST https://your-domain.com/webhook --> Your bot
Requirements:
- HTTPS with a valid SSL certificate (self-signed works but not recommended)
- Public URL accessible from Telegram's servers
- Port must be one of: 443, 80, 88, or 8443 (this is a hard Telegram restriction, agents frequently miss this)
- Secret token for verification (recommended, prevents spoofed requests)
grammY webhook setup (Express):
import express from "express";
import { webhookCallback } from "grammy";
const app = express();
app.use(express.json());
// The webhook path should include a secret or random string
app.use("/webhook/" + process.env.WEBHOOK_SECRET, webhookCallback(bot, "express"));
app.listen(443, () => {
console.log("Webhook server running on port 443");
});
// Set webhook URL with Telegram
await bot.api.setWebhook(`https://your-domain.com/webhook/${process.env.WEBHOOK_SECRET}`, {
secret_token: process.env.WEBHOOK_SECRET_TOKEN, // Telegram sends this in X-Telegram-Bot-Api-Secret-Token header
});
Telegraf webhook setup:
// Option 1: Built-in webhook server
bot.launch({
webhook: {
domain: "https://your-domain.com",
port: 443,
secretToken: process.env.WEBHOOK_SECRET_TOKEN,
},
});
// Option 2: Express integration
import express from "express";
const app = express();
app.use(bot.webhookCallback("/webhook"));
app.listen(443);
await bot.telegram.setWebhook("https://your-domain.com/webhook", {
secret_token: process.env.WEBHOOK_SECRET_TOKEN,
});
// Option 3: Lambda/serverless
// Export the handler
export const handler = bot.createWebhook({ domain: "https://your-domain.com" });
python-telegram-bot webhook setup:
application = ApplicationBuilder().token(TOKEN).build()
# ... add handlers ...
# Option 1: Built-in webhook server
application.run_webhook(
listen="0.0.0.0",
port=443,
url_path="webhook",
webhook_url="https://your-domain.com/webhook",
secret_token=os.getenv("WEBHOOK_SECRET_TOKEN"),
)
# Option 2: Custom ASGI/WSGI integration
# Use application.update_queue.put() to feed updates manually
Webhook Verification
Always verify the X-Telegram-Bot-Api-Secret-Token header matches your secret token. All three frameworks support this via the secret_token parameter in setWebhook.
Switching Between Modes
To remove a webhook (switch back to polling):
GET https://api.telegram.org/bot<token>/deleteWebhook
Or in code:
await bot.api.deleteWebhook(); // grammY
await bot.telegram.deleteWebhook(); // Telegraf
Hebrew Message Handling
The Bidirectional Text Problem
Hebrew is RTL, but Telegram messages often mix Hebrew with LTR content (English words, URLs, numbers, code). This creates rendering issues:
- Mixed-direction inline keyboards - A button showing "שלח 5 הודעות" may render the number in the wrong position.
- Callback data encoding - Keep callback data in ASCII/English. Hebrew in callback data wastes the 64-byte limit (Hebrew UTF-8 = 2-3 bytes per char).
- Markdown/HTML parsing with Hebrew - Bold/italic markers can break with RTL text reordering.
Solutions
Use Unicode directional markers when mixing languages:
const RTL_MARK = "\u200F"; // Right-to-Left Mark
const LTR_MARK = "\u200E"; // Left-to-Right Mark
// Force RTL context for Hebrew text containing numbers
await ctx.reply(`${RTL_MARK}סה"כ: ${LTR_MARK}₪150${RTL_MARK} לתשלום`);
Use HTML parse mode (more predictable than Markdown for RTL):
await ctx.reply(
`<b>סיכום הזמנה</b>\n` +
`מוצר: חולצה\n` +
`מחיר: ₪150\n` +
`כמות: 3`,
{ parse_mode: "HTML" }
);
Why HTML over Markdown for Hebrew:
- Markdown's
*bold*and_italic_markers can get confused by RTL reordering - HTML tags (
<b>,<i>) are unambiguous regardless of text direction - MarkdownV2 requires escaping many characters that appear in Hebrew text
Hebrew Command Aliases
Telegram commands must start with / and use Latin characters. For Hebrew UX, provide both:
// Register Latin commands with BotFather
// But also handle Hebrew text triggers
bot.command("help", handleHelp);
bot.hears("עזרה", handleHelp);
bot.hears("תפריט", handleMenu);
// Or use a regex for flexible matching
bot.hears(/^(help|עזרה)$/i, handleHelp);
Hebrew Keyboard Buttons (ReplyKeyboard)
For non-technical users, reply keyboards with Hebrew buttons are more accessible than slash commands:
import { Keyboard } from "grammy";
const hebrewMenu = new Keyboard()
.text("תפריט ראשי").text("עזרה").row()
.text("ההזמנות שלי").text("צור קשר")
.resized() // Fit to content
.persistent(); // Keep visible
await ctx.reply("בחר מהתפריט:", { reply_markup: hebrewMenu });
Israeli Phone-Number Contact Discovery
The cleanest way to identify a user by their Israeli phone number is request_contact on a reply-keyboard button. The user taps the button, Telegram sends a confirmation sheet, and on confirm the bot gets a contact field with the verified phone_number. Israeli numbers may arrive with or without the leading +972, so always normalize.
import { Keyboard } from "grammy";
bot.command("verify", async (ctx) => {
const kb = new Keyboard()
.requestContact("שתף את מספר הטלפון שלי")
.resized()
.oneTime();
await ctx.reply("כדי להמשיך, שתף את מספר הטלפון שלך:", { reply_markup: kb });
});
function normalizeIsraeliPhone(raw: string): string | null {
// Strip spaces, dashes, parens
let p = raw.replace(/[\s\-()]/g, "");
// +972XXXXXXXXX, 972XXXXXXXXX, 0XXXXXXXXX -> +972XXXXXXXXX
if (p.startsWith("+972")) return p;
if (p.startsWith("972")) return "+" + p;
if (p.startsWith("0")) return "+972" + p.slice(1);
return null;
}
bot.on("message:contact", async (ctx) => {
const contact = ctx.message.contact;
// Security: ensure the contact belongs to the sender, not someone they pasted
if (contact.user_id !== ctx.from.id) {
return ctx.reply("אנא שתף את המספר שלך, לא של אדם אחר.");
}
const phone = normalizeIsraeliPhone(contact.phone_number);
if (!phone) {
return ctx.reply("המספר שהתקבל לא נראה כמספר ישראלי תקין.");
}
await ctx.reply(`תודה! המספר שלך נשמר: ${phone}`);
});
Rate Limits & File Size Limits
Telegram enforces hard limits on outgoing traffic. Hitting them returns HTTP 429 with retry_after; ignore them and your bot gets throttled or banned.
Outgoing message rates:
- 30 messages/second global, across all chats
- 1 message/second per individual chat (DM or group)
- 20 messages/minute per group chat (broadcasts to the same group)