Back to Blog
Tutorial8 min read

How to Create a Telegram Bot with Python — Step by Step (2026)

By AgentBackend Team

Most Telegram bot tutorials start with polling loops, webhook servers, and handling updates manually. You end up spending more time on infrastructure than on the bot itself. This guide skips all of that. You'll create an AI-powered Telegram bot, connect it to AgentBackend, and have it live in about 15 minutes. No servers to manage. No webhooks to configure. Just an agent that responds to your users on Telegram.

TL;DR: Create an AI-powered Telegram bot in ~15 minutes. Register a bot with BotFather, create an agent on AgentBackend, link them together, and optionally add a knowledge base and Data Store for domain-specific answers.

What You'll Build

A Telegram bot that:

  • Responds intelligently to user messages using an LLM (Gemini 2.5 Flash by default, but you can swap models)
  • Uses tools to perform actions — look up data, call APIs, run calculations
  • Answers from your docs — Upload a knowledge base and the bot retrieves relevant information before responding
  • Queries structured data — Connect a Data Store and the bot can look up records, check statuses, and pull reports

The bot runs entirely on AgentBackend's infrastructure. You register the Telegram token, link it to an agent, and the platform handles message routing, conversation state, and scaling.

Prerequisites

  • An AgentBackend account — sign up here. The $3 free credit is more than enough for this tutorial.
  • A Telegram account — you'll need it to create a bot via BotFather.
  • Python 3.8+ installed on your machine.

Install the SDK:

bash
pip install agentbackend

Step 1: Create a Telegram Bot

Open Telegram and search for @BotFather. This is Telegram's official bot for creating and managing bots. Start a conversation and follow this flow:

You: /newbot BotFather: Alright, a new bot. How are we going to call it? Please choose a name for your bot. You: Acme Support Bot BotFather: Good. Now let's choose a username for your bot. It must end in `bot`. Like this, for example: TetrisBot or tetris_bot. You: acme_support_bot BotFather: Done! Congratulations on your new bot. You will find it at t.me/acme_support_bot. You can now add a description, about section and profile picture for your bot, see /help for a list of commands. By the way, when you've finished creating your cool bot, ping our Bot Support if you want a better username for it. Just make sure the bot is fully functional before you do this. Use this token to access the HTTP API: 7123456789:AAH1BcDeFgHiJkLmNoPqRsTuVwXyZ0123 Keep your token secure and store it safely.

Copy that token. You'll need it in Step 3.

Important: Treat your bot token like a password. Anyone with this token can control your bot. Don't commit it to version control or share it publicly.

Step 2: Create Your Agent

Now let's create the AI agent that will power your bot. You can do this in the AgentBackend Console or via the SDK. Let's use Python:

python
from agentbackend import AgentBackend

ab = AgentBackend("ak_YOUR_API_KEY")

agent = ab.agents.create(
    name="My Telegram Bot",
    instructions="""You are a helpful assistant available on Telegram.
Keep responses concise — Telegram users expect quick, chat-style answers.
Use bullet points and short paragraphs instead of long blocks of text.
If you don't know something, say so rather than guessing.""",
    model="gemini-2.5-flash",
)

print(f"Agent ID: {agent.agent_id}")

A few notes on the instructions:

  • Keep it concise. Telegram has a 4096-character message limit. Your agent should write short, focused responses.
  • Be specific about behavior. What should the bot do when it doesn't know something? How should it handle off-topic messages? Define this upfront.
  • Mention the platform. Telling the model it's on Telegram helps it adopt the right tone and formatting.

You can also create the agent in JavaScript if you prefer:

javascript
import { AgentBackend } from "agentbackend";

const ab = new AgentBackend({ apiKey: "ak_YOUR_API_KEY" });

const agent = await ab.agents.create({
  name: "My Telegram Bot",
  instructions: `You are a helpful assistant available on Telegram.
Keep responses concise — Telegram users expect quick, chat-style answers.
Use bullet points and short paragraphs instead of long blocks of text.
If you don't know something, say so rather than guessing.`,
  model: "gemini-2.5-flash",
});

console.log(`Agent ID: ${agent.agentId}`);

Save the agent ID — you'll need it in Step 4.

Step 3: Register the Telegram Channel

This tells AgentBackend about your Telegram bot so it can receive and respond to messages.

python
from agentbackend import AgentBackend

ab = AgentBackend("ak_YOUR_API_KEY")

bot = ab.channels.register_bot("telegram", "7123456789:AAH1BcDeFgHiJkLmNoPqRsTuVwXyZ0123")

print(f"Bot ID: {bot['id']}")
print(f"Status: {bot['status']}")

Behind the scenes, AgentBackend sets up the webhook with Telegram's API, handles message serialization, and manages the connection. You don't need to expose any endpoints or run a polling loop.

Now connect your agent to the Telegram channel. This is the step that makes messages flow from Telegram to your agent and back.

python
from agentbackend import AgentBackend

ab = AgentBackend("ak_YOUR_API_KEY")

