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

# Rocket.Chat

> Deliver agent messages, alarms, and scheduled reports to a Rocket.Chat channel.

## Overview

OpenSRE's Rocket.Chat integration delivers agent-requested posts and scheduled reports to any channel your user or bot account can post to. Useful for teams running self-hosted or cloud Rocket.Chat workspaces.

Start the interactive shell with `opensre` (no subcommand). Slash commands below are run from that REPL.

<Note>
  Rocket.Chat support is **outbound delivery only**. Chatting with the agent from Rocket.Chat is not supported yet. There is no gateway inbound / `messaging pair` for Rocket.Chat.
</Note>

## Prerequisites

* A Rocket.Chat workspace (self-hosted or cloud) and its base URL, e.g. `https://chat.example.com`.
* An account allowed to post in the destination channel. A dedicated bot account is recommended so messages are not attributed to a personal user.
* The **Personal Access Tokens** feature enabled on the server (`Admin → Settings → Accounts → Personal Access Tokens`, on by default in most installs) — or admin access to create an **incoming webhook**.

## Setup

### Pick a mode

| Mode                                    | Credentials                             | Destination                                      | Best for                                               |
| --------------------------------------- | --------------------------------------- | ------------------------------------------------ | ------------------------------------------------------ |
| **Personal Access Token** (recommended) | `server_url` + `auth_token` + `user_id` | Any channel, chosen per message                  | Dynamic channel targeting, verifiable via `/api/v1/me` |
| **Incoming webhook**                    | single `webhook_url`                    | Fixed channel chosen when the webhook is created | Simplest setup; no bot account needed                  |

You can configure both — when both are present, delivery prefers the webhook. Incomplete token trio fails verify.

### Option 1: CLI setup (recommended)

```bash theme={null}
opensre integrations setup rocketchat
```

Interactive shell: `/integrations setup rocketchat`. Choose **token**, **webhook**, or **both**. The setup prompts for:

* Token mode: **Server URL** (`ROCKETCHAT_SERVER_URL`), **personal access token** (`ROCKETCHAT_AUTH_TOKEN` in `.env` and `~/.opensre/credentials.json`), **user ID** (`ROCKETCHAT_USER_ID`), and **default channel** (`ROCKETCHAT_DEFAULT_CHANNEL`)
* Webhook mode: **webhook URL** — saved to the integration store (`~/.opensre/integrations.json`) and/or `ROCKETCHAT_WEBHOOK_URL` in `.env`; never written to the keyring (`*_URL` is non-keyring config). The URL often embeds a token — treat the whole URL like a password.

Credentials are also saved via `upsert_integration("rocketchat", ...)`.

### Option 2: Environment variables

```bash theme={null}
# Token mode
ROCKETCHAT_SERVER_URL=https://chat.example.com
ROCKETCHAT_AUTH_TOKEN=<personal-access-token>
ROCKETCHAT_USER_ID=<user-id>
ROCKETCHAT_DEFAULT_CHANNEL=#incidents

# Webhook mode (either mode alone is enough; both may be set)
ROCKETCHAT_WEBHOOK_URL=https://chat.example.com/hooks/<id>/<token>
```

| Variable                     | Description                                                                                                                         |
| ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `ROCKETCHAT_SERVER_URL`      | Base URL of your Rocket.Chat server. Required for token mode.                                                                       |
| `ROCKETCHAT_AUTH_TOKEN`      | Personal access token. Required for token mode. Resolved via env then keyring.                                                      |
| `ROCKETCHAT_USER_ID`         | User ID shown alongside the token. Required for token mode.                                                                         |
| `ROCKETCHAT_DEFAULT_CHANNEL` | Default delivery destination (`#channel` or `@user`). Required for token-mode delivery.                                             |
| `ROCKETCHAT_WEBHOOK_URL`     | Incoming webhook URL. Store/env only — never keyring. Enables webhook mode on its own; preferred over token mode when both are set. |

<Note>
  **Credential resolution.** Token mode: store → `resolve_env_credential("ROCKETCHAT_AUTH_TOKEN")` (env then keyring). Webhook mode: store → plain `ROCKETCHAT_WEBHOOK_URL` env — never keyring. Server URL, user id, and default channel stay plain env / store.
</Note>

## Credentials

### Token mode: Create a Personal Access Token

1. Sign in to Rocket.Chat with the account that should post messages.
2. Open **My Account → Personal Access Tokens** (avatar menu → **My Account**).
3. Enter a token name (e.g. `opensre`) and select **Add**. Leave *Ignore Two Factor Authentication* checked unless your policy requires otherwise.
4. Rocket.Chat shows the **token** and your **user ID** once. Copy both — the token is your `auth_token` and the ID is your `user_id`. Treat the token like a password.

