tgbot.go 25 KB

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