> ## Documentation Index
> Fetch the complete documentation index at: https://docs.upsonic.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Telegram

> Host agents as Telegram bots with webhooks, multi-media, and chat or task modes

Use the Telegram interface to serve Agents as Telegram bots. It supports text, photos, documents, voice, video, stickers, location, polls, and inline keyboard callbacks.

## Prerequisites

Create a virtual environment and install the required dependencies:

```bash theme={null}
uv venv
source .venv/bin/activate

uv pip install upsonic fastapi uvicorn
# pip install upsonic fastapi uvicorn
```

## Step 1: Create a Telegram Bot

1. Open Telegram and search for [@BotFather](https://t.me/BotFather)
2. Send `/newbot` and follow the prompts to choose a name and username
3. Copy the **Bot API Token** you receive — you'll need it in the next step

## Step 2: Set Up the Webhook with ngrok

Telegram delivers messages to your bot via **webhooks** — it sends HTTPS requests to a **public URL** you provide. Your local `localhost:8000` is not accessible from the internet, so you need a tunnel. We'll use [ngrok](https://ngrok.com/) for this.

<Steps>
  <Step title="Create an ngrok account">
    Go to [ngrok.com/signup](https://dashboard.ngrok.com/signup) and create a free account.
  </Step>

  <Step title="Install ngrok">
    After signing up, follow the instructions on your [ngrok dashboard](https://dashboard.ngrok.com/get-started/setup) to install ngrok for your operating system.

    <CodeGroup>
      ```bash macOS theme={null}
      brew install ngrok
      ```

      ```bash Linux theme={null}
      snap install ngrok
      ```

      ```bash Windows theme={null}
      choco install ngrok
      ```
    </CodeGroup>
  </Step>

  <Step title="Connect your account">
    Copy your authtoken from the [ngrok dashboard](https://dashboard.ngrok.com/get-started/your-authtoken) and run:

    ```bash theme={null}
    ngrok config add-authtoken YOUR_AUTH_TOKEN
    ```
  </Step>

  <Step title="Start the tunnel">
    Open a terminal and run:

    ```bash theme={null}
    ngrok http 8000
    ```

    You'll see output like this:

    ```
    Forwarding  https://abc123.ngrok-free.app -> http://localhost:8000
    ```

    Copy the `https://....ngrok-free.app` URL — this is your public webhook URL.
  </Step>
</Steps>

<Warning>
  Keep this terminal open — if you close ngrok, the tunnel stops and your bot won't receive messages. When you restart ngrok, the URL changes and you'll need to update your `.env` file.
</Warning>

## Step 3: Configure Environment Variables

Create a `.env` file with your credentials:

```bash theme={null}
TELEGRAM_BOT_TOKEN=your-bot-token-from-botfather
TELEGRAM_WEBHOOK_URL=https://abc123.ngrok-free.app
```

<Tip>
  `TELEGRAM_WEBHOOK_URL` is the ngrok URL you copied. When you restart ngrok, this URL changes — update it accordingly.
</Tip>

You can also set an optional secret for webhook validation:

```bash theme={null}
TELEGRAM_WEBHOOK_SECRET=my-secret-token
```

## Step 4: Write Your Bot

There are two operating modes — pick the one that fits your use case:

* **CHAT** — The agent remembers conversation context per user. Best for conversational assistants.
* **TASK** — Each message is processed independently with no history. Best for one-off queries.

<CodeGroup>
  ```python CHAT Mode (Default) theme={null}
  import os
  from upsonic import Agent
  from upsonic.interfaces import InterfaceManager, TelegramInterface, InterfaceMode

  agent = Agent(
      model="anthropic/claude-sonnet-4-6",
      name="TelegramChatBot",
      system_prompt="You are a friendly AI assistant on Telegram. You remember conversation context.",
  )

  telegram = TelegramInterface(
      agent=agent,
      bot_token=os.getenv("TELEGRAM_BOT_TOKEN"),
      webhook_url=os.getenv("TELEGRAM_WEBHOOK_URL"),
      webhook_secret=os.getenv("TELEGRAM_WEBHOOK_SECRET"),
      mode=InterfaceMode.CHAT,
      reset_command="/reset",
  )

  manager = InterfaceManager(interfaces=[telegram])
  manager.serve(host="0.0.0.0", port=8000)
  ```

  ```python TASK Mode theme={null}
  import os
  from upsonic import Agent
  from upsonic.interfaces import InterfaceManager, TelegramInterface, InterfaceMode

  agent = Agent(
      model="anthropic/claude-sonnet-4-6",
      name="TelegramBot",
      system_prompt="You are a helpful AI assistant on Telegram. Be concise.",
  )

  telegram = TelegramInterface(
      agent=agent,
      bot_token=os.getenv("TELEGRAM_BOT_TOKEN"),
      webhook_url=os.getenv("TELEGRAM_WEBHOOK_URL"),
      webhook_secret=os.getenv("TELEGRAM_WEBHOOK_SECRET"),
      mode=InterfaceMode.TASK,
  )

  manager = InterfaceManager(interfaces=[telegram])
  manager.serve(host="0.0.0.0", port=8000)
  ```
</CodeGroup>

## Step 5: Run

Make sure ngrok is running in one terminal, then start your bot in another:

```bash theme={null}
uv run your_bot.py
# python your_bot.py
```

Your bot is now live. Open Telegram, find your bot by username, and send a message.

## Operating Modes

| Mode               | Description                                                               | Best For                                |
| ------------------ | ------------------------------------------------------------------------- | --------------------------------------- |
| **TASK** (default) | Each message is processed independently. No conversation history.         | One-off queries, stateless bots         |
| **CHAT**           | Messages from the same user share a session. The agent remembers context. | Conversational assistants, support bots |

### Reset Command (CHAT mode only)

In CHAT mode, users can clear their conversation by sending `/reset`. Configure it with `reset_command`; set to `None` to disable.

If the agent has a `workspace` configured, the reset command will also trigger a dynamic greeting message based on the workspace configuration.

## Access Control

Restrict your bot to specific users by passing a list of Telegram user IDs:

```python theme={null}
telegram = TelegramInterface(
    agent=agent,
    bot_token=os.getenv("TELEGRAM_BOT_TOKEN"),
    webhook_url=os.getenv("TELEGRAM_WEBHOOK_URL"),
    mode=InterfaceMode.CHAT,
    allowed_user_ids=[1279809673],
)
```

Users not in the list are ignored. Omit `allowed_user_ids` (or set `None`) to allow everyone.

## Supported File & Message Types

Users can send **any file type** through Telegram — images, PDFs, Excel spreadsheets, Word documents, CSVs, and more. The bot receives and forwards all of them to your agent.

* **Images** (PNG, JPG, etc.) – The agent can process these directly via its vision capabilities
* **PDFs, Excel, Word, CSV, and other documents** – The agent receives the file. If you equip your agent with the right tools (e.g. a PDF reader tool or an Excel parser), it can read and analyze the contents
* **Voice / Audio** – Downloaded and processed (e.g. transcription)
* **Video / Video note** – Downloaded and processed with caption
* **Text** – Processed as task or chat input
* **Sticker** – Converted to text (e.g. "User sent a sticker: {emoji}")
* **Location / Venue / Contact / Poll** – Converted to text and processed
* **Callback query** – Inline keyboard button data processed as text

<Tip>
  Your agent can already handle images natively. For other file types like PDF or Excel, add a custom tool to your agent so it can read and process them. See [Creating function tools](/concepts/tools/function-class-tools/creating-function-tool) for how to create one.
</Tip>