<Tip>
  If you missed the user ID, it is also shown when you regenerate the token, or under `Admin → Users` for admins.
</Tip>

### Token mode: Pick a destination channel

Messages are posted with the standard `chat.postMessage` REST endpoint:

| Destination              | Format          | Example      |
| ------------------------ | --------------- | ------------ |
| Public/private channel   | `#channel-name` | `#incidents` |
| Direct message to a user | `@username`     | `@marcos`    |

Make sure the token's account is a member of the channel (or has permission to post there).

### Webhook mode: Create an incoming webhook

1. As an admin, open **Administration → Workspace → Integrations → New → Incoming**.
2. Enable the integration, set a name (e.g. `opensre`), pick the destination **channel**, and choose the user the messages post as.
3. Select **Save**. Rocket.Chat shows the **Webhook URL** (`https://<server>/hooks/<id>/<token>`). Copy it — treat the whole URL like a password.

### Quick local test with Docker (token mode)

Requires `--platform linux/amd64` on Apple Silicon (no arm64 image) and **MongoDB 7.0**, not 8.0 — 8.0 refuses to start under Docker Desktop's Linux VM ("kernel versions 6.19 and newer has a known incompatibility").

```bash theme={null}
docker network create rc-net

docker run -d --name rc-mongo --network rc-net --platform linux/amd64 \
  mongo:7.0 --replSet rs0 --bind_ip_all
i=0
until docker exec rc-mongo mongosh --quiet --eval "db.runCommand('ping')" > /dev/null 2>&1; do
  i=$((i + 1))
  [ "$i" -ge 30 ] && { echo "ERROR: MongoDB never became ready" >&2; exit 1; }
  sleep 2
done
docker exec rc-mongo mongosh --eval "rs.initiate()"

docker run -d --name rc-dev --network rc-net --platform linux/amd64 -p 127.0.0.1:3201:3000 \
  -e 'MONGO_URL=mongodb://rc-mongo:27017/rocketchat?replicaSet=rs0' \
  -e 'MONGO_OPLOG_URL=mongodb://rc-mongo:27017/local?replicaSet=rs0' \
  -e 'ROOT_URL=http://localhost:3201' \
  -e 'ADMIN_USERNAME=verifyadmin' \
  -e 'ADMIN_PASS=verify-admin-pass' \
  -e 'ADMIN_EMAIL=verifyadmin@example.com' \
  -e 'OVERWRITE_SETTING_Show_Setup_Wizard=completed' \
  -e 'OVERWRITE_SETTING_Accounts_TwoFactorAuthentication_Enabled=false' \
  rocket.chat:8.5.1
```

The `OVERWRITE_SETTING_Show_Setup_Wizard=completed` and `ADMIN_*` variables skip the manual setup wizard. The 2FA override lets this disposable instance generate a PAT without a database change or restart.

```bash theme={null}
i=0
until curl -sf -o /dev/null http://localhost:3201/api/info; do
  i=$((i + 1))
  [ "$i" -ge 40 ] && { echo "ERROR: Rocket.Chat never became ready" >&2; exit 1; }
  sleep 10
done
```

Log in and generate a PAT via the API. The password stays out of curl's own argv (piped via stdin, not `-d "password=..."`), and the token is captured into a variable rather than printed:

```bash theme={null}
RC_LOGIN=$(printf 'user=verifyadmin&password=verify-admin-pass' | curl -s -X POST http://localhost:3201/api/v1/login --data-binary @-)
RC_AUTH_TOKEN=$(echo "$RC_LOGIN" | python3 -c "import json,sys;print(json.load(sys.stdin)['data']['authToken'])")
RC_USER_ID=$(echo "$RC_LOGIN" | python3 -c "import json,sys;print(json.load(sys.stdin)['data']['userId'])")
unset RC_LOGIN

RC_PAT=$(printf 'tokenName=opensre-verify' | curl -s -X POST http://localhost:3201/api/v1/users.generatePersonalAccessToken \
  -H "X-Auth-Token: $RC_AUTH_TOKEN" -H "X-User-Id: $RC_USER_ID" --data-binary @- \
  | python3 -c "import json,sys;print(json.load(sys.stdin)['token'])")
```

