tgbot.go 30 KB

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