1
0

tgbot.go 24 KB

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