# TeleMax integrations

Everything that happens in a project goes into one event feed. A receiver either subscribes to it with a webhook or reads it itself with an API key. Usually you want both: the webhook gives speed, and the feed guarantees nothing was lost while your receiver was down.

## What you set up in the interface

The "Integrations" page in the side menu:

- **Receiver**: the address to send events to and a type mask ("*", "monitoring.*", or a comma-separated list). A secret is generated on creation and shown in the list.
- **API key**: for reading the feed. It is shown only once: we store only its hash. A key can be revoked (the record stays in the list) or deleted completely.
- **Delivery log**: what was sent, the response and the number of attempts. A "Retry" button is available for deliveries that finally failed.

## Webhook

A POST request with a JSON body and these headers:

| Header | Value |
|---|---|
| `X-Telemaks-Event` | event type, for example `monitoring.hit.created` |
| `X-Telemaks-Delivery` | delivery ID, an idempotency key |
| `X-Telemaks-Timestamp` | Unix time of sending |
| `X-Telemaks-Signature` | `t=<timestamp>,v1=<HMAC-SHA256>` |

The signature is computed over the string `<timestamp>.<body>` with the receiver's secret:

```python
import hashlib, hmac

def check(secret: str, headers, body: bytes) -> bool:
    stamp = headers["X-Telemaks-Timestamp"]
    want = hmac.new(secret.encode(), stamp.encode() + b"." + body,
                    hashlib.sha256).hexdigest()
    return hmac.compare_digest(f"t={stamp},v1={want}",
                               headers["X-Telemaks-Signature"])
```

The timestamp is part of the signature so that an intercepted request cannot be replayed later: reject timestamps older than a few minutes.

Any 2xx response counts as success. Otherwise we retry after one minute, five minutes, fifteen minutes, one hour and six hours; after that the delivery is marked dead and waits for a person. Respond quickly: the timeout is 10 seconds. Do heavy work after responding.

The same event can arrive twice (for example, the connection dropped after your response), so store the `delivery_id` and skip repeats.

## Feed

The TeleMax address is `https://tmaks.ru`, the API prefix is `/api/v1`. If the receiving side asks for a "base URL", it is `https://tmaks.ru`; if it asks for the full feed URL, it is `https://tmaks.ru/api/v1/integrations/events`.

```
GET https://tmaks.ru/api/v1/integrations/events?since=<cursor>&type=monitoring.*&limit=100
X-API-Key: tmk_…
```

**The response is a bare array of events, with no wrapper object.** An empty feed is `[]`, not `{"events": []}`:

```json
[
  {
    "id": "94b198d6-6a60-40b5-aecc-8208d61e758f",
    "type": "monitoring.hit.created",
    "created_at": "2026-09-15T19:56:49.172601Z",
    "cursor": "2026-09-15T19:56:49.172601Z/94b198d6-6a60-40b5-aecc-8208d61e758f",
    "data": { }
  }
]
```

Note that a feed item and a webhook body are structured **differently**. A webhook has a delivery envelope (`event`, `delivery_id`, `event_id`, `occurred_at`, `project_id`); a feed item has `id`, `type`, `created_at`, `cursor`. What they share is the `data` field: its content is byte-for-byte the same, so one function can parse the payload.

Parameters: `since` is the cursor, `type` filters by type (supports `monitoring.*`), `rule` returns events of one keyword only, `limit` is from 1 to 500, 100 by default.

### One campaign, not the whole project

A key is issued per project, and a project usually has several keywords: ongoing topics live next to a campaign. In the shared feed they are mixed, and the post text alone does not always show which keyword caught it. So:

```
GET /api/v1/integrations/rules
X-API-Key: tmk_…

[{"id": "0ae9a967-…", "query": "\"spring campaign\"", "enabled": true,
  "hits_count": 15, "created_at": "2026-09-22T14:58:11Z"}]
```

and then `…/events?rule=0ae9a967-…`. Instead of the `id` you can pass the keyword text itself; matching ignores case. The filter looks at the event, not at the keyword list, so it also works for a deleted keyword: its events stay in the feed for their thirty days after deletion, and without the filter they would look unrelated.

Events are sorted by time, oldest first. Save the `cursor` of the last processed event and pass it in `since`: you will get only what appeared after it. Without `since` you get the start of the feed. There is no "has more" flag, and you do not need one: if exactly `limit` records came back, request the next page with the cursor of the last one, and repeat until the array is shorter than `limit`.

The cursor is opaque: pass it back as is, without parsing it. The timestamp in it ends with `Z` precisely so that the cursor can go into a URL without encoding. The `+00:00` offset form is accepted too, including when the plus turned into a space through naive URL building.

The feed is kept for 30 days.

Telegram alerts work independently: connecting a receiver neither turns them off nor replaces them. The same mention goes both to Telegram and to the integration.

## Channel stats by link

