tgbot.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  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. var allMessages []string
  359. limit := 2000
  360. // paging message if it is big
  361. if len(msg) > limit {
  362. messages := strings.Split(msg, "\r\n \r\n")
  363. lastIndex := -1
  364. for _, message := range messages {
  365. if (len(allMessages) == 0) || (len(allMessages[lastIndex])+len(message) > limit) {
  366. allMessages = append(allMessages, message)
  367. lastIndex++
  368. } else {
  369. allMessages[lastIndex] += "\r\n \r\n" + message
  370. }
  371. }
  372. } else {
  373. allMessages = append(allMessages, msg)
  374. }
  375. for _, message := range allMessages {
  376. info := tgbotapi.NewMessage(tgid, message)
  377. info.ParseMode = "HTML"
  378. if len(inlineKeyboard) > 0 {
  379. info.ReplyMarkup = inlineKeyboard[0]
  380. }
  381. _, err := bot.Send(info)
  382. if err != nil {
  383. logger.Warning("Error sending telegram message :", err)
  384. }
  385. time.Sleep(500 * time.Millisecond)
  386. }
  387. }
  388. func (t *Tgbot) SendMsgToTgbotAdmins(msg string) {
  389. for _, adminId := range adminIds {
  390. t.SendMsgToTgbot(adminId, msg)
  391. }
  392. }
  393. func (t *Tgbot) SendReport() {
  394. runTime, err := t.settingService.GetTgbotRuntime()
  395. if err == nil && len(runTime) > 0 {
  396. t.SendMsgToTgbotAdmins("🕰 Scheduled reports: " + runTime + "\r\nDate-Time: " + time.Now().Format("2006-01-02 15:04:05"))
  397. }
  398. info := t.getServerUsage()
  399. t.SendMsgToTgbotAdmins(info)
  400. exhausted := t.getExhausted()
  401. t.SendMsgToTgbotAdmins(exhausted)
  402. backupEnable, err := t.settingService.GetTgBotBackup()
  403. if err == nil && backupEnable {
  404. for _, adminId := range adminIds {
  405. t.sendBackup(int64(adminId))
  406. }
  407. }
  408. }
  409. func (t *Tgbot) getServerUsage() string {
  410. var info string
  411. //get hostname
  412. name, err := os.Hostname()
  413. if err != nil {
  414. logger.Error("get hostname error:", err)
  415. name = ""
  416. }
  417. info = fmt.Sprintf("💻 Hostname: %s\r\n", name)
  418. info += fmt.Sprintf("🚀X-UI Version: %s\r\n", config.GetVersion())
  419. //get ip address
  420. var ip string
  421. var ipv6 string
  422. netInterfaces, err := net.Interfaces()
  423. if err != nil {
  424. logger.Error("net.Interfaces failed, err:", err.Error())
  425. info += "🌐 IP: Unknown\r\n \r\n"
  426. } else {
  427. for i := 0; i < len(netInterfaces); i++ {
  428. if (netInterfaces[i].Flags & net.FlagUp) != 0 {
  429. addrs, _ := netInterfaces[i].Addrs()
  430. for _, address := range addrs {
  431. if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
  432. if ipnet.IP.To4() != nil {
  433. ip += ipnet.IP.String() + " "
  434. } else if ipnet.IP.To16() != nil && !ipnet.IP.IsLinkLocalUnicast() {
  435. ipv6 += ipnet.IP.String() + " "
  436. }
  437. }
  438. }
  439. }
  440. }
  441. info += fmt.Sprintf("🌐IP: %s\r\n🌐IPv6: %s\r\n", ip, ipv6)
  442. }
  443. // get latest status of server
  444. t.lastStatus = t.serverService.GetStatus(t.lastStatus)
  445. info += fmt.Sprintf("🔌Server Uptime: %d days\r\n", int(t.lastStatus.Uptime/86400))
  446. info += fmt.Sprintf("📈Server Load: %.1f, %.1f, %.1f\r\n", t.lastStatus.Loads[0], t.lastStatus.Loads[1], t.lastStatus.Loads[2])
  447. info += fmt.Sprintf("📋Server Memory: %s/%s\r\n", common.FormatTraffic(int64(t.lastStatus.Mem.Current)), common.FormatTraffic(int64(t.lastStatus.Mem.Total)))
  448. info += fmt.Sprintf("🔹TcpCount: %d\r\n", t.lastStatus.TcpCount)
  449. info += fmt.Sprintf("🔸UdpCount: %d\r\n", t.lastStatus.UdpCount)
  450. 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)))
  451. info += fmt.Sprintf("ℹXray status: %s", t.lastStatus.Xray.State)
  452. return info
  453. }
  454. func (t *Tgbot) UserLoginNotify(username string, ip string, time string, status LoginStatus) {
  455. if username == "" || ip == "" || time == "" {
  456. logger.Warning("UserLoginNotify failed,invalid info")
  457. return
  458. }
  459. var msg string
  460. // Get hostname
  461. name, err := os.Hostname()
  462. if err != nil {
  463. logger.Warning("get hostname error:", err)
  464. return
  465. }
  466. if status == LoginSuccess {
  467. msg = fmt.Sprintf("✅ Successfully logged-in to the panel\r\nHostname:%s\r\n", name)
  468. } else if status == LoginFail {
  469. msg = fmt.Sprintf("❗ Login to the panel was unsuccessful\r\nHostname:%s\r\n", name)
  470. }
  471. msg += fmt.Sprintf("⏰ Time:%s\r\n", time)
  472. msg += fmt.Sprintf("🆔 Username:%s\r\n", username)
  473. msg += fmt.Sprintf("🌐 IP:%s\r\n", ip)
  474. t.SendMsgToTgbotAdmins(msg)
  475. }
  476. func (t *Tgbot) getInboundUsages() string {
  477. info := ""
  478. // get traffic
  479. inbouds, err := t.inboundService.GetAllInbounds()
  480. if err != nil {
  481. logger.Warning("GetAllInbounds run failed:", err)
  482. info += "❌ Failed to get inbounds"
  483. } else {
  484. // NOTE:If there no any sessions here,need to notify here
  485. // TODO:Sub-node push, automatic conversion format
  486. for _, inbound := range inbouds {
  487. info += fmt.Sprintf("📍Inbound:%s\r\nPort:%d\r\n", inbound.Remark, inbound.Port)
  488. info += fmt.Sprintf("Traffic: %s (↑%s,↓%s)\r\n", common.FormatTraffic((inbound.Up + inbound.Down)), common.FormatTraffic(inbound.Up), common.FormatTraffic(inbound.Down))
  489. if inbound.ExpiryTime == 0 {
  490. info += "Expire date: ♾ Unlimited\r\n \r\n"
  491. } else {
  492. info += fmt.Sprintf("Expire date:%s\r\n \r\n", time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05"))
  493. }
  494. }
  495. }
  496. return info
  497. }
  498. func (t *Tgbot) getClientUsage(chatId int64, tgUserName string, tgUserID string) {
  499. traffics, err := t.inboundService.GetClientTrafficTgBot(tgUserID)
  500. if err != nil {
  501. logger.Warning(err)
  502. msg := "❌ Something went wrong!"
  503. t.SendMsgToTgbot(chatId, msg)
  504. return
  505. }
  506. if len(traffics) == 0 {
  507. if len(tgUserName) == 0 {
  508. 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>"
  509. t.SendMsgToTgbot(chatId, msg)
  510. return
  511. }
  512. traffics, err = t.inboundService.GetClientTrafficTgBot(tgUserName)
  513. }
  514. if err != nil {
  515. logger.Warning(err)
  516. msg := "❌ Something went wrong!"
  517. t.SendMsgToTgbot(chatId, msg)
  518. return
  519. }
  520. if len(traffics) == 0 {
  521. 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>"
  522. t.SendMsgToTgbot(chatId, msg)
  523. return
  524. }
  525. for _, traffic := range traffics {
  526. expiryTime := ""
  527. if traffic.ExpiryTime == 0 {
  528. expiryTime = "♾Unlimited"
  529. } else if traffic.ExpiryTime < 0 {
  530. expiryTime = fmt.Sprintf("%d days", traffic.ExpiryTime/-86400000)
  531. } else {
  532. expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
  533. }
  534. total := ""
  535. if traffic.Total == 0 {
  536. total = "♾Unlimited"
  537. } else {
  538. total = common.FormatTraffic((traffic.Total))
  539. }
  540. 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",
  541. traffic.Enable, traffic.Email, common.FormatTraffic(traffic.Up), common.FormatTraffic(traffic.Down), common.FormatTraffic((traffic.Up + traffic.Down)),
  542. total, expiryTime)
  543. t.SendMsgToTgbot(chatId, output)
  544. }
  545. t.SendAnswer(chatId, "Please choose:", false)
  546. }
  547. func (t *Tgbot) searchClientIps(chatId int64, email string, messageID ...int) {
  548. ips, err := t.inboundService.GetInboundClientIps(email)
  549. if err != nil || len(ips) == 0 {
  550. ips = "No IP Record"
  551. }
  552. output := fmt.Sprintf("📧 Email: %s\r\n🔢 IPs: \r\n%s\r\n", email, ips)
  553. var inlineKeyboard = tgbotapi.NewInlineKeyboardMarkup(
  554. tgbotapi.NewInlineKeyboardRow(
  555. tgbotapi.NewInlineKeyboardButtonData("🔄 Refresh", "ips_refresh "+email),
  556. ),
  557. tgbotapi.NewInlineKeyboardRow(
  558. tgbotapi.NewInlineKeyboardButtonData("❌ Clear IPs", "clear_ips "+email),
  559. ),
  560. )
  561. if len(messageID) > 0 {
  562. t.editMessageTgBot(chatId, messageID[0], output, inlineKeyboard)
  563. } else {
  564. t.SendMsgToTgbot(chatId, output, inlineKeyboard)
  565. }
  566. }
  567. func (t *Tgbot) searchClient(chatId int64, email string, messageID ...int) {
  568. traffic, err := t.inboundService.GetClientTrafficByEmail(email)
  569. if err != nil {
  570. logger.Warning(err)
  571. msg := "❌ Something went wrong!"
  572. t.SendMsgToTgbot(chatId, msg)
  573. return
  574. }
  575. if traffic == nil {
  576. msg := "No result!"
  577. t.SendMsgToTgbot(chatId, msg)
  578. return
  579. }
  580. expiryTime := ""
  581. if traffic.ExpiryTime == 0 {
  582. expiryTime = "♾Unlimited"
  583. } else if traffic.ExpiryTime < 0 {
  584. expiryTime = fmt.Sprintf("%d days", traffic.ExpiryTime/-86400000)
  585. } else {
  586. expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
  587. }
  588. total := ""
  589. if traffic.Total == 0 {
  590. total = "♾Unlimited"
  591. } else {
  592. total = common.FormatTraffic((traffic.Total))
  593. }
  594. 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",
  595. traffic.Enable, traffic.Email, common.FormatTraffic(traffic.Up), common.FormatTraffic(traffic.Down), common.FormatTraffic((traffic.Up + traffic.Down)),
  596. total, expiryTime)
  597. var inlineKeyboard = tgbotapi.NewInlineKeyboardMarkup(
  598. tgbotapi.NewInlineKeyboardRow(
  599. tgbotapi.NewInlineKeyboardButtonData("🔄 Refresh", "client_refresh "+email),
  600. ),
  601. tgbotapi.NewInlineKeyboardRow(
  602. tgbotapi.NewInlineKeyboardButtonData("📈 Reset Traffic", "reset_traffic "+email),
  603. ),
  604. tgbotapi.NewInlineKeyboardRow(
  605. tgbotapi.NewInlineKeyboardButtonData("📅 Reset Expire Days", "reset_exp "+email),
  606. ),
  607. tgbotapi.NewInlineKeyboardRow(
  608. tgbotapi.NewInlineKeyboardButtonData("🔢 IP Log", "ip_log "+email),
  609. tgbotapi.NewInlineKeyboardButtonData("🔢 IP Limit", "ip_limit "+email),
  610. ),
  611. tgbotapi.NewInlineKeyboardRow(
  612. tgbotapi.NewInlineKeyboardButtonData("🔘 Enable / Disable", "toggle_enable "+email),
  613. ),
  614. )
  615. if len(messageID) > 0 {
  616. t.editMessageTgBot(chatId, messageID[0], output, inlineKeyboard)
  617. } else {
  618. t.SendMsgToTgbot(chatId, output, inlineKeyboard)
  619. }
  620. }
  621. func (t *Tgbot) searchInbound(chatId int64, remark string) {
  622. inbouds, err := t.inboundService.SearchInbounds(remark)
  623. if err != nil {
  624. logger.Warning(err)
  625. msg := "❌ Something went wrong!"
  626. t.SendMsgToTgbot(chatId, msg)
  627. return
  628. }
  629. for _, inbound := range inbouds {
  630. info := ""
  631. info += fmt.Sprintf("📍Inbound:%s\r\nPort:%d\r\n", inbound.Remark, inbound.Port)
  632. info += fmt.Sprintf("Traffic: %s (↑%s,↓%s)\r\n", common.FormatTraffic((inbound.Up + inbound.Down)), common.FormatTraffic(inbound.Up), common.FormatTraffic(inbound.Down))
  633. if inbound.ExpiryTime == 0 {
  634. info += "Expire date: ♾ Unlimited\r\n \r\n"
  635. } else {
  636. info += fmt.Sprintf("Expire date:%s\r\n \r\n", time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05"))
  637. }
  638. t.SendMsgToTgbot(chatId, info)
  639. for _, traffic := range inbound.ClientStats {
  640. expiryTime := ""
  641. if traffic.ExpiryTime == 0 {
  642. expiryTime = "♾Unlimited"
  643. } else if traffic.ExpiryTime < 0 {
  644. expiryTime = fmt.Sprintf("%d days", traffic.ExpiryTime/-86400000)
  645. } else {
  646. expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
  647. }
  648. total := ""
  649. if traffic.Total == 0 {
  650. total = "♾Unlimited"
  651. } else {
  652. total = common.FormatTraffic((traffic.Total))
  653. }
  654. 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",
  655. traffic.Enable, traffic.Email, common.FormatTraffic(traffic.Up), common.FormatTraffic(traffic.Down), common.FormatTraffic((traffic.Up + traffic.Down)),
  656. total, expiryTime)
  657. t.SendMsgToTgbot(chatId, output)
  658. }
  659. }
  660. }
  661. func (t *Tgbot) searchForClient(chatId int64, query string) {
  662. traffic, err := t.inboundService.SearchClientTraffic(query)
  663. if err != nil {
  664. logger.Warning(err)
  665. msg := "❌ Something went wrong!"
  666. t.SendMsgToTgbot(chatId, msg)
  667. return
  668. }
  669. if traffic == nil {
  670. msg := "No result!"
  671. t.SendMsgToTgbot(chatId, msg)
  672. return
  673. }
  674. expiryTime := ""
  675. if traffic.ExpiryTime == 0 {
  676. expiryTime = "♾Unlimited"
  677. } else if traffic.ExpiryTime < 0 {
  678. expiryTime = fmt.Sprintf("%d days", traffic.ExpiryTime/-86400000)
  679. } else {
  680. expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
  681. }
  682. total := ""
  683. if traffic.Total == 0 {
  684. total = "♾Unlimited"
  685. } else {
  686. total = common.FormatTraffic((traffic.Total))
  687. }
  688. 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",
  689. traffic.Enable, traffic.Email, common.FormatTraffic(traffic.Up), common.FormatTraffic(traffic.Down), common.FormatTraffic((traffic.Up + traffic.Down)),
  690. total, expiryTime)
  691. t.SendMsgToTgbot(chatId, output)
  692. }
  693. func (t *Tgbot) getExhausted() string {
  694. trDiff := int64(0)
  695. exDiff := int64(0)
  696. now := time.Now().Unix() * 1000
  697. var exhaustedInbounds []model.Inbound
  698. var exhaustedClients []xray.ClientTraffic
  699. var disabledInbounds []model.Inbound
  700. var disabledClients []xray.ClientTraffic
  701. output := ""
  702. TrafficThreshold, err := t.settingService.GetTrafficDiff()
  703. if err == nil && TrafficThreshold > 0 {
  704. trDiff = int64(TrafficThreshold) * 1073741824
  705. }
  706. ExpireThreshold, err := t.settingService.GetExpireDiff()
  707. if err == nil && ExpireThreshold > 0 {
  708. exDiff = int64(ExpireThreshold) * 86400000
  709. }
  710. inbounds, err := t.inboundService.GetAllInbounds()
  711. if err != nil {
  712. logger.Warning("Unable to load Inbounds", err)
  713. }
  714. for _, inbound := range inbounds {
  715. if inbound.Enable {
  716. if (inbound.ExpiryTime > 0 && (inbound.ExpiryTime-now < exDiff)) ||
  717. (inbound.Total > 0 && (inbound.Total-(inbound.Up+inbound.Down) < trDiff)) {
  718. exhaustedInbounds = append(exhaustedInbounds, *inbound)
  719. }
  720. if len(inbound.ClientStats) > 0 {
  721. for _, client := range inbound.ClientStats {
  722. if client.Enable {
  723. if (client.ExpiryTime > 0 && (client.ExpiryTime-now < exDiff)) ||
  724. (client.Total > 0 && (client.Total-(client.Up+client.Down) < trDiff)) {
  725. exhaustedClients = append(exhaustedClients, client)
  726. }
  727. } else {
  728. disabledClients = append(disabledClients, client)
  729. }
  730. }
  731. }
  732. } else {
  733. disabledInbounds = append(disabledInbounds, *inbound)
  734. }
  735. }
  736. output += fmt.Sprintf("Exhausted Inbounds count:\r\n🛑 Disabled: %d\r\n🔜 Deplete soon: %d\r\n \r\n", len(disabledInbounds), len(exhaustedInbounds))
  737. if len(exhaustedInbounds) > 0 {
  738. output += "Exhausted Inbounds:\r\n"
  739. for _, inbound := range exhaustedInbounds {
  740. 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))
  741. if inbound.ExpiryTime == 0 {
  742. output += "Expire date: ♾Unlimited\r\n \r\n"
  743. } else {
  744. output += fmt.Sprintf("Expire date:%s\r\n \r\n", time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05"))
  745. }
  746. }
  747. }
  748. output += fmt.Sprintf("Exhausted Clients count:\r\n🛑 Exhausted: %d\r\n🔜 Deplete soon: %d\r\n \r\n", len(disabledClients), len(exhaustedClients))
  749. if len(exhaustedClients) > 0 {
  750. output += "Exhausted Clients:\r\n"
  751. for _, traffic := range exhaustedClients {
  752. expiryTime := ""
  753. if traffic.ExpiryTime == 0 {
  754. expiryTime = "♾Unlimited"
  755. } else if traffic.ExpiryTime < 0 {
  756. expiryTime += fmt.Sprintf("%d days", traffic.ExpiryTime/-86400000)
  757. } else {
  758. expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
  759. }
  760. total := ""
  761. if traffic.Total == 0 {
  762. total = "♾Unlimited"
  763. } else {
  764. total = common.FormatTraffic((traffic.Total))
  765. }
  766. 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",
  767. traffic.Enable, traffic.Email, common.FormatTraffic(traffic.Up), common.FormatTraffic(traffic.Down), common.FormatTraffic((traffic.Up + traffic.Down)),
  768. total, expiryTime)
  769. }
  770. }
  771. return output
  772. }
  773. func (t *Tgbot) sendBackup(chatId int64) {
  774. sendingTime := time.Now().Format("2006-01-02 15:04:05")
  775. t.SendMsgToTgbot(chatId, "Backup time: "+sendingTime)
  776. file := tgbotapi.FilePath(config.GetDBPath())
  777. msg := tgbotapi.NewDocument(chatId, file)
  778. _, err := bot.Send(msg)
  779. if err != nil {
  780. logger.Warning("Error in uploading backup: ", err)
  781. }
  782. file = tgbotapi.FilePath(xray.GetConfigPath())
  783. msg = tgbotapi.NewDocument(chatId, file)
  784. _, err = bot.Send(msg)
  785. if err != nil {
  786. logger.Warning("Error in uploading config.json: ", err)
  787. }
  788. }
  789. func (t *Tgbot) sendCallbackAnswerTgBot(id string, message string) {
  790. callback := tgbotapi.NewCallback(id, message)
  791. if _, err := bot.Request(callback); err != nil {
  792. logger.Warning(err)
  793. }
  794. }
  795. func (t *Tgbot) editMessageCallbackTgBot(chatId int64, messageID int, inlineKeyboard tgbotapi.InlineKeyboardMarkup) {
  796. edit := tgbotapi.NewEditMessageReplyMarkup(chatId, messageID, inlineKeyboard)
  797. if _, err := bot.Request(edit); err != nil {
  798. logger.Warning(err)
  799. }
  800. }
  801. func (t *Tgbot) editMessageTgBot(chatId int64, messageID int, text string, inlineKeyboard ...tgbotapi.InlineKeyboardMarkup) {
  802. edit := tgbotapi.NewEditMessageText(chatId, messageID, text)
  803. edit.ParseMode = "HTML"
  804. if len(inlineKeyboard) > 0 {
  805. edit.ReplyMarkup = &inlineKeyboard[0]
  806. }
  807. if _, err := bot.Request(edit); err != nil {
  808. logger.Warning(err)
  809. }
  810. }