gateway.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694
  1. package discord
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "net/http"
  8. "net/url"
  9. "os"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "sync/atomic"
  14. "time"
  15. "github.com/gorilla/websocket"
  16. "github.com/mhsanaei/3x-ui/v3/internal/config"
  17. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  18. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  19. "github.com/mhsanaei/3x-ui/v3/internal/web/service"
  20. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  21. )
  22. const (
  23. defaultGatewayURL = "wss://gateway.discord.gg/?v=10&encoding=json"
  24. opDispatch = 0
  25. opHeartbeat = 1
  26. opIdentify = 2
  27. opHello = 10
  28. opHeartbeatACK = 11
  29. // GUILDS (1<<0) | GUILD_MESSAGES (1<<9) | DIRECT_MESSAGES (1<<12) | MESSAGE_CONTENT (1<<15)
  30. discordIntents = 37377
  31. )
  32. // GatewayPayload represents a Discord Gateway WebSocket frame.
  33. type GatewayPayload struct {
  34. Op int `json:"op"`
  35. D json.RawMessage `json:"d,omitempty"`
  36. S *int64 `json:"s,omitempty"`
  37. T string `json:"t,omitempty"`
  38. }
  39. // HelloData represents the payload received in Opcode 10 Hello.
  40. type HelloData struct {
  41. HeartbeatInterval int `json:"heartbeat_interval"`
  42. }
  43. // IdentifyData represents the payload sent in Opcode 2 Identify.
  44. type IdentifyData struct {
  45. Token string `json:"token"`
  46. Intents int `json:"intents"`
  47. Properties IdentifyProperties `json:"properties"`
  48. }
  49. // IdentifyProperties metadata for Discord identification.
  50. type IdentifyProperties struct {
  51. OS string `json:"os"`
  52. Browser string `json:"browser"`
  53. Device string `json:"device"`
  54. }
  55. // MessageCreateData represents incoming message data from Discord.
  56. type MessageCreateData struct {
  57. ID string `json:"id"`
  58. ChannelID string `json:"channel_id"`
  59. Content string `json:"content"`
  60. Author struct {
  61. ID string `json:"id"`
  62. Username string `json:"username"`
  63. Bot bool `json:"bot"`
  64. } `json:"author"`
  65. }
  66. // XrayRestartProvider abstracts restarting the core.
  67. type XrayRestartProvider interface {
  68. RestartXray(force bool) error
  69. }
  70. // GatewayClient manages the Discord Gateway WebSocket connection for interactive commands.
  71. type GatewayClient struct {
  72. discordService *DiscordService
  73. settingService service.SettingService
  74. serverService ServerProvider
  75. inboundService InboundProvider
  76. xrayService XrayRestartProvider
  77. gatewayURL string
  78. egressProxyURL func() string
  79. mu sync.Mutex
  80. writeMu sync.Mutex // gorilla panics on concurrent writes; the ticker and op 1 replies both write
  81. conn *websocket.Conn
  82. cancel context.CancelFunc
  83. running bool
  84. lastSeq *int64
  85. }
  86. // NewGatewayClient creates a new Discord Gateway client instance.
  87. func NewGatewayClient(
  88. discordService *DiscordService,
  89. settingService service.SettingService,
  90. server ServerProvider,
  91. inbound InboundProvider,
  92. xray XrayRestartProvider,
  93. ) *GatewayClient {
  94. return &GatewayClient{
  95. discordService: discordService,
  96. settingService: settingService,
  97. serverService: server,
  98. inboundService: inbound,
  99. xrayService: xray,
  100. gatewayURL: defaultGatewayURL,
  101. egressProxyURL: settingService.PanelEgressProxyURL,
  102. }
  103. }
  104. // SetGatewayURL overrides the gateway URL for testing.
  105. func (g *GatewayClient) SetGatewayURL(url string) {
  106. g.gatewayURL = url
  107. }
  108. // IsRunning reports whether the Gateway client is active.
  109. func (g *GatewayClient) IsRunning() bool {
  110. g.mu.Lock()
  111. defer g.mu.Unlock()
  112. return g.running
  113. }
  114. // Start begins the Gateway connection and listening loop.
  115. func (g *GatewayClient) Start(parentCtx context.Context) error {
  116. g.mu.Lock()
  117. if g.running {
  118. g.mu.Unlock()
  119. return nil
  120. }
  121. ctx, cancel := context.WithCancel(parentCtx)
  122. g.cancel = cancel
  123. g.running = true
  124. g.mu.Unlock()
  125. go func() {
  126. defer func() {
  127. g.mu.Lock()
  128. g.running = false
  129. g.mu.Unlock()
  130. }()
  131. for {
  132. select {
  133. case <-ctx.Done():
  134. return
  135. default:
  136. }
  137. enabled, err := g.settingService.GetDiscordBotEnable()
  138. if err != nil || !enabled {
  139. return
  140. }
  141. err = g.connectAndListen(ctx)
  142. // Discord marks these close codes non-reconnectable: a bad token or an intent not enabled in the portal.
  143. if websocket.IsCloseError(err, 4004, 4010, 4011, 4012, 4013, 4014) {
  144. logger.Warning("Discord Gateway closed for good: ", err, "; not reconnecting until the bot token changes, the bot is re-enabled or the panel restarts")
  145. return
  146. }
  147. if err != nil && ctx.Err() == nil {
  148. logger.Warning("Discord Gateway disconnected: ", err, "; reconnecting in 5s...")
  149. select {
  150. case <-ctx.Done():
  151. return
  152. case <-time.After(5 * time.Second):
  153. }
  154. }
  155. }
  156. }()
  157. return nil
  158. }
  159. // Stop terminates the Gateway connection cleanly.
  160. func (g *GatewayClient) Stop() {
  161. g.mu.Lock()
  162. defer g.mu.Unlock()
  163. if !g.running {
  164. return
  165. }
  166. if g.cancel != nil {
  167. g.cancel()
  168. }
  169. if g.conn != nil {
  170. _ = g.conn.Close()
  171. }
  172. g.running = false
  173. }
  174. func (g *GatewayClient) writeJSON(conn *websocket.Conn, v any) error {
  175. g.writeMu.Lock()
  176. defer g.writeMu.Unlock()
  177. return conn.WriteJSON(v)
  178. }
  179. func (g *GatewayClient) connectAndListen(ctx context.Context) error {
  180. token, err := g.settingService.GetDiscordBotToken()
  181. if err != nil || strings.TrimSpace(token) == "" {
  182. return errors.New("discord bot token not configured")
  183. }
  184. cleanToken := strings.TrimSpace(token)
  185. cleanToken = strings.TrimPrefix(cleanToken, "Bot ")
  186. cleanToken = strings.TrimSpace(cleanToken)
  187. dialer := *websocket.DefaultDialer
  188. if raw := g.egressProxyURL(); raw != "" {
  189. proxyURL, err := url.Parse(raw)
  190. if err != nil {
  191. return fmt.Errorf("parse panel egress proxy: %w", err)
  192. }
  193. dialer.Proxy = http.ProxyURL(proxyURL)
  194. }
  195. conn, resp, err := dialer.DialContext(ctx, g.gatewayURL, nil)
  196. if err != nil {
  197. if resp != nil && resp.Body != nil {
  198. _ = resp.Body.Close()
  199. }
  200. return fmt.Errorf("dial discord gateway: %w", err)
  201. }
  202. g.mu.Lock()
  203. g.conn = conn
  204. g.mu.Unlock()
  205. defer func() {
  206. _ = conn.Close()
  207. g.mu.Lock()
  208. if g.conn == conn {
  209. g.conn = nil
  210. }
  211. g.mu.Unlock()
  212. }()
  213. // 1. Read Hello opcode 10
  214. var helloPayload GatewayPayload
  215. if err := conn.ReadJSON(&helloPayload); err != nil {
  216. return fmt.Errorf("read hello payload: %w", err)
  217. }
  218. if helloPayload.Op != opHello {
  219. return fmt.Errorf("expected opcode 10, got %d", helloPayload.Op)
  220. }
  221. var helloData HelloData
  222. if err := json.Unmarshal(helloPayload.D, &helloData); err != nil {
  223. return fmt.Errorf("unmarshal hello data: %w", err)
  224. }
  225. // 2. Send Identify opcode 2
  226. identifyPayload := GatewayPayload{
  227. Op: opIdentify,
  228. }
  229. identData := IdentifyData{
  230. Token: "Bot " + cleanToken,
  231. Intents: discordIntents,
  232. Properties: IdentifyProperties{
  233. OS: "linux",
  234. Browser: "3x-ui",
  235. Device: "3x-ui",
  236. },
  237. }
  238. dataBytes, _ := json.Marshal(identData)
  239. identifyPayload.D = dataBytes
  240. if err := conn.WriteJSON(identifyPayload); err != nil {
  241. return fmt.Errorf("send identify payload: %w", err)
  242. }
  243. // 3. Heartbeat loop
  244. hbStop := make(chan struct{})
  245. defer close(hbStop)
  246. // Discord answers every heartbeat with op 11; a half-open socket keeps taking
  247. // writes and never answers, so a missing ACK means this one must be dropped.
  248. var acked atomic.Bool
  249. acked.Store(true)
  250. go func() {
  251. interval := time.Duration(helloData.HeartbeatInterval) * time.Millisecond
  252. if interval <= 0 {
  253. interval = 40 * time.Second
  254. }
  255. ticker := time.NewTicker(interval)
  256. defer ticker.Stop()
  257. for {
  258. select {
  259. case <-hbStop:
  260. return
  261. case <-ctx.Done():
  262. return
  263. case <-ticker.C:
  264. if !acked.Swap(false) {
  265. logger.Warning("Discord heartbeats went unanswered; dropping the zombied gateway connection")
  266. _ = conn.Close()
  267. return
  268. }
  269. g.mu.Lock()
  270. seq := g.lastSeq
  271. c := g.conn
  272. g.mu.Unlock()
  273. if c == nil {
  274. return
  275. }
  276. hb := GatewayPayload{Op: opHeartbeat}
  277. if seq != nil {
  278. seqBytes, _ := json.Marshal(*seq)
  279. hb.D = seqBytes
  280. }
  281. if err := g.writeJSON(c, hb); err != nil {
  282. logger.Warning("Discord heartbeat write failed: ", err)
  283. return
  284. }
  285. }
  286. }
  287. }()
  288. // 4. Message dispatch loop
  289. for {
  290. select {
  291. case <-ctx.Done():
  292. return nil
  293. default:
  294. }
  295. var payload GatewayPayload
  296. if err := conn.ReadJSON(&payload); err != nil {
  297. return err
  298. }
  299. if payload.S != nil {
  300. g.mu.Lock()
  301. g.lastSeq = payload.S
  302. g.mu.Unlock()
  303. }
  304. switch payload.Op {
  305. case opHeartbeatACK:
  306. acked.Store(true)
  307. case opHeartbeat:
  308. // Discord requested immediate heartbeat
  309. g.mu.Lock()
  310. seq := g.lastSeq
  311. g.mu.Unlock()
  312. hb := GatewayPayload{Op: opHeartbeat}
  313. if seq != nil {
  314. seqBytes, _ := json.Marshal(*seq)
  315. hb.D = seqBytes
  316. }
  317. _ = g.writeJSON(conn, hb)
  318. case opDispatch:
  319. if payload.T == "MESSAGE_CREATE" {
  320. var msg MessageCreateData
  321. if err := json.Unmarshal(payload.D, &msg); err == nil {
  322. go func(m MessageCreateData) {
  323. defer func() {
  324. if r := recover(); r != nil {
  325. logger.Error("Recovered panic in Discord message handler: ", r)
  326. }
  327. }()
  328. g.handleMessage(ctx, m)
  329. }(msg)
  330. }
  331. }
  332. }
  333. }
  334. }
  335. func (g *GatewayClient) handleMessage(ctx context.Context, msg MessageCreateData) {
  336. if msg.Author.Bot {
  337. return
  338. }
  339. channelID, err := g.settingService.GetDiscordChannelId()
  340. if err != nil || strings.TrimSpace(channelID) == "" {
  341. return
  342. }
  343. if msg.ChannelID != strings.TrimSpace(channelID) {
  344. return
  345. }
  346. content := strings.TrimSpace(msg.Content)
  347. if !strings.HasPrefix(content, "!") && !strings.HasPrefix(content, "/") {
  348. return
  349. }
  350. if !g.isAdmin(msg.Author.ID) {
  351. return
  352. }
  353. parts := strings.Fields(content)
  354. if len(parts) == 0 {
  355. return
  356. }
  357. cmd := strings.ToLower(parts[0])
  358. cmd = strings.TrimLeft(cmd, "!/")
  359. args := parts[1:]
  360. switch cmd {
  361. case "help", "start":
  362. g.sendHelp(ctx)
  363. case "status":
  364. g.sendStatus(ctx)
  365. case "report":
  366. _ = g.discordService.SendReport(ctx, g.serverService, g.inboundService)
  367. case "backup":
  368. g.sendBackup(ctx)
  369. case "usage":
  370. if len(args) == 0 {
  371. _ = g.discordService.SendMessage(ctx, MessagePayload{
  372. Content: translator(g.settingService)("discord.commands.usageHint"),
  373. })
  374. return
  375. }
  376. g.sendUsage(ctx, args[0])
  377. case "inbounds":
  378. g.sendInbounds(ctx)
  379. case "restart":
  380. g.restartXray(ctx)
  381. }
  382. }
  383. // isAdmin reports whether a Discord user is listed in discordAdminIds; an empty list admits nobody.
  384. func (g *GatewayClient) isAdmin(userID string) bool {
  385. ids, err := g.settingService.GetDiscordAdminIds()
  386. if err != nil {
  387. return false
  388. }
  389. for id := range strings.SplitSeq(ids, ",") {
  390. if id = strings.TrimSpace(id); id != "" && id == userID {
  391. return true
  392. }
  393. }
  394. return false
  395. }
  396. func (g *GatewayClient) sendHelp(ctx context.Context) {
  397. tr := translator(g.settingService)
  398. embed := Embed{
  399. Title: tr("discord.commands.helpTitle"),
  400. Description: tr("discord.commands.helpDescription"),
  401. Color: ColorBlue,
  402. Timestamp: time.Now().UTC().Format(time.RFC3339),
  403. Fields: []EmbedField{
  404. {Name: "!status", Value: tr("discord.commands.helpStatus"), Inline: false},
  405. {Name: "!report", Value: tr("discord.commands.helpReport"), Inline: false},
  406. {Name: "!backup", Value: tr("discord.commands.helpBackup"), Inline: false},
  407. {Name: "!usage <email>", Value: tr("discord.commands.helpUsage"), Inline: false},
  408. {Name: "!inbounds", Value: tr("discord.commands.helpInbounds"), Inline: false},
  409. {Name: "!restart", Value: tr("discord.commands.helpRestart"), Inline: false},
  410. {Name: "!help", Value: tr("discord.commands.helpHelp"), Inline: false},
  411. },
  412. Footer: &EmbedFooter{Text: tr("discord.footer")},
  413. }
  414. _ = g.discordService.SendEmbed(ctx, embed)
  415. }
  416. func (g *GatewayClient) sendStatus(ctx context.Context) {
  417. var status *service.Status
  418. if g.serverService != nil {
  419. status = g.serverService.GetStatus(nil)
  420. }
  421. if status == nil {
  422. status = &service.Status{}
  423. }
  424. hostname, _ := os.Hostname()
  425. if hostname == "" {
  426. hostname = "3x-ui"
  427. }
  428. days := status.Uptime / 86400
  429. hours := (status.Uptime % 86400) / 3600
  430. var onlines []string
  431. if process := service.XrayProcess(); process != nil && process.IsRunning() {
  432. onlines = process.GetOnlineClients()
  433. }
  434. load1, load2, load3 := 0.0, 0.0, 0.0
  435. if len(status.Loads) > 0 {
  436. load1 = status.Loads[0]
  437. }
  438. if len(status.Loads) > 1 {
  439. load2 = status.Loads[1]
  440. }
  441. if len(status.Loads) > 2 {
  442. load3 = status.Loads[2]
  443. }
  444. tr := translator(g.settingService)
  445. embed := Embed{
  446. Title: tr("discord.commands.statusTitle"),
  447. Description: tr("discord.commands.statusDescription", "Host=="+hostname),
  448. Color: ColorGreen,
  449. Timestamp: time.Now().UTC().Format(time.RFC3339),
  450. Fields: []EmbedField{
  451. {Name: tr("discord.fields.panelVersion"), Value: config.GetPanelVersion(), Inline: true},
  452. {Name: tr("discord.fields.xrayCore"), Value: fmt.Sprintf("%s (%s)", status.Xray.Version, status.Xray.State), Inline: true},
  453. {Name: tr("pages.index.uptime"), Value: tr("discord.values.uptime", "Days=="+fmt.Sprint(days), "Hours=="+fmt.Sprint(hours)), Inline: true},
  454. {Name: tr("discord.fields.systemLoad"), Value: fmt.Sprintf("%.2f, %.2f, %.2f", load1, load2, load3), Inline: true},
  455. {Name: tr("pages.index.memory"), Value: fmt.Sprintf("%s / %s", common.FormatTraffic(int64(status.Mem.Current)), common.FormatTraffic(int64(status.Mem.Total))), Inline: true},
  456. {Name: tr("pages.index.historyTitleOnline"), Value: strconv.Itoa(len(onlines)), Inline: true},
  457. {Name: tr("pages.index.historyTabConnections"), Value: fmt.Sprintf("TCP: %d | UDP: %d", status.TcpCount, status.UdpCount), Inline: true},
  458. {Name: tr("pages.index.sent"), Value: common.FormatTraffic(int64(status.NetTraffic.Sent)), Inline: true},
  459. {Name: tr("pages.index.received"), Value: common.FormatTraffic(int64(status.NetTraffic.Recv)), Inline: true},
  460. },
  461. Footer: &EmbedFooter{Text: tr("discord.footer")},
  462. }
  463. _ = g.discordService.SendEmbed(ctx, embed)
  464. }
  465. func (g *GatewayClient) sendBackup(ctx context.Context) {
  466. tr := translator(g.settingService)
  467. if g.serverService == nil {
  468. _ = g.discordService.SendMessage(ctx, MessagePayload{Content: tr("discord.commands.backupUnavailable")})
  469. return
  470. }
  471. dbData, err := g.serverService.GetDb()
  472. if err != nil || len(dbData) == 0 {
  473. _ = g.discordService.SendMessage(ctx, MessagePayload{Content: tr("discord.commands.backupFailed", "Error=="+fmt.Sprint(err))})
  474. return
  475. }
  476. filename := g.serverService.BackupFilename("")
  477. if filename == "" {
  478. filename = "x-ui.db"
  479. }
  480. files := []FileAttachment{
  481. {Filename: filename, Data: dbData},
  482. }
  483. configPath := xray.GetConfigPath()
  484. if configData, err := os.ReadFile(configPath); err == nil && len(configData) > 0 {
  485. files = append(files, FileAttachment{
  486. Filename: "config.json",
  487. Data: configData,
  488. })
  489. }
  490. payload := MessagePayload{
  491. Embeds: []Embed{
  492. {
  493. Title: tr("discord.commands.backupTitle"),
  494. Description: tr("discord.commands.backupDescription", "Time=="+time.Now().UTC().Format(time.RFC3339)),
  495. Color: ColorBlue,
  496. Timestamp: time.Now().UTC().Format(time.RFC3339),
  497. Footer: &EmbedFooter{Text: tr("discord.footer")},
  498. },
  499. },
  500. }
  501. _ = g.discordService.SendMessageWithFiles(ctx, payload, files...)
  502. }
  503. func (g *GatewayClient) sendUsage(ctx context.Context, email string) {
  504. tr := translator(g.settingService)
  505. if g.inboundService == nil {
  506. _ = g.discordService.SendMessage(ctx, MessagePayload{Content: tr("discord.commands.inboundsUnavailable")})
  507. return
  508. }
  509. inbounds, err := g.inboundService.GetAllInbounds()
  510. if err != nil {
  511. _ = g.discordService.SendMessage(ctx, MessagePayload{Content: tr("discord.commands.inboundsFailed", "Error=="+err.Error())})
  512. return
  513. }
  514. target := strings.ToLower(strings.TrimSpace(email))
  515. for _, in := range inbounds {
  516. for _, client := range in.ClientStats {
  517. if strings.ToLower(client.Email) == target {
  518. color := ColorGreen
  519. statusStr := tr("enabled")
  520. if !client.Enable {
  521. color = ColorRed
  522. statusStr = tr("disabled")
  523. }
  524. expireStr := tr("unlimited")
  525. switch {
  526. case client.ExpiryTime > 0:
  527. expireStr = time.Unix(client.ExpiryTime/1000, 0).Format("2006-01-02 15:04:05")
  528. // Start After First Use stores the duration negated, so such a client is
  529. // not unlimited: it starts counting down on its first connection.
  530. case client.ExpiryTime < 0:
  531. expireStr = fmt.Sprintf("%d %s", client.ExpiryTime/-86400000, tr("tgbot.days"))
  532. }
  533. totalLimitStr := tr("unlimited")
  534. if client.Total > 0 {
  535. totalLimitStr = common.FormatTraffic(client.Total)
  536. }
  537. embed := Embed{
  538. Title: tr("discord.commands.usageTitle", "Email=="+client.Email),
  539. Description: tr("discord.commands.usageDescription", "Remark=="+in.Remark, "Port=="+strconv.Itoa(in.Port)),
  540. Color: color,
  541. Timestamp: time.Now().UTC().Format(time.RFC3339),
  542. Fields: []EmbedField{
  543. {Name: tr("status"), Value: statusStr, Inline: true},
  544. {Name: tr("pages.index.upload"), Value: common.FormatTraffic(client.Up), Inline: true},
  545. {Name: tr("pages.index.download"), Value: common.FormatTraffic(client.Down), Inline: true},
  546. {Name: tr("discord.fields.totalUsed"), Value: common.FormatTraffic(client.Up + client.Down), Inline: true},
  547. {Name: tr("discord.fields.quota"), Value: totalLimitStr, Inline: true},
  548. {Name: tr("pages.clients.expiryTime"), Value: expireStr, Inline: true},
  549. },
  550. Footer: &EmbedFooter{Text: tr("discord.footer")},
  551. }
  552. _ = g.discordService.SendEmbed(ctx, embed)
  553. return
  554. }
  555. }
  556. }
  557. _ = g.discordService.SendMessage(ctx, MessagePayload{
  558. Content: tr("discord.commands.clientNotFound", "Email=="+email),
  559. })
  560. }
  561. func (g *GatewayClient) sendInbounds(ctx context.Context) {
  562. tr := translator(g.settingService)
  563. if g.inboundService == nil {
  564. _ = g.discordService.SendMessage(ctx, MessagePayload{Content: tr("discord.commands.inboundsUnavailable")})
  565. return
  566. }
  567. inbounds, err := g.inboundService.GetAllInbounds()
  568. if err != nil {
  569. _ = g.discordService.SendMessage(ctx, MessagePayload{Content: tr("discord.commands.inboundsFailed", "Error=="+err.Error())})
  570. return
  571. }
  572. if len(inbounds) == 0 {
  573. _ = g.discordService.SendMessage(ctx, MessagePayload{Content: tr("discord.commands.noInbounds")})
  574. return
  575. }
  576. var fields []EmbedField
  577. for _, in := range inbounds {
  578. state := tr("enabled")
  579. if !in.Enable {
  580. state = tr("disabled")
  581. }
  582. val := tr("discord.values.inbound",
  583. "Protocol=="+string(in.Protocol),
  584. "Port=="+strconv.Itoa(in.Port),
  585. "Clients=="+strconv.Itoa(len(in.ClientStats)),
  586. "Up=="+common.FormatTraffic(in.Up),
  587. "Down=="+common.FormatTraffic(in.Down),
  588. "State=="+state,
  589. )
  590. fields = append(fields, EmbedField{
  591. Name: fmt.Sprintf("📍 %s", in.Remark),
  592. Value: val,
  593. Inline: false,
  594. })
  595. }
  596. embed := Embed{
  597. Title: tr("discord.commands.inboundsTitle"),
  598. Description: tr("discord.commands.inboundsDescription", "Count=="+strconv.Itoa(len(inbounds))),
  599. Color: ColorBlue,
  600. Timestamp: time.Now().UTC().Format(time.RFC3339),
  601. Fields: fields,
  602. Footer: &EmbedFooter{Text: tr("discord.footer")},
  603. }
  604. _ = g.discordService.SendEmbed(ctx, embed)
  605. }
  606. func (g *GatewayClient) restartXray(ctx context.Context) {
  607. tr := translator(g.settingService)
  608. if g.xrayService == nil {
  609. _ = g.discordService.SendMessage(ctx, MessagePayload{Content: tr("discord.commands.xrayUnavailable")})
  610. return
  611. }
  612. _ = g.discordService.SendMessage(ctx, MessagePayload{Content: tr("discord.commands.restarting")})
  613. if err := g.xrayService.RestartXray(false); err != nil {
  614. _ = g.discordService.SendMessage(ctx, MessagePayload{Content: tr("discord.commands.restartFailed", "Error=="+err.Error())})
  615. } else {
  616. _ = g.discordService.SendMessage(ctx, MessagePayload{Content: tr("discord.commands.restartSuccess")})
  617. }
  618. }