mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-10-06 22:22:08 +03:00
bf7ce2daaa
* feat(discord): add Discord notification bot service, settings UI, and event subscriber - internal/web/service/discord: implement lightweight Discord REST API v10 client and EventBus subscriber - internal/web/service/setting: add discordBotEnable, discordBotToken, discordChannelId, discordEnabledEvents, discordCpu, discordMemory settings and secret protection - internal/web/controller: register POST /panel/api/setting/testDiscord endpoint - frontend: add Discord settings tab, notifications configuration, sidebar navigation, and command palette integration - translation: add localization keys across all 13 locales - tests: add comprehensive unit tests with httptest server and verify route/i18n contracts * fix(discord): address PR review findings on concurrency, linting, i18n, and stories - subscriber: eliminate unbounded goroutines, sending inline per EventBus contract - discord: accept context.Context in SendMessage, SendEmbed, SendTest with http.NewRequestWithContext - format: apply gofumpt to controller and entity struct alignments - i18n: localize testDiscord controller responses across all 13 locales - storybook: add DiscordNotifications.stories.tsx component story * docs: add Discord bot setup and operations guide - add docs/content/docs/en/operations/discord-bot.mdx with setup steps, event indicators, settings, and troubleshooting - add docs/content/docs/ru/operations/discord-bot.mdx with localized instructions - update operations/meta.json across en, ru, zh, fa - link Discord bot from panel configuration overview * feat(discord): add discordLang, discordRunTime, discordBotBackup settings and update settings UI - internal/web/entity: add DiscordRunTime, DiscordBotBackup, DiscordLang fields to AllSetting - internal/web/service/setting: add defaultValueMap entries, getters, and setters - frontend: update AllSetting schema, model defaults, and generate OpenAPI / Zod contracts - frontend: extract shared NotifyTimeField component and update DiscordTab with General and Notifications tabs - translation: add localization keys across all 13 locales * feat(discord): implement scheduled status reports and database backup attachments - internal/web/service/discord: add SendMessageWithFiles supporting multipart uploads - internal/web/service/discord: implement BuildReport and SendReport generating rich status embeds - internal/web/service/discord: attach database backup (and config.json) when discordBotBackup is enabled - internal/web/job: implement DiscordNotifyJob scheduled via robfig/cron - internal/web/locale: add LocalizerFor and I18nForLang helpers - internal/web/controller: trigger reloadDiscordFunc to dynamically reschedule cron upon setting changes - internal/web/web: register and reschedule DiscordNotifyJob - tests: comprehensive unit tests for multipart uploads, status reporting, and job execution * feat(discord): add interactive bot commands via Gateway WebSocket and update documentation - internal/web/service/discord/gateway: connect to Discord Gateway v10 via WebSocket (gorilla/websocket) - internal/web/service/discord/gateway: handle heartbeat loop, reconnection, and command dispatch - commands: implement !status, !report, !backup, !usage <email>, !inbounds, !restart, !help (with ! and / prefixes) - internal/web/web: start/stop Gateway client with server and reload dynamically on setting updates - docs: update operations guide (en, ru) with scheduled reports, backups, commands, and privileged intents - tests: add end-to-end WebSocket Gateway test verifying command handling * style(discord): fix goimports formatting and add 3x-ui to gitignore * fix(discord): stop gateway panics, reconnect storms and proxy bypass The Gateway client wrote to its websocket from both the heartbeat ticker and the read loop answering server-requested op 1 heartbeats. gorilla panics on concurrent writes and neither goroutine recovers, so a colliding heartbeat took the whole panel process down; writes now share writeMu. It also reconnected every 5s forever after close codes Discord marks non-reconnectable (4004 bad token, 4010-4014, including 4014 when Message Content Intent is off), re-identifying and logging a warning each time. The loop now stops on those codes; the docs say to restart the panel. The gateway dialed with websocket.DefaultDialer, bypassing the panel egress proxy the REST client already uses, so where Discord is filtered notifications arrived but commands never connected. * fix(discord): deliver the scheduled report when the backup upload fails SendReport posted the report embed and the x-ui.db/config.json attachments in one multipart request. Once the database outgrows Discord's upload cap (20 MiB by default) the request is rejected and the report embed is lost with it on every run, leaving only a log warning. Send the embed first and the attachments as a second message. * chore(discord): delete tests that pass whether or not the code works TestDiscordNotifyJob_NilServiceNoPanic and TestHandleEvent_NilDiscordService feed a nil DiscordService that web.go never passes, and TestDiscordNotifyJob_DisabledNoPanic passes with or without the enable guard because Xray is not running under test. * fix(discord): require admin user IDs for bot commands and honor discordLang Any member who could post in the configured channel could run !backup (the whole x-ui.db and config.json, even with discordBotBackup off), !restart and !usage. Commands now run only for the Discord user IDs in the new discordAdminIds setting; an empty list turns commands off. discordLang was saved and offered in the UI, but nothing read it, so every embed stayed English. The test message, alerts, the scheduled report and command replies now render through I18nForLang in the chosen language, with a discord section in all 13 locales. InitLocalizer takes an fs.FS so tests load the real translation files. --------- Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
122 lines
12 KiB
Plaintext
122 lines
12 KiB
Plaintext
---
|
||
title: Discord-бот
|
||
description: Подключите Discord-бота к 3x-ui для получения оповещений о событиях панели (сбои сервисов, доступность узлов, нагрузка CPU/RAM и попытки входа) прямо в канал Discord.
|
||
icon: Bot
|
||
---
|
||
|
||
3x-ui предоставляет полную интеграцию с Discord: мгновенные уведомления о событиях через шину событий панели (`EventBus`), периодические отчёты о состоянии сервера с резервным копированием базы данных, а также интерактивные команды через Discord Gateway.
|
||
|
||
<Callout type="info">
|
||
Уведомления и периодические отчёты отправляются через исходящие HTTPS-запросы к REST API Discord v10. Интерактивные команды бота работают через постоянное защищённое WebSocket-соединение с Discord Gateway.
|
||
</Callout>
|
||
|
||
## Настройка
|
||
|
||
<Steps>
|
||
|
||
<Step>
|
||
### Создайте приложение и бота в Discord
|
||
|
||
1. Откройте [Discord Developer Portal](https://discord.com/developers/applications) и авторизуйтесь.
|
||
2. Нажмите **New Application** в правом верхнем углу, укажите имя (например, `3x-ui Notifier`) и подтвердите создание.
|
||
3. В боковом меню перейдите во вкладку **Bot**.
|
||
4. Нажмите **Reset Token** (или **Add Bot**, если бот ещё не создан) и скопируйте **Bot Token**. Сохраните токен в надёжном месте.
|
||
5. В блоке **Privileged Gateway Intents** включите переключатель **Message Content Intent** (необходимо, чтобы бот мог читать команды вида `!status`).
|
||
</Step>
|
||
|
||
<Step>
|
||
### Пригласите бота на свой сервер Discord
|
||
|
||
1. В Developer Portal перейдите в раздел **OAuth2** $\rightarrow$ **URL Generator**.
|
||
2. В блоке **Scopes** отметьте галочкой `bot`.
|
||
3. В блоке **Bot Permissions** выберите:
|
||
- **Send Messages** (Отправка сообщений)
|
||
- **Embed Links** (Встраивание ссылок / Embeds)
|
||
- **Attach Files** (Прикрепление файлов — необходимо для резервных копий БД)
|
||
- **Read Message History** (Чтение истории сообщений)
|
||
4. Скопируйте полученную ссылку внизу страницы, откройте её в браузере и добавьте бота на нужный сервер.
|
||
</Step>
|
||
|
||
<Step>
|
||
### Скопируйте ID канала (Channel ID)
|
||
|
||
1. В клиенте Discord включите режим разработчика: **Настройки пользователя** $\rightarrow$ **Расширенные** $\rightarrow$ **Режим разработчика** (Developer Mode).
|
||
2. Нажмите правой кнопкой мыши по каналу, куда должны приходить уведомления и команды, и выберите **Копировать ID канала**.
|
||
3. Убедитесь, что у бота есть права на просмотр и отправку сообщений в этот канал.
|
||
</Step>
|
||
|
||
<Step>
|
||
### Настройте панель 3x-ui
|
||
|
||
1. В веб-интерфейсе 3x-ui перейдите в **Настройки панели** $\rightarrow$ **Discord Bot** (или перейдите по адресу `/settings#discord`).
|
||
2. Во вкладке **Основные настройки**:
|
||
- Включите **Включить уведомления Discord**.
|
||
- Укажите **Токен Discord-бота** и **ID канала**.
|
||
- Укажите свой ID пользователя Discord в поле **ID администраторов** (правый клик по своему имени → **Копировать ID пользователя**; несколько ID разделяйте запятыми).
|
||
- Выберите **Язык Discord-бота**.
|
||
3. Во вкладке **Уведомления**:
|
||
- Настройте **Частоту уведомлений** (например, `@daily`, `@weekly` или произвольное выражение crontab).
|
||
- При необходимости включите **Резервное копирование базы данных**, чтобы отчёт сопровождался файлом `x-ui.db`.
|
||
- Выберите отслеживаемые события и настройте пороги нагрузки CPU/RAM.
|
||
4. Нажмите **Отправить тестовое сообщение**, чтобы проверить доставку. В канале Discord появится тестовое Embed-сообщение.
|
||
5. Нажмите **Сохранить** для применения настроек.
|
||
</Step>
|
||
|
||
</Steps>
|
||
|
||
## Команды бота
|
||
|
||
Когда бот включён, он принимает текстовые команды в настроенном канале (поддерживаются префиксы `!` и `/`). Выполнять их могут только пользователи из списка **ID администраторов**; сообщения остальных игнорируются, а при пустом списке команды отключены. `!backup` и плановые резервные копии публикуют базу данных в канал, поэтому выбирайте канал, доступный только администраторам:
|
||
|
||
| Команда | Описание |
|
||
| ------- | -------- |
|
||
| `!status` | Вывести нагрузку системы, память, процессор, число соединений и активных клиентов. |
|
||
| `!report` | Немедленно сгенерировать и отправить подробный отчёт о состоянии сервера. |
|
||
| `!backup` | Отправить файл резервной копии базы данных (`x-ui.db`) и `config.json`. |
|
||
| `!usage <email>` | Запросить статистику трафика (Upload/Download), лимит и срок действия клиента. |
|
||
| `!inbounds` | Показать список всех активных подключений (порты, протоколы, клиенты, трафик). |
|
||
| `!restart` | Перезапустить ядро Xray без перезапуска веб-панели. |
|
||
| `!help` | Показать справку по доступным командам. |
|
||
|
||
## Оповещения о событиях
|
||
|
||
Уведомления приходят в виде Embed-карточек с цветовым обозначением важности:
|
||
|
||
| Событие | Индикатор | Описание |
|
||
| ------- | --------- | -------- |
|
||
| `xray.crash` | 🔴 Красный | Сбой процесса Xray-core с указанием причины и времени |
|
||
| `outbound.down` | 🔴 Красный | Неудачная проверка доступности исходящего соединения (outbound) |
|
||
| `outbound.up` | 🟢 Зеленый | Восстановление доступности исходящего соединения |
|
||
| `node.down` | 🔴 Красный | Удалённый под-узел (node) отключился или недоступен |
|
||
| `node.up` | 🟢 Зеленый | Удалённый под-узел снова в сети и готов к работе |
|
||
| `cpu.high` | 🟠 Оранжевый | Нагрузка процессора превысила заданный порог (`discordCpu`) |
|
||
| `memory.high` | 🟠 Оранжевый | Использование оперативной памяти превысило порог (`discordMemory`) |
|
||
| `login.attempt` | 🟢 / 🔴 | Попытка авторизации в панели (с указанием IP и логина) |
|
||
|
||
<Callout type="warn">
|
||
Оповещения о входе содержат только введённое имя пользователя и IP-адрес. Пароли никогда не логируются и не передаются.
|
||
</Callout>
|
||
|
||
## Параметры конфигурации
|
||
|
||
| Параметр | По умолчанию | Описание |
|
||
| -------- | ------------ | -------- |
|
||
| `discordBotEnable` | `false` | Главный переключатель бота и уведомлений Discord. |
|
||
| `discordBotToken` | _(секрет)_ | Токен бота из Discord Developer Portal. |
|
||
| `discordChannelId` | _(пусто)_ | Идентификатор канала Discord (17–20 цифр). |
|
||
| `discordAdminIds` | _(пусто)_ | ID пользователей Discord через запятую, которым разрешено выполнять команды бота. Пустой список отключает команды. |
|
||
| `discordLang` | `en-US` | Язык сообщений и отчётов бота. |
|
||
| `discordRunTime` | `@daily` | Расписание генерации периодических отчётов (crontab). |
|
||
| `discordBotBackup` | `false` | Отправлять ли файл резервной копии базы данных (`x-ui.db`) вместе с отчётом. |
|
||
| `discordEnabledEvents` | `login.attempt,cpu.high` | Список отслеживаемых событий через запятую. |
|
||
| `discordCpu` | `80` | Порог нагрузки процессора для алерта (в процентах, 0–100). |
|
||
| `discordMemory` | `80` | Порог использования RAM для алерта (в процентах, 0–100). |
|
||
|
||
## Устранение неполадок
|
||
|
||
- **Ошибка "invalid bot token (401)"**: Проверьте, что вы скопировали именно Bot Token из раздела **Bot**, а не Client Secret или Application ID.
|
||
- **Ошибка "missing permissions (403)"**: Проверьте, выданы ли роли бота права **Send Messages**, **Embed Links** и **Attach Files** в целевом канале или категории каналов.
|
||
- **Бот не реагирует на команды**: Проверьте, что ваш ID пользователя Discord указан в **ID администраторов**. Затем убедитесь, что в Discord Developer Portal в разделе **Bot** включен **Message Content Intent**, и перезапустите панель: без этого разрешения Discord окончательно закрывает соединение, и бот не переподключается сам.
|
||
- **Ошибка "channel not found (404)"**: Проверьте правильность числового Channel ID и убедитесь, что бот состоит на сервере, которому принадлежит канал.
|
||
- **Проксирование запросов**: Если сервер не имеет прямого доступа к серверам Discord, настройте исходящий прокси в **Настройках панели** (**Исходящий трафик панели** / `panelOutbound`). Запросы бота будут автоматически направляться через этот прокси.
|