tgbot.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. package service
  2. import (
  3. "fmt"
  4. "net"
  5. "os"
  6. "strconv"
  7. "strings"
  8. "time"
  9. "x-ui/config"
  10. "x-ui/database/model"
  11. "x-ui/logger"
  12. "x-ui/util/common"
  13. "x-ui/xray"
  14. tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
  15. )
  16. var bot *tgbotapi.BotAPI
  17. var adminIds []int64
  18. var isRunning bool
  19. type LoginStatus byte
  20. const (
  21. LoginSuccess LoginStatus = 1
  22. LoginFail LoginStatus = 0
  23. )
  24. type Tgbot struct {
  25. inboundService InboundService
  26. settingService SettingService
  27. serverService ServerService
  28. lastStatus *Status
  29. }
  30. func (t *Tgbot) NewTgbot() *Tgbot {
  31. return new(Tgbot)
  32. }
  33. func (t *Tgbot) Start() error {
  34. tgBottoken, err := t.settingService.GetTgBotToken()
  35. if err != nil || tgBottoken == "" {
  36. logger.Warning("Get TgBotToken failed:", err)
  37. return err
  38. }
  39. tgBotid, err := t.settingService.GetTgBotChatId()
  40. if err != nil {
  41. logger.Warning("Get GetTgBotChatId failed:", err)
  42. return err
  43. }
  44. for _, adminId := range strings.Split(tgBotid, ",") {
  45. id, err := strconv.Atoi(adminId)
  46. if err != nil {
  47. logger.Warning("Failed to get IDs from GetTgBotChatId:", err)
  48. return err
  49. }
  50. adminIds = append(adminIds, int64(id))
  51. }
  52. bot, err = tgbotapi.NewBotAPI(tgBottoken)
  53. if err != nil {
  54. fmt.Println("Get tgbot's api error:", err)
  55. return err
  56. }
  57. bot.Debug = false
  58. // listen for TG bot income messages
  59. if !isRunning {
  60. logger.Info("Starting Telegram receiver ...")
  61. go t.OnReceive()
  62. isRunning = true
  63. }
  64. return nil
  65. }
  66. func (t *Tgbot) IsRunnging() bool {
  67. return isRunning
  68. }
  69. func (t *Tgbot) Stop() {
  70. bot.StopReceivingUpdates()
  71. logger.Info("Stop Telegram receiver ...")
  72. isRunning = false
  73. adminIds = nil
  74. }
  75. func (t *Tgbot) OnReceive() {
  76. u := tgbotapi.NewUpdate(0)
  77. u.Timeout = 10
  78. updates := bot.GetUpdatesChan(u)
  79. for update := range updates {
  80. tgId := update.FromChat().ID
  81. chatId := update.FromChat().ChatConfig().ChatID
  82. isAdmin := checkAdmin(tgId)
  83. if update.Message == nil {
  84. if update.CallbackQuery != nil {
  85. t.asnwerCallback(update.CallbackQuery, isAdmin)
  86. }
  87. } else {
  88. if update.Message.IsCommand() {
  89. t.answerCommand(update.Message, chatId, isAdmin)
  90. }
  91. }
  92. }
  93. }
  94. func (t *Tgbot) answerCommand(message *tgbotapi.Message, chatId int64, isAdmin bool) {
  95. msg := ""
  96. // Extract the command from the Message.
  97. switch message.Command() {
  98. case "help":
  99. msg = "This bot is providing you some specefic data from the server.\n\n Please choose:"
  100. case "start":
  101. msg = "Hello <i>" + message.From.FirstName + "</i> 👋"
  102. if isAdmin {
  103. hostname, _ := os.Hostname()
  104. msg += "\nWelcome to <b>" + hostname + "</b> management bot"
  105. }
  106. msg += "\n\nI can do some magics for you, please choose:"
  107. case "status":
  108. msg = "bot is ok ✅"
  109. case "usage":
  110. if len(message.CommandArguments()) > 1 {
  111. if isAdmin {
  112. t.searchClient(chatId, message.CommandArguments())
  113. } else {
  114. t.searchForClient(chatId, message.CommandArguments())
  115. }
  116. } else {
  117. msg = "❗Please provide a text for search!"
  118. }
  119. case "inbound":
  120. if isAdmin {
  121. t.searchInbound(chatId, message.CommandArguments())
  122. } else {
  123. msg = "❗ Unknown command"
  124. }
  125. default:
  126. msg = "❗ Unknown command"
  127. }
  128. t.SendAnswer(chatId, msg, isAdmin)
  129. }
  130. func (t *Tgbot) asnwerCallback(callbackQuery *tgbotapi.CallbackQuery, isAdmin bool) {
  131. // Respond to the callback query, telling Telegram to show the user
  132. // a message with the data received.
  133. callback := tgbotapi.NewCallback(callbackQuery.ID, callbackQuery.Data)
  134. if _, err := bot.Request(callback); err != nil {
  135. logger.Warning(err)
  136. }
  137. switch callbackQuery.Data {
  138. case "get_usage":
  139. t.SendMsgToTgbot(callbackQuery.From.ID, t.getServerUsage())
  140. case "inbounds":
  141. t.SendMsgToTgbot(callbackQuery.From.ID, t.getInboundUsages())
  142. case "exhausted_soon":
  143. t.SendMsgToTgbot(callbackQuery.From.ID, t.getExhausted())
  144. case "get_backup":
  145. t.sendBackup(callbackQuery.From.ID)
  146. case "client_traffic":
  147. t.getClientUsage(callbackQuery.From.ID, callbackQuery.From.UserName)
  148. case "client_commands":
  149. t.SendMsgToTgbot(callbackQuery.From.ID, "To search for statistics, just use folowing command:\r\n \r\n<code>/usage [UID|Passowrd]</code>\r\n \r\nUse UID for vmess and vless and Password for Trojan.")
  150. case "commands":
  151. t.SendMsgToTgbot(callbackQuery.From.ID, "Search for a client email:\r\n<code>/usage email</code>\r\n \r\nSearch for inbounds (with client stats):\r\n<code>/inbound [remark]</code>")
  152. }
  153. }
  154. func checkAdmin(tgId int64) bool {
  155. for _, adminId := range adminIds {
  156. if adminId == tgId {
  157. return true
  158. }
  159. }
  160. return false
  161. }
  162. func (t *Tgbot) SendAnswer(chatId int64, msg string, isAdmin bool) {
  163. var numericKeyboard = tgbotapi.NewInlineKeyboardMarkup(
  164. tgbotapi.NewInlineKeyboardRow(
  165. tgbotapi.NewInlineKeyboardButtonData("Server Usage", "get_usage"),
  166. tgbotapi.NewInlineKeyboardButtonData("Get DB Backup", "get_backup"),
  167. ),
  168. tgbotapi.NewInlineKeyboardRow(
  169. tgbotapi.NewInlineKeyboardButtonData("Get Inbounds", "inbounds"),
  170. tgbotapi.NewInlineKeyboardButtonData("Exhausted soon", "exhausted_soon"),
  171. ),
  172. tgbotapi.NewInlineKeyboardRow(
  173. tgbotapi.NewInlineKeyboardButtonData("Commands", "commands"),
  174. ),
  175. )
  176. var numericKeyboardClient = tgbotapi.NewInlineKeyboardMarkup(
  177. tgbotapi.NewInlineKeyboardRow(
  178. tgbotapi.NewInlineKeyboardButtonData("Get Usage", "client_traffic"),
  179. tgbotapi.NewInlineKeyboardButtonData("Commands", "client_commands"),
  180. ),
  181. )
  182. msgConfig := tgbotapi.NewMessage(chatId, msg)
  183. msgConfig.ParseMode = "HTML"
  184. if isAdmin {
  185. msgConfig.ReplyMarkup = numericKeyboard
  186. } else {
  187. msgConfig.ReplyMarkup = numericKeyboardClient
  188. }
  189. _, err := bot.Send(msgConfig)
  190. if err != nil {
  191. logger.Warning("Error sending telegram message :", err)
  192. }
  193. }
  194. func (t *Tgbot) SendMsgToTgbot(tgid int64, msg string) {
  195. var allMessages []string
  196. limit := 2000
  197. // paging message if it is big
  198. if len(msg) > limit {
  199. messages := strings.Split(msg, "\r\n \r\n")
  200. lastIndex := -1
  201. for _, message := range messages {
  202. if (len(allMessages) == 0) || (len(allMessages[lastIndex])+len(message) > limit) {
  203. allMessages = append(allMessages, message)
  204. lastIndex++
  205. } else {
  206. allMessages[lastIndex] += "\r\n \r\n" + message
  207. }
  208. }
  209. } else {
  210. allMessages = append(allMessages, msg)
  211. }
  212. for _, message := range allMessages {
  213. info := tgbotapi.NewMessage(tgid, message)
  214. info.ParseMode = "HTML"
  215. _, err := bot.Send(info)
  216. if err != nil {
  217. logger.Warning("Error sending telegram message :", err)
  218. }
  219. time.Sleep(500 * time.Millisecond)
  220. }
  221. }
  222. func (t *Tgbot) SendMsgToTgbotAdmins(msg string) {
  223. for _, adminId := range adminIds {
  224. t.SendMsgToTgbot(adminId, msg)
  225. }
  226. }
  227. func (t *Tgbot) SendReport() {
  228. runTime, err := t.settingService.GetTgbotRuntime()
  229. if err == nil && len(runTime) > 0 {
  230. t.SendMsgToTgbotAdmins("🕰 Scheduled reports: " + runTime + "\r\nDate-Time: " + time.Now().Format("2006-01-02 15:04:05"))
  231. }
  232. info := t.getServerUsage()
  233. t.SendMsgToTgbotAdmins(info)
  234. exhausted := t.getExhausted()
  235. t.SendMsgToTgbotAdmins(exhausted)
  236. backupEnable, err := t.settingService.GetTgBotBackup()
  237. if err == nil && backupEnable {
  238. for _, adminId := range adminIds {
  239. t.sendBackup(int64(adminId))
  240. }
  241. }
  242. }
  243. func (t *Tgbot) getServerUsage() string {
  244. var info string
  245. //get hostname
  246. name, err := os.Hostname()
  247. if err != nil {
  248. logger.Error("get hostname error:", err)
  249. name = ""
  250. }
  251. info = fmt.Sprintf("💻 Hostname: %s\r\n", name)
  252. info += fmt.Sprintf("🚀X-UI Version: %s\r\n", config.GetVersion())
  253. //get ip address
  254. var ip string
  255. var ipv6 string
  256. netInterfaces, err := net.Interfaces()
  257. if err != nil {
  258. logger.Error("net.Interfaces failed, err:", err.Error())
  259. info += "🌐 IP: Unknown\r\n \r\n"
  260. } else {
  261. for i := 0; i < len(netInterfaces); i++ {
  262. if (netInterfaces[i].Flags & net.FlagUp) != 0 {
  263. addrs, _ := netInterfaces[i].Addrs()
  264. for _, address := range addrs {
  265. if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
  266. if ipnet.IP.To4() != nil {
  267. ip += ipnet.IP.String() + " "
  268. } else if ipnet.IP.To16() != nil && !ipnet.IP.IsLinkLocalUnicast() {
  269. ipv6 += ipnet.IP.String() + " "
  270. }
  271. }
  272. }
  273. }
  274. }
  275. info += fmt.Sprintf("🌐IP: %s\r\n🌐IPv6: %s\r\n", ip, ipv6)
  276. }
  277. // get latest status of server
  278. t.lastStatus = t.serverService.GetStatus(t.lastStatus)
  279. info += fmt.Sprintf("🔌Server Uptime: %d days\r\n", int(t.lastStatus.Uptime/86400))
  280. info += fmt.Sprintf("📈Server Load: %.1f, %.1f, %.1f\r\n", t.lastStatus.Loads[0], t.lastStatus.Loads[1], t.lastStatus.Loads[2])
  281. info += fmt.Sprintf("📋Server Memory: %s/%s\r\n", common.FormatTraffic(int64(t.lastStatus.Mem.Current)), common.FormatTraffic(int64(t.lastStatus.Mem.Total)))
  282. info += fmt.Sprintf("🔹TcpCount: %d\r\n", t.lastStatus.TcpCount)
  283. info += fmt.Sprintf("🔸UdpCount: %d\r\n", t.lastStatus.UdpCount)
  284. info += fmt.Sprintf("🚦Traffic: %s (↑%s,↓%s)\r\n", common.FormatTraffic(int64(t.lastStatus.NetTraffic.Sent+t.lastStatus.NetTraffic.Recv)), common.FormatTraffic(int64(t.lastStatus.NetTraffic.Sent)), common.FormatTraffic(int64(t.lastStatus.NetTraffic.Recv)))
  285. info += fmt.Sprintf("ℹXray status: %s", t.lastStatus.Xray.State)
  286. return info
  287. }
  288. func (t *Tgbot) UserLoginNotify(username string, ip string, time string, status LoginStatus) {
  289. if username == "" || ip == "" || time == "" {
  290. logger.Warning("UserLoginNotify failed,invalid info")
  291. return
  292. }
  293. var msg string
  294. // Get hostname
  295. name, err := os.Hostname()
  296. if err != nil {
  297. logger.Warning("get hostname error:", err)
  298. return
  299. }
  300. if status == LoginSuccess {
  301. msg = fmt.Sprintf("✅ Successfully logged-in to the panel\r\nHostname:%s\r\n", name)
  302. } else if status == LoginFail {
  303. msg = fmt.Sprintf("❗ Login to the panel was unsuccessful\r\nHostname:%s\r\n", name)
  304. }
  305. msg += fmt.Sprintf("⏰ Time:%s\r\n", time)
  306. msg += fmt.Sprintf("🆔 Username:%s\r\n", username)
  307. msg += fmt.Sprintf("🌐 IP:%s\r\n", ip)
  308. t.SendMsgToTgbotAdmins(msg)
  309. }
  310. func (t *Tgbot) getInboundUsages() string {
  311. info := ""
  312. // get traffic
  313. inbouds, err := t.inboundService.GetAllInbounds()
  314. if err != nil {
  315. logger.Warning("GetAllInbounds run failed:", err)
  316. info += "❌ Failed to get inbounds"
  317. } else {
  318. // NOTE:If there no any sessions here,need to notify here
  319. // TODO:Sub-node push, automatic conversion format
  320. for _, inbound := range inbouds {
  321. info += fmt.Sprintf("📍Inbound:%s\r\nPort:%d\r\n", inbound.Remark, inbound.Port)
  322. info += fmt.Sprintf("Traffic: %s (↑%s,↓%s)\r\n", common.FormatTraffic((inbound.Up + inbound.Down)), common.FormatTraffic(inbound.Up), common.FormatTraffic(inbound.Down))
  323. if inbound.ExpiryTime == 0 {
  324. info += "Expire date: ♾ Unlimited\r\n \r\n"
  325. } else {
  326. info += fmt.Sprintf("Expire date:%s\r\n \r\n", time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05"))
  327. }
  328. }
  329. }
  330. return info
  331. }
  332. func (t *Tgbot) getClientUsage(chatId int64, tgUserName string) {
  333. traffics, err := t.inboundService.GetClientTrafficTgBot(tgUserName)
  334. if err != nil {
  335. logger.Warning(err)
  336. msg := "❌ Something went wrong!"
  337. t.SendMsgToTgbot(chatId, msg)
  338. return
  339. }
  340. if len(traffics) == 0 {
  341. msg := "Your configuration is not found!\nPlease ask your Admin to use your telegram username in your configuration(s).\n\nYour username: <b>@" + tgUserName + "</b>"
  342. t.SendMsgToTgbot(chatId, msg)
  343. }
  344. for _, traffic := range traffics {
  345. expiryTime := ""
  346. if traffic.ExpiryTime == 0 {
  347. expiryTime = "♾Unlimited"
  348. } else {
  349. expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
  350. }
  351. total := ""
  352. if traffic.Total == 0 {
  353. total = "♾Unlimited"
  354. } else {
  355. total = common.FormatTraffic((traffic.Total))
  356. }
  357. output := fmt.Sprintf("💡 Active: %t\r\n📧 Email: %s\r\n🔼 Upload↑: %s\r\n🔽 Download↓: %s\r\n🔄 Total: %s / %s\r\n📅 Expire in: %s\r\n",
  358. traffic.Enable, traffic.Email, common.FormatTraffic(traffic.Up), common.FormatTraffic(traffic.Down), common.FormatTraffic((traffic.Up + traffic.Down)),
  359. total, expiryTime)
  360. t.SendMsgToTgbot(chatId, output)
  361. }
  362. t.SendAnswer(chatId, "Please choose:", false)
  363. }
  364. func (t *Tgbot) searchClient(chatId int64, email string) {
  365. traffics, err := t.inboundService.GetClientTrafficByEmail(email)
  366. if err != nil {
  367. logger.Warning(err)
  368. msg := "❌ Something went wrong!"
  369. t.SendMsgToTgbot(chatId, msg)
  370. return
  371. }
  372. if len(traffics) == 0 {
  373. msg := "No result!"
  374. t.SendMsgToTgbot(chatId, msg)
  375. return
  376. }
  377. for _, traffic := range traffics {
  378. expiryTime := ""
  379. if traffic.ExpiryTime == 0 {
  380. expiryTime = "♾Unlimited"
  381. } else {
  382. expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
  383. }
  384. total := ""
  385. if traffic.Total == 0 {
  386. total = "♾Unlimited"
  387. } else {
  388. total = common.FormatTraffic((traffic.Total))
  389. }
  390. output := fmt.Sprintf("💡 Active: %t\r\n📧 Email: %s\r\n🔼 Upload↑: %s\r\n🔽 Download↓: %s\r\n🔄 Total: %s / %s\r\n📅 Expire in: %s\r\n",
  391. traffic.Enable, traffic.Email, common.FormatTraffic(traffic.Up), common.FormatTraffic(traffic.Down), common.FormatTraffic((traffic.Up + traffic.Down)),
  392. total, expiryTime)
  393. t.SendMsgToTgbot(chatId, output)
  394. }
  395. }
  396. func (t *Tgbot) searchInbound(chatId int64, remark string) {
  397. inbouds, err := t.inboundService.SearchInbounds(remark)
  398. if err != nil {
  399. logger.Warning(err)
  400. msg := "❌ Something went wrong!"
  401. t.SendMsgToTgbot(chatId, msg)
  402. return
  403. }
  404. for _, inbound := range inbouds {
  405. info := ""
  406. info += fmt.Sprintf("📍Inbound:%s\r\nPort:%d\r\n", inbound.Remark, inbound.Port)
  407. info += fmt.Sprintf("Traffic: %s (↑%s,↓%s)\r\n", common.FormatTraffic((inbound.Up + inbound.Down)), common.FormatTraffic(inbound.Up), common.FormatTraffic(inbound.Down))
  408. if inbound.ExpiryTime == 0 {
  409. info += "Expire date: ♾ Unlimited\r\n \r\n"
  410. } else {
  411. info += fmt.Sprintf("Expire date:%s\r\n \r\n", time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05"))
  412. }
  413. t.SendMsgToTgbot(chatId, info)
  414. for _, traffic := range inbound.ClientStats {
  415. expiryTime := ""
  416. if traffic.ExpiryTime == 0 {
  417. expiryTime = "♾Unlimited"
  418. } else {
  419. expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
  420. }
  421. total := ""
  422. if traffic.Total == 0 {
  423. total = "♾Unlimited"
  424. } else {
  425. total = common.FormatTraffic((traffic.Total))
  426. }
  427. output := fmt.Sprintf("💡 Active: %t\r\n📧 Email: %s\r\n🔼 Upload↑: %s\r\n🔽 Download↓: %s\r\n🔄 Total: %s / %s\r\n📅 Expire in: %s\r\n",
  428. traffic.Enable, traffic.Email, common.FormatTraffic(traffic.Up), common.FormatTraffic(traffic.Down), common.FormatTraffic((traffic.Up + traffic.Down)),
  429. total, expiryTime)
  430. t.SendMsgToTgbot(chatId, output)
  431. }
  432. }
  433. }
  434. func (t *Tgbot) searchForClient(chatId int64, query string) {
  435. traffic, err := t.inboundService.SearchClientTraffic(query)
  436. if err != nil {
  437. logger.Warning(err)
  438. msg := "❌ Something went wrong!"
  439. t.SendMsgToTgbot(chatId, msg)
  440. return
  441. }
  442. if traffic == nil {
  443. msg := "No result!"
  444. t.SendMsgToTgbot(chatId, msg)
  445. return
  446. }
  447. expiryTime := ""
  448. if traffic.ExpiryTime == 0 {
  449. expiryTime = "♾Unlimited"
  450. } else {
  451. expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
  452. }
  453. total := ""
  454. if traffic.Total == 0 {
  455. total = "♾Unlimited"
  456. } else {
  457. total = common.FormatTraffic((traffic.Total))
  458. }
  459. output := fmt.Sprintf("💡 Active: %t\r\n📧 Email: %s\r\n🔼 Upload↑: %s\r\n🔽 Download↓: %s\r\n🔄 Total: %s / %s\r\n📅 Expire in: %s\r\n",
  460. traffic.Enable, traffic.Email, common.FormatTraffic(traffic.Up), common.FormatTraffic(traffic.Down), common.FormatTraffic((traffic.Up + traffic.Down)),
  461. total, expiryTime)
  462. t.SendMsgToTgbot(chatId, output)
  463. }
  464. func (t *Tgbot) getExhausted() string {
  465. trDiff := int64(0)
  466. exDiff := int64(0)
  467. now := time.Now().Unix() * 1000
  468. var exhaustedInbounds []model.Inbound
  469. var exhaustedClients []xray.ClientTraffic
  470. var disabledInbounds []model.Inbound
  471. var disabledClients []xray.ClientTraffic
  472. output := ""
  473. TrafficThreshold, err := t.settingService.GetTgTrafficDiff()
  474. if err == nil && TrafficThreshold > 0 {
  475. trDiff = int64(TrafficThreshold) * 1073741824
  476. }
  477. ExpireThreshold, err := t.settingService.GetTgExpireDiff()
  478. if err == nil && ExpireThreshold > 0 {
  479. exDiff = int64(ExpireThreshold) * 84600000
  480. }
  481. inbounds, err := t.inboundService.GetAllInbounds()
  482. if err != nil {
  483. logger.Warning("Unable to load Inbounds", err)
  484. }
  485. for _, inbound := range inbounds {
  486. if inbound.Enable {
  487. if (inbound.ExpiryTime > 0 && (inbound.ExpiryTime-now < exDiff)) ||
  488. (inbound.Total > 0 && (inbound.Total-inbound.Up+inbound.Down < trDiff)) {
  489. exhaustedInbounds = append(exhaustedInbounds, *inbound)
  490. }
  491. if len(inbound.ClientStats) > 0 {
  492. for _, client := range inbound.ClientStats {
  493. if client.Enable {
  494. if (client.ExpiryTime > 0 && (client.ExpiryTime-now < exDiff)) ||
  495. (client.Total > 0 && (client.Total-client.Up+client.Down < trDiff)) {
  496. exhaustedClients = append(exhaustedClients, client)
  497. }
  498. } else {
  499. disabledClients = append(disabledClients, client)
  500. }
  501. }
  502. }
  503. } else {
  504. disabledInbounds = append(disabledInbounds, *inbound)
  505. }
  506. }
  507. output += fmt.Sprintf("Exhausted Inbounds count:\r\n🛑 Disabled: %d\r\n🔜 Exhaust soon: %d\r\n \r\n", len(disabledInbounds), len(exhaustedInbounds))
  508. if len(exhaustedInbounds) > 0 {
  509. output += "Exhausted Inbounds:\r\n"
  510. for _, inbound := range exhaustedInbounds {
  511. output += fmt.Sprintf("📍Inbound:%s\r\nPort:%d\r\nTraffic: %s (↑%s,↓%s)\r\n", inbound.Remark, inbound.Port, common.FormatTraffic((inbound.Up + inbound.Down)), common.FormatTraffic(inbound.Up), common.FormatTraffic(inbound.Down))
  512. if inbound.ExpiryTime == 0 {
  513. output += "Expire date: ♾Unlimited\r\n \r\n"
  514. } else {
  515. output += fmt.Sprintf("Expire date:%s\r\n \r\n", time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05"))
  516. }
  517. }
  518. }
  519. output += fmt.Sprintf("Exhausted Clients count:\r\n🛑 Disabled: %d\r\n🔜 Exhaust soon: %d\r\n \r\n", len(disabledClients), len(exhaustedClients))
  520. if len(exhaustedClients) > 0 {
  521. output += "Exhausted Clients:\r\n"
  522. for _, traffic := range exhaustedClients {
  523. expiryTime := ""
  524. if traffic.ExpiryTime == 0 {
  525. expiryTime = "♾Unlimited"
  526. } else {
  527. expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
  528. }
  529. total := ""
  530. if traffic.Total == 0 {
  531. total = "♾Unlimited"
  532. } else {
  533. total = common.FormatTraffic((traffic.Total))
  534. }
  535. output += fmt.Sprintf("💡 Active: %t\r\n📧 Email: %s\r\n🔼 Upload↑: %s\r\n🔽 Download↓: %s\r\n🔄 Total: %s / %s\r\n📅 Expire date: %s\r\n \r\n",
  536. traffic.Enable, traffic.Email, common.FormatTraffic(traffic.Up), common.FormatTraffic(traffic.Down), common.FormatTraffic((traffic.Up + traffic.Down)),
  537. total, expiryTime)
  538. }
  539. }
  540. return output
  541. }
  542. func (t *Tgbot) sendBackup(chatId int64) {
  543. sendingTime := time.Now().Format("2006-01-02 15:04:05")
  544. t.SendMsgToTgbot(chatId, "Backup time: "+sendingTime)
  545. file := tgbotapi.FilePath(config.GetDBPath())
  546. msg := tgbotapi.NewDocument(chatId, file)
  547. _, err := bot.Send(msg)
  548. if err != nil {
  549. logger.Warning("Error in uploading backup: ", err)
  550. }
  551. file = tgbotapi.FilePath(xray.GetConfigPath())
  552. msg = tgbotapi.NewDocument(chatId, file)
  553. _, err = bot.Send(msg)
  554. if err != nil {
  555. logger.Warning("Error in uploading config.json: ", err)
  556. }
  557. }