---
title: "Host a Telegram bot"
description: "Run an AI Telegram bot on an exe.dev VM: python-telegram-bot under systemd, SQLite memory, photos and PDFs, Claude with no key, no bot token."
url: https://exe.dev/deploy/telegram-bot
category: "AI agents"
updated: 2026-11-17
---

# Host a Telegram bot

An AI Telegram bot that runs all the time. The bot token stays with exe.dev.

- **Software:** Telegram bot (https://core.telegram.org/bots)
- **Source:** https://exe.dev/deploy/telegram-bot/bot.py
- **License:** python-telegram-bot is LGPL-3.0
- **Time:** 10 minutes
- **Example VM name:** `my-telegram-bot` (yours will differ; on the VM, `hostname` prints it)
- **Machine-readable:** https://exe.dev/deploy/telegram-bot/manifest.json
- **File:** https://exe.dev/deploy/telegram-bot/bot.py

## What you get

- `telegram-bot.service`, restarted on failure and reboot, long-polling Telegram through the integration and logging `connected to Telegram as @<bot>`.
- Claude answering in private chats, and when mentioned or replied to in groups, with each chat's last 20 messages remembered in SQLite.
- Photos, PDFs, and text files sent to the bot downloaded through the integration's `/file/` path and read by the model.
- The bot token held by exe.dev's Telegram integration and models from the LLM integration, with neither secret on the VM.
- The bot claimed by its owner through a one-time link, and ignoring everyone they haven't invited.

Running on the VM:

- **bot.py**: [one Python file](https://exe.dev/deploy/telegram-bot/bot.py) on python-telegram-bot 22.8, run by uv as `telegram-bot.service`, data in `~/telegram-bot`
- **SQLite**: each chat's recent messages, who may use the bot, open groups, data in `~/telegram-bot/data/bot.db`
- **Telegram integration**: `telegram.int.exe.xyz` adds the bot token to Bot API calls and file downloads
- **LLM integration**: `llm.int.exe.xyz`, Claude Sonnet 5.5 by default

How it is reached:

- Telegram (shared): the bot, for you and the people you invite
- https://telegram.int.exe.xyz/ (private): the Bot API as your bot, from this VM only
- ssh my-telegram-bot.exe.xyz (private): code, prompt, logs

## Deploy with Shelley

Open https://exe.dev/new?prompt=Set%20up%20Telegram%20bot%20on%20this%20VM%20by%20following%20the%20exe.dev%20recipe%20at%20https%3A%2F%2Fexe.dev%2Fdeploy%2Ftelegram-bot.md%20from%20top%20to%20bottom.%0A%0AThe%20recipe%27s%20example%20VM%20name%20is%20my-telegram-bot.%20This%20VM%27s%20name%20is%20the%20output%20of%20%60hostname%60%3A%20use%20it%20wherever%20the%20recipe%20writes%20my-telegram-bot.%20Skip%20the%20step%20that%20creates%20the%20VM%3B%20you%20are%20on%20it.%0A%0AYou%20are%20done%20when%20all%20of%20these%20are%20true.%20Check%20each%20one%20yourself%3A%0A-%20%60telegram-bot.service%60%2C%20restarted%20on%20failure%20and%20reboot%2C%20long-polling%20Telegram%20through%20the%20integration%20and%20logging%20%60connected%20to%20Telegram%20as%20%40%3Cbot%3E%60.%0A-%20Claude%20answering%20in%20private%20chats%2C%20and%20when%20mentioned%20or%20replied%20to%20in%20groups%2C%20with%20each%20chat%27s%20last%2020%20messages%20remembered%20in%20SQLite.%0A-%20Photos%2C%20PDFs%2C%20and%20text%20files%20sent%20to%20the%20bot%20downloaded%20through%20the%20integration%27s%20%60%2Ffile%2F%60%20path%20and%20read%20by%20the%20model.%0A-%20The%20bot%20token%20held%20by%20exe.dev%27s%20Telegram%20integration%20and%20models%20from%20the%20LLM%20integration%2C%20with%20neither%20secret%20on%20the%20VM.%0A-%20The%20bot%20claimed%20by%20its%20owner%20through%20a%20one-time%20link%2C%20and%20ignoring%20everyone%20they%20haven%27t%20invited.%0A%0ARead%20the%20whole%20recipe%2C%20closed%20details%20included%2C%20and%20follow%20%22Set%20up%20by%0Ahand%22%20in%20order%2C%20skipping%20VM%20creation%3B%20the%20walkthrough%20above%20it%20is%20for%0Athe%20owner.%20The%20bot%20token%20must%20never%20be%20on%20this%20VM%3A%20don%27t%20ask%20for%20it.%0AFirst%20give%20the%20owner%20the%20steps%20in%20%22Make%20a%20bot%22%20and%20%22Give%20exe.dev%20the%0Atoken%22%2C%20with%20the%20connect%20link%20for%20this%20VM%27s%20name%2C%20and%20install%20the%20bot%0Awhile%20they%20do%20that%3B%20the%20service%20retries%20until%20the%20integration%20is%0Aattached.%20If%20%60curl%20-s%20https%3A%2F%2Freflection.int.exe.xyz%2Fintegrations%60%20shows%0Atheir%20Telegram%20integration%20under%20a%20name%20other%20than%20%60telegram%60%2C%20set%0ATELEGRAM_API%20in%20~%2Ftelegram-bot%2Fbot.env%20to%20match.%20When%20the%20log%20shows%20the%0Aowner%20link%2C%20give%20it%20to%20the%20owner.%20Stay%20with%20long%20polling%20unless%20they%20ask%0Afor%20webhooks.%20End%20with%20the%20owner%20link%2C%20what%20to%20try%2C%20and%20how%20to%20change%0Athe%20prompt.%0A%0AFinish%20with%20the%20URLs%20I%20should%20open.%0A to create a VM whose agent, Shelley, follows this recipe. From a terminal:

```sh
curl -fsSL https://exe.dev/deploy/telegram-bot/prompt.txt | ssh exe.dev new --prompt=/dev/stdin
```

Or follow the steps below by hand.

An AI Telegram bot that answers you and the people you invite, reads the
photos, PDFs, and files you send it, and remembers each conversation. It's
one Python file on [python-telegram-bot](https://python-telegram-bot.org),
running all the time on an exe.dev VM under systemd, with its memory in
SQLite on the VM's disk.

No secret lives on the VM. exe.dev's Telegram integration keeps the bot
token and adds it to each Bot API call on the way out; the
[LLM integration](/docs/integrations-llm) does the same for Claude. The bot
long-polls Telegram, so it needs no public URL either: the VM stays private
behind exe.dev login. The same setup runs any other bot code, in any
language, as the last sections show.

## Make a bot

In Telegram, open [@BotFather](https://t.me/BotFather), send `/newbot`,
and answer its two questions: a display name, and a username that ends in
`bot`. It replies with the bot's token, a line like
`123456789:AAH...`. You'll hand it to exe.dev in the next step; don't put
it anywhere else.

## Give exe.dev the token

Open the connect link for your VM,
[exe.dev/integrations/add?service=telegram&attach=vm:my-telegram-bot](https://exe.dev/integrations/add?service=telegram&attach=vm:my-telegram-bot),
name it `telegram`, paste the token, and add it. Then delete the
token from your BotFather chat, or wherever else you pasted it. (Over
SSH, `ssh exe.dev integrations list --available` prints the command that
adds a `telegram` integration instead; see
[Integrations](/docs/integrations).)

On the VM, the bot's API is now `https://telegram.int.exe.xyz`:

```bash
curl -s https://telegram.int.exe.xyz/getMe
```

prints `"ok":true` and your bot's username. The token isn't in the URL,
and it isn't anywhere on the VM.

## Claim your bot

The first time it starts, the bot logs a one-time link that makes whoever
opens it the bot's owner. Shelley gives it to you; or, on the VM:

```bash
journalctl -u telegram-bot | grep -o 'https://t.me/[^ ]*' | tail -1
```

Open it on a device with Telegram and press **Start**. The bot says hi.
Anyone else who messages it gets "This bot is private".

## Talk to it

- **In a private chat**, just write. Follow-ups work: it remembers the
  chat's last 20 messages.
- **Send a photo, a PDF, or a text file**, with a question as the caption.
  The bot downloads it through the integration and Claude reads it.
- **In a group**, add the bot, then mention it (`@yourbot what's...`) or
  reply to one of its messages. Invited people can use it anywhere;
  `/open` lets everyone in that group use it, and `/close` undoes that.
- `/invite` gives you a one-time link for one more person.
- `/forget` clears what it remembers of the chat.

While Claude works, the chat shows "typing…". Replies use Telegram's
formatting: bold, italics, code, links.

## Make it yours

The bot's instructions are in `~/telegram-bot/prompt.md`; its settings,
including `MODEL`, in `~/telegram-bot/bot.env`. Change either, then
`sudo systemctl restart telegram-bot`.

Shelley, the agent on the VM, can change the bot itself: "add a `/summary`
command", "send me the weather every morning at 7", "answer voice notes".
[bot.py](https://exe.dev/deploy/telegram-bot/bot.py) is short and
commented, and the integration passes every Bot API method through.

## Run your own bot code

The integration is the Bot API at a different address, without the token.
Where Telegram's docs say `https://api.telegram.org/bot<token>/METHOD`,
call `https://telegram.int.exe.xyz/METHOD`; where they say
`https://api.telegram.org/file/bot<token>/<file_path>`, call
`https://telegram.int.exe.xyz/file/<file_path>`. With curl, on the VM:

```bash
curl -s https://telegram.int.exe.xyz/getUpdates          # find a chat_id
curl -s https://telegram.int.exe.xyz/sendMessage -d chat_id=123456789 -d text='Deployed!'
```

That's also the simplest way to send yourself alerts from cron jobs and
scripts. Libraries need their base URL changed, and most insist on some
token; give them a placeholder, which never leaves the VM. Each snippet
below was tested through the integration, with `getMe` and a file
download, at the version shown:

**python-telegram-bot** 22.8. A plain string `base_url` gets the token
appended, so pass a function:

```python
API = "https://telegram.int.exe.xyz"
app = (ApplicationBuilder().token("exe-dev-integration")
       .base_url(lambda _: API).base_file_url(lambda _: API + "/file").build())
```

**aiogram** 3.32. aiogram checks the token's shape and takes the bot's ID
from it, so use your bot's numeric ID (the part of the token before the
colon) and anything after it:

```python
from aiogram import Bot
from aiogram.client.session.aiohttp import AiohttpSession
from aiogram.client.telegram import TelegramAPIServer

API = "https://telegram.int.exe.xyz"
session = AiohttpSession(api=TelegramAPIServer(base=API + "/{method}", file=API + "/file/{path}"))
bot = Bot(token="123456789:exe-dev-integration", session=session)
```

**pyTelegramBotAPI** (telebot) 4.37. It also wants `<digits>:<anything>`:

```python
import telebot
from telebot import apihelper

apihelper.API_URL = "https://telegram.int.exe.xyz/{1}"
apihelper.FILE_URL = "https://telegram.int.exe.xyz/file/{1}"
bot = telebot.TeleBot("123456789:exe-dev-integration")
```

For `AsyncTeleBot`, set the same two names on `telebot.asyncio_helper`.

**grammY** 1.46 (tested on Node.js 24):

```js
import { Bot } from "grammy";

const API = "https://telegram.int.exe.xyz";
const bot = new Bot("exe-dev-integration", {
  client: { apiRoot: API, buildUrl: (root, _token, method) => `${root}/${method}` },
});
// files: fetch(`${API}/file/${(await ctx.getFile()).file_path}`)
```

**Telegraf** has no way to drop the token from its URLs, and hasn't had a
release since February 2024; prefer grammY. Bots in other languages work
the same way if their library takes an API base URL; the Go
[telegram-bot-api](https://github.com/go-telegram-bot-api/telegram-bot-api)
has `NewBotAPIWithAPIEndpoint`, whose endpoint is a format string.

Run your bot under systemd as in [Set up by hand](#create-the-vm), with
its own `ExecStart`, and keep its state in a file on the VM's disk
(SQLite is plenty; see [SQLite](/deploy/sqlite)).

## Switch to webhooks

With a webhook, Telegram POSTs each update to your HTTPS URL instead of
the bot asking for them. On exe.dev that's the VM's own address,
`https://my-telegram-bot.exe.xyz/`, which the [HTTPS proxy](/docs/proxy)
sends to port 8000 (Telegram only calls ports 443, 80, 88, and 8443, so
use that one rather than `:8443`). It has to be public, so Telegram can
reach it. On your computer:

```bash
ssh exe.dev share set-public my-telegram-bot
```

On the VM, switch the bot over and restart it:

```bash
cd ~/telegram-bot
printf 'MODE=webhook\nPUBLIC_URL=https://%s.exe.xyz\n' "$(hostname)" >> bot.env
sudo systemctl restart telegram-bot
curl -s https://telegram.int.exe.xyz/getWebhookInfo; echo
```

The bot serves `/telegram` on port 8000 and calls `setWebhook` through
the integration with a random `secret_token` it keeps in
`data/webhook-secret`. Telegram sends that secret in the
`X-Telegram-Bot-Api-Secret-Token` header of every update, and the bot
rejects requests without it, so nobody else can feed it updates.
`getWebhookInfo` should show your URL and `"pending_update_count":0`.
To check the secret from your computer (not from the VM, which can't
reach its own public address), `curl -s -o /dev/null -w '%{http_code}\n'
-X POST https://my-telegram-bot.exe.xyz/telegram` should print `403`.

To go back, delete the two lines from `bot.env` and restart: the bot
removes the webhook when it starts polling. Then
`ssh exe.dev share set-private my-telegram-bot`.

## The nuts and bolts

These are Shelley's setup steps and your maintenance reference.

<details id="create-the-vm" data-manual-setup class="dp-details">
<summary>Set up by hand</summary>

### Create the VM

On your computer (pick another name if `my-telegram-bot` is taken):

```bash
ssh exe.dev new --name=my-telegram-bot
```

Then do [Make a bot](#make-a-bot) and
[Give exe.dev the token](#give-exe-dev-the-token). The rest runs **on the
VM** (`ssh my-telegram-bot.exe.xyz`).

### Install the bot

[bot.py](https://exe.dev/deploy/telegram-bot/bot.py) declares its one
dependency, `python-telegram-bot[webhooks]==22.8`, inline; `uv` installs
it, and a Python to run it, on first start.

```bash
mkdir -p ~/telegram-bot && cd ~/telegram-bot
curl -fsSL https://exe.dev/deploy/telegram-bot/bot.py -o bot.py
cat > prompt.md <<'EOF'
You are a helpful assistant in Telegram. Messages start with the sender's
first name. Answer briefly and in plain language. Format with Telegram's
HTML only: <b>, <i>, <code>, <pre>, <a href="...">, and plain line breaks;
no Markdown, headings, tables, or other tags. Escape <, > and & in text as
&lt; &gt; &amp;. Keep replies under 3,000 characters unless asked for more.
EOF
cat > bot.env <<'EOF'
TELEGRAM_API=https://telegram.int.exe.xyz
MODEL=claude-sonnet-5-5
EOF
```

`TELEGRAM_API` is the integration's URL: `https://<name>.int.exe.xyz`
for an integration called `<name>`.

### Run it under systemd

```bash
sudo tee /etc/systemd/system/telegram-bot.service >/dev/null <<'EOF'
[Unit]
Description=AI Telegram bot (exe.dev/deploy/telegram-bot)
After=network-online.target
Wants=network-online.target

[Service]
User=exedev
WorkingDirectory=/home/exedev/telegram-bot
EnvironmentFile=/home/exedev/telegram-bot/bot.env
ExecStart=/usr/local/bin/uv run --script bot.py
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable --now telegram-bot
```

Until the integration is attached, the log shows `integration not found`
and systemd restarts the bot every 10 seconds.

### Check it

```bash
curl -s https://telegram.int.exe.xyz/getMe; echo
journalctl -u telegram-bot -n 20 --no-pager
```

The first prints the bot. The log should say
`connected to Telegram as @<your bot>`, then the owner link (until someone
has used it).

</details>

<details id="back-up-and-restore" class="dp-details">
<summary>Back up and move</summary>

Everything is in `~/telegram-bot`: the code, `prompt.md`, `bot.env`, and
`data/bot.db`, which holds who may use the bot, the open groups, and each
chat's recent messages. Back it up to keep your invitations; losing it
means claiming the bot again. Nothing in it lets anyone control the bot.
On your computer:

```bash
ssh my-telegram-bot.exe.xyz 'sqlite3 telegram-bot/data/bot.db ".backup /tmp/bot.db" && tar -czf - -C ~ --exclude=data telegram-bot -C /tmp bot.db' > telegram-bot.tar.gz
```

To restore on a new VM, attach the integration to it
(`ssh exe.dev integrations attach telegram vm:new-vm`), set up the
systemd unit as above, then unpack:

```bash
scp telegram-bot.tar.gz new-vm.exe.xyz:
ssh new-vm.exe.xyz 'tar -xzf telegram-bot.tar.gz && mkdir -p telegram-bot/data && mv bot.db telegram-bot/data/ && sudo systemctl restart telegram-bot'
```

Stop the bot on the old VM first: Telegram gives updates to only one
poller at a time (see Troubleshooting).

</details>

<details id="update" class="dp-details">
<summary>Update</summary>

On the VM, fetch the latest `bot.py` (this replaces local changes), and
restart:

```bash
cd ~/telegram-bot
curl -fsSL https://exe.dev/deploy/telegram-bot/bot.py -o bot.py
sudo systemctl restart telegram-bot
```

To rotate the token, send BotFather `/revoke`, then paste the new token
into the integration on the [Integrations page](https://exe.dev/integrations).
The VM needs no change.

</details>

<details id="troubleshooting" class="dp-details">
<summary>Troubleshooting</summary>

Start with the log, on the VM: `journalctl -u telegram-bot -n 50`.

- **`integration not found or not attached to this VM`**: attach it, on
  your computer: `ssh exe.dev integrations attach telegram vm:my-telegram-bot`.
- **`Unauthorized` or `401`**: the token was revoked or mistyped; paste
  the current one into the integration.
- **`Conflict: terminated by other getUpdates request`**: another copy of
  the bot is polling with the same token, on another VM or your laptop.
  Stop it; only one poller gets updates.
- **`Conflict: can't use getUpdates method while webhook is active`**:
  something set a webhook. The bot deletes it when it starts polling, so
  restart it, or run `curl -s https://telegram.int.exe.xyz/deleteWebhook`.
- **No answer in a group**: mention the bot by its @username or reply to
  it, and make sure you're invited or the group is `/open`. The log lists
  ignored messages with the sender's ID.
- **Webhook: `getWebhookInfo` shows `last_error_message`**: the VM isn't
  public (`ssh exe.dev share set-public my-telegram-bot`), or the bot
  isn't listening on port 8000 (`curl -s localhost:8000/telegram` should
  answer, with an error, rather than refuse the connection).
- **Raw `<b>` tags in replies**: the model wrote HTML Telegram rejected,
  and the bot fell back to plain text. Tighten the formatting rules in
  `prompt.md`.

</details>

## Frequently asked questions

### Where does the bot token live?

With exe.dev. The Telegram integration (in the [integration catalog](/docs/integrations-catalog)) stores it and puts it into each request the VM sends to `telegram.int.exe.xyz`, so the VM, its agent, and anyone who breaks into it can use the bot but can't copy the token. Detach the integration and the VM can't reach the bot at all.

### Polling or webhooks?

Long polling, unless you have a reason. It needs no public URL, works the moment the integration is attached, and answers just as fast for a personal or team bot. Webhooks suit bots with heavy traffic, or code that already expects them; see [Switch to webhooks](#switch-to-webhooks).

### Can I use aiogram, grammY, or my own bot?

Yes. Any library that lets you set the API's base URL works; point it at `https://telegram.int.exe.xyz` with a placeholder token, as in [Run your own bot code](#run-your-own-bot-code). Code that builds `https://api.telegram.org/bot<token>/` URLs itself needs that one line changed.

### Who can talk to my bot?

Anyone can find a Telegram bot and message it, so this one answers only its owner and the people they invite, and in groups only after `/open`. Everyone else gets "This bot is private", and the model is never called for them.

### How much does it cost?

The VM is part of your [exe.dev plan](https://exe.dev/pricing), and model calls count against your exe.dev LLM allocation; Telegram's Bot API is free. Each answer sends the chat's last 20 messages to the model, plus any photo or PDF. `MODEL=claude-haiku-5-5` costs about a fifth as much.

### Can it use GPT or an open model?

Any model the LLM integration serves on the Anthropic Messages API: set `MODEL` in `~/telegram-bot/bot.env`. `curl -s https://llm.int.exe.xyz/models.json` on the VM lists models and the APIs they speak. For GPT models, ask Shelley to switch `ask_claude` to the OpenAI API, which the integration also serves.

### Why not Railway or a VPS?

They run a Telegram bot fine, with the token in an environment variable. Here the token never reaches the server, the SQLite file sits on a disk that stays put, models need no key, and the VM's agent can change the bot when you ask.


## Related

- [Self-host Hermes Agent](https://exe.dev/deploy/hermes-agent.md): An agent that remembers you, on a computer that never sleeps.
- [SQLite in production](https://exe.dev/deploy/sqlite.md): One file on a real disk, streamed to your own bucket every second.
- [Give agents API access without giving them the keys](https://exe.dev/deploy/agent-secrets.md): Your agents call your APIs. The keys stay with exe.dev, outside the VM.
- [Deploy a FastAPI app](https://exe.dev/deploy/fastapi.md): Your API on a VM of its own. Push to deploy; the data stays put.
- [Run Claude Code on a remote server](https://exe.dev/deploy/claude-code.md): A computer for Claude. A breather for your laptop.
- [Host OpenClaw](https://exe.dev/deploy/openclaw.md): An AI sidekick with its own computer. Your laptop can take a nap.
