1
0

tgbot.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  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. if isAdmin {
  132. dataArray := strings.Split(callbackQuery.Data, " ")
  133. if len(dataArray) >= 2 && len(dataArray[1]) > 0 {
  134. email := dataArray[1]
  135. switch dataArray[0] {
  136. case "admin_cancel":
  137. t.sendCallbackAnswerTgBot(callbackQuery.ID, fmt.Sprintf("❌ %s : Operation canceled.", email))
  138. t.searchClient(callbackQuery.From.ID, email, callbackQuery.Message.MessageID)
  139. case "reset_traffic":
  140. var inlineKeyboard = tgbotapi.NewInlineKeyboardMarkup(
  141. tgbotapi.NewInlineKeyboardRow(
  142. tgbotapi.NewInlineKeyboardButtonData("❌ Cancel Reset", "admin_cancel "+email),
  143. ),
  144. tgbotapi.NewInlineKeyboardRow(
  145. tgbotapi.NewInlineKeyboardButtonData("✅ Confirm Reset?", "reset_traffic_confirm "+email),
  146. ),
  147. )
  148. t.editMessageCallbackTgBot(callbackQuery.From.ID, callbackQuery.Message.MessageID, inlineKeyboard)
  149. case "reset_traffic_confirm":
  150. t.inboundService.ResetClientTrafficByEmail(email)
  151. t.sendCallbackAnswerTgBot(callbackQuery.ID, fmt.Sprintf("✅ %s : Traffic reset successfully.", email))
  152. t.searchClient(callbackQuery.From.ID, email, callbackQuery.Message.MessageID)
  153. case "reset_expire_days":
  154. var inlineKeyboard = tgbotapi.NewInlineKeyboardMarkup(
  155. tgbotapi.NewInlineKeyboardRow(
  156. tgbotapi.NewInlineKeyboardButtonData("❌ Cancel Reset", "admin_cancel "+email),
  157. ),
  158. tgbotapi.NewInlineKeyboardRow(
  159. tgbotapi.NewInlineKeyboardButtonData("1 Mounth", "reset_expire_days_confirm "+email+" 30"),
  160. tgbotapi.NewInlineKeyboardButtonData("2 Mounth", "reset_expire_days_confirm "+email+" 60"),
  161. ),
  162. tgbotapi.NewInlineKeyboardRow(
  163. tgbotapi.NewInlineKeyboardButtonData("3 Mounth", "reset_expire_days_confirm "+email+" 90"),
  164. tgbotapi.NewInlineKeyboardButtonData("6 Mounth", "reset_expire_days_confirm "+email+" 180"),
  165. ),
  166. tgbotapi.NewInlineKeyboardRow(
  167. tgbotapi.NewInlineKeyboardButtonData("9 Mounth", "reset_expire_days_confirm "+email+" 270"),
  168. tgbotapi.NewInlineKeyboardButtonData("12 Mounth", "reset_expire_days_confirm "+email+" 360"),
  169. ),
  170. tgbotapi.NewInlineKeyboardRow(
  171. tgbotapi.NewInlineKeyboardButtonData("10 Days", "reset_expire_days_confirm "+email+" 10"),
  172. tgbotapi.NewInlineKeyboardButtonData("20 Days", "reset_expire_days_confirm "+email+" 20"),
  173. ),
  174. )
  175. t.editMessageCallbackTgBot(callbackQuery.From.ID, callbackQuery.Message.MessageID, inlineKeyboard)
  176. case "reset_expire_days_confirm":
  177. err := len(dataArray) < 3
  178. if !err {
  179. days, error := strconv.Atoi(dataArray[2])
  180. if error == nil {
  181. t.inboundService.ResetClientExpiryTimeByEmail(email, int64(-(days * 24 * 60 * 60000)))
  182. t.sendCallbackAnswerTgBot(callbackQuery.ID, fmt.Sprintf("✅ %s : Expire days reset successfully.", email))
  183. t.searchClient(callbackQuery.From.ID, email, callbackQuery.Message.MessageID)
  184. } else {
  185. err = true
  186. }
  187. }
  188. if err {
  189. t.sendCallbackAnswerTgBot(callbackQuery.ID, "❗ Error in Operation.")
  190. t.searchClient(callbackQuery.From.ID, email, callbackQuery.Message.MessageID)
  191. }
  192. }
  193. return
  194. }
  195. }
  196. // Respond to the callback query, telling Telegram to show the user
  197. // a message with the data received.
  198. callback := tgbotapi.NewCallback(callbackQuery.ID, callbackQuery.Data)
  199. if _, err := bot.Request(callback); err != nil {
  200. logger.Warning(err)
  201. }
  202. switch callbackQuery.Data {
  203. case "get_usage":
  204. t.SendMsgToTgbot(callbackQuery.From.ID, t.getServerUsage())
  205. case "inbounds":
  206. t.SendMsgToTgbot(callbackQuery.From.ID, t.getInboundUsages())
  207. case "deplete_soon":
  208. t.SendMsgToTgbot(callbackQuery.From.ID, t.getExhausted())
  209. case "get_backup":
  210. t.sendBackup(callbackQuery.From.ID)
  211. case "client_traffic":
  212. t.getClientUsage(callbackQuery.From.ID, callbackQuery.From.UserName)
  213. case "client_commands":
  214. t.SendMsgToTgbot(callbackQuery.From.ID, "To search for statistics, just use folowing command:\r\n \r\n<code>/usage [UID|Password]</code>\r\n \r\nUse UID for vmess/vless and Password for Trojan.")
  215. case "commands":
  216. 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>")
  217. }
  218. }
  219. func checkAdmin(tgId int64) bool {
  220. for _, adminId := range adminIds {
  221. if adminId == tgId {
  222. return true
  223. }
  224. }
  225. return false
  226. }
  227. func (t *Tgbot) SendAnswer(chatId int64, msg string, isAdmin bool) {
  228. var numericKeyboard = tgbotapi.NewInlineKeyboardMarkup(
  229. tgbotapi.NewInlineKeyboardRow(
  230. tgbotapi.NewInlineKeyboardButtonData("Server Usage", "get_usage"),
  231. tgbotapi.NewInlineKeyboardButtonData("Get DB Backup", "get_backup"),
  232. ),
  233. tgbotapi.NewInlineKeyboardRow(
  234. tgbotapi.NewInlineKeyboardButtonData("Get Inbounds", "inbounds"),
  235. tgbotapi.NewInlineKeyboardButtonData("Deplete soon", "deplete_soon"),
  236. ),
  237. tgbotapi.NewInlineKeyboardRow(
  238. tgbotapi.NewInlineKeyboardButtonData("Commands", "commands"),
  239. ),
  240. )
  241. var numericKeyboardClient = tgbotapi.NewInlineKeyboardMarkup(
  242. tgbotapi.NewInlineKeyboardRow(
  243. tgbotapi.NewInlineKeyboardButtonData("Get Usage", "client_traffic"),
  244. tgbotapi.NewInlineKeyboardButtonData("Commands", "client_commands"),
  245. ),
  246. )
  247. msgConfig := tgbotapi.NewMessage(chatId, msg)
  248. msgConfig.ParseMode = "HTML"
  249. if isAdmin {
  250. msgConfig.ReplyMarkup = numericKeyboard
  251. } else {
  252. msgConfig.ReplyMarkup = numericKeyboardClient
  253. }
  254. _, err := bot.Send(msgConfig)
  255. if err != nil {
  256. logger.Warning("Error sending telegram message :", err)
  257. }
  258. }
  259. func (t *Tgbot) SendMsgToTgbot(tgid int64, msg string, inlineKeyboard ...tgbotapi.InlineKeyboardMarkup) {
  260. var allMessages []string
  261. limit := 2000
  262. // paging message if it is big
  263. if len(msg) > limit {
  264. messages := strings.Split(msg, "\r\n \r\n")
  265. lastIndex := -1
  266. for _, message := range messages {
  267. if (len(allMessages) == 0) || (len(allMessages[lastIndex])+len(message) > limit) {
  268. allMessages = append(allMessages, message)
  269. lastIndex++
  270. } else {
  271. allMessages[lastIndex] += "\r\n \r\n" + message
  272. }
  273. }
  274. } else {
  275. allMessages = append(allMessages, msg)
  276. }
  277. for _, message := range allMessages {
  278. info := tgbotapi.NewMessage(tgid, message)
  279. info.ParseMode = "HTML"
  280. if len(inlineKeyboard) > 0 {
  281. info.ReplyMarkup = inlineKeyboard[0]
  282. }
  283. _, err := bot.Send(info)
  284. if err != nil {
  285. logger.Warning("Error sending telegram message :", err)
  286. }
  287. time.Sleep(500 * time.Millisecond)
  288. }
  289. }
  290. func (t *Tgbot) SendMsgToTgbotAdmins(msg string) {
  291. for _, adminId := range adminIds {
  292. t.SendMsgToTgbot(adminId, msg)
  293. }
  294. }
  295. func (t *Tgbot) SendReport() {
  296. runTime, err := t.settingService.GetTgbotRuntime()
  297. if err == nil && len(runTime) > 0 {
  298. t.SendMsgToTgbotAdmins("🕰 Scheduled reports: " + runTime + "\r\nDate-Time: " + time.Now().Format("2006-01-02 15:04:05"))
  299. }
  300. info := t.getServerUsage()
  301. t.SendMsgToTgbotAdmins(info)
  302. exhausted := t.getExhausted()
  303. t.SendMsgToTgbotAdmins(exhausted)
  304. backupEnable, err := t.settingService.GetTgBotBackup()
  305. if err == nil && backupEnable {
  306. for _, adminId := range adminIds {
  307. t.sendBackup(int64(adminId))
  308. }
  309. }
  310. }
  311. func (t *Tgbot) getServerUsage() string {
  312. var info string
  313. //get hostname
  314. name, err := os.Hostname()
  315. if err != nil {
  316. logger.Error("get hostname error:", err)
  317. name = ""
  318. }
  319. info = fmt.Sprintf("💻 Hostname: %s\r\n", name)
  320. info += fmt.Sprintf("🚀X-UI Version: %s\r\n", config.GetVersion())
  321. //get ip address
  322. var ip string
  323. var ipv6 string
  324. netInterfaces, err := net.Interfaces()
  325. if err != nil {
  326. logger.Error("net.Interfaces failed, err:", err.Error())
  327. info += "🌐 IP: Unknown\r\n \r\n"
  328. } else {
  329. for i := 0; i < len(netInterfaces); i++ {
  330. if (netInterfaces[i].Flags & net.FlagUp) != 0 {
  331. addrs, _ := netInterfaces[i].Addrs()
  332. for _, address := range addrs {
  333. if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
  334. if ipnet.IP.To4() != nil {
  335. ip += ipnet.IP.String() + " "
  336. } else if ipnet.IP.To16() != nil && !ipnet.IP.IsLinkLocalUnicast() {
  337. ipv6 += ipnet.IP.String() + " "
  338. }
  339. }
  340. }
  341. }
  342. }
  343. info += fmt.Sprintf("🌐IP: %s\r\n🌐IPv6: %s\r\n", ip, ipv6)
  344. }
  345. // get latest status of server
  346. t.lastStatus = t.serverService.GetStatus(t.lastStatus)
  347. info += fmt.Sprintf("🔌Server Uptime: %d days\r\n", int(t.lastStatus.Uptime/86400))
  348. info += fmt.Sprintf("📈Server Load: %.1f, %.1f, %.1f\r\n", t.lastStatus.Loads[0], t.lastStatus.Loads[1], t.lastStatus.Loads[2])
  349. info += fmt.Sprintf("📋Server Memory: %s/%s\r\n", common.FormatTraffic(int64(t.lastStatus.Mem.Current)), common.FormatTraffic(int64(t.lastStatus.Mem.Total)))
  350. info += fmt.Sprintf("🔹TcpCount: %d\r\n", t.lastStatus.TcpCount)
  351. info += fmt.Sprintf("🔸UdpCount: %d\r\n", t.lastStatus.UdpCount)
  352. 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)))
  353. info += fmt.Sprintf("ℹXray status: %s", t.lastStatus.Xray.State)
  354. return info
  355. }
  356. func (t *Tgbot) UserLoginNotify(username string, ip string, time string, status LoginStatus) {
  357. if username == "" || ip == "" || time == "" {
  358. logger.Warning("UserLoginNotify failed,invalid info")
  359. return
  360. }
  361. var msg string
  362. // Get hostname
  363. name, err := os.Hostname()
  364. if err != nil {
  365. logger.Warning("get hostname error:", err)
  366. return
  367. }
  368. if status == LoginSuccess {
  369. msg = fmt.Sprintf("✅ Successfully logged-in to the panel\r\nHostname:%s\r\n", name)
  370. } else if status == LoginFail {
  371. msg = fmt.Sprintf("❗ Login to the panel was unsuccessful\r\nHostname:%s\r\n", name)
  372. }
  373. msg += fmt.Sprintf("⏰ Time:%s\r\n", time)
  374. msg += fmt.Sprintf("🆔 Username:%s\r\n", username)
  375. msg += fmt.Sprintf("🌐 IP:%s\r\n", ip)
  376. t.SendMsgToTgbotAdmins(msg)
  377. }
  378. func (t *Tgbot) getInboundUsages() string {
  379. info := ""
  380. // get traffic
  381. inbouds, err := t.inboundService.GetAllInbounds()
  382. if err != nil {
  383. logger.Warning("GetAllInbounds run failed:", err)
  384. info += "❌ Failed to get inbounds"
  385. } else {
  386. // NOTE:If there no any sessions here,need to notify here
  387. // TODO:Sub-node push, automatic conversion format
  388. for _, inbound := range inbouds {
  389. info += fmt.Sprintf("📍Inbound:%s\r\nPort:%d\r\n", inbound.Remark, inbound.Port)
  390. info += fmt.Sprintf("Traffic: %s (↑%s,↓%s)\r\n", common.FormatTraffic((inbound.Up + inbound.Down)), common.FormatTraffic(inbound.Up), common.FormatTraffic(inbound.Down))
  391. if inbound.ExpiryTime == 0 {
  392. info += "Expire date: ♾ Unlimited\r\n \r\n"
  393. } else {
  394. info += fmt.Sprintf("Expire date:%s\r\n \r\n", time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05"))
  395. }
  396. }
  397. }
  398. return info
  399. }
  400. func (t *Tgbot) getClientUsage(chatId int64, tgUserName string) {
  401. if len(tgUserName) == 0 {
  402. msg := "Your configuration is not found!\nYou should configure your telegram username and ask Admin to add it to your configuration."
  403. t.SendMsgToTgbot(chatId, msg)
  404. return
  405. }
  406. traffics, err := t.inboundService.GetClientTrafficTgBot(tgUserName)
  407. if err != nil {
  408. logger.Warning(err)
  409. msg := "❌ Something went wrong!"
  410. t.SendMsgToTgbot(chatId, msg)
  411. return
  412. }
  413. if len(traffics) == 0 {
  414. 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>"
  415. t.SendMsgToTgbot(chatId, msg)
  416. return
  417. }
  418. for _, traffic := range traffics {
  419. expiryTime := ""
  420. if traffic.ExpiryTime == 0 {
  421. expiryTime = "♾Unlimited"
  422. } else if traffic.ExpiryTime < 0 {
  423. expiryTime = fmt.Sprintf("%d days", traffic.ExpiryTime/-86400000)
  424. } else {
  425. expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
  426. }
  427. total := ""
  428. if traffic.Total == 0 {
  429. total = "♾Unlimited"
  430. } else {
  431. total = common.FormatTraffic((traffic.Total))
  432. }
  433. 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",
  434. traffic.Enable, traffic.Email, common.FormatTraffic(traffic.Up), common.FormatTraffic(traffic.Down), common.FormatTraffic((traffic.Up + traffic.Down)),
  435. total, expiryTime)
  436. t.SendMsgToTgbot(chatId, output)
  437. }
  438. t.SendAnswer(chatId, "Please choose:", false)
  439. }
  440. func (t *Tgbot) searchClient(chatId int64, email string, messageID ...int) {
  441. traffic, err := t.inboundService.GetClientTrafficByEmail(email)
  442. if err != nil {
  443. logger.Warning(err)
  444. msg := "❌ Something went wrong!"
  445. t.SendMsgToTgbot(chatId, msg)
  446. return
  447. }
  448. if traffic == nil {
  449. msg := "No result!"
  450. t.SendMsgToTgbot(chatId, msg)
  451. return
  452. }
  453. expiryTime := ""
  454. if traffic.ExpiryTime == 0 {
  455. expiryTime = "♾Unlimited"
  456. } else if traffic.ExpiryTime < 0 {
  457. expiryTime = fmt.Sprintf("%d days", traffic.ExpiryTime/-86400000)
  458. } else {
  459. expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
  460. }
  461. total := ""
  462. if traffic.Total == 0 {
  463. total = "♾Unlimited"
  464. } else {
  465. total = common.FormatTraffic((traffic.Total))
  466. }
  467. 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",
  468. traffic.Enable, traffic.Email, common.FormatTraffic(traffic.Up), common.FormatTraffic(traffic.Down), common.FormatTraffic((traffic.Up + traffic.Down)),
  469. total, expiryTime)
  470. var inlineKeyboard = tgbotapi.NewInlineKeyboardMarkup(
  471. tgbotapi.NewInlineKeyboardRow(
  472. tgbotapi.NewInlineKeyboardButtonData("🔄 Reset Traffic", "reset_traffic "+email),
  473. ),
  474. tgbotapi.NewInlineKeyboardRow(
  475. tgbotapi.NewInlineKeyboardButtonData("📅 Reset Expire Days", "reset_expire_days "+email),
  476. ),
  477. )
  478. if len(messageID) > 0 {
  479. t.editMessageTgBot(chatId, messageID[0], output, inlineKeyboard)
  480. } else {
  481. t.SendMsgToTgbot(chatId, output, inlineKeyboard)
  482. }
  483. }
  484. func (t *Tgbot) searchInbound(chatId int64, remark string) {
  485. inbouds, err := t.inboundService.SearchInbounds(remark)
  486. if err != nil {
  487. logger.Warning(err)
  488. msg := "❌ Something went wrong!"
  489. t.SendMsgToTgbot(chatId, msg)
  490. return
  491. }
  492. for _, inbound := range inbouds {
  493. info := ""
  494. info += fmt.Sprintf("📍Inbound:%s\r\nPort:%d\r\n", inbound.Remark, inbound.Port)
  495. info += fmt.Sprintf("Traffic: %s (↑%s,↓%s)\r\n", common.FormatTraffic((inbound.Up + inbound.Down)), common.FormatTraffic(inbound.Up), common.FormatTraffic(inbound.Down))
  496. if inbound.ExpiryTime == 0 {
  497. info += "Expire date: ♾ Unlimited\r\n \r\n"
  498. } else {
  499. info += fmt.Sprintf("Expire date:%s\r\n \r\n", time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05"))
  500. }
  501. t.SendMsgToTgbot(chatId, info)
  502. for _, traffic := range inbound.ClientStats {
  503. expiryTime := ""
  504. if traffic.ExpiryTime == 0 {
  505. expiryTime = "♾Unlimited"
  506. } else if traffic.ExpiryTime < 0 {
  507. expiryTime = fmt.Sprintf("%d days", traffic.ExpiryTime/-86400000)
  508. } else {
  509. expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
  510. }
  511. total := ""
  512. if traffic.Total == 0 {
  513. total = "♾Unlimited"
  514. } else {
  515. total = common.FormatTraffic((traffic.Total))
  516. }
  517. 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",
  518. traffic.Enable, traffic.Email, common.FormatTraffic(traffic.Up), common.FormatTraffic(traffic.Down), common.FormatTraffic((traffic.Up + traffic.Down)),
  519. total, expiryTime)
  520. t.SendMsgToTgbot(chatId, output)
  521. }
  522. }
  523. }
  524. func (t *Tgbot) searchForClient(chatId int64, query string) {
  525. traffic, err := t.inboundService.SearchClientTraffic(query)
  526. if err != nil {
  527. logger.Warning(err)
  528. msg := "❌ Something went wrong!"
  529. t.SendMsgToTgbot(chatId, msg)
  530. return
  531. }
  532. if traffic == nil {
  533. msg := "No result!"
  534. t.SendMsgToTgbot(chatId, msg)
  535. return
  536. }
  537. expiryTime := ""
  538. if traffic.ExpiryTime == 0 {
  539. expiryTime = "♾Unlimited"
  540. } else if traffic.ExpiryTime < 0 {
  541. expiryTime = fmt.Sprintf("%d days", traffic.ExpiryTime/-86400000)
  542. } else {
  543. expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
  544. }
  545. total := ""
  546. if traffic.Total == 0 {
  547. total = "♾Unlimited"
  548. } else {
  549. total = common.FormatTraffic((traffic.Total))
  550. }
  551. 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",
  552. traffic.Enable, traffic.Email, common.FormatTraffic(traffic.Up), common.FormatTraffic(traffic.Down), common.FormatTraffic((traffic.Up + traffic.Down)),
  553. total, expiryTime)
  554. t.SendMsgToTgbot(chatId, output)
  555. }
  556. func (t *Tgbot) getExhausted() string {
  557. trDiff := int64(0)
  558. exDiff := int64(0)
  559. now := time.Now().Unix() * 1000
  560. var exhaustedInbounds []model.Inbound
  561. var exhaustedClients []xray.ClientTraffic
  562. var disabledInbounds []model.Inbound
  563. var disabledClients []xray.ClientTraffic
  564. output := ""
  565. TrafficThreshold, err := t.settingService.GetTrafficDiff()
  566. if err == nil && TrafficThreshold > 0 {
  567. trDiff = int64(TrafficThreshold) * 1073741824
  568. }
  569. ExpireThreshold, err := t.settingService.GetExpireDiff()
  570. if err == nil && ExpireThreshold > 0 {
  571. exDiff = int64(ExpireThreshold) * 86400000
  572. }
  573. inbounds, err := t.inboundService.GetAllInbounds()
  574. if err != nil {
  575. logger.Warning("Unable to load Inbounds", err)
  576. }
  577. for _, inbound := range inbounds {
  578. if inbound.Enable {
  579. if (inbound.ExpiryTime > 0 && (inbound.ExpiryTime-now < exDiff)) ||
  580. (inbound.Total > 0 && (inbound.Total-(inbound.Up+inbound.Down) < trDiff)) {
  581. exhaustedInbounds = append(exhaustedInbounds, *inbound)
  582. }
  583. if len(inbound.ClientStats) > 0 {
  584. for _, client := range inbound.ClientStats {
  585. if client.Enable {
  586. if (client.ExpiryTime > 0 && (client.ExpiryTime-now < exDiff)) ||
  587. (client.Total > 0 && (client.Total-(client.Up+client.Down) < trDiff)) {
  588. exhaustedClients = append(exhaustedClients, client)
  589. }
  590. } else {
  591. disabledClients = append(disabledClients, client)
  592. }
  593. }
  594. }
  595. } else {
  596. disabledInbounds = append(disabledInbounds, *inbound)
  597. }
  598. }
  599. output += fmt.Sprintf("Exhausted Inbounds count:\r\n🛑 Disabled: %d\r\n🔜 Deplete soon: %d\r\n \r\n", len(disabledInbounds), len(exhaustedInbounds))
  600. if len(exhaustedInbounds) > 0 {
  601. output += "Exhausted Inbounds:\r\n"
  602. for _, inbound := range exhaustedInbounds {
  603. 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))
  604. if inbound.ExpiryTime == 0 {
  605. output += "Expire date: ♾Unlimited\r\n \r\n"
  606. } else {
  607. output += fmt.Sprintf("Expire date:%s\r\n \r\n", time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05"))
  608. }
  609. }
  610. }
  611. output += fmt.Sprintf("Exhausted Clients count:\r\n🛑 Exhausted: %d\r\n🔜 Deplete soon: %d\r\n \r\n", len(disabledClients), len(exhaustedClients))
  612. if len(exhaustedClients) > 0 {
  613. output += "Exhausted Clients:\r\n"
  614. for _, traffic := range exhaustedClients {
  615. expiryTime := ""
  616. if traffic.ExpiryTime == 0 {
  617. expiryTime = "♾Unlimited"
  618. } else if traffic.ExpiryTime < 0 {
  619. expiryTime += fmt.Sprintf("%d days", traffic.ExpiryTime/-86400000)
  620. } else {
  621. expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
  622. }
  623. total := ""
  624. if traffic.Total == 0 {
  625. total = "♾Unlimited"
  626. } else {
  627. total = common.FormatTraffic((traffic.Total))
  628. }
  629. 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",
  630. traffic.Enable, traffic.Email, common.FormatTraffic(traffic.Up), common.FormatTraffic(traffic.Down), common.FormatTraffic((traffic.Up + traffic.Down)),
  631. total, expiryTime)
  632. }
  633. }
  634. return output
  635. }
  636. func (t *Tgbot) sendBackup(chatId int64) {
  637. sendingTime := time.Now().Format("2006-01-02 15:04:05")
  638. t.SendMsgToTgbot(chatId, "Backup time: "+sendingTime)
  639. file := tgbotapi.FilePath(config.GetDBPath())
  640. msg := tgbotapi.NewDocument(chatId, file)
  641. _, err := bot.Send(msg)
  642. if err != nil {
  643. logger.Warning("Error in uploading backup: ", err)
  644. }
  645. file = tgbotapi.FilePath(xray.GetConfigPath())
  646. msg = tgbotapi.NewDocument(chatId, file)
  647. _, err = bot.Send(msg)
  648. if err != nil {
  649. logger.Warning("Error in uploading config.json: ", err)
  650. }
  651. }
  652. func (t *Tgbot) sendCallbackAnswerTgBot(id string, message string) {
  653. callback := tgbotapi.NewCallback(id, message)
  654. if _, err := bot.Request(callback); err != nil {
  655. logger.Warning(err)
  656. }
  657. }
  658. func (t *Tgbot) editMessageCallbackTgBot(chatId int64, messageID int, inlineKeyboard tgbotapi.InlineKeyboardMarkup) {
  659. edit := tgbotapi.NewEditMessageReplyMarkup(chatId, messageID, inlineKeyboard)
  660. if _, err := bot.Request(edit); err != nil {
  661. logger.Warning(err)
  662. }
  663. }
  664. func (t *Tgbot) editMessageTgBot(chatId int64, messageID int, text string, inlineKeyboard ...tgbotapi.InlineKeyboardMarkup) {
  665. edit := tgbotapi.NewEditMessageText(chatId, messageID, text)
  666. edit.ParseMode = "HTML"
  667. if len(inlineKeyboard) > 0 {
  668. edit.ReplyMarkup = &inlineKeyboard[0]
  669. }
  670. if _, err := bot.Request(edit); err != nil {
  671. logger.Warning(err)
  672. }
  673. }