Build a Telegram AI bot with APIVAI
A Telegram AI bot is one of the quickest ways to ship an AI assistant: create a bot with BotFather,
run a small script that forwards messages to an OpenAI-compatible model, and reply. APIVAI provides
the model (Claude or GPT) at a fraction of list price, with crypto/USDT/Alipay payment.
This guide is the full working bot.
1. Create the bot
Message @botfather on Telegram → /newbot → choose a name → copy the bot token.
2. The bot (Node.js, long polling — no server needed)
npm install node-telegram-bot-api openai
import TelegramBot from "node-telegram-bot-api";
import OpenAI from "openai";
const bot = new TelegramBot(process.env.TELEGRAM_BOT_TOKEN, { polling: true });
const ai = new OpenAI({ apiKey: process.env.APIVAI_API_KEY, baseURL: "https://api.apivai.com/v1" });
const SYSTEM = "You are a helpful assistant. Answer concisely in the user's language.";
const history = new Map(); // chatId -> messages[]
bot.on("message", async (msg) => {
if (!msg.text || msg.text.startsWith("/")) return;
const chatId = msg.chat.id;
const msgs = history.get(chatId) || [{ role: "system", content: SYSTEM }];
msgs.push({ role: "user", content: msg.text });
bot.sendChatAction(chatId, "typing");
const r = await ai.chat.completions.create({ model: "gpt-5.5", messages: msgs.slice(-12), max_tokens: 500 });
const reply = r.choices[0].message.content;
msgs.push({ role: "assistant", content: reply });
history.set(chatId, msgs.slice(-12)); // keep recent context
bot.sendMessage(chatId, reply);
});
Set TELEGRAM_BOT_TOKEN and APIVAI_API_KEY, run node bot.js, and message your bot.
3. Add commands & polish
-
/start→ a welcome message;/reset→ clear that chat's history. - Trim history (last ~12 messages) to control token cost.
- Stream long answers by editing the message as chunks arrive (optional).
- For groups, only respond when mentioned or replied to.
Pick the model
GPT-5.5 for fast, natural, multilingual replies; Claude Sonnet for coding/long-reasoning bots.
Switch by changing the model string — it's OpenAI-compatible.
FAQ
Can a Telegram bot use APIVAI? Yes — it's a normal OpenAI chat call with the base URL set to
https://api.apivai.com/v1; the bot forwards messages and returns the reply.
Do I need a server? No — long polling (above) runs anywhere Node runs. Use webhooks if you want
a serverless deployment.
Which model should the bot use? GPT-5.5 for general/multilingual chat; Claude Sonnet for
code-heavy bots.
How do I control cost? Trim conversation history and cap max_tokens; APIVAI's per-token price
is already low.
Get started
Create a bot with BotFather, drop in the script with your APIVAI key, and run it. Examples:
APIVAI examples repo.
Top comments (0)