> For the complete documentation index, see [llms.txt](https://adatrack.gitbook.io/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://adatrack.gitbook.io/docs/documentation/features/chatbot.md).

# Chat Bot (Telegram & Slack)

The **AdaTrack Chat Bot** plugin brings bi-directional platform control to your team's existing chat tools. Query devices, view telemetry, receive alert notifications, and check system health — all without leaving Telegram or Slack.

### Key Capabilities

* **13 chat commands** — query devices, view readings, check alerts, browse travel logs, and manage account linking
* **Interactive notifications** — receive alert and geofence events with inline action buttons
* **Secure account linking** — OTP-based flow binds chat identities to AdaTrack user accounts
* **Per-user preferences** — quiet hours, severity filtering, event type toggles, daily digest
* **Two alert dispatchers** — `telegram_bot` and `slack_bot` channel types for the alerting engine
* **RBAC enforcement** — every command checks the linked user's permissions

***

### Prerequisites

Before enabling the Chat Bot plugin, ensure:

* **License:** Standard tier or above with the `plugin:chatbot` feature. Check with `adatrack-ctl license status`.
* **Plugin system enabled:** `PLUGINS_ENABLED=true` (default).
* **Encryption key configured:** Set `PLUGINS_ENCRYPTION_KEY` (64 hex characters) so bot tokens and signing secrets are encrypted at rest. Generate one with `openssl rand -hex 32`.
* **External URL:** Your AdaTrack instance must be reachable from the internet for Telegram and Slack to deliver webhook events. This can be a public IP, domain, or reverse proxy.

***

### Enabling the Plugin

#### From the Admin UI

1. Navigate to **Admin > Plugins**.
2. Find **Chat Bot** in the plugin list.
3. Click **Enable**.
4. Click **Configure** to enter your Telegram/Slack credentials (see sections below).

> **Note:** The **Setup** tab on the Chat Bot page (sidebar) is only visible to users with the **Admin** role. Regular users see the Accounts, Preferences, Log, and Preview tabs.

#### From the CLI

```bash
adatrack-ctl plugin enable chatbot

# Then configure
adatrack-ctl plugin config chatbot --set enable_telegram=true
adatrack-ctl plugin config chatbot --set telegram_bot_token=YOUR_TOKEN
adatrack-ctl plugin config chatbot --set external_base_url=https://your-domain.com
```

***

### Setting Up Telegram

#### Step 1: Create a Bot

1. Open Telegram and search for **@BotFather**.
2. Send `/newbot` and follow the prompts to choose a name and username.
3. Copy the **bot token** (e.g., `123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11`).

#### Step 2: Configure the Plugin

In **Admin > Plugins > Chat Bot > Configure**, set:

| Setting                     | Value                                                                                 |
| --------------------------- | ------------------------------------------------------------------------------------- |
| **Enable Telegram**         | `true`                                                                                |
| **Telegram Bot Token**      | Paste the token from BotFather                                                        |
| **Telegram Webhook Secret** | A random string for webhook verification (e.g., generate with `openssl rand -hex 16`) |
| **External Base URL**       | Your public-facing AdaTrack URL (e.g., `https://track.example.com`)                   |

#### Step 3: Webhook Registration

When the plugin starts, it automatically registers a webhook with Telegram at:

```
{external_base_url}/api/v1/public/plugins/chatbot/telegram/webhook
```

No manual webhook setup is required. Verify the connection by running a health check from **Admin > Plugins > Chat Bot > Health Check** or:

```bash
adatrack-ctl plugin health chatbot
```

#### Step 4: Test

Open a chat with your bot in Telegram and send `/help`. You should see the list of available commands.

***

### Setting Up Slack

#### Step 1: Create a Slack App

1. Go to [api.slack.com/apps](https://api.slack.com/apps) and click **Create New App > From scratch**.
2. Name the app (e.g., "AdaTrack Bot") and select your workspace.

#### Step 2: Configure Bot Scopes

Under **OAuth & Permissions > Bot Token Scopes**, add:

* `chat:write` — Send messages
* `commands` — Register slash commands
* `users:read` — Resolve user info

Install the app to your workspace and copy the **Bot User OAuth Token** (`xoxb-...`).

#### Step 3: Set Up Event Subscriptions

Under **Event Subscriptions**, enable events and set the Request URL to:

```
{external_base_url}/api/v1/public/plugins/chatbot/slack/events
```

Slack will send a verification challenge. The plugin responds automatically once configured.

#### Step 4: Set Up Slash Commands

Under **Slash Commands**, create a new command:

| Field                 | Value                                                              |
| --------------------- | ------------------------------------------------------------------ |
| **Command**           | `/adatrack`                                                        |
| **Request URL**       | `{external_base_url}/api/v1/public/plugins/chatbot/slack/commands` |
| **Short Description** | AdaTrack platform commands                                         |
| **Usage Hint**        | \`help                                                             |

#### Step 5: Set Up Interactivity

Under **Interactivity & Shortcuts**, enable interactivity and set the Request URL to:

```
{external_base_url}/api/v1/public/plugins/chatbot/slack/interactions
```

This enables inline action buttons on notifications (Acknowledge, Mute, View Device).

#### Step 6: Configure the Plugin

In **Admin > Plugins > Chat Bot > Configure**, set:

| Setting                  | Value                                               |
| ------------------------ | --------------------------------------------------- |
| **Enable Slack**         | `true`                                              |
| **Slack Bot Token**      | Paste the `xoxb-...` token                          |
| **Slack Signing Secret** | Found under **Basic Information > App Credentials** |
| **Slack App ID**         | Found under **Basic Information > App Credentials** |
| **External Base URL**    | Your public-facing AdaTrack URL                     |

#### Step 7: Test

In any Slack channel where the bot is invited, type `/adatrack help`. You should see the list of available commands.

***

### Self-Hosted Deployment Notes

Self-hosted deployments require the same Telegram/Slack setup as SaaS, with a few additional considerations:

#### External URL

Your `external_base_url` must be reachable from the public internet. Common approaches:

* **Direct public IP:** Set `external_base_url=http://<your-ip>:8080` (not recommended for production).
* **Domain with reverse proxy:** Point a domain to your server and use HTTPS. This is the recommended approach.

#### Nginx Configuration

If you use Nginx as a reverse proxy, ensure webhook paths are forwarded correctly:

```nginx
location /api/v1/plugins/chatbot/ {
    proxy_pass http://127.0.0.1:8080;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
}
```

#### Firewall

Allow inbound HTTPS (port 443) from Telegram and Slack IP ranges. Telegram publishes its webhook source IPs in the [Bot API documentation](https://core.telegram.org/bots/webhooks).

#### Docker Compose

If running via Docker Compose, the `external_base_url` should point to your host's public address, not the container's internal address:

```yaml
environment:
  - PLUGINS_ENABLED=true
  - PLUGINS_ENCRYPTION_KEY=your-64-hex-char-key
```

Configure the plugin via `adatrack-ctl` or the Admin UI after startup.

***

### Account Linking

The Chat Bot uses a secure OTP-based flow to link chat accounts to AdaTrack user accounts. This ensures that commands execute with the correct permissions and that notifications are routed to the right users.

#### Linking Flow

1. **In chat:** Send `/link` to the bot. The bot generates a 6-digit one-time code (valid for 10 minutes by default).
2. **In the web UI:** Navigate to the Chat Bot page (sidebar). The **Accounts** tab opens by default — enter the code in the **Link Account** section. The web UI verifies the code and creates the binding.
3. **Confirmation:** The bot sends a confirmation message in chat.

> **Default preferences:** When the link is created, a default notification profile is automatically set up for the new account (alerts enabled, geofence enabled, telemetry disabled, min severity: warning, daily digest disabled). You can adjust these at any time from the **Preferences** tab.

#### Managing Linked Accounts

* `/whoami` — Check which AdaTrack account is linked to your current chat identity.
* `/unlink` — Disconnect your chat account. You can re-link at any time.
* **Web UI:** The Chat Bot page shows all linked accounts with options to unlink.

You can link multiple chat accounts (e.g., both Telegram and Slack) to the same AdaTrack user.

***

### Available Commands

All commands are available in both Telegram and Slack. In Telegram, use `/command` directly. In Slack, prefix with `/adatrack` (e.g., `/adatrack devices`).

| Command                                             | Description                                                                   | Requires Link | Permission               |
| --------------------------------------------------- | ----------------------------------------------------------------------------- | ------------- | ------------------------ |
| `/help [command]`                                   | List all commands, or show details for a specific command                     | No            | —                        |
| `/link`                                             | Generate a 6-digit OTP code for account linking                               | No            | —                        |
| `/unlink`                                           | Disconnect your chat account from AdaTrack                                    | Yes           | —                        |
| `/whoami`                                           | Show your linked AdaTrack account info                                        | Yes           | —                        |
| `/devices [--profile X] [--status online\|offline]` | List your devices with optional filters                                       | Yes           | `chatbot.devices.read`   |
| `/device <id\|name>`                                | Show detailed info for a specific device                                      | Yes           | `chatbot.devices.read`   |
| `/telemetry <device> [--limit N] [--field X]`       | Show recent telemetry readings (default 10, max 20)                           | Yes           | `chatbot.telemetry.read` |
| `/latest <device>`                                  | Show the single most recent reading (compact format)                          | Yes           | `chatbot.telemetry.read` |
| `/alerts [--severity critical\|warning\|info]`      | List recent alert events                                                      | Yes           | `chatbot.alerts.read`    |
| `/status`                                           | Platform health summary (devices, online count, pending alerts)               | Yes           | `chatbot.system.status`  |
| `/trips`                                            | List the 10 most recent trips (device, start time, distance, duration)        | Yes           | `chatbot.travel.read`    |
| `/trip <id>`                                        | Full detail for a single trip (speed, stops, addresses)                       | Yes           | `chatbot.travel.read`    |
| `/tripstats`                                        | 30-day travel analytics summary (total trips, distance, hours, avg/max speed) | Yes           | `chatbot.travel.read`    |

***

### Notifications

When enabled, the Chat Bot forwards platform events to linked chat accounts as interactive messages.

#### Alert Notifications

When an alert rule fires, linked users receive a message containing:

* Severity indicator (Critical / Warning / Info)
* Alert rule name and triggered condition
* Device ID and name
* Inline action buttons: **Acknowledge**, **Mute 1h**, **Mute 24h**

#### Geofence Transition Notifications

When a device enters or exits a geofence, linked users receive:

* Transition type (Enter / Exit)
* Device and geofence identifiers

#### Telemetry Notifications

When new telemetry is received, users who opt in receive condensed reading summaries. Telemetry notifications are **deduplicated** — at most one notification per device per 5-minute window to prevent spam.

#### Trip Notifications

When the Travel Log plugin detects a trip event for a device owned by the linked user, two notifications can be sent:

* **Trip Started** — sent immediately when a new trip is detected. Includes the device name and a trip ID for use with `/trip`.
* **Trip Completed** — sent when the trip ends. Includes the final distance (km) and total duration (minutes).

Trip notifications are **opt-in** (`Notify Trips` defaults to `false`) to avoid noise for high-frequency fleets. Quiet hours apply.

***

### Notification Preferences

Each linked account has independent notification preferences, configurable from the **Chat Bot > Preferences** tab in the web UI.

| Setting              | Type           | Default   | Description                                                            |
| -------------------- | -------------- | --------- | ---------------------------------------------------------------------- |
| **Notify Alerts**    | boolean        | `true`    | Receive alert fired notifications                                      |
| **Notify Geofence**  | boolean        | `true`    | Receive geofence enter/exit notifications                              |
| **Notify Telemetry** | boolean        | `false`   | Receive new telemetry notifications (can be noisy)                     |
| **Notify Trips**     | boolean        | `false`   | Receive trip started and trip completed notifications                  |
| **Min Severity**     | enum           | `warning` | Only receive alerts at or above this severity                          |
| **Quiet Start**      | integer (hour) | —         | Start of quiet hours (UTC, 0–23). No notifications during this window. |
| **Quiet End**        | integer (hour) | —         | End of quiet hours (UTC, 0–23). Supports midnight wrap-around.         |
| **Daily Digest**     | boolean        | `false`   | Receive a daily summary of alerts and device status                    |

***

### Alert Dispatchers

The Chat Bot registers two new alert channel types that you can use when configuring alert rules:

* **`telegram_bot`** — Sends alert notifications via the Telegram bot to all linked Telegram accounts.
* **`slack_bot`** — Sends alert notifications via the Slack bot to all linked Slack accounts.

These coexist with the built-in Webhook, Email, and other dispatcher types. To use them:

1. Navigate to **Alerting > Rules** and create or edit an alert rule.
2. Under **Notification Channels**, add a channel of type `telegram_bot` or `slack_bot`.
3. Alerts that fire will be dispatched through the bot with interactive formatting.

> **Note:** Bot dispatchers send to all linked users who have `Notify Alerts` enabled and meet the severity threshold. For targeted notifications, use the existing webhook dispatchers.

***

### Configuration Reference

All settings are configured via **Admin > Plugins > Chat Bot > Configure** or `adatrack-ctl plugin config chatbot`.

| Setting                   | Type            | Default | Description                                                                |
| ------------------------- | --------------- | ------- | -------------------------------------------------------------------------- |
| `enable_telegram`         | boolean         | `false` | Enable the Telegram bot integration                                        |
| `telegram_bot_token`      | string (secret) | —       | Bot token from @BotFather                                                  |
| `telegram_webhook_secret` | string (secret) | —       | Random string for webhook signature verification                           |
| `enable_slack`            | boolean         | `false` | Enable the Slack bot integration                                           |
| `slack_bot_token`         | string (secret) | —       | Bot User OAuth Token (`xoxb-...`)                                          |
| `slack_signing_secret`    | string (secret) | —       | App signing secret from Slack app credentials                              |
| `slack_app_id`            | string          | —       | App ID from Slack app credentials                                          |
| `external_base_url`       | string          | —       | Public URL where AdaTrack is reachable (e.g., `https://track.example.com`) |
| `rate_limit_per_minute`   | integer         | `30`    | Maximum commands per user per minute                                       |
| `otp_expiry_minutes`      | integer         | `10`    | How long account linking codes remain valid                                |
| `daily_digest_hour_utc`   | integer         | `8`     | Hour (0–23 UTC) when daily digest messages are sent                        |

Secret fields (marked as "secret" above) are encrypted at rest and displayed as masked values in the admin UI.

***

### Permissions

The Chat Bot defines 11 RBAC permissions. Assign these to roles via **Admin > Roles** or `adatrack-ctl user role` commands.

| Permission                | Scope | Description                                   |
| ------------------------- | ----- | --------------------------------------------- |
| `chatbot.devices.read`    | Read  | Query devices and device details via chat     |
| `chatbot.telemetry.read`  | Read  | View telemetry readings via chat              |
| `chatbot.alerts.read`     | Read  | View alert events via chat                    |
| `chatbot.geofence.read`   | Read  | View geofence information via chat            |
| `chatbot.workflow.read`   | Read  | View workflow status via chat                 |
| `chatbot.system.status`   | Read  | View platform health summary                  |
| `chatbot.travel.read`     | Read  | View travel logs and trip statistics via chat |
| `chatbot.alerts.manage`   | Write | Acknowledge and mute alerts via chat          |
| `chatbot.workflow.manage` | Write | Trigger workflows via chat                    |
| `chatbot.report.generate` | Write | Request report generation via chat            |
| `chatbot.admin`           | Admin | Configure the Chat Bot plugin settings        |

***

### Troubleshooting

| Issue                                   | Cause                                                | Solution                                                                                                                                            |
| --------------------------------------- | ---------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| Bot does not respond to commands        | Webhook not registered or unreachable                | Run health check: `adatrack-ctl plugin health chatbot`. Verify `external_base_url` is publicly accessible. Check Nginx/firewall configuration.      |
| "Account not linked" error              | Chat account not linked to an AdaTrack user          | Send `/link` in chat and complete the OTP flow in the web UI.                                                                                       |
| "Permission denied" error               | Linked user lacks the required RBAC permission       | Ask an admin to assign the appropriate `chatbot.*` permissions to your role.                                                                        |
| "Rate limited" message                  | Too many commands in a short period                  | Wait 1 minute. Default limit is 30 commands/minute. Adjust `rate_limit_per_minute` in config if needed.                                             |
| "License required" when enabling        | Missing `plugin:chatbot` license feature             | Install a Standard or Enterprise license: `adatrack-ctl license install <key>`.                                                                     |
| Notifications not arriving              | User preferences disabled or quiet hours active      | Check the **Preferences** tab in the Chat Bot page. Verify quiet hours settings.                                                                    |
| Slack verification challenge fails      | Plugin not yet configured when Slack sends challenge | Configure the Slack tokens first, then set the Event Subscriptions URL in Slack.                                                                    |
| Telegram webhook returns 401            | Webhook secret mismatch                              | Verify `telegram_webhook_secret` matches the value used when the webhook was registered. Re-enable the plugin to re-register.                       |
| Bot stops responding after token change | Stale webhook pointing at the old token              | Clear the old token from the config, save, then enter the new token and re-enable the plugin. This forces re-registration with the new credentials. |