A separate method, not tied to monitoring: you give a link to a channel, community, website or post and get subscribers, growth, views and engagement from the TeleMax Catalog. The key is the same as for the feed; request limits follow the project's plan.

Channels from your project's sources are returned without limits. Figures for other channels count against the account quota: on Pro and Max it is 3,000 different channels a month. Each channel counts separately, including inside a list; requesting the same channel again does not use the quota. The remaining quota is in the response headers `X-Channel-Quota-Limit` and `X-Channel-Quota-Left`.

```
GET https://tmaks.ru/api/v1/integrations/channel-stats?url=https://t.me/rian_ru
X-API-Key: tmk_…
```

It understands Telegram links (`t.me/username`, `@username`, a post link), VK (community, page, post `wall-…`), MAX (`max.ru/username`), Odnoklassniki, Rutube (a channel or a video, in which case the author is used) and website addresses. A post link leads to the channel that published it.

```json
{
  "url": "https://t.me/rian_ru",
  "found": true,
  "reason": null,
  "platform": "tg",
  "platform_name": "Telegram",
  "title": "RIA Novosti",
  "handle": "rian_ru",
  "link": "https://t.me/rian_ru",
  "card": "https://tmaks.ru/c/tg/rian_ru",
  "subscribers": 3030098,
  "audience_kind": "subscribers",
  "visitors_month": null,
  "subscribers_at": "2026-10-17T18:46:55Z",
  "growth": {"day": -276, "week": -3715, "month": 18700},
  "views": {"avg": 200652, "median": 202002, "max_30d": 299214},
  "er": 0.83,
  "err": 6.62,
  "posts_30d": 1680,
  "last_post_at": "2026-10-17T16:04:19Z",
  "stats_at": null
}
```

| Field | What it is |
|---|---|
| `subscribers` | subscribers; for a website, visitors per day (`audience_kind: visitors_per_day`), and per month in `visitors_month` |
| `growth` | subscriber growth over 1, 7 and 30 days; `null` for websites |
| `views` | average and median post views over 30 days and the most viewed post |
| `er` | engagement, %: reactions to views over 30 days |
| `err` | reach, %: average post views to subscribers |
| `subscribers_at` | when subscribers were measured |
| `stats_at` | for channels TeleMax does not read constantly, when views were last counted; `null` for channels we read, as their figures are always fresh |
| `card` | the Catalog card; `null` if the channel is in the database but not yet published |

An empty value means there is no figure, not zero: for example, a channel with no posts this month has no views.

Responses without figures are also `200`, with `"found": false` and a reason:

| `reason` | What it means |
|---|---|
| `not_in_catalog` | the channel is not in the Catalog yet. TeleMax starts reading it right away and will add it: repeat the request in a few hours, usually a day is enough. Up to 50 new channels per project are added this way per day |
| `unsupported` | we do not read this platform yet (YouTube, Dzen, Instagram and others; `platform` says which). The request is recorded: we use such requests to decide what to add next |
| `unrecognized` | the link could not be parsed |
| `quota` | the quota for channels outside your sources is used up. Add the channel to the project's sources, move to a larger plan, or repeat the request with `over_quota=true` |

A list of up to 100 links per request; the response keeps the same order:

```
POST https://tmaks.ru/api/v1/integrations/channel-stats
X-API-Key: tmk_…
Content-Type: application/json

{"urls": ["https://t.me/rian_ru", "https://vk.com/ria", "lenta.ru"]}
```

Figures come from the Catalog, not from the platform at the moment of the request: subscribers are updated several times a day, views and ER once a day.

### Over the quota, for tokens

When the quota for other channels is used up, add `?over_quota=true` to the request, for both GET and POST `/channel-stats`. Each further channel then costs 1,000 tokens from the plan's monthly allowance, the same one used by rewrites and the AI editor. Requesting the same channel again this month costs nothing. The tokens spent per request are in the `X-Tokens-Spent` header. Without the parameter, tokens are never spent.

## Event envelope

```json
{
  "event": "monitoring.hit.created",
  "delivery_id": "e3b0c442-…",
  "event_id": "8f14e45f-…",
  "occurred_at": "2026-09-15T08:14:22.481Z",
  "project_id": "…",
  "cursor": "2026-09-15T08:14:22.481Z/8f14e45f-…",
  "data": { }
}
```

`data` for `monitoring.hit.created`:

```json
{
  "hit": {"id": "…"},
  "rule": {"id": "…", "query": "#TogetherWe2026"},
  "match": {"kind": "word", "query": "#TogetherWe2026"},
  "source": {"platform": "max", "title": "Youth Online",
             "username": "molodezh", "url": "https://max.ru/molodezh"},
  "message": {"id": "…", "published_at": "2026-09-15T08:13:40Z",
              "link": "https://max.ru/molodezh/1841",
              "text": "…", "views": 12, "forwards": 34, "replies": 8,
              "cluster_id": "…",
              "media": [{"type": "photo", "url": "https://…jpg",
                         "thumbnail": null, "width": 1440, "height": 1814}]}
}
```

