Files
3x-ui/docs/content/docs/en/operations/discord-bot.mdx
T
Egor bf7ce2daaa feat(discord): add Discord notification bot service (#6486)
* 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>
2026-09-13 14:04:53 +02:00

122 lines
6.9 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
title: Discord Bot
description: Connect a Discord bot to 3x-ui to receive real-time Embed notifications in a channel for panel events (service crashes, node status, CPU/RAM load, and login attempts).
icon: Bot
---
3x-ui provides comprehensive Discord integration: real-time event notifications via the event bus (`EventBus`), periodic scheduled health reports with database backups, and interactive commands via the Discord Gateway.
<Callout type="info">
Discord notifications and scheduled reports use outbound HTTPS REST API v10 calls. Interactive bot commands connect via a secure background WebSocket connection to the Discord Gateway.
</Callout>
## Set it up
<Steps>
<Step>
### Create a Discord Application & Bot
1. Open the [Discord Developer Portal](https://discord.com/developers/applications) and sign in.
2. Click **New Application** at the top right, enter a name (e.g., `3x-ui Notifier`), and confirm.
3. In the left sidebar, navigate to the **Bot** tab.
4. Click **Reset Token** (or **Add Bot** if not already created) and copy the **Bot Token**. Keep this token secure.
5. Under **Privileged Gateway Intents**, toggle on **Message Content Intent** (required for the bot to read prefix commands like `!status`).
</Step>
<Step>
### Invite the Bot to your Discord Server
1. In the Discord Developer Portal, navigate to **OAuth2** $\rightarrow$ **URL Generator**.
2. Under **Scopes**, check `bot`.
3. Under **Bot Permissions**, select:
- **Send Messages**
- **Embed Links**
- **Attach Files** (required for database backups)
- **Read Message History**
4. Copy the generated URL at the bottom and open it in your browser to invite the bot to your server.
</Step>
<Step>
### Copy the Channel ID
1. In your Discord client, enable Developer Mode: **User Settings** $\rightarrow$ **Advanced** $\rightarrow$ **Developer Mode** (toggle on).
2. Right-click the channel where you want alerts and bot interaction to occur and select **Copy Channel ID**.
3. Ensure the bot has access to view and send messages in this specific channel.
</Step>
<Step>
### Configure the Panel
1. In the 3x-ui panel, open **Panel Settings** $\rightarrow$ **Discord Bot** (or navigate to `/settings#discord`).
2. Under **General**:
- Toggle **Enable Discord Notifications** on.
- Enter your **Discord Bot Token** and **Channel ID**.
- Enter your own Discord user ID in **Admin User IDs** (right-click your name → **Copy User ID**; separate several IDs with commas).
- Select your preferred **Discord Bot Language**.
3. Under **Notifications**:
- Set the **Notification Time** schedule (e.g., `@daily`, `@weekly`, or custom crontab).
- Optionally toggle **Database Backups** to automatically attach `x-ui.db` with periodic reports.
- Select which events trigger notifications and adjust CPU/RAM thresholds.
4. Click **Send Test Notification** to verify delivery. A test embed will immediately appear in your Discord channel.
5. Click **Save** to apply changes.
</Step>
</Steps>
## Bot Commands
When enabled, the bot listens to commands in the configured Discord channel (supporting both `!` and `/` prefixes). Only users listed in **Admin User IDs** can run them; messages from anyone else are ignored, and an empty list turns commands off. `!backup` and scheduled backups post the database into the channel, so pick a channel only admins can read:
| Command | Description |
| ------- | ----------- |
| `!status` | Display system load, RAM, CPU usage, TCP/UDP connections, and active clients. |
| `!report` | Generate and send a complete status report embed immediately. |
| `!backup` | Download current database backup file (`x-ui.db`) and `config.json`. |
| `!usage <email>` | Query bandwidth usage (upload/download), quota limit, and expiration date for a client. |
| `!inbounds` | List all active inbounds with port, protocol, traffic, and client counts. |
| `!restart` | Safely restart the Xray core without restarting the web panel. |
| `!help` | Display list of available bot commands. |
## Event Alerts
Alerts are sent as Discord Embeds with color coding and relevant diagnostics:
| Event | Indicator | Description |
| ----- | --------- | ----------- |
| `xray.crash` | 🔴 Red | Xray-core crashed; includes reason and timestamp |
| `outbound.down` | 🔴 Red | Outbound connectivity test failed |
| `outbound.up` | 🟢 Green | Outbound connectivity restored |
| `node.down` | 🔴 Red | Remote sub-node offline or unreachable |
| `node.up` | 🟢 Green | Remote sub-node reconnected and healthy |
| `cpu.high` | 🟠 Orange | Host CPU usage exceeded configured threshold (`discordCpu`) |
| `memory.high` | 🟠 Orange | Host memory usage exceeded configured threshold (`discordMemory`) |
| `login.attempt` | 🟢 / 🔴 | Web panel login attempt with username, IP, and status |
<Callout type="warn">
Login alerts report the attempted username and client IP address. Passwords are never logged or transmitted.
</Callout>
## Settings Reference
| Setting | Default | Description |
| ------- | ------- | ----------- |
| `discordBotEnable` | `false` | Master toggle for Discord bot and notifications. |
| `discordBotToken` | _(secret)_ | Discord Bot token from Developer Portal. |
| `discordChannelId` | _(none)_ | Target Discord channel snowflake ID (17–20 digits). |
| `discordAdminIds` | _(none)_ | Comma-separated Discord user IDs allowed to run bot commands. Empty turns commands off. |
| `discordLang` | `en-US` | Language for Discord bot messages and reports. |
| `discordRunTime` | `@daily` | Cron expression or interval for periodic status reports. |
| `discordBotBackup` | `false` | Whether to attach database backup (`x-ui.db`) to reports. |
| `discordEnabledEvents` | `login.attempt,cpu.high` | Comma-separated list of enabled event types. |
| `discordCpu` | `80` | CPU utilization percentage threshold for alerts (0–100). |
| `discordMemory` | `80` | RAM utilization percentage threshold for alerts (0–100). |
## Troubleshooting
- **Test fails with "invalid bot token (401)"**: Verify that you copied the full Bot Token from the **Bot** tab in Developer Portal, not the Client Secret or Application ID.
- **Test fails with "missing permissions (403)"**: Ensure the bot role has **Send Messages**, **Embed Links**, and **Attach Files** permissions in the target channel or category.
- **Commands do not respond**: Check that your Discord user ID is listed in **Admin User IDs**. Then ensure **Message Content Intent** is enabled under the **Bot** tab in Discord Developer Portal and restart the panel: Discord closes the connection for good when the intent is missing, so the bot does not retry on its own.
- **Test fails with "channel not found (404)"**: Verify the numeric Channel ID. Ensure the bot is present in the server that owns the channel.
- **Proxying outbound requests**: If your host requires a proxy to connect to Discord, configure **Panel Outbound** in Panel Settings. Discord requests automatically route through the configured panel outbound proxy.