SokkoSokko
← Back to blog

How to Connect Your AI Agent to Telegram (Bot Token to Live Chat)

Sokko Team11 min read

Telegram is one of the fastest ways to put an AI agent in front of real users. There is no app to publish, no review queue, and no frontend to build. You register a bot, grab a token, and point your code at the Bot API. This tutorial shows you how to connect AI agent to Telegram end to end: you create a bot with BotFather, read incoming messages, forward each one to your agent, and send the reply back into the chat. Budget about 30 minutes. Every command and code block below is runnable as written once you paste in your own token, and each step ends with a check so you always know whether it worked before moving to the next one.

What you need before you start

You need four things, and none of them cost money:

  1. A Telegram account and the app open on your phone or desktop.

  2. A running AI agent or an LLM API call you can invoke from code (OpenAI, Anthropic, a local model, or your own function).

  3. Python 3.10+ or Node.js 18+ installed.

  4. curl for the first two sanity checks against the Bot API.

The whole system has three moving parts: Telegram's servers, your bot's token (the credential that proves your code owns the bot), and your handler (the loop or endpoint that turns a message into an agent reply). Keep those three in mind and the rest follows. Nothing here requires a domain name, a database, or a cloud account to get the first reply working, which is why long-polling is the right starting point. You add those pieces only when you are ready to run the bot for real users, and the last section covers that.

One decision you do not have to make yet is which agent framework to use. The Bot API does not care whether the answer comes from a single model call, a retrieval-augmented pipeline, or a multi-step tool-using agent. As far as Telegram is concerned, a message goes in and text comes out. That clean boundary is what makes this integration quick.

It also helps to know how the pieces relate before you touch code. BotFather is a one-time setup step that hands you a token. The token authenticates every later request. The Bot API is a plain HTTPS interface, so anything that can make an HTTPS call can drive the bot, which is why the same four calls work from curl, Python, or Node. When something misbehaves later, you can always drop back to a raw curl request to isolate whether the problem is Telegram, the token, or your handler code. Keeping that mental model straight saves a lot of guesswork once the agent logic grows.

How to Connect AI Agent to Telegram in 4 Steps

Here is the full path from zero to a live chat. Each step is small and verifiable.

Step 1: Create the bot with BotFather

BotFather is Telegram's official bot for registering other bots. Open it at https://t.me/BotFather and send /newbot. It asks two questions:

  1. A display name (for example, Support Agent).

  2. A username that must end in bot (for example, acme_support_bot).

When you finish, BotFather replies with your token. It looks like 123456789:AA... and it is the only secret in this whole setup. Treat it like a password. Anyone with the token can send messages as your bot, read what users send it, and impersonate it, so never paste it into a public chat, a screenshot, or a git commit.

While you are still in the chat, set a couple of niceties:

  • /setdescription sets the text shown before a user starts the bot.

  • /setcommands defines the slash-command menu users see when they type /.

  • /setuserpic gives the bot a recognizable avatar.

Step 2: Confirm the token works

Before writing any handler, prove the token is valid with a single call. The getMe endpoint returns your bot's identity:

curl "https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getMe"

Replace the placeholder with your real token (keep the bot prefix directly in front of it). A working token returns JSON like this:

{
  "ok": true,
  "result": {
    "id": 123456789,
    "is_bot": true,
    "first_name": "Support Agent",
    "username": "acme_support_bot"
  }
}

If ok is false, the token is wrong or has a stray space. Fix that before moving on, because every later step depends on it.

Step 3: Read incoming messages with getUpdates

There are two ways to receive messages: long-polling (you ask Telegram for new updates in a loop) and webhooks (Telegram pushes updates to your public URL). Start with long-polling because it needs nothing but an outbound internet connection. Send yourself a message in the bot chat first, then run:

curl "https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getUpdates"

You get back an array of update objects. A text message looks like this:

{
  "ok": true,
  "result": [
    {
      "update_id": 700000001,
      "message": {
        "message_id": 12,
        "from": { "id": 555000111, "first_name": "Sam" },
        "chat": { "id": 555000111, "type": "private" },
        "text": "hello agent"
      }
    }
  ]
}

The two fields you care about are chat.id (where to send the reply) and text (what the user said). That is the entire contract. Everything else in the object, like message_id and the sender's name, is context you can use but do not strictly need for a first reply.

Step 4: Send a reply with sendMessage

To answer, POST to sendMessage with the chat id and your text:

curl -X POST "https://api.telegram.org/bot<YOUR_BOT_TOKEN>/sendMessage" \
  -d "chat_id=555000111" \
  -d "text=Hi Sam, the agent is online."

Watch the message land in your Telegram chat. You have now done every operation your bot needs: read a message, run logic, send a reply. The code below just automates this loop so you are not running curl by hand for every message.

How do you wire the agent into the loop?

The handler is where a user's text becomes a prompt for your agent and the agent's answer becomes the text of a reply. Below is a minimal long-polling handler in Python using python-telegram-bot. Install it first:

pip install python-telegram-bot
import os
from telegram import Update
from telegram.ext import (
    ApplicationBuilder, MessageHandler, CommandHandler, ContextTypes, filters
)

TOKEN = os.environ["TELEGRAM_BOT_TOKEN"]

async def run_agent(user_text: str) -> str:
    # Replace this with your real agent call.
    # e.g. an OpenAI/Anthropic request, a LangChain chain, or your own function.
    return f"You said: {user_text}. (agent reply goes here)"

