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

# Telegram Bots

> Connect your Telegram bot to Shoppex for notifications, broadcasts, and AI-powered customer support

## Quick Start

Connect your Telegram bot and send your first notification in under 5 minutes.

<Steps>
  <Step title="Create a bot with BotFather">
    Open [@BotFather](https://t.me/BotFather) in Telegram, run `/newbot`, and copy the bot token.
  </Step>

  <Step title="Connect it to Shoppex">
    ```bash theme={"system"}
    curl -X POST https://api.shoppex.io/dev/v1/telegram/bots \
      -H "Authorization: Bearer YOUR_DEV_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{"bot_token": "123456:AAExampleToken"}'
    ```
  </Step>

  <Step title="Share your deep link">
    The response includes a `deep_link_url` — share it with customers so they can opt in to notifications via Telegram.
  </Step>

  <Step title="Send a broadcast">
    Once customers have connected, you can send broadcasts, set up automated journeys, or enable the AI agent.
  </Step>
</Steps>

That's it — your bot is live. The rest of this guide covers everything you can build on top of it.

***

## What You Can Do

Once your bot is connected, Shoppex gives you:

* **Automatic notifications** — order confirmations, restock alerts, and promotional messages that respect each customer's preferences
* **Broadcasts** — scheduled or immediate messages to segmented audiences, with click tracking and revenue attribution
* **Journeys** — event-driven follow-up automation (post-purchase, abandoned cart, renewal reminders)
* **Two-way inbox** — customers can reply, and merchants can respond from the API or dashboard
* **AI agent** — route inbound messages to an AI that can search products, look up orders, and create coupons

***

## Bot Response Shape

When you connect a bot, Shoppex returns a grouped resource:

```json theme={"system"}
{
  "data": {
    "id": "9d40c284-4f39-4d2e-a9d5-56ea2e7d5bc7",
    "shop_id": "3c649ff2-0a87-42de-897a-c07fc2f9a79d",
    "identity": {
      "telegram_bot_id": "123456789",
      "username": "shoppex_demo_bot",
      "display_name": "Shoppex Demo Bot"
    },
    "verification": {
      "status": "VERIFIED",
      "last_verified_at": "2026-04-06T11:20:00.000Z",
      "last_error": null
    },
    "connection": {
      "webhook_url": "https://api.shoppex.io/telegram-webhook-url",
      "deep_link_url": "https://t.me/shoppex_demo_bot?start=shop:3c649ff2-0a87-42de-897a-c07fc2f9a79d",
      "merchant_deep_link_url": "https://t.me/shoppex_demo_bot?start=shop%3A3c649ff2-0a87-42de-897a-c07fc2f9a79d%2Cmanager%3Ausr_123%2Csig%3Aabc123"
    },
    "agent": {
      "enabled": false,
      "mode": "CUSTOMER_SALES",
      "has_api_key": false,
      "api_key_generated_at": null,
      "last_routed_at": null
    }
  }
}
```

***

## Customer Linking

Customers connect to your shop through the bot deep link:

```text theme={"system"}
https://t.me/<bot_username>?start=shop:<shop_id>
```

You can add context to the deep link for richer linking:

| Link format                                               | Use case                                          |
| --------------------------------------------------------- | ------------------------------------------------- |
| `?start=shop:<shop_id>`                                   | Basic opt-in                                      |
| `?start=shop:<shop_id>,customer:<customer_id>`            | Link to existing customer for order confirmations |
| `?start=shop:<shop_id>,email:<urlencoded_email>`          | Link guest checkouts by email                     |
| `?start=shop:<shop_id>,manager:<user_id>,sig:<signature>` | Merchant assistant mode (signed)                  |

The merchant deep link is pre-built in the bot response under `connection.merchant_deep_link_url` — it binds the Telegram chat to a Shoppex manager so merchant-only agent flows route safely.

Once linked, list users with:

```bash theme={"system"}
curl "https://api.shoppex.io/dev/v1/telegram/bots/BOT_ID/users?is_active=true&limit=25" \
  -H "Authorization: Bearer YOUR_DEV_API_KEY"
```

***

## Automatic Notifications

Before you touch broadcasts or journeys, Shoppex already sends Telegram messages automatically when:

* An order is confirmed
* A product comes back in stock
* You create promotional broadcasts for opted-in users

These messages respect each user's notification preferences. This is the default behavior — most shops start here and add broadcasts or journeys later.

***

## Notification Preferences

Each user has a `notification_preferences` object that controls what they receive.

Update a single user:

```bash theme={"system"}
curl -X PUT https://api.shoppex.io/dev/v1/telegram/bots/BOT_ID/users/USER_ID/notifications \
  -H "Authorization: Bearer YOUR_DEV_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "notification_preferences": {
      "enabled_types": ["ORDER_CONFIRMATION", "PRODUCT_RESTOCK"]
    }
  }'
```

Bulk update multiple users:

```bash theme={"system"}
curl -X PUT https://api.shoppex.io/dev/v1/telegram/bots/BOT_ID/users/bulk/notifications \
  -H "Authorization: Bearer YOUR_DEV_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "user_ids": [
      "11111111-1111-4111-8111-111111111111",
      "22222222-2222-4222-8222-222222222222"
    ],
    "notification_preferences": {
      "enabled_types": ["PROMOTIONAL_OFFERS"]
    }
  }'
```

***

## Broadcasts

Broadcasts let you send messages to a filtered audience — immediately or scheduled.

A broadcast request has three parts:

| Group      | What it controls                                                           |
| ---------- | -------------------------------------------------------------------------- |
| `content`  | The Telegram message, parse mode, and inline keyboard buttons              |
| `audience` | Who receives it — filter by notification type, activity, or saved segments |
| `delivery` | When to send and at what rate (up to 30 messages/second)                   |

```bash theme={"system"}
curl -X POST https://api.shoppex.io/dev/v1/telegram/bots/BOT_ID/broadcasts \
  -H "Authorization: Bearer YOUR_DEV_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "content": {
      "body": "<b>Restock alert</b>\nYour item is back in stock.",
      "parse_mode": "HTML",
      "inline_keyboard": [
        [{"text": "Open product", "url": "https://demo.myshoppex.io/product/prod_123"}]
      ]
    },
    "audience": {
      "notification_types": ["PRODUCT_RESTOCK"],
      "only_active_users": true,
      "last_activity_after": "2026-04-01T00:00:00.000Z"
    },
    "delivery": {
      "scheduled_for": "2026-04-07T09:00:00.000Z",
      "messages_per_second": 15
    }
  }'
```

<Note>
  URL buttons are automatically wrapped in Shoppex tracking links, so you get click-through rates and revenue attribution for free.
</Note>

Broadcasts move through these states: `DRAFT → SCHEDULED → SENDING → COMPLETED / CANCELLED / FAILED`

### Warehouse Restock Broadcasts

For product-specific restocks, use the dedicated endpoint — Shoppex generates the message around the product data:

```bash theme={"system"}
curl -X POST https://api.shoppex.io/dev/v1/telegram/bots/BOT_ID/broadcasts/warehouse-restock \
  -H "Authorization: Bearer YOUR_DEV_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "product_id": "33333333-3333-4333-8333-333333333333",
    "variant_id": "44444444-4444-4444-8444-444444444444",
    "content": {"body": "Back in stock now", "parse_mode": "HTML"},
    "audience": {"only_active_users": true},
    "delivery": {"messages_per_second": 10}
  }'
```

***

## Saved Segments

When you find yourself targeting the same audience across multiple broadcasts, save it as a segment:

```bash theme={"system"}
curl -X POST https://api.shoppex.io/dev/v1/telegram/bots/BOT_ID/segments \
  -H "Authorization: Bearer YOUR_DEV_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Active buyers",
    "description": "Customers active in the last 30 days",
    "filters": {
      "only_active_users": true,
      "linked_only": true,
      "notification_types": ["ORDER_CONFIRMATION"]
    }
  }'
```

Then reference it in any broadcast:

```json theme={"system"}
{
  "audience": {
    "segment_ids": ["11111111-1111-4111-8111-111111111111"]
  }
}
```

Manage segments with `GET`, `PUT`, and `DELETE` on `/dev/v1/telegram/bots/:botId/segments/:segmentId`.

***

## Analytics and Click Tracking

Shoppex tracks URL button clicks per broadcast and attributes completed orders back to the broadcast that drove them.

```bash theme={"system"}
curl https://api.shoppex.io/dev/v1/telegram/bots/BOT_ID/broadcasts/BROADCAST_ID/analytics \
  -H "Authorization: Bearer YOUR_DEV_API_KEY"
```

```json theme={"system"}
{
  "data": {
    "overview": {
      "delivered_count": 1200,
      "failed_count": 13,
      "unique_clicked_users": 340,
      "click_count": 412,
      "click_through_rate": 28.33,
      "attributed_orders": 14,
      "attributed_revenue": 1940
    },
    "buttons": [
      {
        "button_id": "primary_cta",
        "text": "Open product",
        "destination_url": "https://demo.myshoppex.io/product/prod_123",
        "unique_clicked_users": 250,
        "click_count": 301
      }
    ]
  }
}
```

The attribution flow: you send a broadcast with a product button → Shoppex rewrites the URL to a tracking link → customer clicks → Shoppex records the click and redirects to the product page → if the customer completes an order within the attribution window, the revenue counts back to that broadcast.

***

## Journeys

Journeys are event-driven follow-up flows — think "post-purchase drip" or "abandoned cart reminder" without sending each message manually.

### Supported Triggers

| Trigger                | When it fires                                           |
| ---------------------- | ------------------------------------------------------- |
| `ORDER_COMPLETED`      | After a successful order                                |
| `ABANDONED_CART`       | When a customer starts checkout but doesn't complete it |
| `PAYMENT_REMINDER`     | Before a payment deadline                               |
| `SUBSCRIPTION_RENEWAL` | Before a subscription renews                            |
| `MANUAL`               | Triggered by your API call                              |

### Example: Post-Purchase Follow-Up

```bash theme={"system"}
curl -X POST https://api.shoppex.io/dev/v1/telegram/bots/BOT_ID/journeys \
  -H "Authorization: Bearer YOUR_DEV_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Post-purchase follow-up",
    "trigger": "ORDER_COMPLETED",
    "filters": {"only_active_users": true},
    "steps": [
      {
        "delay_minutes": 0,
        "content": {"body": "Thanks for your order.", "parse_mode": "HTML"}
      },
      {
        "delay_minutes": 1440,
        "content": {"body": "Need help with your order?", "parse_mode": "NONE"}
      }
    ]
  }'
```

The journey fires when a customer completes an order, sends the first message immediately, and queues the follow-up for 24 hours later. Test journeys before going live with `POST /dev/v1/telegram/bots/:botId/journeys/:journeyId/test`.

***

## Preference Center and Inbox

The bot doubles as a two-way support channel.

**Customer commands:**

| Command     | What it does                         |
| ----------- | ------------------------------------ |
| `/settings` | Opens notification preference center |
| `/track`    | Track an order                       |
| `/buyagain` | Quick reorder from last purchase     |
| `/help`     | Opens support flow                   |

**Merchant inbox endpoints:**

* `GET /dev/v1/telegram/bots/:botId/inbox` — list conversations
* `GET /dev/v1/telegram/bots/:botId/inbox/:conversationId` — read a conversation
* `POST /dev/v1/telegram/bots/:botId/inbox/:conversationId/reply` — send a reply
* `PUT /dev/v1/telegram/bots/:botId/inbox/:conversationId/status` — close or reopen

```bash theme={"system"}
curl -X POST https://api.shoppex.io/dev/v1/telegram/bots/BOT_ID/inbox/CONVERSATION_ID/reply \
  -H "Authorization: Bearer YOUR_DEV_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"message": "We are checking your order now.", "parse_mode": "HTML"}'
```

***

## AI Agent

The AI agent routes inbound Telegram messages through Shoppex's commerce tools — product search, order lookup, coupon creation, payment links, and more.

### Agent Modes

| Mode                 | Who it serves                    | What it can do                                                       |
| -------------------- | -------------------------------- | -------------------------------------------------------------------- |
| `CUSTOMER_SALES`     | Customers                        | Search products, look up orders, share payment links                 |
| `MERCHANT_ASSISTANT` | Merchants (via signed deep link) | Create coupons, check revenue, manage products                       |
| `BOTH`               | Both on the same bot             | Routes based on whether the chat is linked to a customer or merchant |

### Enable the Agent

```bash theme={"system"}
curl -X PUT https://api.shoppex.io/dev/v1/telegram/bots/BOT_ID/agent \
  -H "Authorization: Bearer YOUR_DEV_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"agent_enabled": true, "agent_mode": "BOTH"}'
```

When enabled, Shoppex provisions a shop-scoped Dev API key for the bot, stores inbound messages as inbox history, routes them to the AI model, and sends the response back to Telegram.

### Usage Stats

```bash theme={"system"}
curl https://api.shoppex.io/dev/v1/telegram/bots/BOT_ID/agent/stats \
  -H "Authorization: Bearer YOUR_DEV_API_KEY"
```

```json theme={"system"}
{
  "data": {
    "calls": 28,
    "completed_calls": 24,
    "failed_calls": 2,
    "rate_limited_calls": 2,
    "conversations": 11,
    "total_tokens": 18420,
    "estimated_cost_usd": 0.31,
    "average_response_time_ms": 1820,
    "last_run_at": "2026-04-07T16:40:00.000Z"
  }
}
```

A customer asking "Do you have the hoodie in black?" gets a product search and direct answer. A merchant saying "Create a 15% coupon for the hoodie" gets a coupon created through the Dev API. The `estimated_cost_usd` field tracks AI token costs so there are no surprises on your bill.

***

## Lifecycle and Monitoring

Track broadcast delivery with:

* `GET /dev/v1/telegram/bots/:botId/broadcasts` — list all
* `GET /dev/v1/telegram/bots/:botId/broadcasts/:id` — single broadcast
* `GET /dev/v1/telegram/bots/:botId/broadcasts/:id/stats` — delivery progress
* `GET /dev/v1/telegram/bots/:botId/analytics` — bot-level analytics

The broadcast response groups delivery progress under `delivery`: `sent_count`, `failed_count`, `progress_percentage`, `estimated_time_remaining_seconds`, and `failure_reasons`.

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Developer API Quickstart" icon="code" href="/api-reference/quickstart">
    Set up your API key and make your first call
  </Card>

  <Card title="Authentication" icon="key" href="/api-reference/authentication">
    Scopes, API keys, and OAuth2 for Telegram integrations
  </Card>

  <Card title="Webhooks Guide" icon="webhook" href="/guides/webhooks">
    Listen for order events that trigger Telegram journeys
  </Card>

  <Card title="Payments Guide" icon="credit-card" href="/guides/payments">
    Create payment links that your bot can share
  </Card>
</CardGroup>