ab.channels.link_agent("agent_xxx", bot["id"])

print("Agent linked to Telegram channel!")

That's it. Your bot is live.

Step 5: Test It

Open Telegram, find your bot (search for the username you chose in Step 1), and send it a message.

You: Hey, what can you do? Bot: I'm a helpful assistant! I can: - Answer questions on a wide range of topics - Help you think through problems - Provide explanations and summaries What would you like help with? You: What's the capital of New Zealand? Bot: Wellington. It's located at the southern tip of the North Island.

The response should come back within a couple of seconds. If the bot doesn't respond, check:

  1. The bot token is correct (no extra spaces or missing characters)
  2. The channel status is active — you can verify via ab.channels.get_bot(bot["id"])
  3. The agent is linked to the channel

At this point, you have a working Telegram bot powered by an LLM. But a generic chatbot isn't that useful. Let's give it domain knowledge and data access.

Step 6: Add Knowledge

Upload documents so your bot can answer questions about your specific domain — product docs, FAQs, policies, guides.

python
from agentbackend import AgentBackend

ab = AgentBackend("ak_YOUR_API_KEY")

# Upload your docs
ab.knowledge.upload("agent_xxx", "product-guide.pdf")
ab.knowledge.upload("agent_xxx", "faq.md")
ab.knowledge.upload("agent_xxx", "shipping-policy.txt")

print("Knowledge uploaded!")

Now test it on Telegram:

You: What's your return policy? Bot: You can return any item within 30 days of delivery for a full refund. The item must be unused and in its original packaging. Returns are free for orders over $50 — otherwise there's a $5.99 return shipping fee.

The agent searches your uploaded documents, finds the relevant section, and composes an answer. No hallucination about policies that don't exist — it's grounded in your actual docs. For more on how knowledge retrieval works, see the Knowledge documentation.

Step 7: Add Data Store

If your bot needs access to structured data — customer records, inventory, order status — set up a Data Store.

You can create tables via the console or the SDK. Here's a quick example:

python
from agentbackend import AgentBackend

ab = AgentBackend("ak_YOUR_API_KEY")

# Enable data store tools on your agent
ab.agents.update(
    agent_id="agent_xxx",
    tools=[
        {"name": "tenant_query"},
        {"name": "tenant_schema_info"},
    ],
)

Once the Data Store is populated (via the console's conversational interface or the API), your bot can answer data-driven questions on Telegram:

You: What's the status of order #1234? Bot: Order #1234 is currently "shipped." It was dispatched on March 10 and the estimated delivery is March 14. Shipping address: 456 Oak Ave, Seattle WA.

The agent writes a SQL query against your Data Store, gets the results, and formats them into a natural response. Your users never see the query — they just get the answer.

Going Further

You have a working Telegram bot with AI, knowledge retrieval, and data access. Here are some ideas for what to build next:

  • Scheduled messages — Use AgentBackend Schedules to have the bot send daily reports, reminders, or updates to a channel at specific times.
  • Group chat support — Your bot can work in Telegram groups. Add it to a group and it will respond when mentioned or when messages match its trigger conditions.
  • Multiple agents, one bot — Route different types of questions to specialized agents. A triage layer detects the topic and forwards to the right agent.
  • Multi-channel deployment — The same agent that powers your Telegram bot can also serve an API endpoint for your web app. One agent, multiple surfaces.

For a deeper look at what you can build with channels, check out the Channels documentation. And if you're building a support-focused bot, our tutorial on building an AI support bot in 30 minutes covers escalation, guardrails, and cost optimization.

Frequently Asked Questions

Can I deploy the bot to Telegram groups, not just direct messages?

Yes. Add the bot to a group and it will receive messages. You can configure it to respond to all messages or only when mentioned with @your_bot_username. Group conversations maintain separate session context from direct messages.

Does the bot support images, voice messages, or file attachments?

Currently, the bot processes text messages. If a user sends an image or voice message, the bot won't be able to interpret it. You can handle this gracefully by adding a note to your agent's instructions like "If a user sends a non-text message, let them know you can only process text for now." Media support is on the roadmap.

Are there rate limits on Telegram messages?

Telegram imposes its own rate limits: bots can send up to 30 messages per second to different chats, and 1 message per second to the same chat. AgentBackend respects these limits automatically. On the AgentBackend side, rate limits depend on your plan — the free tier supports up to 100 conversations per day, which is plenty for testing and small deployments.

Can I use a different model instead of Gemini 2.5 Flash?

Absolutely. AgentBackend supports multiple models. You can switch to GPT-4o, Claude, or other available models by changing the model parameter when creating or updating your agent. Flash is a good default for Telegram because it's fast and cost-effective, but if you need stronger reasoning, swap in a more capable model. See the Agents documentation for the full list of supported models.

Want to get your Telegram bot live in the next 15 minutes? Create a free AgentBackend account, grab your API key, and follow the steps above. The $3 free credit is enough to run hundreds of conversations. Check the SDK documentation if you want to explore more capabilities.

Related Posts