Blog

Building a Telegram Bot with Claude Code

How to build a Telegram bot with Claude Code: Bot API basics, the build workflow from registration to deployment, command handlers, inline keyboards, and a deployment comparison table.

Phos Team ·
claude code

Telegram bots are one of the fastest paths from idea to deployed product in the developer toolkit. The Telegram Bot API is well-documented, has generous free limits, and Claude Code understands the python-telegram-bot and telegraf (Node.js) libraries well enough to scaffold a working bot handler in minutes.

The build workflow is straightforward: register your bot with BotFather, scaffold handlers with Claude Code, test locally with polling, then deploy with webhooks to a platform like Railway or Render.

Telegram bots are an underutilized tool for internal team automation. A bot that posts daily summaries, answers questions from a knowledge base, or routes support requests costs almost nothing to run and can be built in a day with Claude Code.


Telegram Bot API basics

What you control

A Telegram bot is a server-side application that responds to messages, commands, and interactions sent through the Telegram app. You register a bot identity with BotFather (Telegram’s official bot management bot), receive a token, and your server handles all incoming events.

The Telegram platform handles message delivery, user authentication, and the mobile/desktop interface. You handle the application logic.

Two communication modes

Polling: Your server periodically calls the Telegram API to check for new messages. Simpler to set up, works without a public URL, ideal for local development and low-traffic bots. Not suitable for production at scale.

Webhooks: Telegram calls your server when a new message arrives. Requires a public HTTPS URL. More efficient, lower latency, the right approach for production deployment.

Choosing a library

LibraryLanguageBest for
python-telegram-botPythonPython teams, data-heavy bots, AI integration
telegrafNode.jsJavaScript teams, rapid prototyping
GrammyNode.js/DenoModern TypeScript, edge deployment
aiogramPython (async)High-throughput bots, async-first codebases

python-telegram-bot v20+ (async) is the most fluent choice for Claude Code-generated Python bots. telegraf is the equivalent for Node.js. Specify your library in every prompt.


The build workflow

Step 1: Register your bot

Open Telegram and message @BotFather. Send /newbot, follow the prompts to choose a name and username, and receive your bot token. Store the token in a .env file immediately. Never commit it to version control.

Claude Code cannot do this step. Bot registration requires a Telegram account and interaction with BotFather.

Step 2: Scaffold the project structure

A clean scaffold prompt: “Create a Telegram bot using python-telegram-bot v20+ (async). Structure the project with: main.py for the Application setup, a handlers/ directory with one file per command group, a utils/ directory for helper functions, and a .env file template for BOT_TOKEN and WEBHOOK_URL. Include a requirements.txt. Use polling mode for local development.”

Review the generated main.py to verify it uses ApplicationBuilder (the v20+ pattern) rather than the deprecated Updater pattern from earlier versions.

Step 3: Implement command handlers

Commands are the primary interface for most bots. Claude Code generates clean command handlers: “Add a handler for /start that sends a welcome message with the bot’s capabilities listed. Add a handler for /help that lists all available commands with descriptions. Add a handler for /status that replies with the current date and a status message.”

Each handler is a separate async function. Claude Code generates them with proper type annotations and the correct update and context parameter pattern.

Step 4: Add message handlers

Message handlers respond to non-command text. These are where conversational logic lives. “Add a message handler that receives any text message, passes it to the OpenAI API as a user message with the system prompt in SYSTEM_PROMPT (loaded from config), and replies with the API response. Handle errors by replying with ‘Something went wrong, please try again.’”

Keep message handlers focused. A single handler that does too much becomes hard to debug. Claude Code respects this when prompted for specific handler responsibilities.

Step 5: Add inline keyboards

Inline keyboards add buttons to bot messages that users can tap to trigger actions. They are one of the most common Telegram bot UX patterns. “Create a function that sends a message with an inline keyboard containing two buttons: ‘Yes’ (callback data: ‘confirm_yes’) and ‘No’ (callback data: ‘confirm_no’). Add a callback query handler that responds to both buttons with an appropriate confirmation message.”

Claude Code generates inline keyboard markup correctly using InlineKeyboardMarkup and InlineKeyboardButton. Verify that callback data strings are consistent between the keyboard creation and the handler.

Step 6: Configure for production with webhooks

