Files
3x-ui/internal/web/service/discord/subscriber.go
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

339 lines
8.5 KiB
Go

package discord
import (
"context"
"fmt"
"os"
"strings"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/eventbus"
"github.com/mhsanaei/3x-ui/v3/internal/logger"
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
)
// Subscriber handles event bus messages and forwards them to Discord.
type Subscriber struct {
settingService service.SettingService
discordService *DiscordService
limiter *eventbus.RateLimiter
}
// NewSubscriber creates a new Discord event subscriber.
func NewSubscriber(settingService service.SettingService, discordService *DiscordService) *Subscriber {
return &Subscriber{
settingService: settingService,
discordService: discordService,
limiter: eventbus.NewRateLimiter(1 * time.Minute),
}
}
// HandleEvent is the eventbus subscriber callback.
func (s *Subscriber) HandleEvent(e eventbus.Event) {
if s.discordService == nil {
return
}
if on, err := s.settingService.GetDiscordBotEnable(); err != nil || !on {
return
}
if !s.isEventEnabled(e.Type) {
return
}
embed, ok := s.FormatEmbed(e)
if !ok {
return
}
if e.Type != eventbus.EventLoginAttempt {
if !s.limiter.Allow(e.Type, e.Source) {
return
}
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := s.discordService.SendEmbed(ctx, embed); err != nil {
logger.Warning("discord subscriber: send failed:", err)
}
}
func (s *Subscriber) isEventEnabled(t eventbus.EventType) bool {
events, err := s.settingService.GetDiscordEnabledEvents()
if err != nil || events == "" {
return false
}
for e := range strings.SplitSeq(events, ",") {
if strings.TrimSpace(e) == string(t) {
return true
}
}
return false
}
func truncateRunes(s string, maxRunes int) string {
r := []rune(s)
if len(r) <= maxRunes {
return s
}
if maxRunes <= 3 {
return string(r[:maxRunes])
}
return string(r[:maxRunes-3]) + "..."
}
func cleanField(name, value string, inline bool) EmbedField {
name = strings.TrimSpace(name)
if name == "" {
name = "-"
} else {
name = truncateRunes(name, 256)
}
value = strings.TrimSpace(value)
if value == "" {
value = "-"
} else {
value = truncateRunes(value, 1024)
}
return EmbedField{
Name: name,
Value: value,
Inline: inline,
}
}
// FormatEmbed converts an eventbus.Event into a Discord Embed.
// Returns false if the event should not produce a message (e.g. thresholds not exceeded).
func (s *Subscriber) FormatEmbed(e eventbus.Event) (Embed, bool) {
h, _ := os.Hostname()
if h == "" {
h = "unknown"
}
var ts string
if e.Timestamp.IsZero() {
ts = time.Now().UTC().Format(time.RFC3339)
} else {
ts = e.Timestamp.UTC().Format(time.RFC3339)
}
footer := &EmbedFooter{
Text: truncateRunes("3x-ui • "+h, 2048),
}
tr := translator(s.settingService)
switch e.Type {
case eventbus.EventOutboundDown:
fields := []EmbedField{
cleanField(tr("discord.fields.outbound"), e.Source, true),
}
var data *eventbus.OutboundHealthData
switch d := e.Data.(type) {
case *eventbus.OutboundHealthData:
data = d
case eventbus.OutboundHealthData:
data = &d
}
if data != nil {
if data.Error != "" {
fields = append(fields, cleanField(tr("discord.fields.error"), data.Error, false))
}
if data.Delay > 0 {
fields = append(fields, cleanField(tr("discord.fields.delay"), fmt.Sprintf("%dms", data.Delay), true))
}
}
return Embed{
Title: tr("discord.alerts.outboundDown"),
Color: ColorRed,
Timestamp: ts,
Fields: fields,
Footer: footer,
}, true
case eventbus.EventOutboundUp:
fields := []EmbedField{
cleanField(tr("discord.fields.outbound"), e.Source, true),
}
var data *eventbus.OutboundHealthData
switch d := e.Data.(type) {
case *eventbus.OutboundHealthData:
data = d
case eventbus.OutboundHealthData:
data = &d
}
if data != nil && data.Delay > 0 {
fields = append(fields, cleanField(tr("discord.fields.delay"), fmt.Sprintf("%dms", data.Delay), true))
}
return Embed{
Title: tr("discord.alerts.outboundUp"),
Color: ColorGreen,
Timestamp: ts,
Fields: fields,
Footer: footer,
}, true
case eventbus.EventNodeDown:
fields := []EmbedField{
cleanField(tr("discord.fields.node"), e.Source, true),
}
var data *eventbus.NodeHealthData
switch d := e.Data.(type) {
case *eventbus.NodeHealthData:
data = d
case eventbus.NodeHealthData:
data = &d
}
if data != nil && data.XrayError != "" {
fields = append(fields, cleanField(tr("discord.fields.error"), data.XrayError, false))
}
return Embed{
Title: tr("discord.alerts.nodeDown"),
Color: ColorRed,
Timestamp: ts,
Fields: fields,
Footer: footer,
}, true
case eventbus.EventNodeUp:
fields := []EmbedField{
cleanField(tr("discord.fields.node"), e.Source, true),
}
var data *eventbus.NodeHealthData
switch d := e.Data.(type) {
case *eventbus.NodeHealthData:
data = d
case eventbus.NodeHealthData:
data = &d
}
if data != nil && data.LatencyMs > 0 {
fields = append(fields, cleanField(tr("discord.fields.delay"), fmt.Sprintf("%dms", data.LatencyMs), true))
}
return Embed{
Title: tr("discord.alerts.nodeUp"),
Color: ColorGreen,
Timestamp: ts,
Fields: fields,
Footer: footer,
}, true
case eventbus.EventXrayCrash:
var fields []EmbedField
if e.Data != nil {
fields = append(fields, cleanField(tr("discord.fields.error"), fmt.Sprint(e.Data), false))
}
return Embed{
Title: tr("discord.alerts.xrayCrash"),
Color: ColorRed,
Timestamp: ts,
Fields: fields,
Footer: footer,
}, true
case eventbus.EventCPUHigh:
var data *eventbus.SystemMetricData
switch d := e.Data.(type) {
case *eventbus.SystemMetricData:
data = d
case eventbus.SystemMetricData:
data = &d
}
if data != nil {
discordCpu, err := s.settingService.GetDiscordCpu()
if err != nil || discordCpu <= 0 || data.Percent <= float64(discordCpu) {
return Embed{}, false
}
fields := []EmbedField{
cleanField(tr("usage"), fmt.Sprintf("%.2f%%", data.Percent), true),
cleanField(tr("discord.fields.threshold"), fmt.Sprintf("%d%%", discordCpu), true),
}
return Embed{
Title: tr("discord.alerts.cpuHigh"),
Color: ColorOrange,
Timestamp: ts,
Fields: fields,
Footer: footer,
}, true
}
return Embed{}, false
case eventbus.EventMemoryHigh:
var data *eventbus.SystemMetricData
switch d := e.Data.(type) {
case *eventbus.SystemMetricData:
data = d
case eventbus.SystemMetricData:
data = &d
}
if data != nil {
discordMem, err := s.settingService.GetDiscordMemory()
if err != nil || discordMem <= 0 || data.Percent <= float64(discordMem) {
return Embed{}, false
}
fields := []EmbedField{
cleanField(tr("usage"), fmt.Sprintf("%.2f%%", data.Percent), true),
cleanField(tr("discord.fields.threshold"), fmt.Sprintf("%d%%", discordMem), true),
}
return Embed{
Title: tr("discord.alerts.memoryHigh"),
Color: ColorOrange,
Timestamp: ts,
Fields: fields,
Footer: footer,
}, true
}
return Embed{}, false
case eventbus.EventLoginAttempt:
var data *eventbus.LoginEventData
switch d := e.Data.(type) {
case *eventbus.LoginEventData:
data = d
case eventbus.LoginEventData:
data = &d
}
if data != nil {
if data.Status == "success" {
fields := []EmbedField{
cleanField(tr("username"), data.Username, true),
cleanField("IP", data.IP, true),
}
if data.Time != "" {
fields = append(fields, cleanField(tr("discord.fields.time"), data.Time, true))
}
return Embed{
Title: tr("discord.alerts.loginSuccess"),
Color: ColorGreen,
Timestamp: ts,
Fields: fields,
Footer: footer,
}, true
}
fields := []EmbedField{
cleanField(tr("username"), data.Username, true),
cleanField("IP", data.IP, true),
}
if data.Reason != "" {
fields = append(fields, cleanField(tr("discord.fields.reason"), data.Reason, false))
}
if data.Time != "" {
fields = append(fields, cleanField(tr("discord.fields.time"), data.Time, true))
}
return Embed{
Title: tr("discord.alerts.loginFailed"),
Color: ColorRed,
Timestamp: ts,
Fields: fields,
Footer: footer,
}, true
}
fields := []EmbedField{
cleanField(tr("discord.fields.source"), e.Source, true),
}
return Embed{
Title: tr("discord.alerts.loginFailed"),
Color: ColorRed,
Timestamp: ts,
Fields: fields,
Footer: footer,
}, true
}
return Embed{}, false
}