Building a basic Telegram bot that echoes text back to a user is straightforward. However, deploying a production lead generation bot that prompts users for multi-step information—such as a service booking request, business contact details, or project scope—exposes your server to subtle operational bugs. In a active bot, two major failures regularly occur: conversational state drops when users tap out of sequence, and process crashes caused by unhandled Telegram HTTP 429 Too Many Requests status codes during high-traffic bursts.
If your Node.js application relies on simple global variables to manage user progress, a server restart or concurrent request will overwrite half-filled forms. Even worse, if your bot sends notifications or confirmation messages to multiple administrators simultaneously without rate-limit throttling, Telegram's Bot API will throttle your request, return a 429 status, and crash an unhandled promise chain. This leaves user input unacknowledged and drops incoming leads completely.
In this walkthrough, we will construct a production-ready Node.js lead capture bot using the grammY framework. You will learn how to structure environment configuration, build persistent step-by-step prompt flows using grammY conversations, escape dynamic string values safely, convert long polling to secure webhooks, and integrate automated retry handling for rate limits.
Section 1: Secure Initialization and Error Mitigation
Before writing conversation logic, your application structure must isolate credentials and catch API errors gracefully. Instantiating a bot directly with hardcoded API tokens risks committing secrets to public repositories. Additionally, default Node.js error behavior will terminate the entire server process if a single Telegram API call fails due to networking glitches or blocked users.
Create a clean project directory and install the required dependencies:
npm init -y
npm install grammy @grammyjs/conversations @grammyjs/auto-retry dotenv express
Create a .env file in your root folder containing your secret Telegram bot token obtained from @BotFather alongside a secure secret token string for webhook validation:
BOT_TOKEN=123456789:ABCdefGhIJKlmNoPQRsTUVwxyZ
WEBHOOK_SECRET=a_random_high_entropy_secret_string_32_chars
NODE_ENV=development
PORT=3000
Next, configure your main bot instance with explicit environment checking and a global error boundary. If a user blocks the bot mid-conversation, Telegram returns an HTTP 403 Forbidden error when the bot tries to respond. Without a dedicated bot.catch() middleware handler, this error bubbles up as an unhandled rejection and crashes your server.
// bot.js
import { Bot, session } from 'grammy';
import dotenv from 'dotenv';
dotenv.config();
if (!process.env.BOT_TOKEN) {
throw new Error('Fatal: BOT_TOKEN is missing from environment variables.');
}
export const bot = new Bot(process.env.BOT_TOKEN);
// Global error handler to catch Telegram API and middleware errors
bot.catch((err) => {
const ctx = err.ctx;
console.error(`Error while handling update ${ctx.update.update_id}:`);
const e = err.error;
if (e instanceof Error) {
console.error('Execution Error:', e.message);
} else {
console.error('Unknown Error:', e);
}
});
By registering bot.catch(), any failing update is safely isolated. The process stays online, allowing other users to continue submitting forms uninterrupted.
Section 2: Building Multi-Step Form Conversations
Managing user state manually across incoming message updates creates fragile code. Users might send unexpected text, attach images instead of text, or ignore prompts. The @grammyjs/conversations plugin provides a linear async/await syntax to step through prompts sequentially while holding the user context in state.
When accepting input from arbitrary Telegram users, you must also generate a unique server-side key for the lead and sanitize all dynamic string inputs before embedding them inside HTML formatted messages. Using raw unescaped input inside Telegram's HTML parse_mode allows broken formatting tags to crash the messaging API, or enables script/markup injection in administrative displays.
Create the lead collection conversation script below:
// leadFlow.js
import { createConversation } from '@grammyjs/conversations';
import crypto from 'crypto';
// Helper to escape special HTML characters for Telegram parse_mode='HTML'
function escapeHtml(text) {
if (typeof text !== 'string') return '';
return text
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
}
export async function captureLeadConversation(conversation, ctx) {
await ctx.reply('Welcome! Let us set up your quote request. What is your full name?');
// Wait specifically for a text response from the user
const nameCtx = await conversation.waitFor('message:text');
const fullName = escapeHtml(nameCtx.message.text.trim());
await ctx.reply(`Thanks, ${fullName}. What is your business email address?`);
const emailCtx = await conversation.waitFor('message:text');
const email = escapeHtml(emailCtx.message.text.trim());
await ctx.reply('Please describe your project scope or budget briefly:');
const scopeCtx = await conversation.waitFor('message:text');
const projectScope = escapeHtml(scopeCtx.message.text.trim());
// Generate a collision-resistant lead ID prior to DB persistence
const leadId = crypto.randomBytes(7).toString('hex');
const leadData = {
leadId,
telegramUserId: ctx.from.id,
fullName,
email,
projectScope,
createdAt: new Date().toISOString()
};
// Simulate persistent storage write (e.g., PostgreSQL or MongoDB)
await conversation.external(() => {
console.log('PERSISTING LEAD TO DATABASE:', leadData);
});
const summaryHtml = `<b>New Lead Submitted!</b>\n` +
`<b>ID:</b> <code>${leadData.leadId}</code>\n` +
`<b>Name:</b> ${leadData.fullName}\n` +
`<b>Email:</b> ${leadData.email}\n` +
`<b>Scope:</b> ${leadData.projectScope}`;
await ctx.reply(`Thank you! Your request has been logged under ID <code>${leadId}</code>.`, {
parse_mode: 'HTML'
});
}
Attach the conversation plugin and register the root /quote command inside your bot pipeline:
// register-lead.js
import { session } from 'grammy';
import { conversations, createConversation } from '@grammyjs/conversations';
import { bot } from './bot.js';
import { captureLeadConversation } from './leadFlow.js';
// Session storage is required for stateful conversations
bot.use(session({ initial: () => ({}) }));
bot.use(conversations());
// Register conversation handler
bot.use(createConversation(captureLeadConversation));
// Entry command
bot.command('quote', async (ctx) => {
await ctx.conversation.enter('captureLeadConversation');
});
If a user sends text outside the expected step, the step-by-step runner pauses cleanly until valid text arrives instead of corrupting global variables.
Section 3: Eliminating 429 Rate Limits and Handling Webhook Payloads
Telegram imposes strict outbound rate limits: no more than 30 messages per second across all users, and no more than 1 message per second to a single individual chat or channel. If your bot sends a broadcast to leads or posts notifications rapidly, Telegram returns an HTTP status code 429 with a JSON payload indicating retry_after: N seconds.
If you simply loop over a list of user IDs using Promise.all(), Telegram will throttle your IP address and reject requests for minutes. To prevent this without manual math, wrap your bot API calls using @grammyjs/auto-retry.
Furthermore, for production environments, running local long polling (bot.start()) leads to duplicate processing if multiple bot instances run simultaneously. Production apps should use Webhooks with strict authentication tokens (X-Telegram-Bot-Api-Secret-Token).
Here is how to set up the auto-retry plugin alongside an Express HTTP server operating safely in either webhook or long polling mode:
// server.js
import express from 'express';
import { webhookCallback } from 'grammy';
import { autoRetry } from '@grammyjs/auto-retry';
import { bot } from './bot.js';
import './register-lead.js'; // Ensure handlers are registered
// 1. Attach auto-retry plugin to outbound Telegram API calls
bot.api.config.use(autoRetry({
maxRetryAttempts: 3, // Retry up to 3 times on 429 errors
maxDelaySeconds: 60, // Maximum backoff wait window
}));
const app = express();
app.use(express.json());
const PORT = process.env.PORT || 3000;
const IS_PRODUCTION = process.env.NODE_ENV === 'production';
if (IS_PRODUCTION) {
const secretToken = process.env.WEBHOOK_SECRET;
if (!secretToken) {
throw new Error('Fatal: WEBHOOK_SECRET must be set in production mode.');
}
// Webhook route handler with explicit secret check
app.post(`/telegram/webhook`, (req, res, next) => {
const incomingHeader = req.headers['x-telegram-bot-api-secret-token'];
if (incomingHeader !== secretToken) {
console.warn('Unauthorized webhook request rejected: Secret mismatch.');
return res.status(403).send('Forbidden');
}
return next();
}, webhookCallback(bot, 'express'));
app.listen(PORT, () => {
console.log(`Production webhook server listening on port ${PORT}`);
});
} else {
// Local Development fallback using Long Polling
bot.start({
onStart: (info) => console.log(`Development bot started as @${info.username}`),
});
}
When a 429 error occurs during notification sends, the auto-retry middleware interceptor reads the retry_after response header from Telegram, pauses execution asynchronously for the requested duration, and transparently retries the API call. The core conversation logic does not drop the message.
Production Notes
- Session Storage Persistence: The default memory session storage used by grammY resets whenever the Node.js process restarts. In production, pass a persistent storage adapter (such as @grammyjs/storage-redis or MongoDB) into session({ storage: ... }) so active user form states survive server redeployments. - Idempotency & Processing Updates: Telegram retries webhook payloads if your HTTP server does not respond with an HTTP 200 OK within 60 seconds. Store incoming update_id values in Redis for a short TTL (e.g., 24 hours) to skip processing duplicate payloads sent by Telegram during temporary network latency spikes. - Callback Query Resolution: If your lead form includes inline buttons (such as selecting project timelines), always execute await ctx.answerCallbackQuery() immediately in your route handler. Failing to call this method leaves a loading spinner on the user's Telegram client until it eventually times out.
With structured input escaping, process error boundaries, auto-retrying HTTP plugins, and secure secret header checks, your Node.js grammY bot can reliably log incoming customer leads without suffering from silent crashes or rate-limit blocks.
When scaling up custom Telegram applications or complex web applications, building infrastructure from scratch can consume valuable development time. You can work with BotCreator — studio that ships Telegram bots / Mini Apps, or read more about API integration patterns on