```bash theme={null}
export ROCKETCHAT_SERVER_URL="http://localhost:3201"
export ROCKETCHAT_AUTH_TOKEN="$RC_PAT"
export ROCKETCHAT_USER_ID="$RC_USER_ID"
export ROCKETCHAT_DEFAULT_CHANNEL="#general"
unset RC_PAT RC_AUTH_TOKEN RC_USER_ID
```

Verify:

```bash theme={null}
opensre integrations verify rocketchat
```

```
SERVICE    │ SOURCE    │ STATUS   │ DETAIL
rocketchat │ local env │ ✓ passed │ Connected to Rocket.Chat as @verifyadmin.
```

Teardown:

```bash theme={null}
docker rm -f rc-dev rc-mongo && docker network rm rc-net
unset ROCKETCHAT_SERVER_URL ROCKETCHAT_AUTH_TOKEN
unset ROCKETCHAT_USER_ID ROCKETCHAT_DEFAULT_CHANNEL
```

## Rocket.Chat tools

| Tool                      | What it does                                                   |
| ------------------------- | -------------------------------------------------------------- |
| `rocketchat_send_message` | Send a message to the default channel or an explicit `channel` |

```json theme={null}
{
  "name": "rocketchat_send_message",
  "arguments": {
    "channel": "#incidents",
    "message": "DB CPU is back below 70%; keeping the incident open for 10 minutes."
  }
}
```

The tool resolves credentials internally from the integration store, then the same env/keyring rules as setup (PAT via `resolve_env_credential`; webhook URL via plain env) — the agent never sees them. In token mode an explicit `channel` (or the configured `default_channel`) is targeted via `chat.postMessage`; in webhook-only mode messages go to the webhook's fixed destination, and an explicit `channel` returns a configuration error instead of being silently ignored.

Delivery is an external side effect but does not require a separate approval. The result includes a stable `status`, `sent`, `error_type`, `channel`, and `message_length` shape so follow-up tool calls can tell configuration failures from Rocket.Chat delivery failures.

### Scheduled deliveries (cron)

```bash theme={null}
opensre cron add --kind github_pr_sweep --cron "0 9 * * mon-fri" \
  --tz America/Sao_Paulo --provider rocketchat --chat-id "#ops"
```

`--chat-id` is the Rocket.Chat destination (`#channel` or `@user`). Scheduled deliveries always target that explicit destination, so they require **token credentials** — an incoming webhook's destination is fixed at creation time and cannot honor `--chat-id`. See [Cron](/docs/platform/cron).

## Verify

```bash theme={null}
opensre integrations verify rocketchat
```

Interactive shell: `/integrations verify rocketchat` or `/verify rocketchat`.

With token credentials configured, this calls Rocket.Chat's [`/api/v1/me`](https://developer.rocket.chat/apidocs/get-user-information) endpoint and reports the authenticated `@username`. With webhook-only configuration, it runs a **non-posting reachability probe** against the webhook URL (a 404 means the URL or its embedded token is wrong; no message is delivered by the probe).

Long messages are truncated to 4,096 characters.

## Troubleshooting

`/integrations verify rocketchat` only calls `/api/v1/me` (or the webhook reachability probe), so it surfaces credential errors but cannot detect channel-routing problems. Delivery-time errors only show up when a message actually posts; they appear in OpenSRE logs as `[rocketchat] post message failed: <error>`.

| Symptom                                                                     | Fix                                                                                                                                                                                                  |
| --------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **`Rocket.Chat auth failed: auth_token or user_id is invalid or expired.`** | Regenerate the token under **My Account → Personal Access Tokens** and update both values.                                                                                                           |
| **`error-room-not-found` (delivery-time)**                                  | Check `ROCKETCHAT_DEFAULT_CHANNEL` spelling (including `#`) and membership.                                                                                                                          |
| **`Rocket.Chat API check failed: <connection error>`**                      | Confirm `ROCKETCHAT_SERVER_URL` includes the scheme and is reachable.                                                                                                                                |
| **`Rocket.Chat webhook returned 404`**                                      | Re-copy the full enabled webhook URL from **Administration → Integrations**.                                                                                                                         |
| **Messages never arrive, but verify passes**                                | In token mode, confirm `ROCKETCHAT_DEFAULT_CHANNEL` is set — without it (and without a webhook), delivery is silently skipped. In webhook mode, confirm the webhook posts to the channel you expect. |

## Security

* Prefer a dedicated bot account and Personal Access Token for OpenSRE.
* Treat PAT and webhook URLs like passwords; webhook URLs are never stored in the keyring.
* Store secrets in the integration store / keyring / secret manager — not in source control.
