Telegram Bot API: Complete 2026 Guide (With Code Examples)
Everything you need to build Telegram bots: polling vs. webhooks, sendMessage, inline keyboards, and hosting options explained with real code examples.
Telegram Bot API: Complete AI Chatbot Guide 2026
Telegram bots handle over 15 billion messages every month. From customer support to personal AI assistants, bots have become essential to how people use Telegram.
But building an AI-powered Telegram bot from scratch? That's where things get complicated. You need to understand the Bot API, set up a server, write code, integrate an LLM, handle errors, and keep everything running 24/7.
This guide covers two paths: the DIY approach (with full code examples) and the 60-second approach using ClawdHost.
Short on time? ClawdHost deploys a ready-made AI assistant on Telegram in 60 seconds. No coding required. Skip to the easy way →
What is the Telegram Bot API?
The Telegram Bot API is an HTTP-based interface that lets developers build bots for Telegram. It's the official way to create automated accounts that can send messages, respond to commands, handle inline queries, process payments, and more.
Every bot you've ever interacted with on Telegram—from @gif to custom AI assistants—uses this API under the hood.
Common use cases include:
- Customer support bots that answer FAQs
- Notification bots that send alerts and updates
- AI assistants that chat using Claude, GPT, or other LLMs
- Utility bots for translations, reminders, or file conversions
OpenClaw (also known as Moltbot and Clawdbot) is an open-source personal AI assistant with 79K+ GitHub stars that uses the Telegram Bot API to connect your AI to Telegram, Discord, Slack, and WhatsApp.
Two Paths: DIY vs Managed
Before diving into code, understand your options:
| Approach | What You Get | Effort | Cost |
|---|---|---|---|
| DIY (this guide) | Full control, your code | 30-60 min setup + ongoing maintenance | $5-20/mo for VPS |
| Generic bot hosting | Runs YOUR code 24/7 | You still write and debug code | $2-5/mo |
| ClawdHost | Pre-built AI assistant, ready to use | 60 seconds, no code | $29/mo |
Generic bot hosting services like PebbleHost or BisectHosting run whatever code you give them. You still need to build the bot yourself.
ClawdHost is different—it gives you OpenClaw, a complete AI assistant that's already built. You just add your LLM API key and connect to Telegram.
If you want full control and enjoy coding, keep reading. If you want an AI assistant running today, jump to ClawdHost.
Prerequisites for DIY
To build a Telegram AI bot from scratch, you'll need:
- A Telegram account
- Node.js (v18+) or Python (3.9+) installed
- A server or VPS for hosting (DigitalOcean, Hetzner, Railway, etc.)
- An LLM API key (Anthropic, OpenAI, or similar)
- Basic JavaScript or Python knowledge
Don't want to manage servers? ClawdHost handles hosting, updates, and security. Just bring your LLM API key. Get started →
Step 1: Create Your Bot with BotFather
Every Telegram bot starts with @BotFather—Telegram's official bot for creating bots.
- Open Telegram and search for
@BotFather - Send the
/newbotcommand - Choose a display name (e.g., "My AI Assistant")
- Choose a username ending in
bot(e.g.,my_ai_assistant_bot) - BotFather will reply with your bot token
Your token looks like this:
7123456789:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw
Security warning: Never commit your bot token to a public repository or share it publicly. Anyone with your token can control your bot. Store it in environment variables.
Step 2: Set Up Your Environment
We'll use Node.js with the Telegraf library. Create a new project:
mkdir telegram-ai-bot
cd telegram-ai-bot
npm init -y
npm install telegraf dotenv
Create a .env file for your secrets:
BOT_TOKEN=your_telegram_bot_token_here
ANTHROPIC_API_KEY=your_anthropic_api_key_here
Create .gitignore to protect your secrets:
.env
node_modules
Step 3: Build a Basic Echo Bot
Let's start with a simple bot that echoes messages back. Create index.js:
require('dotenv').config();
const { Telegraf } = require('telegraf');
const bot = new Telegraf(process.env.BOT_TOKEN);
// Handle /start command
bot.start((ctx) => {
ctx.reply('Welcome! Send me a message and I\'ll echo it back.');
});
// Handle /help command
bot.help((ctx) => {
ctx.reply('Just send me any message and I\'ll repeat it.');
});
// Echo all text messages
bot.on('text', (ctx) => {
ctx.reply(`You said: ${ctx.message.text}`);
});
// Start the bot
bot.launch();
console.log('Bot is running...');
// Graceful shutdown
process.once('SIGINT', () => bot.stop('SIGINT'));
process.once('SIGTERM', () => bot.stop('SIGTERM'));
Run it:
node index.js
Open Telegram, find your bot, and send a message. It should echo it back.
Step 4: Add AI Capabilities
Now let's make it intelligent. Install the Anthropic SDK:
npm install @anthropic-ai/sdk
Update index.js to integrate Claude:
require('dotenv').config();
const { Telegraf } = require('telegraf');
const Anthropic = require('@anthropic-ai/sdk');
const bot = new Telegraf(process.env.BOT_TOKEN);
const anthropic = new Anthropic();
// Store conversation history per user
const conversations = new Map();
bot.start((ctx) => {
conversations.delete(ctx.from.id);
ctx.reply('Hello! I\'m your AI assistant. How can I help you today?');
});
bot.on('text', async (ctx) => {
const userId = ctx.from.id;
const userMessage = ctx.message.text;
// Get or create conversation history
if (!conversations.has(userId)) {
conversations.set(userId, []);
}
const history = conversations.get(userId);
// Add user message to history
history.push({ role: 'user', content: userMessage });
try {
// Show typing indicator
await ctx.sendChatAction('typing');
// Call Claude API
const response = await anthropic.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 1024,
system: 'You are a helpful AI assistant on Telegram. Keep responses concise.',
messages: history
});
const assistantMessage = response.content[0].text;
// Add assistant response to history
history.push({ role: 'assistant', content: assistantMessage });
// Keep history manageable (last 20 messages)
if (history.length > 20) {
history.splice(0, 2);
}
await ctx.reply(assistantMessage);
} catch (error) {
console.error('API Error:', error);
await ctx.reply('Sorry, I encountered an error. Please try again.');
}
});
bot.launch();
console.log('AI Bot is running...');
process.once('SIGINT', () => bot.stop('SIGINT'));
process.once('SIGTERM', () => bot.stop('SIGTERM'));
This adds conversation memory, error handling, and the typing indicator. But we're just getting started—production bots need rate limiting, better error handling, database storage for conversations, and more.
Managing conversation context, error handling, and rate limits adds complexity fast. This is where most DIY projects get abandoned.
Step 5: Deploy to Production
Your bot works locally, but it stops when your computer sleeps. For 24/7 operation, you need to deploy it.
Option A: VPS with PM2
# On your server
npm install -g pm2
pm2 start index.js --name "telegram-bot"
pm2 save
pm2 startup
Option B: Use Webhooks (recommended for production)
Polling (what we've been using) constantly asks Telegram "any new messages?" Webhooks are more efficient—Telegram pushes updates to your server.
Webhooks require:
- A domain name
- SSL certificate (HTTPS required)
- Ports 443, 80, 88, or 8443
// Webhook setup (replace polling)
const WEBHOOK_URL = 'https://yourdomain.com/webhook';
bot.telegram.setWebhook(WEBHOOK_URL);
// Express server to receive webhooks
const express = require('express');
const app = express();
app.use(bot.webhookCallback('/webhook'));
app.listen(3000);
Ongoing maintenance includes:
- Monitoring uptime
- Updating dependencies
- Handling API changes
- Managing server security
- Scaling as users grow
The Easy Way: ClawdHost
Get an AI Assistant on Telegram in 60 Seconds
If Steps 2-5 feel like a lot of work, that's because they are. ClawdHost eliminates all of it.
Here's how it works:
- Sign up at clawdhost.net
- Enter your LLM API key (Claude, GPT, OpenRouter, etc.)
- Select Telegram as your platform
- Follow the BotFather link to connect your bot token
That's it. Your AI assistant is live.
What You Get with ClawdHost
- Pre-configured OpenClaw instance - The same open-source assistant with 79K+ GitHub stars, fully managed
- Multi-platform support - Telegram, Discord, Slack (WhatsApp coming soon)
- Your choice of AI provider - Anthropic, OpenAI, OpenRouter, Moonshot, Zai
- Automatic updates - Security patches and new features without lifting a finger
- Your Own VPS - Your instance runs in isolation, not shared hosting
- 24-hour money-back guarantee - Try it risk-free
ClawdHost vs DIY
| DIY | ClawdHost | |
|---|---|---|
| Setup time | 30-60 minutes | 60 seconds |
| Coding required | Yes | No |
| Server management | You handle it | We handle it |
| Updates & security | Manual | Automatic |
| Multi-platform | Build each separately | Built-in |
| Monthly cost | $5-20 + your time | $29 |
ClawdHost vs Generic Bot Hosting
Generic bot hosting ($2-5/month) runs your code. You still need to:
- Write the bot from scratch
- Integrate the LLM API
- Handle conversation memory
- Debug issues yourself
ClawdHost gives you a working AI assistant. No code to write, no infrastructure to manage.
Ready to skip the setup? Get your AI assistant running →
Troubleshooting
Bot not responding?
- Verify your bot token is correct
- Check if another instance is running (only one can use polling)
- Ensure your server can reach api.telegram.org
Getting 429 (rate limit) errors?
- Implement exponential backoff
- Queue messages instead of sending immediately
- Telegram limits: ~30 messages/second to different chats
Webhook not receiving updates?
- Confirm SSL certificate is valid
- Check you're using an allowed port (443, 80, 88, 8443)
- Verify the webhook URL with
getWebhookInfo
Messages not arriving?
- Check
allowed_updatesparameter - Ensure bot has permission in group chats
- Verify bot wasn't blocked by user
FAQ
How much does a Telegram AI bot cost to run?
DIY: $5-20/month for a VPS plus your LLM API costs (varies by usage). ClawdHost: $29/month plus your LLM API costs. The LLM costs are the same either way—you bring your own API key. For a full cost breakdown, see our OpenClaw pricing guide.
Can I use Claude with Telegram?
Yes. You can build a custom integration (as shown in this guide) or use ClawdHost, which supports Claude out of the box along with GPT and other providers.
Do I need coding skills?
For DIY, yes—you need JavaScript or Python knowledge plus familiarity with APIs and servers. With ClawdHost, no coding is required.
What's the difference between bot hosting and ClawdHost?
Bot hosting services run your code on their servers. You still write, debug, and maintain the bot. ClawdHost gives you a ready-made AI assistant (OpenClaw)—no code to write, no debugging, no maintenance.
Is my data secure?
With ClawdHost, each user gets their own isolated VPS. We don't store your chat history or OpenClaw memory files. Your LLM API keys are encrypted with AES-256.
Conclusion
The Telegram Bot API is powerful, and building your own AI bot is a great learning experience. But it's also a commitment—setup, hosting, maintenance, and ongoing updates.
Your personal AI assistant doesn't have to be a weekend project that drags into weeks.
Two paths:
- DIY for full control and the satisfaction of building it yourself
- ClawdHost for a working AI assistant in 60 seconds
Ready to skip the setup?
ClawdHost: OpenClaw on Telegram in 60 seconds. No servers. No code. No maintenance.
Related Articles
OpenClaw Docker Setup: Common Problems & How to Skip Docker Entirely
Docker is the default way to run OpenClaw, but it comes with real problems — port conflicts, permission errors, memory issues, and upgrade crashes. Here's how to fix them, or skip Docker altogether.
Hostinger vs ClawdHost for OpenClaw: VPS DIY or Managed Hosting?
Hostinger offers cheap VPS with a 1-click OpenClaw template. ClawdHost offers fully managed hosting. Here's an honest comparison — pricing, setup, maintenance, and who should pick which.
7 Best OpenClaw Hosting Providers Compared (March 2026)
An honest comparison of every major OpenClaw hosting provider — pricing, features, and who each one is actually best for. No fluff, real trade-offs.