How to Build an AI Telegram Bot with Claude API and Cloudflare Workers
AI Chat Assistants on the Edge
Building a chat assistant directly inside messaging platforms (like Telegram or WhatsApp) is a highly effective way to automate customer support or build consumer AI utilities.
By leveraging Cloudflare Workers (serverless runtime) and Anthropic's Claude API, you can deploy a scalable AI assistant that processes webhooks instantly, runs on cheap credits, and responds within seconds.
This tutorial walks through creating a Telegram bot that consumes webhooks and answers using Claude.
1. Setting Up Your Telegram Bot Token
1. Search for @BotFather on Telegram.
2. Send `/newbot` and follow the instructions to set a name and username.
3. Save the generated API HTTP Token (e.g., `7283921829:AAHg82...`).
2. Project Initializer
Create a TypeScript worker with Hono:
npm create cloudflare@latest ai-bot -- --template=hono
cd ai-bot
npm installInstall the official Anthropic SDK client:
npm install @anthropic-ai/sdk3. Webhook Logic & Claude Call
Update `src/index.ts` to parse incoming Telegram messages and fetch replies from Claude:
import { Hono } from 'hono';
import Anthropic from '@anthropic-ai/sdk';
type Bindings = {
TELEGRAM_TOKEN: string;
ANTHROPIC_API_KEY: string;
};
const app = new Hono<{ Bindings: Bindings }>();
app.post('/webhook', async (c) => {
const body = await c.req.json();
const message = body?.message;
if (!message || !message.text) {
return c.text('OK'); // Ignore non-text messages
}
const chatId = message.chat.id;
const userText = message.text;
// Initialize Claude Client
const anthropic = new Anthropic({
apiKey: c.env.ANTHROPIC_API_KEY,
});
// Call Claude
const response = await anthropic.messages.create({
model: 'claude-3-5-sonnet-latest',
max_tokens: 1000,
messages: [{ role: 'user', content: userText }],
});
const replyText = response.content[0].text;
// Send message back to Telegram
const telegramUrl = `https://api.telegram.org/bot${c.env.TELEGRAM_TOKEN}/sendMessage`;
await fetch(telegramUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
chat_id: chatId,
text: replyText,
}),
});
return c.text('OK');
});
export default app;4. Deploying & Registering the Webhook
Encrypt your secrets in wrangler:
npx wrangler secret put TELEGRAM_TOKEN
npx wrangler secret put ANTHROPIC_API_KEY
npx wrangler deployRegister your deployed worker URL as the official Telegram webhook receiver:
curl -X POST "https://api.telegram.org/bot<YOUR_TELEGRAM_TOKEN>/setWebhook" -H "Content-Type: application/json" -d '{"url": "https://your-worker.your-subdomain.workers.dev/webhook"}'Your bot is now live! Send a message to your Telegram bot, and Claude will respond.
CTA: AI App Consulting
I built ReplyGeniusAI, an AI assistant handling context-aware email and chat routing with smart prompt pipelines. Let's build your AI product: email me at [hello@anmolmaan.dev](mailto:hello@anmolmaan.dev).
Frequently Asked Questions
Q:How do you prevent duplicate webhook triggers from Telegram?
Telegram webhooks retry if they don't receive a 200 OK response within 7 seconds. Ensure your worker immediately processes or caches message IDs, returning a fast HTTP 200 response while running the AI request asynchronously using c.executionCtx.waitUntil().
Q:Can I use other LLMs like Google Gemini on Cloudflare Workers?
Yes. You can import Google's generative-ai SDK or call Gemini via fetch endpoints using your API key.
Q:What is the cost of running a bot on Cloudflare Workers?
Cloudflare's free tier allows up to 100,000 requests per day. The paid tier is only $5 USD per million requests, making it incredibly cheap.
Q:How do you persist chat history for context-aware bots?
You can store chat message history in Cloudflare KV store or D1 SQLite database, fetching the last few conversation blocks on every new message to pass as context.
Q:Is Telegram webhook communication secure?
Yes, it is encrypted via HTTPS. You can also validate incoming webhook headers using a secret token parameter to ensure requests originate from Telegram.