U

Ultimate Telegram Framework

Enterprise-grade skill for expert, building, telegram, mini. Includes structured workflows, validation checks, and reusable patterns for enterprise communication.

SkillClipticsenterprise communicationv1.0.0MIT
0 views0 copies

Ultimate Telegram Framework

A comprehensive skill for building Telegram bots — covering bot setup with BotFather, command handling, inline keyboards, callback queries, webhook configuration, state management, and deployment with the Telegraf or node-telegram-bot-api frameworks.

When to Use This Skill

Choose Ultimate Telegram Framework when you need to:

  • Build a Telegram bot from scratch with command handling
  • Implement interactive menus with inline keyboards
  • Create multi-step conversation flows with state management
  • Set up webhooks for production Telegram bot hosting
  • Build group management bots with admin commands

Consider alternatives when:

  • You need a Discord bot (use a Discord bot skill)
  • You need a Slack bot (use a Slack bot skill)
  • You need SMS/voice communications (use a Twilio skill)

Quick Start

# Initialize a Telegram bot project mkdir my-telegram-bot && cd my-telegram-bot npm init -y npm install telegraf dotenv
// bot.js — Telegraf bot setup const { Telegraf, Markup } = require("telegraf"); require("dotenv").config(); const bot = new Telegraf(process.env.BOT_TOKEN); // Start command bot.start((ctx) => { ctx.reply( `Welcome ${ctx.from.first_name}! I'm your assistant bot.`, Markup.inlineKeyboard([ [Markup.button.callback("Get Help", "help")], [Markup.button.callback("Settings", "settings")], [Markup.button.url("Website", "https://example.com")], ]) ); }); // Help command bot.help((ctx) => { ctx.reply( "Available commands:\n" + "/start — Start the bot\n" + "/help — Show this help\n" + "/status — Check system status\n" + "/settings — Configure preferences" ); }); // Custom command bot.command("status", (ctx) => { ctx.reply("All systems operational ✅\nUptime: 99.9%\nLatency: 45ms"); }); // Callback query handler bot.action("help", (ctx) => { ctx.answerCbQuery(); ctx.reply("What do you need help with?", Markup.inlineKeyboard([ [Markup.button.callback("Account", "help_account")], [Markup.button.callback("Billing", "help_billing")], [Markup.button.callback("Technical", "help_technical")], ])); }); bot.action("settings", (ctx) => { ctx.answerCbQuery(); ctx.reply("Settings", Markup.inlineKeyboard([ [Markup.button.callback("Notifications: ON", "toggle_notif")], [Markup.button.callback("Language: English", "change_lang")], ])); }); // Launch bot bot.launch(); process.once("SIGINT", () => bot.stop("SIGINT")); process.once("SIGTERM", () => bot.stop("SIGTERM"));

Core Concepts

Bot Architecture

ComponentPurposeTelegraf Method
CommandsHandle /command messagesbot.command()
Text handlersRespond to text messagesbot.on("text")
Callback queriesHandle inline keyboard button clicksbot.action()
Inline queriesHandle @bot inline mentionsbot.on("inline_query")
MiddlewareProcess every updatebot.use()
ScenesMulti-step conversation flowsScenes.WizardScene

Conversation Scenes (Wizard)

const { Scenes, session } = require("telegraf"); // Multi-step registration wizard const registrationWizard = new Scenes.WizardScene( "registration", // Step 1: Ask for name (ctx) => { ctx.reply("What is your name?"); return ctx.wizard.next(); }, // Step 2: Ask for email (ctx) => { ctx.wizard.state.name = ctx.message.text; ctx.reply("What is your email address?"); return ctx.wizard.next(); }, // Step 3: Confirm (ctx) => { ctx.wizard.state.email = ctx.message.text; const { name, email } = ctx.wizard.state; ctx.reply( `Please confirm:\nName: ${name}\nEmail: ${email}`, Markup.inlineKeyboard([ [Markup.button.callback("Confirm", "confirm_reg")], [Markup.button.callback("Cancel", "cancel_reg")], ]) ); return ctx.wizard.next(); }, // Step 4: Process confirmation (ctx) => { ctx.scene.leave(); } ); const stage = new Scenes.Stage([registrationWizard]); bot.use(session()); bot.use(stage.middleware()); bot.command("register", (ctx) => ctx.scene.enter("registration"));

Webhook Setup for Production

// webhook.js — Production webhook setup const { Telegraf } = require("telegraf"); const express = require("express"); const bot = new Telegraf(process.env.BOT_TOKEN); const app = express(); // Set webhook const WEBHOOK_URL = `https://yourdomain.com/webhook/${bot.secretPathComponent()}`; app.use(bot.webhookCallback(`/webhook/${bot.secretPathComponent()}`)); app.get("/health", (req, res) => res.json({ status: "ok" })); app.listen(3000, async () => { await bot.telegram.setWebhook(WEBHOOK_URL); console.log(`Bot webhook set to ${WEBHOOK_URL}`); });

Configuration

ParameterDescriptionExample
bot_tokenBot token from BotFatherprocess.env.BOT_TOKEN
webhook_urlPublic HTTPS URL for webhooks"https://bot.example.com"
pollingUse long polling instead of webhookstrue (development)
session_storeSession persistence backend"redis" / "memory"
admin_idsTelegram user IDs for admin commands[123456789]
rate_limitMessages per second limit30

Best Practices

  1. Use long polling for development, webhooks for production — Long polling (bot.launch()) requires no public URL and works locally. Webhooks require HTTPS and a public domain but are more efficient and reliable for production bots.

  2. Always call answerCbQuery() for callback queries — When a user clicks an inline keyboard button, Telegram shows a loading spinner until you call answerCbQuery(). Forgetting this leaves the spinner visible, making the bot feel unresponsive.

  3. Use Scenes for multi-step conversations — Don't manage conversation state manually with global variables. Telegraf's Scene and WizardScene system handles state per user, supports step navigation, and prevents state collisions between concurrent users.

  4. Implement rate limiting for group bots — Telegram enforces rate limits (roughly 30 messages per second globally, 20 per minute per group). If your bot serves multiple groups, implement a message queue that respects these limits to avoid HTTP 429 errors.

  5. Include a secret path component in webhook URLs — Use bot.secretPathComponent() to generate a random path for your webhook endpoint. Without this, anyone who discovers your webhook URL can send fake updates to your bot.

Common Issues

Bot works locally but not after deploying with webhooks — Ensure your server has a valid SSL certificate (Telegram requires HTTPS for webhooks), the webhook URL is publicly accessible, and the port isn't blocked by a firewall. Test with curl https://api.telegram.org/bot<TOKEN>/getWebhookInfo to verify webhook status.

Inline keyboard buttons stop working after bot restart — Callback queries from old messages are still delivered to the bot after restart. If your handlers changed or were reorganized, old callback data may not match new handler patterns. Use consistent action_id values and handle unknown callbacks gracefully.

Multi-step conversation state is lost between messages — If you're using in-memory sessions, they reset on restart. For production bots, use a persistent session store (Redis, MongoDB) so conversation state survives restarts and scales across multiple bot instances.

Community

Reviews

Write a review

No reviews yet. Be the first to review this template!

Similar Templates