async def on_start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text("Hi! Send me a message and the agent will answer.")

async def on_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await context.bot.send_chat_action(update.effective_chat.id, "typing")
    reply = await run_agent(update.message.text)
    await update.message.reply_text(reply)

app = ApplicationBuilder().token(TOKEN).build()
app.add_handler(CommandHandler("start", on_start))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, on_message))
app.run_polling()

Run it with your token in the environment:

export TELEGRAM_BOT_TOKEN="123456789:AA..."
python bot.py

Now every message in the chat flows through run_agent. Swap that function for your model call and you have a working bot. The send_chat_action line shows the "typing..." animation while the agent thinks, which keeps users from wondering whether the bot froze during a slow model call. Prefer Node.js? The same shape works with grammY:

npm install grammy
import { Bot } from "grammy";

const bot = new Bot(process.env.TELEGRAM_BOT_TOKEN);

async function runAgent(userText) {
  // Replace with your real agent / LLM call.
  return `You said: ${userText}. (agent reply goes here)`;
}

bot.command("start", (ctx) => ctx.reply("Hi! Send me a message and the agent will answer."));
bot.on("message:text", async (ctx) => {
  await ctx.replyWithChatAction("typing");
  const reply = await runAgent(ctx.message.text);
  await ctx.reply(reply);
});

bot.start();

Both frameworks handle the polling loop, retries, and update parsing so you focus on the agent logic. Two refinements pay off quickly. First, key your agent's memory by chat.id so each user keeps their own conversation context instead of sharing one global history. Second, remember Telegram caps a single message near 4096 characters, so split long agent output into multiple sends rather than letting a large reply fail silently. If you want a broader tour of the framework choices and message patterns, the AI agent Telegram bot guide goes deeper than this quick start.

Long-polling or webhook: which should you use?

Long-polling is perfect for development and small bots. Webhooks scale better and cut latency because Telegram pushes each update to your endpoint the instant it arrives. Here is the trade-off:

FactorLong-polling (getUpdates)Webhook (setWebhook)
Setup effortRun one script, no URL neededNeeds a public HTTPS URL and TLS
LatencySlight delay per pollNear-instant push
InfrastructureAny machine with outbound internetPublic host or tunnel
Best forLocal dev, low trafficProduction, high traffic
ScalingOne process pulls all updatesLoad-balanced endpoints

When you are ready for a webhook, register your public URL once:

curl -X POST "https://api.telegram.org/bot<YOUR_BOT_TOKEN>/setWebhook" \
  -d "url=https://your-domain.example/telegram/webhook"

Telegram then POSTs each update as JSON to that path. Your handler reads the same message.chat.id and message.text fields, runs the agent, and calls sendMessage. One caveat: long-polling and webhooks are mutually exclusive. Call deleteWebhook before you go back to getUpdates, or the polling call returns an error. For local webhook testing you can expose your machine with a tunneling tool, but that tunnel is not something to depend on in production, which brings us to the one requirement most tutorials skip.

Why your bot has to stay online

Here is the honest part of running a chat bot. With long-polling, your script must keep looping to catch messages. With a webhook, your endpoint must be reachable every second. If the process is on your laptop and the lid closes, or on a free-tier host that sleeps after 15 minutes of inactivity, messages sent during downtime are delivered late or missed while the process is dead. Telegram queues updates for a limited window, not forever, so a bot that is down for an hour can simply lose the messages people sent in that hour.

That means an AI agent you connect to Telegram needs an always-on host. This is where a managed runtime earns its place. Sokko runs agents on secure, always-on infrastructure with a persistent workspace and encrypted storage for your bot token, so the polling loop or webhook endpoint never quietly dies between messages. You get the same behavior whether one person or a thousand people are chatting, and a crash restarts the process instead of leaving your bot silent overnight. If you want the full deployment path from local script to a durable service, see how to deploy an AI agent. If your agent is OpenClaw or Hermes, you can skip the wiring and connect Telegram from the dashboard.

Quick troubleshooting checklist

Most first-time problems come from one of a handful of causes. Run down this list before you assume the code is broken:

  • Bot never replies: confirm getMe returns ok: true and that you sent the bot a message after starting it, not before.

  • getUpdates is empty: you may have a webhook set; run deleteWebhook first, since the two modes cannot both be active.

  • 401 Unauthorized: the token has a typo or a leading space, or you dropped the bot prefix in front of it.

  • Webhook not firing: the URL must be HTTPS with a valid certificate; test it with getWebhookInfo, which reports the last error Telegram saw.

  • Replies go to the wrong person: you hardcoded a chat_id; always read it from the incoming update instead.

  • Bot works locally but not after you close the laptop: the process stopped; this is the uptime issue, not a code bug.

  • Duplicate replies: you are running two copies of the handler against the same token, so stop one, since a single token should be polled by one process only.

Wrapping up

You now have every piece to connect AI agent to Telegram: a bot registered with BotFather, a validated token, a read loop with getUpdates, a reply with sendMessage, and a handler that routes each message through your agent. Start on long-polling to get a live chat in minutes, then move to a webhook when traffic grows. The one detail that separates a demo from a real product is uptime, so put the bot on a host that stays awake and restarts on failure. For the exact endpoints and object fields, keep the official Telegram Bot API docs open while you build, and when you want the architecture behind a production bot, read the deeper pillar guide linked above.