`platform` is `tg`, `max`, `vk`, `web`, `ok` (Odnoklassniki) or `rutube`.

`match` tells how the post was caught (since 29.10.2026):

| `kind` | What it means | `query` |
|---|---|---|
| `word` | by the words of the keyword itself | the keyword |
| `sem` | by meaning: the post may not contain the keyword's words | the keyword |

The payload is nested on purpose: `rule` answers "what caught it", `source` answers "where it was published", and `message` answers "what exactly". Read it as `data.message.text`, not as a flat object; with naive parsing all events look equally empty.

### Attachments

`message.media` holds up to four attachments of the post, in publication order:

| Field | What it is |
|---|---|
| `type` | `photo` or `video` |
| `url` | the file itself, if we have it; otherwise `null` |
| `thumbnail` | a preview image; videos have only this |
| `width`, `height`, `duration` | when the platform provides them |

URLs are absolute and ready to use in `<img>`. Where they point depends on the platform: for VK it is their CDN, for MAX a video cover on okcdn, for Telegram a frame from our server (`tmaks.ru/media/…`) or the Telegram CDN (`cdn*.telesco.pe`), for websites the outlet's own image. For Telegram the attachment type is not always known: a video frame can arrive as `photo`. No platform provides the video file itself, so videos only have `thumbnail`.

`media` is empty for posts from a private Telegram channel: there is nowhere to take the image from except Telegram itself.

Third-party CDNs change over time and may close a link one day. If you need an attachment for a long time (in a report or a campaign archive), download it when you receive the event rather than following the link a year later.

The array is empty when the post has no attachments or the platform did not provide them.

### Response figures

`views`, `forwards`, `replies` are views, forwards and comments. We return what the platform reports: forwards exist for Telegram and VK, comments only for Telegram, and MAX and websites have neither. Where a value is missing, it is `null`, not `0`: zero would mean "measured, and nobody forwarded it".

Figures grow after publication, so in the mention event they are almost always small. For reports, use the `monitoring.hit.metrics` event: it arrives with measurements one hour and one day later.

**The feed also returns a keyword's history.** A newly added keyword pulls in past posts right away; on the page you see something like "15 found" in the first minute. These mentions go to the feed as the same `monitoring.hit.created` events, with no special flag: for a campaign report, a week-old post is as good as today's. The only difference is the event's `created_at` and `message.published_at`. Up to 2,000 latest mentions per keyword are sent back in time, which is enough for a whole campaign; the monitoring page itself knows the full history and can show more.

`cluster_id` is a reference field only. Each found post arrives as a separate event: we never merge posts or count them as one, even when the texts match. For a campaign where communities publish the same text with a hashtag, this is exactly what you need: the receiving side counts every post. You can ignore the field; it helps if you ever need the opposite, telling an original from a reprint.

For `monitoring.hit.metrics` this is added:

```json
{"metrics": {"stage": "d1", "views": 4120, "views_total": 4380}}
```

`stage` is `h1` (measured one hour after publication) or `d1` (one day after). The event comes with the same `hit.id` as the mention: views at the moment of discovery are almost always near zero, and these measurements are what a campaign report needs. Metrics are sent only to projects that have a receiver or a key.

## Event types

| Type | When |
|---|---|
| `ping` | the "Test" button in the interface |
| `monitoring.hit.created` | monitoring found a mention, new or in the history of an added keyword |
| `monitoring.hit.metrics` | view measurements are available for a found post |
| `monitoring.story.rising` | a story with a project keyword (with the "Growth signal" box ticked) or from the project's regions and topics started to grow; one event per story |
| `monitoring.tone.negative` | many negative mentions of a keyword from different independent sources within an hour (Max and Business plans); no more than once every few hours per keyword |

For `monitoring.story.rising`, `data` contains `story` (`id`, `title`, `summary`, `url`, `theme`, `region` as the main ones; `themes`, `regions` as all topics and places of the story), `metrics` (`posts`, `posts_last_hour`, `channels`, `new_channels_last_hour`, `platforms`, `regions`, `federal_channels`, `first_published_at`, `score`) and `reasons`, which say why it was sent: `phrases`, `region`, `theme`.

For `monitoring.tone.negative`, `data` contains `rule` (`id`, `query`), `window_minutes`, `negative_posts`, `independent_sources`, `url` (a feed of negative posts for the keyword) and `posts`, up to five latest posts (`message_id`, `platform`, `source`, `link`, `text`, `published_at`).

## About hashtags

Search uses a Russian-language dictionary, and the hash sign is dropped during parsing: the rule `#TogetherWe2026` also catches a post that says `TogetherWe2026` without the hash. If a campaign needs a strict count of hashtags only, filter by text on your side: it arrives in `message.text`.
