1
0

gateway.go 19 KB

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