When ready to deploy, switch from polling to webhooks. Claude Code generates the webhook setup: “Modify main.py to support both polling (for local dev, when WEBHOOK_URL is not set) and webhook mode (for production, when WEBHOOK_URL is set). The webhook should run on port 8080 at path /webhook/{BOT_TOKEN}.”

This dual-mode pattern (polling locally, webhook in production) is the cleanest development workflow for Telegram bots.


Common bot patterns

Daily scheduled messages

Telegram bots can send proactive messages using scheduled jobs. Claude Code generates JobQueue patterns for python-telegram-bot: “Add a daily job that runs at 9:00 AM UTC and sends a message to ADMIN_CHAT_ID (from environment variables) with yesterday’s summary from the database.”

AI-powered responses

The combination of a Telegram bot frontend and an LLM backend is one of the most common patterns Claude Code is used for. The bot handles message routing. The LLM handles response generation. Keep conversation history in context.user_data for within-session continuity and in a database for cross-session persistence.

Storage and state

For simple bots, context.user_data and context.chat_data handle in-memory state. For anything that needs persistence across restarts, use a database. Claude Code generates SQLite (for simple bots), PostgreSQL (via psycopg2 or asyncpg), or Redis (for session state) integrations depending on what you specify.


Deployment comparison table

PlatformFree tierWebhook supportPersistent storageBest for
Railway$5/month creditYesYes (volumes)Most bots; simple deployment
RenderFree tier (spins down)YesYes (disks)Low-traffic or hobby bots
Fly.ioGenerous free tierYesYes (volumes)Global deployment needs
VPS (Hetzner, DigitalOcean)~$5/monthYesYes (full disk)Full control, long-running bots
Google Cloud RunFree tierYesExternal DB neededServerless, scales to zero

Railway is the simplest deployment path for most Telegram bots. It handles environment variables, HTTPS, and persistent storage with minimal configuration. Claude Code generates Railway deployment files (railway.toml) when you specify Railway as your target.


Frequently asked questions

What is the difference between polling and webhooks for a Telegram bot?

Polling has your server check Telegram for new messages every few seconds. Webhooks have Telegram push new messages to your server as they arrive. Polling is simpler to set up and works without a public URL (ideal for local development). Webhooks are more efficient and lower-latency (required for production). Claude Code can generate both modes and a configuration toggle between them.

Can Claude Code generate a bot that maintains conversation context?

Yes. Claude Code generates conversation context patterns using ConversationHandler (for multi-step flows) and context.user_data (for within-session state). For cross-session memory, ask Claude Code to generate a database-backed conversation history that stores and retrieves messages by user ID.

How do I handle user authentication in a Telegram bot?

Telegram provides a user.id for every message sender. This ID is stable and can be used to whitelist specific users or admins. For more formal authentication, the Telegram Login Widget allows users to authenticate your web app with their Telegram identity. Claude Code generates whitelist patterns (check user.id against an ALLOWED_USERS env var) and can scaffold the Login Widget flow.

Can a Telegram bot send rich media like images and files?

Yes. The Telegram Bot API supports sending photos, documents, audio, video, and stickers. Claude Code generates the send methods correctly: context.bot.send_photo(), context.bot.send_document(), etc. Specify the media type in your prompt and whether you are sending a file URL or a local file path.


Ready to build your Telegram bot?

Telegram bots are one of the fastest projects in Claude Code’s wheelhouse. The Bot API is well-defined, the libraries are mature, and the deployment path is straightforward. A working bot with command handlers, a message handler, and Railway deployment can be scaffolded and running within a day. If the bot is part of a larger application, how to build a full-stack app with Claude Code covers how to integrate it into a broader backend architecture. For containerized production deployments, the Docker and Kubernetes guide covers the infrastructure side.

The best internal automation bots are the ones that solve a specific, repeated team pain point: the daily standup reminder, the deployment status notification, the customer support question router. Start with one use case and deploy it before adding more.

Path one: do it yourself. Register your bot with BotFather today and create your bot token. Write down the three to five commands your bot needs. Run the scaffold prompt with your library of choice and have a local polling bot running within an hour.

Path two: work with Phos AI Labs. If you want an experienced team building and deploying your bot from concept through production, Phos AI Labs runs structured build engagements. Start with a conversation.

Related articles

The fastest way to know whether we're the right fit, is a conversation.

STEP 1/2 · ABOUT YOU