# Telegram alerts in SyncTide — admin setup

This is the **administrator** guide for wiring SyncTide alarm notifications
through a Telegram bot. End users (operators who only need to *receive*
alarms) follow a much shorter guide — see **TELEGRAM_FOR_RECIPIENTS.md**.

Telegram is the cheapest "phone alert" path SyncTide supports. It's free,
has no per-message cost, no SIM card requirement, and works on any phone
with the Telegram app installed.

---

## What you'll end up with

- A Telegram **bot** (the sender) registered under your organisation.
- A SyncTide messaging gateway pointing at the bot's API token.
- One contact entry in SyncTide per recipient, holding the recipient's
  numeric chat ID.
- Alarm rules wired to those contacts (or to escalation lists containing
  those contacts).

---

## Step 1 — create the SyncTide bot (one-time per organisation)

1. Install Telegram on any phone, sign up.
2. In Telegram, search for **`@BotFather`** and open the chat.
3. Send `/newbot`.
4. BotFather prompts for:
   - **Display name** — something operators will recognise, e.g. `Acme Alerts`.
   - **Username** — must end in `bot`, e.g. `acme_alerts_bot`.
5. BotFather replies with an **API token** that looks like
   `1234567890:ABCdefGHIjklMNOpqrSTUvwxYZ`.

Copy that token — it's the one you'll paste into SyncTide. Treat it as a
password. Anyone with this token can send messages on behalf of your bot.

> **Tip — privacy mode.** New bots default to "privacy mode on", meaning
> they only see messages directed at them (`/command`, replies, or DMs).
> For SyncTide's alarm-only use case, leave it on. Turn it off only if you
> want the bot to read freeform group chatter (BotFather → `/mybots` → pick
> your bot → **Bot Settings → Group Privacy → Turn off**).

---

## Step 2 — collect chat IDs from each recipient

Telegram identifies every user and group by a numeric ID. SyncTide needs
that ID to know where to send each alarm.

**Hand the recipients the companion guide TELEGRAM_FOR_RECIPIENTS.md** —
it walks them through finding their own ID and authorising the bot. You'll
get back from each recipient:

- their **chat ID** (a positive number for individual users, e.g.
  `987654321`)
- confirmation that they tapped `/start` on your SyncTide bot

For a shared on-call group, see **Adding a group chat** below.

---

## Step 3 — configure the gateway in SyncTide

1. Open **Messaging Center** in SyncTide (sidebar).
2. Go to the **Configuration** tab.
3. Click **Add gateway** and fill in:
   - **Gateway type**: `Telegram Bot`
   - **Channel type**: `telegram`
   - **Label**: a name for yourself, e.g. `Telegram (operations)`.
   - **Bot Token**: paste the token from Step 1.
   - **Parse Mode**: leave as `HTML` unless you have a reason to change it.
   - **Active**: ✅
4. Save.

---

## Step 4 — add a contact per recipient

1. **Messaging Center → Contacts → Add contact**.
2. Fill in:
   - **Contact name** — operator's name, or the group name for a group contact.
   - **Telegram chat ID** — the number you collected in Step 2 (negative
     for groups, positive for DMs).
   - Phone number is required by the form but unused for Telegram-only
     contacts — set any placeholder.
3. Save.

Repeat for every recipient.

---

## Step 5 — wire it to alarm rules

