tgbot.go 25 KB

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