Files
3x-ui/docs/content/docs/ru/operations/telegram-bot.mdx
T
pcxzs 7aa5fc085f feat(tgbot): access levels and /start account binding (#6518)
* feat(tgbot): gate the bot behind three user levels

Every Telegram account that found the bot could run /help, /status and
/usage, and tap any client button it could forge: nothing separated an
account no admin had bound from a customer.

Each update now resolves to stranger, client or admin, and commands are
allowlisted per level so a command added later stays admin-only until it
is listed. A stranger may run /start and /id only, and /start answers with
the ChatID an admin needs to bind it; a stranger's callbacks are answered
and dropped. Client detection reads the same tgId lookup as
clientOwnedByTgUser, so the level gate and the ownership check agree.

The bot also ignores everything outside private chats: authorization keys
on the sender while wizard state keys on the chat, and the two are the
same identity only in a private chat.

* feat(tgbot): bind Telegram accounts through /start deep links

Linking a customer meant the customer sending /id and an admin copying
the ChatID into the client by hand, which does not scale past a few
customers and is easy to get wrong.

The admin client card now offers an invite link, t.me/<bot>?start=<subId>,
and the first account to open it is bound through the existing
SetClientTelegramUserID. A subId already grants the subscription, so
binding gives the holder nothing the token did not. A subscription that
spans several clients binds all of them, and is refused if any part
belongs to another account; re-opening your own link is idempotent.
Unknown and already-claimed tokens share one reply, so the link cannot
be used to probe for valid subIds.

* fix(tgbot): harden invite claims after review

Review of the access-level and binding change found five problems:

- Concurrent claims of one link all read the client as unbound, all bound
  and all were told so, while only the last write held. Resolving and
  binding now share one lock, and a bind that fails part-way through a
  multi-client subscription undoes the bindings it already made.
- A subId has no minimum strength and the bot needs only its public
  username, so /start was an unthrottled guessing oracle. Non-admin claim
  attempts are capped at five per account per hour, the first refused one
  notifies the admins, and the Subscription ID field now says it doubles
  as the bot invite code.
- levelOf expanded every inbound's client JSON on every non-admin update.
  It now reads the indexed tg_id column of the clients table.
- A button tapped in a group chat was dropped unanswered and kept
  spinning, with nothing logged. It is answered now, and each ignored chat
  is logged once.
- The subId was pasted raw into the t.me link, so '#' or '&' truncated it
  and Telegram rejects anything outside A-Za-z0-9_-. The payload is now
  base64url, and a subId too long for the 64-character limit is refused.

* fix(tgbot): answer group chats again and make the claim race test bite

ignoredChat dropped every non-private chat because wizard state was
keyed by chat while authorization keyed on the sender. #6604 on main
re-keyed that state by (chat, user) so admins can drive the bot from a
group, so after the merge the drop only took the whole bot away from
those admins, report keyboards sent to a group included. The level gate
already keys on the sender, so group chats need no special case.

TestConcurrentClaimsBindOnlyOneAccount passed with inviteClaimMu
removed: the first claimant took the pool's idle connection and bound
before the rest had opened theirs, so no two ever raced. It now holds
the inbound write the binds need until every claimant has resolved,
and fails without the lock ("6 accounts told they bound").

TestCommandAllowed restated the commandsByLevel map; TestGateCommand
drives the same allowlist through gateCommand. TestIgnoredChat goes
with the code it pinned.

* docs(tgbot): document access levels and invite links

The command table still said /help and /status answer anyone. An
account no admin has linked now reaches only /start and /id, and a
customer is linked through the client card's Invite Link, whose token
is the Subscription ID. Updated in en, fa, ru and zh.

---------

Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
2026-09-27 13:33:29 +02:00

131 lines
9.5 KiB
Plaintext

---
title: Telegram-бот
description: Подключите Telegram-бота к 3x-ui для выполнения команд, периодических отчётов, оповещений о событиях (вход, CPU, доступность узлов), резервных копий и самообслуживания клиентов.
icon: Send
---
3x-ui умеет управлять Telegram-ботом для мониторинга, оповещений, резервного
копирования и удалённого управления. Администраторы получают полный контроль;
обычные пользователи (привязанные по Telegram ID) могут проверять собственный
расход трафика и ссылки.
<Callout type="info">
Ищете новости и поддержку сообщества? Присоединяйтесь к официальному
Telegram-каналу [@XrayUI](https://t.me/XrayUI). Это отдельный канал, не
связанный с описанным ниже ботом, которого вы запускаете самостоятельно для
управления собственной панелью.
</Callout>
## Настройка
<Steps>
<Step>
### Создайте бота
Напишите [@BotFather](https://t.me/BotFather), отправьте `/newbot` и скопируйте
**токен бота**.
</Step>
<Step>
### Узнайте свой Telegram ID
Получите свой числовой идентификатор пользователя Telegram (после подключения
бот сообщит его по собственной команде `/id`). Это ваш **админский** ID.
</Step>
<Step>
### Настройте панель
В настройках панели включите Telegram-бота и задайте **токен** и **админские
chat ID** (через запятую). Сохраните, затем напишите своему боту.
</Step>
</Steps>
Проверьте свой токен, админские ID и расписание отчётов, прежде чем вставлять их
в панель:
<TelegramSetupHelper />
## Команды
Эти команды отображаются в меню команд Telegram: `/start`, `/help`, `/status`, `/id`.
Дополнительные команды:
| Команда | Кому | Действие |
| ------------------ | ------ | ------------------------------------------------------------ |
| `/start` | всем | Приветствие и меню встроенных кнопок; непривязанный аккаунт получает только свой Telegram ID |
| `/help` | обоим | Меню встроенных кнопок |
| `/status` | обоим | Подтверждает, что бот работает |
| `/id` | всем | Показывает ваш числовой Telegram ID |
| `/usage <arg>` | обоим | Администраторы ищут клиентов; пользователи смотрят свой расход |
| `/inbound <remark>`| админ | Показывает сведения о входящем подключении |
| `/restart` | админ | Перезапускает Xray |
Пользователь — это аккаунт Telegram, привязанный хотя бы к одному клиенту. Любой
другой аккаунт может выполнять только `/start` и `/id`; остальные его команды и
нажатия кнопок бот игнорирует. Чтобы привязать клиента, нажмите
**Ссылка-приглашение** в карточке клиента в боте и отправьте ему ссылку `t.me`: первый
открывший её аккаунт привязывается ко всем клиентам с этим ID подписки. ID
подписки служит кодом приглашения, поэтому делайте его длинным и случайным.
У каждого аккаунта пять попыток в час, после чего администраторы получают
уведомление.
Администраторам также доступны сценарии со встроенными кнопками: использование
сервера, отсортированные отчёты по трафику, сброс трафика, резервные копии БД,
журналы блокировок, список входящих подключений/клиентов, онлайн-клиенты,
«скоро исчерпают» и полноценный мастер **добавления клиента**. Обычным
пользователям доступны кнопки для своего расхода, ссылок на подписку, отдельных
ссылок и QR-кодов.
## Отчёты и оповещения
- **Периодический отчёт** — по расписанию `tgRunTime` (по умолчанию `@daily`) бот
отправляет администраторам сведения об использовании сервера (хост, версии,
время работы, нагрузка, память, онлайн-клиенты, трафик), список
исчерпанных/истекающих клиентов и — если включён `tgBotBackup` — резервную
копию базы данных и конфигурации Xray. Клиенты, привязанные по Telegram ID,
получают собственные предупреждения об истечении срока/исчерпании квоты.
- **Оповещения о событиях** — выбираются параметром `tgEnabledEvents` (по умолчанию `login.attempt,cpu.high`):
| Событие | Когда |
| --------------- | ------------------------------------------------------- |
| `login.attempt` | Вход в панель удался или не удался (с IP и именем пользователя) |
| `cpu.high` | Загрузка CPU превышает `tgCpu` процентов (по умолчанию 80) |
| `memory.high` | Использование памяти превышает `tgMemory` процентов (по умолчанию 80) |
| `xray.crash` | Аварийное завершение Xray-core |
| `outbound.down` / `outbound.up` | Исходящее подключение упало / восстановилось |
| `node.down` / `node.up` | Узел ушёл в офлайн / вернулся в строй |
Время предупреждения определяется параметрами `expireDiff` (дней до истечения
срока) и `trafficDiff` (ГБ оставшейся квоты); оба по умолчанию равны `0`
(отключено).
## Параметры
| Параметр | По умолчанию | Значение |
| -------------- | -------------------------- | ---------------------------------------------- |
| `tgBotEnable` | `false` | Главный переключатель вкл./выкл. |
| `tgBotToken` | _(секрет)_ | Токен Bot API. |
| `tgBotChatId` | _(нет)_ | **Админские** Telegram ID через запятую. |
| `tgBotProxy` | _(нет)_ | Прокси `socks5://`, `http://` или `https://`. |
| `tgBotAPIServer` | _(по умолчанию)_ | Пользовательский сервер Telegram Bot API. |
| `tgRunTime` | `@daily` | Расписание отчётов (cron / `@daily` / `@every …`).|
| `tgBotBackup` | `false` | Прикладывать резервную копию БД к периодическому отчёту. |
| `tgCpu` / `tgMemory` | `80` / `80` | Пороги оповещений по CPU / памяти (в процентах). |
| `tgLang` | `en-US` | Язык бота. |
| `tgEnabledEvents` | `login.attempt,cpu.high`| Какие события доставлять. |
<Callout type="warn">
Токен бота управляет вашим ботом — храните его в секрете и добавляйте только
**доверенные** админские chat ID. Оповещения о входе никогда не содержат
паролей.
</Callout>
<Callout type="info">
Уведомления по электронной почте (SMTP) дублируют те же события
(`smtpEnabledEvents`), если вы предпочитаете получать оповещения на почту —
настройте SMTP в настройках панели.
</Callout>