1. **Messaging Center → Alarm rules → Add rule**.
2. Pick the device + tag (or site KPI) you want notifications for.
3. **Channel type**: `Telegram` (or leave as `Any` to use whichever active
   gateway matches the contact's available channels).
4. **Recipients**: pick the contact(s) you added in Step 4, or an
   escalation list if you've configured one.
5. Optionally set:
   - **Acknowledgement timeout** — if no operator acknowledges within N
     seconds, the alarm escalates to the next tier.
   - **Require ack** — message asks the recipient to reply to close the
     alarm. From v1.0.1 onwards, recipients can simply send `ack`, `ok`,
     `sim`, `confirmo`, ✅ or 👍 in the same Telegram chat — or use
     Telegram's swipe-to-reply gesture on the original message. The
     legacy `ACK-{token}` reply still works.
6. Save.

> **How inbound acks work.** A dedicated background worker
> (`telegram-inbound`) long-polls Telegram's `getUpdates` API for every
> active Telegram gateway — one HTTP round-trip per ~25 s when idle, so
> Telegram's free quota is more than enough. When an operator replies,
> the worker matches the reply against open alarms using this cascade:
>
> 1. **Telegram reply gesture** (swipe-to-reply) — matched by
>    `provider_message_id`. Most precise; works even if other alarms came
>    in afterwards.
> 2. **`ACK-{token}` literal** — legacy format, still honoured.
> 3. **Keyword** (`ack` / `ok` / `okay` / `sim` / `confirmo` / `confirmar`
>    / `yes` / `✅` / `👍` / `✓`) — matched against the most recent
>    un-acknowledged Telegram message for the sender's `chat_id` within
>    the last 24 hours.
>
> The bot replies *"✅ Acknowledged. Escalation cancelled."* the moment a
> match lands, so the operator gets explicit confirmation.

---

## Step 6 — smoke test

In **Messaging Center → Configuration → Send Test Message**:

1. Pick the Telegram gateway you just created.
2. Enter the chat ID (Step 2) in the test recipient field.
3. Send.

The message should arrive on the recipient's phone within 1–2 seconds.

If it doesn't, check **Messaging Center → History** — Telegram returns a
clear error message that's logged verbatim. Common ones:

| Telegram error | Cause | Fix |
| --- | --- | --- |
| `Forbidden: bot can't initiate conversation with a user` | Recipient never `/start`-ed the bot | Send them TELEGRAM_FOR_RECIPIENTS.md again — Step 3 |
| `Bad Request: chat not found` | Wrong chat ID — typo, or user ID used instead of group ID (or vice-versa) | Re-check the ID with the recipient |
| `Unauthorized` | Wrong bot token | Re-copy from BotFather (`/mybots → API Token`) |
| `Bad Request: can't parse entities` | HTML/Markdown parse error in the alarm template | Switch parse mode to plain HTML, or remove the offending characters from the message template |

---

## Adding a group chat (shared on-call room)

If you want every alarm going into a team room instead of individual DMs:

1. Create the group in Telegram.
2. Add your SyncTide bot as a member (search by the `@…_bot` username from Step 1).
3. Send any message in the group (the bot needs to "see" the group at least once).
4. Open this URL in any browser, replacing `<TOKEN>` with the API token from Step 1:
   ```
   https://api.telegram.org/bot<TOKEN>/getUpdates
   ```
5. Look for `"chat":{"id":-1001234567890,"title":"<your group>", …}`.
6. **Group IDs are negative.** Copy the whole negative number including the
   minus sign — that's the chat ID.
7. Add it in SyncTide as a contact (Step 4) the same way as a personal one.

> **If `getUpdates` returns an empty array (`{"ok":true,"result":[]}`)**:
> send another message in the group and refresh the URL. Telegram only
> buffers ~24 hours of pending updates per bot. Once SyncTide is running
> and consuming updates, this URL will routinely show empty — that's
> normal behaviour, not an error.

---

## Why Telegram and not WhatsApp / SMS?

Telegram is the right default when:

- Your operators already use the app, or are willing to install it.
- You want a free, no-billing-relationship setup.
- You're OK with a "messaging app" channel rather than a carrier SMS.

WhatsApp and SMS make more sense when:

- Operators don't have Telegram and won't install it.
- You need delivery to landlines (Voice / SMS only).
- Your compliance team requires a Business-grade carrier path.

SyncTide supports all three concurrently — most deployments use **Telegram +
Email as primary** and reserve SMS / WhatsApp for a small VIP list.

---

## Reference

- BotFather:  https://t.me/BotFather
- Telegram Bot API docs:  https://core.telegram.org/bots/api
- SyncTide gateway code:  `messaging_engine.py → TelegramBotChannel`
- Companion guide for recipients:  TELEGRAM_FOR_RECIPIENTS.md
