> The index of all pages is at https://docs.afffast.com/llms.txt.

# Notification channels

Send messages to people with Slack, Telegram, email, Discord, Microsoft Teams, ntfy and more.

A notification channel sends messages to people. A message is one of the events that you select, or the daily digest. The types are Slack, Telegram, email and Shoutrrr. Shoutrrr reaches Discord, Microsoft Teams, ntfy, Pushover, Gotify, Matrix and many other services. Use a [destination](https://docs.afffast.com/docs/destinations.md) to sync data to a tool (Google Sheets, BigQuery, Google Analytics 4), and a [webhook](https://docs.afffast.com/docs/webhooks.md) to send raw events to your own server.

A notification channel uses the same delivery engine as a destination: the same cursors, the same order and the same rules for a failure. Delivery is **at least once**.

## Types

Read the types and their fields with `GET /v1/notification_channel_types`. Each type has `config_fields` (settings) and `credential_fields` (secrets).

| Type     | What it does                                                   | Fields                                                                                                                       |
| -------- | -------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| Slack    | Posts the events that you select. It can post a daily digest.  | `channel`. Credential: `bot_token` (starts with `xoxb-`; the app needs the scope `chat:write`).                              |
| Telegram | Sends the events that you select. It can send a digest.        | `chat_id`. Credential: `bot_token` (from BotFather).                                                                         |
| Email    | Emails the events that you select. It can send a daily digest. | `members`, `member_ids`, `addresses`. No credentials.                                                                        |
| Shoutrrr | Sends the events that you select as plain text. No digest.     | `service` and the fields of the service. Credentials: `url`, or the secret fields of the service. See [Shoutrrr](#shoutrrr). |

The `GET /v1/notification_channel_types` response is the source of truth.

## When a channel sends

A sync can change many objects in a few minutes, for example 500 conversions that a network approves, or a commission that changes in 20 accounts. A channel does not send one message for each event. It collects the events and sends them together:

- A channel sends when no new event came for 2 minutes, or 10 minutes after the oldest event that waits. So a single event arrives after about 2 minutes.
- While a programs sync of the workspace runs, a channel waits for the end of the sync, at most 60 minutes. A programs sync reads each account of a connection, one after the other. So the message of the sync has the changes of all accounts.
- A system notice (`connection.failed`, `destination.failed`, `notification_channel.failed`, `log_drain.failed`, `webhook_endpoint.disabled`, `usage.limit_near`) does not wait. It is always its own message.
- One event alone gets its full text. More events are one message with one section for each event type. A section has the count, and for conversions and payouts the total amount in each currency, for example "New conversions: 24 (€ 230.00)". It shows at most 20 lines and then "+N more", with a link to the dashboard.
- A program has one row for each account of a connection. When the same change comes from several accounts, the section shows one line, for example "Freska FI: € 9.50 → € 8.00 (22 accounts)".

Only the notification channels wait. [Webhooks](https://docs.afffast.com/docs/webhooks.md) and [destinations](https://docs.afffast.com/docs/destinations.md) get each event at once.

## Make a channel

You need an API key with the scope `notification_channels:write`. Only an owner or an admin can make a channel in the dashboard.

```bash
curl -X POST https://api.afffast.com/v1/notification_channels \
  -H "Authorization: Bearer $AFFFAST_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "slack",
    "label": "Conversions channel",
    "config": { "channel": "C0123456789" },
    "credentials": { "bot_token": "xoxb-..." },
    "event_types": ["conversion.created", "program.status_changed"]
  }'
```

The API checks `config` and `credentials` with the fields of the type. It encrypts the credentials. It never returns them. The response shows `credentials_fields_set`: the names of the credential fields that have a value.

- `event_types` are the events that the channel gets. The default is `conversion.created`, `conversion.status_changed` and `conversion.updated`. An empty list means that the channel gets no event.
- `filters` limit the items by sites, connections, networks, tags and conversion statuses. See [Delivery filters](https://docs.afffast.com/docs/delivery-filters.md).
- `include_historic` is `false` by default. The channel then skips the events of the first sync and of the history load of a connection. See [Historic events](#historic-events).
- `digest` turns on the daily digest. It goes out at the send time of the digest, in the time zone that you set. The default time zone is the time zone of the workspace.
- A channel gets only the items that come **after** you make it.
- A channel has the mode of your key. A test key makes a channel that gets test data only.

## Test, pause and resume

- `POST /v1/notification_channels/{id}/test` sends one test message. The response is always 200. `ok` says if the channel accepted the message. When `ok` is `false`, `reason` says why.
- `PATCH /v1/notification_channels/{id}` with `"status": "paused"` stops the delivery. A paused channel keeps its place and gets the items that came in the time of the pause.
- `POST /v1/notification_channels/{id}/resume` starts a paused or failed channel again. Fix the cause of a failure first, or send new credentials.
- A message is useful only when it is new. When a send fails with a temporary error, the API tries again (the wait grows to 15 minutes). When the message is more than 6 hours old, the API skips it and goes on. When a channel has failed for more than 6 hours, its status is `failing` and the API writes the event `notification_channel.failed` once. The channel keeps trying, and the first delivery that works sets the status `active` again. A channel never gets its own failure event: it goes to the other channels that select it, so select it on a second channel. `delivery.skipped_count` of the channel counts the skipped messages, and the next digest says how many ("3 alerts could not be sent in time and were skipped."). A channel type has the `category` `notification` in `GET /v1/notification_channel_types`.
- When a channel has an error that a retry cannot fix (for example a bad token), its status is `failed`. The API writes the event `notification_channel.failed`. A channel that selects it tells you about the failure. A failed channel cannot tell you about its own failure, so select it on a second channel.

## Delivery log

`GET /v1/notification_channels/{id}/deliveries` lists the delivery log of a channel, newest first. A row is one call to the channel: a `batch` of items (also one page of a backfill), a `digest` or a `test`. The list has cursor pagination (`limit`, `starting_after`, `ending_before`). Use `result` to filter: `succeeded`, `failed`, `rate_limited` or `skipped`.

```bash
curl "https://api.afffast.com/v1/notification_channels/nch_.../deliveries?result=failed" \
  -H "Authorization: Bearer $AFFFAST_API_KEY"
```

- A row has the time, the duration, the number of items (`item_count`) and the IDs of the items (`item_ids`, `cev_` and `evt_` IDs, 50 at most), the `result`, the `attempt` number and, for a failure, the `error` and the time of the next attempt (`next_attempt_at`).
- `failed` means that the call failed. `next_attempt_at` says if the API tries again. `rate_limited` means that the channel asked the API to wait: it is not a failure and it does not use an attempt. `skipped` means that each item was too old (see the retry rules) and the API sent nothing. `skipped_count` of a `succeeded` row is the number of items that the API left out of that batch.
- The `error` has no secret. The API removes the values of the credentials from the message, and cuts it to 500 characters.
- The API keeps the log for 30 days.
- You cannot replay one item. To send old data again, use a [backfill](https://docs.afffast.com/docs/destinations.md#backfill).
- `POST /v1/notification_channels/{id}/retry` runs the delivery job now. A job that waits for a retry does not wait. The retry does not reset the count of failed attempts: a call that fails adds to it, and a call that works clears it. The response is `202` with a channel. Read the log to see the result. A channel needs the status `active` or `failing`. A `paused` or `failed` one gets `422`. A job that runs now is left alone.
- The log is also a source of the [log drains](https://docs.afffast.com/docs/log-drains.md): each row is one record of the source `delivery`, channel `destination`.

## Events

A channel gets the events that you select in `event_types`. The `type` of an event is one of these:

| Group          | Event types                                                                                                                                   |
| -------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| Conversions    | `conversion.created`, `conversion.status_changed`, `conversion.updated`, `click.attributed`                                                   |
| Payouts        | `payout.created`, `payout.updated`                                                                                                            |
| Program alerts | `program.status_changed`, `commission.changed`                                                                                                |
| System notices | `connection.failed`, `webhook_endpoint.disabled`, `destination.failed`, `notification_channel.failed`, `log_drain.failed`, `usage.limit_near` |
| Other          | `connection.synced`                                                                                                                           |

Each channel type shows an event in its own format, with the same content.

- **Program alerts** tell you that the join status of a program changed (`program.status_changed`), or that its commission or cookie time changed (`commission.changed`). A commission alert shows the old and the new value, for example "Commission changed for Freska FI: € 9.50 → € 8.00" or "cookie days 30 → 45". The email of one status change lists the program, the connection, the old status, the new status and the time.
- **System notices** tell you about a problem that needs an action: a connection that needs attention, a webhook endpoint that the API disabled, a destination, a notification channel or a log drain that the API stopped, and a usage that reaches 80 % or 100 % of the included amount of your plan (the clicks of a paid plan also 200 % and 500 %). An email channel sends one email for each notice. A notice is an event of the API too: you can also read it with `GET /v1/events` and send it to a [webhook](https://docs.afffast.com/docs/webhooks.md) endpoint.

## Historic events

A new connection reads its past data when you add it: the first sync, and then the history load (the backfill). This can give thousands of events in a short time. A channel must not send a message for each of them. So a channel skips the **historic events** by default.

A historic event is an event that a sync run writes during one of these:

- the first sync of a connection (the first run of each kind: conversions, programs and payouts),
- a history backfill of a connection, also a later one that you start with another start date.

These events are **not** historic:

- A conversion that a later normal sync reports for the first time, also when the sale is old. It sends a message.
- A status change (for example from `pending` to `approved`) that a normal sync finds. It always sends a message.
- The events of a manual re-sync of an old date range.
- A system notice, for example `connection.failed`. A new connection that cannot sign in tells you at once.

The event object of the API has the field `historic`. It is `true` for a historic event. Webhook endpoints and data destinations (BigQuery, Google Sheets and the others) are not changed: they get all events, also the historic ones. A webhook user can use `historic` to filter.

To get the historic events in a channel, set `include_historic` to `true` when you make or change the channel. The dashboard form has the setting "Send the historic events too". It shows this warning: "A new connection can send thousands of messages."

```bash
curl -X PATCH https://api.afffast.com/v1/notification_channels/nch_... \
  -H "Authorization: Bearer $AFFFAST_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "include_historic": true }'
```

The daily digest follows the same rule. A channel without `include_historic` does not count the status changes and the program changes of historic events in its digest. The totals of the digest are the sales of the day, like `GET /v1/stats`.

## Format of amounts and dates

A message shows an amount with the currency symbol, the separators of the locale of the workspace and the decimals of the currency. Example: a commission of `41.8800` DKK is `kr. 41,88` with the locale `da-DK` and `DKK 41.88` with the locale `en-GB`. A message never shows the four decimals of the database. It also writes the dates and the times of a message in the format of the locale. A time uses the time zone of the workspace.

The locale is the workspace setting `locale`. It is a BCP 47 language tag, for example `da-DK`, `en-GB` or `sv-SE`. `GET /v1/workspace` returns it, and an API key can read it. Only the dashboard can change it: open Settings and select the language and region. A new workspace gets the language of the browser of the user who creates it, or `en-GB`. The dashboard uses the same locale for the amounts, the numbers and the dates on its pages. The text of a message stays English.

The API does not use the locale. The amounts in the API stay decimal texts, for example `"41.88"`.

## Daily digest

The digest is one summary of one day. Turn it on with `digest` when you make or change a channel. It goes out once a day at the send time of the channel, in its time zone. All channel types send the same content:

- the number of conversions, the order amount and the commission of the day, in the currency of the workspace,
- the split by status,
- the conversions that changed status,
- the five programs with the most commission,
- the program status changes of the day (at most 20, with the number of the others).

Use the events for a message at once, the digest for one message each day, or both.

## Message templates

Each channel can have its own text for each event type and for the daily digest. A channel that has no template for a message sends the default text. Templates are for Slack, Telegram, email and Shoutrrr. They are not for webhooks and data destinations.

A template is a text with variables. `{{.Conversion.ID}}` writes the ID of the conversion. The engine is Go `text/template`. It runs no code and reads no file.

### Set a template

Send `templates` when you make or change a channel. The key is an event type, or `digest` for the daily digest.

```bash
curl -X PATCH https://api.afffast.com/v1/notification_channels/nch_... \
  -H "Authorization: Bearer $AFFFAST_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "templates": {
      "conversion.created": {
        "body": ":moneybag: New sale *{{.Conversion.ID}}*, {{.Commission}} ({{upper .Conversion.Status}})"
      },
      "conversion.updated": null
    }
  }'
```

- A key that you send replaces the template of that key.
- `null` resets the key to the default text. A key that you leave out stays as it is. `templates` of the channel has only the custom templates.
- The `body` has 4096 bytes at most. An email also has a `subject` (300 bytes at most). If an email template has no `subject`, the email uses the default subject of the event type.
- Only an email channel has a `subject`. A Slack or Telegram template with a `subject` gets `422`.
- The API checks each template when you save it. A template that is not valid gets `422` with the code `parameter_invalid`. The message has the line and the reason, for example `Line 2: The variable .Nope does not exist for this event type.` The API saves nothing from that request, also not the other templates of the same request.

### Variables and default texts

`GET /v1/notification_channel_types` returns `templates` for each type. `templates.messages` has one entry for each event type and for the digest. Each entry has:

- `variables`: the name, the type, the description and a sample value of each variable,
- `default`: the template that the channel uses when you set none. Use it as the start of your own template.
- `default_is_exact`: `true` when the channel sends the text of `default`. It is `false` for the program alert and the system notices of the **email** type. The email type sends them in their own layout, so `default` is only a plain text start for your own template.

The same list is in the dashboard editor. Some variables are the same for all event types:

| Variable          | Meaning                                                                             |
| ----------------- | ----------------------------------------------------------------------------------- |
| `.Event.ID`       | The ID of the event, or of the change of the conversion.                            |
| `.Event.Type`     | The event type, for example `conversion.created`.                                   |
| `.Event.ObjectID` | The ID of the object of the event.                                                  |
| `.Event.Time`     | The time of the event. Use the function `date` to write it.                         |
| `.Livemode`       | `true` for live data, `false` for test data.                                        |
| `.Link`           | The address of the object in the dashboard. It is empty when the event has no page. |

The other variables depend on the event type. A conversion event has `.Conversion.ID`, `.Conversion.Status`, `.Status.From`, `.Status.To`, `.Commission`, `.OrderAmount` and more. It also has the names `.Program.Name`, `.Network.Name` and `.Site.Name`. A name is empty when the program or the site does not exist, so use `default` for a fallback, for example `{{.Site.Name | default "No site"}}`. A program alert has `.Program.Name`. A commission alert also has `.Change` (the old and the new values, for example `8% → 10%, cookie days 30 → 45`), `.Commission.From`, `.Commission.To`, `.CookieDays.From` and `.CookieDays.To`. When a channel sends more events in one message, each event is one line: the first line of your template. The digest has `.Day`, `.Totals.Commission`, and the lists `.Statuses`, `.StatusChanges`, `.TopPrograms` and `.ProgramChanges`. A template that uses a variable that its event type does not have gets `422`.

### Ready-made templates

`templates.messages` of a channel type also has `presets`: ready-made templates for each message. The presets are `short` (one line), `detailed` (a title and one line for each value) and `with_link` (the detailed text and a link to the object in the dashboard). The digest has `short` and `detailed`. A preset is in the format of the channel type, and it passes the check on save. Send a preset as your template, or use it as the start of your own text.

### Functions

A template can use only these functions:

| Function  | What it does                                                                                          |
| --------- | ----------------------------------------------------------------------------------------------------- |
| `money`   | Writes an amount in the format of the workspace locale. `{{money .CommissionRaw .Currency}}`          |
| `date`    | Writes a time in the locale and in the time zone of the workspace. `{{date .Event.Time}}`             |
| `upper`   | Writes a text in upper case.                                                                          |
| `lower`   | Writes a text in lower case.                                                                          |
| `default` | Gives the second value, or the first value when the second value is empty. `{{default "none" .Name}}` |

The comparison and logic functions `eq`, `ne`, `lt`, `le`, `gt`, `ge`, `and`, `or`, `not` and `len` work with `{{if}}`. The actions `{{if}}`, `{{else}}`, `{{with}}` and `{{range}}` work. `range` works on a list of the digest, for example `{{range .TopPrograms}}{{.Rank}}. {{.Name}}{{end}}`. A `range` cannot be inside another `range`. The functions `printf`, `call`, `index`, `html`, `js` and the actions `template`, `define` and `block` are not allowed.

A variable like `.Commission` is already written in the format of the workspace locale. See [Format of amounts and dates](#format-of-amounts-and-dates). `money` uses the same locale.

### Format of each channel

The engine escapes each **value** for the format of the channel. It does not change the text that you write.

| Type     | Format of the body                                                                                                                                                                                                                    |
| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Slack    | Slack mrkdwn. Use `*bold*`, `_italic_` and `<https://example.com\|a link>` in your text. In a value, the engine writes `&`, `<` and `>` as entities, so a value cannot make a mention or a link. Slack has no escape for `*` and `_`. |
| Telegram | Telegram HTML (`parse_mode=HTML`). Use `<b>`, `<i>`, `<code>` and `<a href="...">` in your text. In a value, the engine writes `&`, `<`, `>` and `"` as entities. A value has 500 characters at most.                                 |
| Email    | Plain text. The HTML part of the email is made from the text, with escaping. A blank line starts a new paragraph.                                                                                                                     |
| Shoutrrr | Plain text. The engine does not escape a value. A service that reads Markdown, for example Discord, shows the Markdown marks that you write.                                                                                          |

A Telegram template must be valid HTML for Telegram: the tags must be known and closed, and a `<`, `>` or `&` in your own text must be an entity. The check on save refuses a template that breaks the rule. If a template makes a text that Telegram would refuse (for example when an optional tag stays open), or a text that is longer than 4096 characters, the channel sends the default text. A Slack section has 2900 characters at most. The channel cuts a longer text.

The Slack digest has one section for each paragraph of the template (a blank line starts a paragraph). The title of the digest and the line with the digest ID stay. The Telegram digest is cut between two lines when it is longer than one message.

### Slack

The Slack channel uses your own Slack app. AffFast has no shared app. You make the app, you install it in your workspace, and you give AffFast the bot token and the channel ID. The dashboard shows the same steps next to the form.

### Set up Slack

1. Open the Slack page [Your Apps](https://api.slack.com/apps). Select Create New App and make an app for your workspace.
2. In the settings of the app, open OAuth & Permissions. Under Bot Token Scopes, add the scope `chat:write`.
3. Select Install to Workspace and allow the app. Copy the Bot User OAuth Token. It starts with `xoxb-`. Paste it in the field Bot token.
4. In Slack, invite the app to the channel. Type /invite @ and the name of the app in the channel.
5. Open the details of the channel (select the channel name). Copy the Channel ID at the bottom of the About tab. It looks like `C0123456789`. Paste it in the field Channel.
6. Save the channel. Then use Send test on the channel to post one message.

### Common mistakes in Slack

- The app is not in the channel. Invite the app to the channel. A private channel needs the invite too.
- The app has no scope `chat:write`. Add the scope, then install the app again.
- You pasted the name of the channel, for example #sales. Use the Channel ID.
- You pasted a token that does not start with `xoxb-`. Use the Bot User OAuth Token.

## Email

A template for an event type makes an email of its own for each item: the subject and the text come from the template. An item without a template goes into the shared email for the batch, as before. The program alerts and the system notices keep their own emails until you set a template for their event type.

An email always keeps the link to manage the channel, the footer, the unsubscribe link and the headers `List-Unsubscribe` and `List-Unsubscribe-Post`. A template cannot remove them. A line break in a subject becomes a space. An email stays under the size limit: a long text is cut.

### Preview

`POST /v1/notification_channels/preview` renders a template with sample data. It sends nothing and saves nothing. It needs the scope `notification_channels:read`. The response has the text that a channel sends. The preview and the delivery use the same code, so the text is the same. The amounts and the dates use the locale and the time zone of the workspace.

```bash
curl -X POST https://api.afffast.com/v1/notification_channels/preview \
  -H "Authorization: Bearer $AFFFAST_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "telegram",
    "event_type": "program.status_changed",
    "template": { "body": "<b>{{.Program.Name}}</b>: {{.Status.From}} to {{.Status.To}}" }
  }'
```

An email preview also returns the `subject` and the `html`. A template that is not valid gets `422` with the line and the reason.

### Dashboard

Open a channel and select **Edit templates**. Choose an event type. The editor shows the variables, the default text and a live preview. **Reset to default** removes the template. The selected event type is in the address of the page.

## Email

An email channel sends to people. A recipient is one of these:

- **A member of the workspace.** `members` is `owners_admins` (all owners and admins, the default), `selected` (the members in `member_ids`, user IDs) or `none`.
- **An address that confirmed a link.** `addresses` is a list of other addresses. AffFast sends a confirmation email to each new address. The channel sends nothing to the address until its owner opens the link and presses the button. The link works one time and ends after 72 hours. Read the state of each address in `addresses` of the channel (`pending` or `confirmed`). `POST /v1/notification_channels/{id}/confirmations` sends the confirmation emails again.

An address that is the address of a member is `confirmed` at once. An address that you remove from the list loses its state. If you add it again, it must confirm again.

Each workspace has an email channel `Owners and admins` in live mode and in test mode. It sends to all owners and admins. It selects the program alerts and the system notices (`program.status_changed`, `commission.changed`, `connection.failed`, `webhook_endpoint.disabled`, `destination.failed`, `notification_channel.failed`, `log_drain.failed` and `usage.limit_near`). Its digest is off. So the owners and admins get an email at once when a program changes or when a system notice comes. Change the channel like any other channel:

- To stop the program alerts, remove `program.status_changed` and `commission.changed` from `event_types`, or pause the channel.
- To get the changes in one email each day, remove them from `event_types` and turn on `digest`.
- To send the alerts to other people, change `members` and `addresses`.

```bash
curl -X POST https://api.afffast.com/v1/notification_channels \
  -H "Authorization: Bearer $AFFFAST_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "email",
    "label": "Finance",
    "event_types": ["payout.created", "payout.updated"],
    "config": { "members": "none", "addresses": ["finance@example.com"] }
  }'
```

### Set up an email channel

1. Choose who gets the email. The default is all owners and admins of the workspace. You can choose members, or no member.
2. To send to a person who is not a member, add the email address under Other addresses. The person gets a confirmation email.
3. The person must open the link in the confirmation email. The channel sends nothing to the address before that.
4. Save the channel. Then use Send test on the channel to send one email.

### Common mistakes in email

- An address gets no email. The owner of the address did not open the link of the confirmation email yet.
- An address stopped getting email. The person used the unsubscribe link. Remove the address from the list of unsubscribed addresses to send to it again.

## Dashboard

Open [Integrations](https://docs.afffast.com/docs/integrations.md) in the dashboard. The **Connected** list shows the channels of the workspace. In the catalog, select **Connect** on the card of Slack, Telegram, email or Shoutrrr. The row menu has Send test, Pause or Resume, Edit and Delete. Only owners and admins see the change actions.

## Telegram

The Telegram channel uses your own bot. AffFast has no shared bot. You make the bot, you add it to a group, and you give AffFast the bot token and the chat ID. The dashboard shows the same steps next to the form.

### Make a bot

1. In Telegram, open [@BotFather](https://t.me/BotFather) and send the command `/newbot`.
2. Enter a name for the bot. Then enter a unique username that ends in `bot`.
3. BotFather sends the bot token. Copy the token and keep it secret. Paste it in the field Bot token.
4. To check the token, open `https://api.telegram.org/bot<token>/getMe` in a browser. Replace `<token>` with your token. The answer must have `"ok": true`.

The token looks like `123456789:AAH...`. To see it again, send `/token` to BotFather. To get a new token, send `/revoke` to BotFather. Then save the new token in the channel.

### Add the bot to a group

5. Make a Telegram group: select New Group, add at least one member, enter a name and select Create.
6. Add the bot to the group: open the group, select its name, select Add Members and search for the username of the bot. Then open the group settings, select Administrators and make the bot an administrator.

A Telegram **channel** also needs the bot as an **administrator** with the right to post messages. To write to only yourself, open the bot and send `/start`. A bot cannot write to a user who did not start it.

### Find the chat ID

7. Send one message to the bot, or add the bot to the group. The form looks for the chats of the bot every few seconds and shows them below the field Chat ID.
8. Select the chat. The form puts its ID in the field Chat ID. The ID of a supergroup starts with `-100`, for example `-1001234567890`.

The ID of a normal group is a negative number. The ID of a channel also starts with `-100`. For a **public channel** you can use its username instead, for example `@mychannel`.

The form uses `POST /v1/notification_channels/telegram_chats`. The API calls the Telegram methods `getMe` and `getUpdates` with the token and returns the chats of the bot, the newest first. Use it with an API key too:

```bash
curl -X POST https://api.afffast.com/v1/notification_channels/telegram_chats \
  -H "Authorization: Bearer $AFFFAST_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "bot_token": "123456789:AAH..." }'
```

The lookup only reads. It confirms no update, so another program of the bot still gets all updates. It does not change the settings or the webhook of the bot. It does not save the token, and the request log does not show it. Telegram keeps the updates of a bot for 24 hours.

To find the chat ID without AffFast, send a message to the bot. Then open `https://api.telegram.org/bot<token>/getUpdates` in a browser. Replace `<token>` with your token. The chat ID is the number in `"chat":{"id":...}`.

### Test the bot

9. Save the channel. Then use Send test on the channel to send one message to the group.

To test the bot without AffFast, open this address in a browser. Replace `<token>` and `<chat_id>`: `https://api.telegram.org/bot<token>/sendMessage?chat_id=<chat_id>&text=Hello`. The group must get the message "Hello".

### Troubleshooting

- The form finds no chat. Send a new message to the bot. If the bot is already in the group, send `/start@<bot username>` in the group. Telegram keeps the messages of a bot for 24 hours only.
- The bot has a webhook, so Telegram gives no messages to the form. Check with getWebhookInfo. If you do not use the webhook, remove it with deleteWebhook. Or type the chat ID.
- The bot is not an administrator of the group. Make it an administrator. A Telegram channel also needs an administrator bot.
- You shared the bot token. Never share the token. Send /revoke to BotFather to get a new token.

Use only the [Telegram Bot API](https://core.telegram.org/bots/api) for the calls above.

### Make the channel

```bash
curl -X POST https://api.afffast.com/v1/notification_channels \
  -H "Authorization: Bearer $AFFFAST_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "telegram",
    "label": "Conversions chat",
    "config": { "chat_id": "-1001234567890" },
    "credentials": { "bot_token": "123456789:AAH..." }
  }'
```

`chat_id` is a text field. Send the number as text, or send `@channelusername`.

### How it works

- Each selected event type sends one message in HTML format. AffFast escapes all values.
- The daily digest goes out at the send time of your workspace. A digest that is longer than 4096 characters goes out as more messages, split between lines.
- Telegram limits the rate. AffFast sends about one message each second. When Telegram says "wait", AffFast waits for the time that Telegram gives, and then it sends the rest.
- Use `POST /v1/notification_channels/{id}/test` to check the token, the chat and the rights of the bot. It sends one test message.
- The bot token is write-only. The API never returns it. AffFast does not put it in logs or error messages.

### Errors

| Reason                     | What to do                                                                       |
| -------------------------- | -------------------------------------------------------------------------------- |
| `telegram_invalid_token`   | The token is wrong or revoked. Copy a new token from BotFather.                  |
| `telegram_chat_not_found`  | The chat ID is wrong, or the bot is not in the chat. Check both.                 |
| `telegram_bot_not_in_chat` | The bot was removed or may not post. Add it again. A channel needs an admin bot. |
| `telegram_bot_blocked`     | The user blocked the bot. Ask the user to unblock it.                            |
| `telegram_chat_migrated`   | The group became a supergroup. Use the new chat ID from the message.             |

A permanent error sets the status of the channel to `failed`. Fix the cause, then resume the channel with `POST /v1/notification_channels/{id}/resume`.

## Shoutrrr

The type `shoutrrr` sends a plain text message to one of many services. It uses the open source library [Shoutrrr](https://shoutrrr.nickfedor.com). Six services have a form that builds the Shoutrrr URL for you. For all other services, paste the Shoutrrr URL.

| Service         | Form  | Docs                                        |
| --------------- | ----- | ------------------------------------------- |
| Discord         | Yes   | [Chat services](https://docs.afffast.com/docs/notifications-chat.md)   |
| Microsoft Teams | Yes   | [Chat services](https://docs.afffast.com/docs/notifications-chat.md)   |
| Matrix          | Yes   | [Chat services](https://docs.afffast.com/docs/notifications-chat.md)   |
| ntfy            | Yes   | [Push services](https://docs.afffast.com/docs/notifications-push.md)   |
| Pushover        | Yes   | [Push services](https://docs.afffast.com/docs/notifications-push.md)   |
| Gotify          | Yes   | [Push services](https://docs.afffast.com/docs/notifications-push.md)   |
| Other services  | A URL | [Other services](https://docs.afffast.com/docs/notifications-other.md) |

### Set up a Shoutrrr channel

1. Select the service. Discord, Microsoft Teams, ntfy, Pushover, Gotify and Matrix have a form. For any other service, select Shoutrrr URL.
2. Fill the fields of the service. The form builds the Shoutrrr URL for you. For Shoutrrr URL, paste the URL of the service.
3. Save the channel. Then use Send test on the channel to send one message.

### Make the channel

`config.service` selects the service. It is `url`, `discord`, `teams`, `ntfy`, `pushover`, `gotify` or `matrix`. `config` has the settings of the service. `credentials` has the secrets of the service. Read `services` of the channel type (`GET /v1/notification_channel_types`) for the fields, the labels and the setup steps of each service.

```bash
curl -X POST https://api.afffast.com/v1/notification_channels \
  -H "Authorization: Bearer $AFFFAST_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "shoutrrr",
    "label": "Team Discord",
    "config": { "service": "discord", "webhook_id": "123456789012345678" },
    "credentials": { "token": "..." }
  }'
```

To use any Shoutrrr URL, set `config.service` to `url` and send the URL in the credential `url`:

```json
{
  "type": "shoutrrr",
  "label": "Pushbullet",
  "config": { "service": "url" },
  "credentials": { "url": "pushbullet://API_TOKEN/DEVICE" }
}
```

The API builds the URL from the fields each time it sends. It never returns the credentials. The response shows `credentials_fields_set`. New credentials replace all old credentials, so send all secret fields.

### Rules

- The channel sends plain text. A template can change the text of each message. See [Message templates](#message-templates).
- The channel has no daily digest and no backfill.
- A pasted URL must use one of the supported services: `bark`, `discord`, `generic`, `gotify`, `googlechat`, `homeassistant`, `ifttt`, `join`, `lark`, `matrix`, `mattermost`, `notifiarr`, `ntfy`, `opsgenie`, `pagerduty`, `pushbullet`, `pushover`, `rocketchat`, `signalgrid`, `teams`, `twilio`, `wecom` or `zulip`. Slack, Telegram and email are not in the list. They have their own channel types.
- AffFast always connects with TLS and checks the certificate. The URL parameters `disabletls`, `skiptlsverify`, `insecureskipverify` and `scheme` are not allowed.
- AffFast does not connect to a private address (a private network, the local host or a link-local address). It does not follow a redirect.
- AffFast sends about one message each second. When a service says "wait", AffFast waits and sends the rest.
- A secret is write-only. AffFast does not put it in logs or error messages.

### Errors

| Reason                     | What to do                                                                               |
| -------------------------- | ---------------------------------------------------------------------------------------- |
| `shoutrrr_unauthorized`    | The service refused the credentials. Save new credentials.                               |
| `shoutrrr_not_found`       | The service did not find the target. Check the host, the topic, the room or the webhook. |
| `shoutrrr_bad_request`     | The service did not accept the message. Check the fields of the channel.                 |
| `shoutrrr_bad_url`         | The fields do not make a valid address. Check the fields and save them again.            |
| `shoutrrr_blocked_address` | The address of the service is in a private network. Use a public address.                |
| `shoutrrr_insecure`        | The address of the service does not use TLS. Check the address of the service.           |
| `shoutrrr_redirect`        | The service answered with a redirect. Check the address of the service.                  |

A permanent error sets the status of the channel to `failed`. Fix the cause, then resume the channel with `POST /v1/notification_channels/{id}/resume`. A network error, a timeout and an answer of the type 5xx are not permanent: the worker tries again.

### Common mistakes

- The service is not in the list of supported services. Slack, Telegram and email have their own channel types.
- The Shoutrrr URL has a space or a special character. Encode each part with percent signs.
- The URL has a parameter that turns off TLS (disabletls, skiptlsverify or scheme). AffFast does not accept these parameters.
- The server of the service is in a private network. AffFast cannot reach a private address. Use a public address.
