Telegram stands recognized as one of the most developer-friendly instant messaging platforms globally. Unlike competing messaging networks that burden software teams with onerous business verification procedures and restrictive message templates, Telegram provides an open, highly capable bot API accessible in minutes via @BotFather.
Coupling Telegram's real-time messaging interface with modern foundation language models like DeepSeek V4 Pro or Claude Sonnet 5 through the TOP AI Gateway empowers you to build personal productivity assistants, community support bots, or automated customer triage services operating 24/7 with unmatched capital efficiency.
Below is an end-to-end tutorial authoring a production-grade Telegram AI bot utilizing the modern grammY framework in Node.js.

Step 1: Provision Your Bot via Telegram BotFather
- Launch Telegram on your mobile device or desktop workstation.
- Search for the verified @BotFather account.
- Dispatch the command:
/newbot. - Enter a friendly display title (e.g.,
TOP AI Assistant). - Specify a unique handle ending with
bot(e.g.,topai_assistant_bot). - BotFather will issue an HTTP API Token. Store this credential securely.
Step 2: Initialize Node.js Workspace
Open your terminal and create a dedicated workspace directory:
mkdir telegram-ai-bot && cd telegram-ai-bot
npm init -y
npm install grammy openai dotenvCreate an environment configuration file named .env:
TELEGRAM_BOT_TOKEN=123456789:ABCdefGHIjklMNOpqrSTUvwxYZ
TOPAI_API_KEY=tp-live-xxxxxxxxxxxxxxxxxxxxStep 3: Author the Core Bot Application
Create bot.mjs and paste the complete implementation:
import { Bot } from "grammy";
import OpenAI from "openai";
import dotenv from "dotenv";
dotenv.config();
// Initialize OpenAI Client Directed at TOP AI Gateway
const ai = new OpenAI({
baseURL: "https://api.topai.id/v1",
apiKey: process.env.TOPAI_API_KEY
});
// Initialize Telegram Bot via grammY
const bot = new Bot(process.env.TELEGRAM_BOT_TOKEN);
// Handle /start Greeting Command
bot.command("start", async (ctx) => {
await ctx.reply("Greetings! I am an AI Assistant powered by the TOP AI Gateway. Inquire about any topic, and I will resolve your query instantly!");
});
// Text Message Listener Handling Inbound Interactions
bot.on("message:text", async (ctx) => {
const userText = ctx.message.text;
// Stream typing indicator to the Telegram user client
await ctx.replyWithChatAction("typing");
try {
const completion = await ai.chat.completions.create({
model: "deepseek-v4-pro", // Fast and exceptionally cost-effective
messages: [
{
role: "system",
content: "You are an articulate, professional virtual assistant on Telegram. Provide concise, high-value answers formatted in clean Markdown."
},
{
role: "user",
content: userText
}
],
max_tokens: 600,
temperature: 0.5
});
const aiReply = completion.choices[0].message.content;
await ctx.reply(aiReply, { parse_mode: "Markdown" });
} catch (err) {
console.error("AI Gateway Invocation Error:", err);
await ctx.reply("Apologies, an unexpected network issue occurred. Please retry your inquiry in a moment.");
}
});
// Launch the Bot via Long Polling
console.log("Telegram AI Bot successfully launched and listening...");
bot.start();Testing Your Bot Locally
In your terminal, execute:
node bot.mjsOpen Telegram, locate your bot handle, tap Start, and send a message. Your bot will synthesize intelligent responses immediately!
| Architectural Layer | Solution Deployed | Strategic Role |
|---|---|---|
| Telegram Bot SDK | grammY | Premier, modern TypeScript-native Telegram framework |
| Inference Client | openai | Official OpenAI client configured with TOP AI base URL |
| Default Engine | deepseek-v4-pro | Blazing generation speed (~60 TPS) at accessible token rates |
| Connection Mode | Long Polling | Ideal for immediate local development without public HTTPS webhooks |
Adding Multi-Turn Conversational Memory
In this introductory baseline, each message is processed statelessly. To endow your bot with persistent memory:
- Maintain an in-memory or Redis-backed message array keyed by
ctx.from.id(the user's unique Telegram ID). - Constrain memory payloads to the most recent 6 conversational turns using a sliding window to keep token usage disciplined.
- Prepend that historical turn context into the
messagesarray before dispatching the invocation to TOP AI.
This architecture establishes a resilient foundation for enterprise-ready conversational bots operating under predictable budget ceilings.
Production Deployment Strategies for 24/7 Availability
Executing your bot locally is optimal for early prototyping, but sustaining continuous enterprise availability demands migrating workloads to a cloud server:
- Process Orchestration with PM2: On a cloud virtual machine, install PM2 (
npm install -g pm2) and launch your application viapm2 start bot.mjs --name telegram-ai. PM2 guarantees automated restarts in the event of unexpected exceptions or server reboots. - Transitioning from Long Polling to Webhooks: When conversation volume surpasses thousands of messages hourly, migrate from polling to Webhook mode. Register your secure HTTPS endpoint with Telegram using
bot.api.setWebhook("https://api.yourdomain.com/telegram-webhook"). Webhooks eliminate polling CPU cycles and enhance scalability. - Inbound Rate Limiting: Enforce inbound throttling using plugins like
@grammyjs/ratelimiterto prevent individual spammers from flooding your bot with abusive bursts that drain computational credits.
Persona Engineering for Superior User Retention
A conversational bot's persona dictates user satisfaction. Inside your system prompt, instruct the model to adopt an articulate, solution-oriented demeanor, eliminate conversational filler, and structure actionable insights using Markdown typographic hierarchy. Paired with TOP AI's high-speed inference, your Telegram bot delivers a seamless assistant experience that delights enterprise communities.
High-Concurrency Architectural Patterns for Community Bots
When deploying a Telegram AI bot into massive community groups housing thousands of active members, a single-instance polling topology rapidly encounters concurrency bottlenecks. Adopt these distributed engineering principles:
- Decouple Inbound Ingestion from Inference Workers: Introduce an asynchronous message broker such as BullMQ or RabbitMQ. Your HTTP webhook receiver acknowledges Telegram within 5 milliseconds, enqueuing tasks for distributed worker nodes that query TOP AI models out-of-band.
- Filter Unsolicited Group Chatter: Guard against having the bot process every ambient conversation turn in noisy group threads. Configure listener predicates so the agent activates exclusively upon direct mentions (@bot_handle) or explicit command prefixes like /ask.
- Deploy In-Memory Semantic Caching: Store answers to common community inquiries—such as community guidelines, onboarding requirements, and event schedules—inside Redis caches. Serving recurring inquiries locally slashes latency to zero and preserves token balances.
Frequently Asked Questions
Does developing a Telegram AI bot require expensive cloud server infrastructure?+
No. You can run and test bots locally during development and deploy to lightweight containers like Render, Railway, or inexpensive VPS instances costing under $3/month.
What foundation engine provides the ideal cost profile for scaling Telegram bots to thousands of daily users?+
DeepSeek V4 Pro provides the optimal combination of sub-second streaming latencies and accessible pricing (roughly $0.14 per million input tokens).



