tgbot.go 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060
  1. package service
  2. import (
  3. "embed"
  4. "fmt"
  5. "net"
  6. "os"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "x-ui/config"
  11. "x-ui/database/model"
  12. "x-ui/logger"
  13. "x-ui/util/common"
  14. "x-ui/web/global"
  15. "x-ui/web/locale"
  16. "x-ui/xray"
  17. "github.com/gin-gonic/gin"
  18. "github.com/mymmrac/telego"
  19. th "github.com/mymmrac/telego/telegohandler"
  20. tu "github.com/mymmrac/telego/telegoutil"
  21. )
  22. var bot *telego.Bot
  23. var botHandler *th.BotHandler
  24. var adminIds []int64
  25. var isRunning bool
  26. type LoginStatus byte
  27. const (
  28. LoginSuccess LoginStatus = 1
  29. LoginFail LoginStatus = 0
  30. )
  31. type Tgbot struct {
  32. inboundService InboundService
  33. settingService SettingService
  34. serverService ServerService
  35. xrayService XrayService
  36. lastStatus *Status
  37. hashStorage *global.HashStorage
  38. }
  39. func (t *Tgbot) NewTgbot() *Tgbot {
  40. return new(Tgbot)
  41. }
  42. func (t *Tgbot) BotI18n(name string, params ...string) string {
  43. return locale.I18n(locale.Bot, name, params...)
  44. }
  45. func (t *Tgbot) GetHashStorage() *global.HashStorage {
  46. return t.hashStorage
  47. }
  48. func (t *Tgbot) Start(i18nFS embed.FS) error {
  49. err := locale.InitLocalizer(i18nFS, &t.settingService)
  50. if err != nil {
  51. return err
  52. }
  53. // init hash storage => store callback queries
  54. // NOTE: it only save the query if its length is more than 64 chars.
  55. t.hashStorage = global.NewHashStorage(20*time.Minute, false)
  56. tgBottoken, err := t.settingService.GetTgBotToken()
  57. if err != nil || tgBottoken == "" {
  58. logger.Warning("Get TgBotToken failed:", err)
  59. return err
  60. }
  61. tgBotid, err := t.settingService.GetTgBotChatId()
  62. if err != nil {
  63. logger.Warning("Get GetTgBotChatId failed:", err)
  64. return err
  65. }
  66. for _, adminId := range strings.Split(tgBotid, ",") {
  67. id, err := strconv.Atoi(adminId)
  68. if err != nil {
  69. logger.Warning("Failed to get IDs from GetTgBotChatId:", err)
  70. return err
  71. }
  72. adminIds = append(adminIds, int64(id))
  73. }
  74. bot, err = telego.NewBot(tgBottoken)
  75. if err != nil {
  76. fmt.Println("Get tgbot's api error:", err)
  77. return err
  78. }
  79. // listen for TG bot income messages
  80. if !isRunning {
  81. logger.Info("Starting Telegram receiver ...")
  82. go t.OnReceive()
  83. isRunning = true
  84. }
  85. return nil
  86. }
  87. func (t *Tgbot) IsRunning() bool {
  88. return isRunning
  89. }
  90. func (t *Tgbot) Stop() {
  91. botHandler.Stop()
  92. bot.StopLongPolling()
  93. logger.Info("Stop Telegram receiver ...")
  94. isRunning = false
  95. adminIds = nil
  96. }
  97. func (t *Tgbot) OnReceive() {
  98. params := telego.GetUpdatesParams{
  99. Timeout: 10,
  100. }
  101. updates, _ := bot.UpdatesViaLongPolling(&params)
  102. botHandler, _ = th.NewBotHandler(bot, updates)
  103. botHandler.HandleMessage(func(_ *telego.Bot, message telego.Message) {
  104. t.SendMsgToTgbot(message.Chat.ID, "Custom Keyboard Closed!", tu.ReplyKeyboardRemove())
  105. }, th.TextEqual("❌ Close Keyboard"))
  106. botHandler.HandleMessage(func(_ *telego.Bot, message telego.Message) {
  107. t.answerCommand(&message, message.Chat.ID, checkAdmin(message.From.ID))
  108. }, th.AnyCommand())
  109. botHandler.HandleCallbackQuery(func(_ *telego.Bot, query telego.CallbackQuery) {
  110. t.asnwerCallback(&query, checkAdmin(query.From.ID))
  111. }, th.AnyCallbackQueryWithMessage())
  112. botHandler.HandleMessage(func(_ *telego.Bot, message telego.Message) {
  113. if message.UserShared != nil {
  114. if checkAdmin(message.From.ID) {
  115. err := t.inboundService.SetClientTelegramUserID(message.UserShared.RequestID, strconv.FormatInt(message.UserShared.UserID, 10))
  116. var output string
  117. if err != nil {
  118. output = "❌ Error in user selection!"
  119. } else {
  120. output = "✅ Telegram User saved."
  121. }
  122. t.SendMsgToTgbot(message.Chat.ID, output, tu.ReplyKeyboardRemove())
  123. } else {
  124. t.SendMsgToTgbot(message.Chat.ID, "No result!", tu.ReplyKeyboardRemove())
  125. }
  126. }
  127. }, th.AnyMessage())
  128. botHandler.Start()
  129. }
  130. func (t *Tgbot) answerCommand(message *telego.Message, chatId int64, isAdmin bool) {
  131. msg := ""
  132. command, commandArgs := tu.ParseCommand(message.Text)
  133. // Extract the command from the Message.
  134. switch command {
  135. case "help":
  136. msg = "This bot is providing you some specefic data from the server.\n\n Please choose:"
  137. case "start":
  138. msg = "Hello <i>" + message.From.FirstName + "</i> 👋"
  139. if isAdmin {
  140. hostname, _ := os.Hostname()
  141. msg += "\nWelcome to <b>" + hostname + "</b> management bot"
  142. }
  143. msg += "\n\nI can do some magics for you, please choose:"
  144. case "status":
  145. msg = "bot is ok ✅"
  146. case "usage":
  147. if len(commandArgs) > 0 {
  148. if isAdmin {
  149. t.searchClient(chatId, commandArgs[0])
  150. } else {
  151. t.searchForClient(chatId, commandArgs[0])
  152. }
  153. } else {
  154. msg = "❗Please provide a text for search!"
  155. }
  156. case "inbound":
  157. if isAdmin && len(commandArgs) > 0 {
  158. t.searchInbound(chatId, commandArgs[0])
  159. } else {
  160. msg = "❗ Unknown command"
  161. }
  162. default:
  163. msg = "❗ Unknown command"
  164. }
  165. t.SendAnswer(chatId, msg, isAdmin)
  166. }
  167. func (t *Tgbot) asnwerCallback(callbackQuery *telego.CallbackQuery, isAdmin bool) {
  168. chatId := callbackQuery.Message.Chat.ID
  169. if isAdmin {
  170. // get query from hash storage
  171. decodedQuery, err := t.hashStorage.GetValue(callbackQuery.Data)
  172. if err != nil {
  173. t.SendMsgToTgbot(chatId, "Query not found! Please use the command again!")
  174. return
  175. }
  176. dataArray := strings.Split(decodedQuery, " ")
  177. if len(dataArray) >= 2 && len(dataArray[1]) > 0 {
  178. email := dataArray[1]
  179. switch dataArray[0] {
  180. case "client_refresh":
  181. t.sendCallbackAnswerTgBot(callbackQuery.ID, fmt.Sprintf("✅ %s : Client refreshed successfully.", email))
  182. t.searchClient(chatId, email, callbackQuery.Message.MessageID)
  183. case "client_cancel":
  184. t.sendCallbackAnswerTgBot(callbackQuery.ID, fmt.Sprintf("❌ %s : Operation canceled.", email))
  185. t.searchClient(chatId, email, callbackQuery.Message.MessageID)
  186. case "ips_refresh":
  187. t.sendCallbackAnswerTgBot(callbackQuery.ID, fmt.Sprintf("✅ %s : IPs refreshed successfully.", email))
  188. t.searchClientIps(chatId, email, callbackQuery.Message.MessageID)
  189. case "ips_cancel":
  190. t.sendCallbackAnswerTgBot(callbackQuery.ID, fmt.Sprintf("❌ %s : Operation canceled.", email))
  191. t.searchClientIps(chatId, email, callbackQuery.Message.MessageID)
  192. case "tgid_refresh":
  193. t.sendCallbackAnswerTgBot(callbackQuery.ID, fmt.Sprintf("✅ %s : Client's Telegram User refreshed successfully.", email))
  194. t.clientTelegramUserInfo(chatId, email, callbackQuery.Message.MessageID)
  195. case "tgid_cancel":
  196. t.sendCallbackAnswerTgBot(callbackQuery.ID, fmt.Sprintf("❌ %s : Operation canceled.", email))
  197. t.clientTelegramUserInfo(chatId, email, callbackQuery.Message.MessageID)
  198. case "reset_traffic":
  199. inlineKeyboard := tu.InlineKeyboard(
  200. tu.InlineKeyboardRow(
  201. tu.InlineKeyboardButton("❌ Cancel Reset").WithCallbackData(t.hashStorage.AddHash("client_cancel "+email)),
  202. ),
  203. tu.InlineKeyboardRow(
  204. tu.InlineKeyboardButton("✅ Confirm Reset Traffic?").WithCallbackData(t.hashStorage.AddHash("reset_traffic_c "+email)),
  205. ),
  206. )
  207. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.MessageID, inlineKeyboard)
  208. case "reset_traffic_c":
  209. err := t.inboundService.ResetClientTrafficByEmail(email)
  210. if err == nil {
  211. t.xrayService.SetToNeedRestart()
  212. t.sendCallbackAnswerTgBot(callbackQuery.ID, fmt.Sprintf("✅ %s : Traffic reset successfully.", email))
  213. t.searchClient(chatId, email, callbackQuery.Message.MessageID)
  214. } else {
  215. t.sendCallbackAnswerTgBot(callbackQuery.ID, "❗ Error in Operation.")
  216. }
  217. case "reset_exp":
  218. var inlineKeyboard = tu.InlineKeyboard(
  219. tu.InlineKeyboardRow(
  220. tu.InlineKeyboardButton("❌ Cancel Reset").WithCallbackData(t.hashStorage.AddHash("client_cancel "+email)),
  221. ),
  222. tu.InlineKeyboardRow(
  223. tu.InlineKeyboardButton("♾ Unlimited").WithCallbackData(t.hashStorage.AddHash("reset_exp_c "+email+" 0")),
  224. ),
  225. tu.InlineKeyboardRow(
  226. tu.InlineKeyboardButton("1 Month").WithCallbackData(t.hashStorage.AddHash("reset_exp_c "+email+" 30")),
  227. tu.InlineKeyboardButton("2 Months").WithCallbackData(t.hashStorage.AddHash("reset_exp_c "+email+" 60")),
  228. ),
  229. tu.InlineKeyboardRow(
  230. tu.InlineKeyboardButton("3 Months").WithCallbackData(t.hashStorage.AddHash("reset_exp_c "+email+" 90")),
  231. tu.InlineKeyboardButton("6 Months").WithCallbackData(t.hashStorage.AddHash("reset_exp_c "+email+" 180")),
  232. ),
  233. tu.InlineKeyboardRow(
  234. tu.InlineKeyboardButton("9 Months").WithCallbackData(t.hashStorage.AddHash("reset_exp_c "+email+" 270")),
  235. tu.InlineKeyboardButton("12 Months").WithCallbackData(t.hashStorage.AddHash("reset_exp_c "+email+" 360")),
  236. ),
  237. tu.InlineKeyboardRow(
  238. tu.InlineKeyboardButton("10 Days").WithCallbackData(t.hashStorage.AddHash("reset_exp_c "+email+" 10")),
  239. tu.InlineKeyboardButton("20 Days").WithCallbackData(t.hashStorage.AddHash("reset_exp_c "+email+" 20")),
  240. ),
  241. )
  242. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.MessageID, inlineKeyboard)
  243. case "reset_exp_c":
  244. if len(dataArray) == 3 {
  245. days, err := strconv.Atoi(dataArray[2])
  246. if err == nil {
  247. var date int64 = 0
  248. if days > 0 {
  249. date = int64(-(days * 24 * 60 * 60000))
  250. }
  251. err := t.inboundService.ResetClientExpiryTimeByEmail(email, date)
  252. if err == nil {
  253. t.xrayService.SetToNeedRestart()
  254. t.sendCallbackAnswerTgBot(callbackQuery.ID, fmt.Sprintf("✅ %s : Expire days reset successfully.", email))
  255. t.searchClient(chatId, email, callbackQuery.Message.MessageID)
  256. return
  257. }
  258. }
  259. }
  260. t.sendCallbackAnswerTgBot(callbackQuery.ID, "❗ Error in Operation.")
  261. t.searchClient(chatId, email, callbackQuery.Message.MessageID)
  262. case "ip_limit":
  263. inlineKeyboard := tu.InlineKeyboard(
  264. tu.InlineKeyboardRow(
  265. tu.InlineKeyboardButton("❌ Cancel IP Limit").WithCallbackData(t.hashStorage.AddHash("client_cancel "+email)),
  266. ),
  267. tu.InlineKeyboardRow(
  268. tu.InlineKeyboardButton("♾ Unlimited").WithCallbackData(t.hashStorage.AddHash("ip_limit_c "+email+" 0")),
  269. ),
  270. tu.InlineKeyboardRow(
  271. tu.InlineKeyboardButton("1").WithCallbackData(t.hashStorage.AddHash("ip_limit_c "+email+" 1")),
  272. tu.InlineKeyboardButton("2").WithCallbackData(t.hashStorage.AddHash("ip_limit_c "+email+" 2")),
  273. ),
  274. tu.InlineKeyboardRow(
  275. tu.InlineKeyboardButton("3").WithCallbackData(t.hashStorage.AddHash("ip_limit_c "+email+" 3")),
  276. tu.InlineKeyboardButton("4").WithCallbackData(t.hashStorage.AddHash("ip_limit_c "+email+" 4")),
  277. ),
  278. tu.InlineKeyboardRow(
  279. tu.InlineKeyboardButton("5").WithCallbackData(t.hashStorage.AddHash("ip_limit_c "+email+" 5")),
  280. tu.InlineKeyboardButton("6").WithCallbackData(t.hashStorage.AddHash("ip_limit_c "+email+" 6")),
  281. tu.InlineKeyboardButton("7").WithCallbackData(t.hashStorage.AddHash("ip_limit_c "+email+" 7")),
  282. ),
  283. tu.InlineKeyboardRow(
  284. tu.InlineKeyboardButton("8").WithCallbackData(t.hashStorage.AddHash("ip_limit_c "+email+" 8")),
  285. tu.InlineKeyboardButton("9").WithCallbackData(t.hashStorage.AddHash("ip_limit_c "+email+" 9")),
  286. tu.InlineKeyboardButton("10").WithCallbackData(t.hashStorage.AddHash("ip_limit_c "+email+" 10")),
  287. ),
  288. )
  289. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.MessageID, inlineKeyboard)
  290. case "ip_limit_c":
  291. if len(dataArray) == 3 {
  292. count, err := strconv.Atoi(dataArray[2])
  293. if err == nil {
  294. err := t.inboundService.ResetClientIpLimitByEmail(email, count)
  295. if err == nil {
  296. t.xrayService.SetToNeedRestart()
  297. t.sendCallbackAnswerTgBot(callbackQuery.ID, fmt.Sprintf("✅ %s : IP limit %d saved successfully.", email, count))
  298. t.searchClient(chatId, email, callbackQuery.Message.MessageID)
  299. return
  300. }
  301. }
  302. }
  303. t.sendCallbackAnswerTgBot(callbackQuery.ID, "❗ Error in Operation.")
  304. t.searchClient(chatId, email, callbackQuery.Message.MessageID)
  305. case "clear_ips":
  306. inlineKeyboard := tu.InlineKeyboard(
  307. tu.InlineKeyboardRow(
  308. tu.InlineKeyboardButton("❌ Cancel").WithCallbackData(t.hashStorage.AddHash("ips_cancel "+email)),
  309. ),
  310. tu.InlineKeyboardRow(
  311. tu.InlineKeyboardButton("✅ Confirm Clear IPs?").WithCallbackData(t.hashStorage.AddHash("clear_ips_c "+email)),
  312. ),
  313. )
  314. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.MessageID, inlineKeyboard)
  315. case "clear_ips_c":
  316. err := t.inboundService.ClearClientIps(email)
  317. if err == nil {
  318. t.sendCallbackAnswerTgBot(callbackQuery.ID, fmt.Sprintf("✅ %s : IPs cleared successfully.", email))
  319. t.searchClientIps(chatId, email, callbackQuery.Message.MessageID)
  320. } else {
  321. t.sendCallbackAnswerTgBot(callbackQuery.ID, "❗ Error in Operation.")
  322. }
  323. case "ip_log":
  324. t.sendCallbackAnswerTgBot(callbackQuery.ID, fmt.Sprintf("✅ %s : Get IP Log.", email))
  325. t.searchClientIps(chatId, email)
  326. case "tg_user":
  327. t.sendCallbackAnswerTgBot(callbackQuery.ID, fmt.Sprintf("✅ %s : Get Telegram User Info.", email))
  328. t.clientTelegramUserInfo(chatId, email)
  329. case "tgid_remove":
  330. inlineKeyboard := tu.InlineKeyboard(
  331. tu.InlineKeyboardRow(
  332. tu.InlineKeyboardButton("❌ Cancel").WithCallbackData(t.hashStorage.AddHash("tgid_cancel "+email)),
  333. ),
  334. tu.InlineKeyboardRow(
  335. tu.InlineKeyboardButton("✅ Confirm Remove Telegram User?").WithCallbackData(t.hashStorage.AddHash("tgid_remove_c "+email)),
  336. ),
  337. )
  338. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.MessageID, inlineKeyboard)
  339. case "tgid_remove_c":
  340. traffic, err := t.inboundService.GetClientTrafficByEmail(email)
  341. if err != nil || traffic == nil {
  342. t.sendCallbackAnswerTgBot(callbackQuery.ID, "❗ Error in Operation.")
  343. return
  344. }
  345. err = t.inboundService.SetClientTelegramUserID(traffic.Id, "")
  346. if err == nil {
  347. t.sendCallbackAnswerTgBot(callbackQuery.ID, fmt.Sprintf("✅ %s : Telegram User removed successfully.", email))
  348. t.clientTelegramUserInfo(chatId, email, callbackQuery.Message.MessageID)
  349. } else {
  350. t.sendCallbackAnswerTgBot(callbackQuery.ID, "❗ Error in Operation.")
  351. }
  352. case "toggle_enable":
  353. enabled, err := t.inboundService.ToggleClientEnableByEmail(email)
  354. if err == nil {
  355. t.xrayService.SetToNeedRestart()
  356. if enabled {
  357. t.sendCallbackAnswerTgBot(callbackQuery.ID, fmt.Sprintf("✅ %s : Enabled successfully.", email))
  358. } else {
  359. t.sendCallbackAnswerTgBot(callbackQuery.ID, fmt.Sprintf("✅ %s : Disabled successfully.", email))
  360. }
  361. t.searchClient(chatId, email, callbackQuery.Message.MessageID)
  362. } else {
  363. t.sendCallbackAnswerTgBot(callbackQuery.ID, "❗ Error in Operation.")
  364. }
  365. }
  366. return
  367. }
  368. }
  369. // Respond to the callback query, telling Telegram to show the user
  370. // a message with the data received.
  371. t.sendCallbackAnswerTgBot(callbackQuery.ID, callbackQuery.Data)
  372. switch callbackQuery.Data {
  373. case "get_usage":
  374. t.SendMsgToTgbot(chatId, t.getServerUsage())
  375. case "inbounds":
  376. t.SendMsgToTgbot(chatId, t.getInboundUsages())
  377. case "deplete_soon":
  378. t.SendMsgToTgbot(chatId, t.getExhausted())
  379. case "get_backup":
  380. t.sendBackup(chatId)
  381. case "client_traffic":
  382. t.getClientUsage(chatId, callbackQuery.From.Username, strconv.FormatInt(callbackQuery.From.ID, 10))
  383. case "client_commands":
  384. t.SendMsgToTgbot(chatId, "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.")
  385. case "commands":
  386. t.SendMsgToTgbot(chatId, "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>")
  387. }
  388. }
  389. func checkAdmin(tgId int64) bool {
  390. for _, adminId := range adminIds {
  391. if adminId == tgId {
  392. return true
  393. }
  394. }
  395. return false
  396. }
  397. func (t *Tgbot) SendAnswer(chatId int64, msg string, isAdmin bool) {
  398. numericKeyboard := tu.InlineKeyboard(
  399. tu.InlineKeyboardRow(
  400. tu.InlineKeyboardButton("Server Usage").WithCallbackData(t.hashStorage.AddHash("get_usage")),
  401. tu.InlineKeyboardButton("Get DB Backup").WithCallbackData(t.hashStorage.AddHash("get_backup")),
  402. ),
  403. tu.InlineKeyboardRow(
  404. tu.InlineKeyboardButton("Get Inbounds").WithCallbackData(t.hashStorage.AddHash("inbounds")),
  405. tu.InlineKeyboardButton("Deplete soon").WithCallbackData(t.hashStorage.AddHash("deplete_soon")),
  406. ),
  407. tu.InlineKeyboardRow(
  408. tu.InlineKeyboardButton("Commands").WithCallbackData(t.hashStorage.AddHash("commands")),
  409. ),
  410. )
  411. numericKeyboardClient := tu.InlineKeyboard(
  412. tu.InlineKeyboardRow(
  413. tu.InlineKeyboardButton("Get Usage").WithCallbackData(t.hashStorage.AddHash("client_traffic")),
  414. tu.InlineKeyboardButton("Commands").WithCallbackData(t.hashStorage.AddHash("client_commands")),
  415. ),
  416. )
  417. var ReplyMarkup telego.ReplyMarkup
  418. if isAdmin {
  419. ReplyMarkup = numericKeyboard
  420. } else {
  421. ReplyMarkup = numericKeyboardClient
  422. }
  423. t.SendMsgToTgbot(chatId, msg, ReplyMarkup)
  424. }
  425. func (t *Tgbot) SendMsgToTgbot(chatId int64, msg string, replyMarkup ...telego.ReplyMarkup) {
  426. if !isRunning {
  427. return
  428. }
  429. if msg == "" {
  430. logger.Info("[tgbot] message is empty!")
  431. return
  432. }
  433. var allMessages []string
  434. limit := 2000
  435. // paging message if it is big
  436. if len(msg) > limit {
  437. messages := strings.Split(msg, "\r\n \r\n")
  438. lastIndex := -1
  439. for _, message := range messages {
  440. if (len(allMessages) == 0) || (len(allMessages[lastIndex])+len(message) > limit) {
  441. allMessages = append(allMessages, message)
  442. lastIndex++
  443. } else {
  444. allMessages[lastIndex] += "\r\n \r\n" + message
  445. }
  446. }
  447. } else {
  448. allMessages = append(allMessages, msg)
  449. }
  450. for _, message := range allMessages {
  451. params := telego.SendMessageParams{
  452. ChatID: tu.ID(chatId),
  453. Text: message,
  454. ParseMode: "HTML",
  455. }
  456. if len(replyMarkup) > 0 {
  457. params.ReplyMarkup = replyMarkup[0]
  458. }
  459. _, err := bot.SendMessage(&params)
  460. if err != nil {
  461. logger.Warning("Error sending telegram message :", err)
  462. }
  463. time.Sleep(500 * time.Millisecond)
  464. }
  465. }
  466. func (t *Tgbot) SendMsgToTgbotAdmins(msg string) {
  467. for _, adminId := range adminIds {
  468. t.SendMsgToTgbot(adminId, msg)
  469. }
  470. }
  471. func (t *Tgbot) SendReport() {
  472. runTime, err := t.settingService.GetTgbotRuntime()
  473. if err == nil && len(runTime) > 0 {
  474. t.SendMsgToTgbotAdmins("🕰 Scheduled reports: " + runTime + "\r\nDate-Time: " + time.Now().Format("2006-01-02 15:04:05"))
  475. }
  476. info := t.getServerUsage()
  477. t.SendMsgToTgbotAdmins(info)
  478. exhausted := t.getExhausted()
  479. t.SendMsgToTgbotAdmins(exhausted)
  480. backupEnable, err := t.settingService.GetTgBotBackup()
  481. if err == nil && backupEnable {
  482. for _, adminId := range adminIds {
  483. t.sendBackup(int64(adminId))
  484. }
  485. }
  486. }
  487. func (t *Tgbot) SendBackUP(c *gin.Context) {
  488. for _, adminId := range adminIds {
  489. t.sendBackup(int64(adminId))
  490. }
  491. }
  492. func (t *Tgbot) getServerUsage() string {
  493. var info string
  494. //get hostname
  495. hostname, err := os.Hostname()
  496. if err != nil {
  497. logger.Error("get hostname error:", err)
  498. hostname = ""
  499. }
  500. info = fmt.Sprintf("💻 Hostname: %s\r\n", hostname)
  501. info += fmt.Sprintf("🚀X-UI Version: %s\r\n", config.GetVersion())
  502. //get ip address
  503. var ip string
  504. var ipv6 string
  505. netInterfaces, err := net.Interfaces()
  506. if err != nil {
  507. logger.Error("net.Interfaces failed, err:", err.Error())
  508. info += "🌐 IP: Unknown\r\n \r\n"
  509. } else {
  510. for i := 0; i < len(netInterfaces); i++ {
  511. if (netInterfaces[i].Flags & net.FlagUp) != 0 {
  512. addrs, _ := netInterfaces[i].Addrs()
  513. for _, address := range addrs {
  514. if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
  515. if ipnet.IP.To4() != nil {
  516. ip += ipnet.IP.String() + " "
  517. } else if ipnet.IP.To16() != nil && !ipnet.IP.IsLinkLocalUnicast() {
  518. ipv6 += ipnet.IP.String() + " "
  519. }
  520. }
  521. }
  522. }
  523. }
  524. info += fmt.Sprintf("🌐IP: %s\r\n🌐IPv6: %s\r\n", ip, ipv6)
  525. }
  526. // get latest status of server
  527. t.lastStatus = t.serverService.GetStatus(t.lastStatus)
  528. info += fmt.Sprintf("🔌Server Uptime: %d days\r\n", int(t.lastStatus.Uptime/86400))
  529. info += fmt.Sprintf("📈Server Load: %.1f, %.1f, %.1f\r\n", t.lastStatus.Loads[0], t.lastStatus.Loads[1], t.lastStatus.Loads[2])
  530. info += fmt.Sprintf("📋Server Memory: %s/%s\r\n", common.FormatTraffic(int64(t.lastStatus.Mem.Current)), common.FormatTraffic(int64(t.lastStatus.Mem.Total)))
  531. info += fmt.Sprintf("🔹TcpCount: %d\r\n", t.lastStatus.TcpCount)
  532. info += fmt.Sprintf("🔸UdpCount: %d\r\n", t.lastStatus.UdpCount)
  533. 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)))
  534. info += fmt.Sprintf("ℹXray status: %s", t.lastStatus.Xray.State)
  535. return info
  536. }
  537. func (t *Tgbot) UserLoginNotify(username string, ip string, time string, status LoginStatus) {
  538. if !t.IsRunning() {
  539. return
  540. }
  541. if username == "" || ip == "" || time == "" {
  542. logger.Warning("UserLoginNotify failed, invalid info!")
  543. return
  544. }
  545. // Get hostname
  546. hostname, err := os.Hostname()
  547. if err != nil {
  548. logger.Warning("get hostname error:", err)
  549. return
  550. }
  551. msg := ""
  552. if status == LoginSuccess {
  553. msg = fmt.Sprintf("✅ Successfully logged-in to the panel\r\nHostname:%s\r\n", hostname)
  554. } else if status == LoginFail {
  555. msg = fmt.Sprintf("❗ Login to the panel was unsuccessful\r\nHostname:%s\r\n", hostname)
  556. }
  557. msg += fmt.Sprintf("⏰ Time:%s\r\n", time)
  558. msg += fmt.Sprintf("🆔 Username:%s\r\n", username)
  559. msg += fmt.Sprintf("🌐 IP:%s\r\n", ip)
  560. t.SendMsgToTgbotAdmins(msg)
  561. }
  562. func (t *Tgbot) getInboundUsages() string {
  563. info := ""
  564. // get traffic
  565. inbouds, err := t.inboundService.GetAllInbounds()
  566. if err != nil {
  567. logger.Warning("GetAllInbounds run failed:", err)
  568. info += "❌ Failed to get inbounds"
  569. } else {
  570. // NOTE:If there no any sessions here,need to notify here
  571. // TODO:Sub-node push, automatic conversion format
  572. for _, inbound := range inbouds {
  573. info += fmt.Sprintf("📍Inbound:%s\r\nPort:%d\r\n", inbound.Remark, inbound.Port)
  574. info += fmt.Sprintf("Traffic: %s (↑%s,↓%s)\r\n", common.FormatTraffic((inbound.Up + inbound.Down)), common.FormatTraffic(inbound.Up), common.FormatTraffic(inbound.Down))
  575. if inbound.ExpiryTime == 0 {
  576. info += "Expire date: ♾ Unlimited\r\n \r\n"
  577. } else {
  578. info += fmt.Sprintf("Expire date:%s\r\n \r\n", time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05"))
  579. }
  580. }
  581. }
  582. return info
  583. }
  584. func (t *Tgbot) getClientUsage(chatId int64, tgUserName string, tgUserID string) {
  585. traffics, err := t.inboundService.GetClientTrafficTgBot(tgUserID)
  586. if err != nil {
  587. logger.Warning(err)
  588. msg := "❌ Something went wrong!"
  589. t.SendMsgToTgbot(chatId, msg)
  590. return
  591. }
  592. if len(traffics) == 0 {
  593. if len(tgUserName) == 0 {
  594. 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>"
  595. t.SendMsgToTgbot(chatId, msg)
  596. return
  597. }
  598. traffics, err = t.inboundService.GetClientTrafficTgBot(tgUserName)
  599. }
  600. if err != nil {
  601. logger.Warning(err)
  602. msg := "❌ Something went wrong!"
  603. t.SendMsgToTgbot(chatId, msg)
  604. return
  605. }
  606. if len(traffics) == 0 {
  607. 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>"
  608. t.SendMsgToTgbot(chatId, msg)
  609. return
  610. }
  611. for _, traffic := range traffics {
  612. expiryTime := ""
  613. if traffic.ExpiryTime == 0 {
  614. expiryTime = "♾Unlimited"
  615. } else if traffic.ExpiryTime < 0 {
  616. expiryTime = fmt.Sprintf("%d days", traffic.ExpiryTime/-86400000)
  617. } else {
  618. expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
  619. }
  620. total := ""
  621. if traffic.Total == 0 {
  622. total = "♾Unlimited"
  623. } else {
  624. total = common.FormatTraffic((traffic.Total))
  625. }
  626. 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",
  627. traffic.Enable, traffic.Email, common.FormatTraffic(traffic.Up), common.FormatTraffic(traffic.Down), common.FormatTraffic((traffic.Up + traffic.Down)),
  628. total, expiryTime)
  629. t.SendMsgToTgbot(chatId, output)
  630. }
  631. t.SendAnswer(chatId, "Please choose:", false)
  632. }
  633. func (t *Tgbot) searchClientIps(chatId int64, email string, messageID ...int) {
  634. ips, err := t.inboundService.GetInboundClientIps(email)
  635. if err != nil || len(ips) == 0 {
  636. ips = "No IP Record"
  637. }
  638. output := fmt.Sprintf("📧 Email: %s\r\n🔢 IPs: \r\n%s\r\n", email, ips)
  639. inlineKeyboard := tu.InlineKeyboard(
  640. tu.InlineKeyboardRow(
  641. tu.InlineKeyboardButton("🔄 Refresh").WithCallbackData(t.hashStorage.AddHash("ips_refresh "+email)),
  642. ),
  643. tu.InlineKeyboardRow(
  644. tu.InlineKeyboardButton("❌ Clear IPs").WithCallbackData(t.hashStorage.AddHash("clear_ips "+email)),
  645. ),
  646. )
  647. if len(messageID) > 0 {
  648. t.editMessageTgBot(chatId, messageID[0], output, inlineKeyboard)
  649. } else {
  650. t.SendMsgToTgbot(chatId, output, inlineKeyboard)
  651. }
  652. }
  653. func (t *Tgbot) clientTelegramUserInfo(chatId int64, email string, messageID ...int) {
  654. traffic, client, err := t.inboundService.GetClientByEmail(email)
  655. if err != nil {
  656. logger.Warning(err)
  657. msg := "❌ Something went wrong!"
  658. t.SendMsgToTgbot(chatId, msg)
  659. return
  660. }
  661. if client == nil {
  662. msg := "No result!"
  663. t.SendMsgToTgbot(chatId, msg)
  664. return
  665. }
  666. tgId := "None"
  667. if len(client.TgID) > 0 {
  668. tgId = client.TgID
  669. }
  670. output := fmt.Sprintf("📧 Email: %s\r\n👤 Telegram User: %s\r\n", email, tgId)
  671. inlineKeyboard := tu.InlineKeyboard(
  672. tu.InlineKeyboardRow(
  673. tu.InlineKeyboardButton("🔄 Refresh").WithCallbackData(t.hashStorage.AddHash("tgid_refresh "+email)),
  674. ),
  675. tu.InlineKeyboardRow(
  676. tu.InlineKeyboardButton("❌ Remove Telegram User").WithCallbackData(t.hashStorage.AddHash("tgid_remove "+email)),
  677. ),
  678. )
  679. if len(messageID) > 0 {
  680. t.editMessageTgBot(chatId, messageID[0], output, inlineKeyboard)
  681. } else {
  682. t.SendMsgToTgbot(chatId, output, inlineKeyboard)
  683. requestUser := telego.KeyboardButtonRequestUser{
  684. RequestID: int32(traffic.Id),
  685. UserIsBot: false,
  686. }
  687. keyboard := tu.Keyboard(
  688. tu.KeyboardRow(
  689. tu.KeyboardButton("👤 Select Telegram User").WithRequestUser(&requestUser),
  690. ),
  691. tu.KeyboardRow(
  692. tu.KeyboardButton("❌ Close Keyboard"),
  693. ),
  694. ).WithIsPersistent().WithResizeKeyboard()
  695. t.SendMsgToTgbot(chatId, "👤 Select a telegram user:", keyboard)
  696. }
  697. }
  698. func (t *Tgbot) searchClient(chatId int64, email string, messageID ...int) {
  699. traffic, err := t.inboundService.GetClientTrafficByEmail(email)
  700. if err != nil {
  701. logger.Warning(err)
  702. msg := "❌ Something went wrong!"
  703. t.SendMsgToTgbot(chatId, msg)
  704. return
  705. }
  706. if traffic == nil {
  707. msg := "No result!"
  708. t.SendMsgToTgbot(chatId, msg)
  709. return
  710. }
  711. expiryTime := ""
  712. if traffic.ExpiryTime == 0 {
  713. expiryTime = "♾Unlimited"
  714. } else if traffic.ExpiryTime < 0 {
  715. expiryTime = fmt.Sprintf("%d days", traffic.ExpiryTime/-86400000)
  716. } else {
  717. expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
  718. }
  719. total := ""
  720. if traffic.Total == 0 {
  721. total = "♾Unlimited"
  722. } else {
  723. total = common.FormatTraffic((traffic.Total))
  724. }
  725. 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",
  726. traffic.Enable, traffic.Email, common.FormatTraffic(traffic.Up), common.FormatTraffic(traffic.Down), common.FormatTraffic((traffic.Up + traffic.Down)),
  727. total, expiryTime)
  728. inlineKeyboard := tu.InlineKeyboard(
  729. tu.InlineKeyboardRow(
  730. tu.InlineKeyboardButton("🔄 Refresh").WithCallbackData(t.hashStorage.AddHash("client_refresh "+email)),
  731. ),
  732. tu.InlineKeyboardRow(
  733. tu.InlineKeyboardButton("📈 Reset Traffic").WithCallbackData(t.hashStorage.AddHash("reset_traffic "+email)),
  734. ),
  735. tu.InlineKeyboardRow(
  736. tu.InlineKeyboardButton("📅 Reset Expire Days").WithCallbackData(t.hashStorage.AddHash("reset_exp "+email)),
  737. ),
  738. tu.InlineKeyboardRow(
  739. tu.InlineKeyboardButton("🔢 IP Log").WithCallbackData(t.hashStorage.AddHash("ip_log "+email)),
  740. tu.InlineKeyboardButton("🔢 IP Limit").WithCallbackData(t.hashStorage.AddHash("ip_limit "+email)),
  741. ),
  742. tu.InlineKeyboardRow(
  743. tu.InlineKeyboardButton("👤 Set Telegram User").WithCallbackData(t.hashStorage.AddHash("tg_user "+email)),
  744. ),
  745. tu.InlineKeyboardRow(
  746. tu.InlineKeyboardButton("🔘 Enable / Disable").WithCallbackData(t.hashStorage.AddHash("toggle_enable "+email)),
  747. ),
  748. )
  749. if len(messageID) > 0 {
  750. t.editMessageTgBot(chatId, messageID[0], output, inlineKeyboard)
  751. } else {
  752. t.SendMsgToTgbot(chatId, output, inlineKeyboard)
  753. }
  754. }
  755. func (t *Tgbot) searchInbound(chatId int64, remark string) {
  756. inbouds, err := t.inboundService.SearchInbounds(remark)
  757. if err != nil {
  758. logger.Warning(err)
  759. msg := "❌ Something went wrong!"
  760. t.SendMsgToTgbot(chatId, msg)
  761. return
  762. }
  763. if len(inbouds) == 0 {
  764. msg := "❌ No inbounds found!"
  765. t.SendMsgToTgbot(chatId, msg)
  766. return
  767. }
  768. for _, inbound := range inbouds {
  769. info := ""
  770. info += fmt.Sprintf("📍Inbound:%s\r\nPort:%d\r\n", inbound.Remark, inbound.Port)
  771. info += fmt.Sprintf("Traffic: %s (↑%s,↓%s)\r\n", common.FormatTraffic((inbound.Up + inbound.Down)), common.FormatTraffic(inbound.Up), common.FormatTraffic(inbound.Down))
  772. if inbound.ExpiryTime == 0 {
  773. info += "Expire date: ♾ Unlimited\r\n \r\n"
  774. } else {
  775. info += fmt.Sprintf("Expire date:%s\r\n \r\n", time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05"))
  776. }
  777. t.SendMsgToTgbot(chatId, info)
  778. for _, traffic := range inbound.ClientStats {
  779. expiryTime := ""
  780. if traffic.ExpiryTime == 0 {
  781. expiryTime = "♾Unlimited"
  782. } else if traffic.ExpiryTime < 0 {
  783. expiryTime = fmt.Sprintf("%d days", traffic.ExpiryTime/-86400000)
  784. } else {
  785. expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
  786. }
  787. total := ""
  788. if traffic.Total == 0 {
  789. total = "♾Unlimited"
  790. } else {
  791. total = common.FormatTraffic((traffic.Total))
  792. }
  793. 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",
  794. traffic.Enable, traffic.Email, common.FormatTraffic(traffic.Up), common.FormatTraffic(traffic.Down), common.FormatTraffic((traffic.Up + traffic.Down)),
  795. total, expiryTime)
  796. t.SendMsgToTgbot(chatId, output)
  797. }
  798. }
  799. }
  800. func (t *Tgbot) searchForClient(chatId int64, query string) {
  801. traffic, err := t.inboundService.SearchClientTraffic(query)
  802. if err != nil {
  803. logger.Warning(err)
  804. msg := "❌ Something went wrong!"
  805. t.SendMsgToTgbot(chatId, msg)
  806. return
  807. }
  808. if traffic == nil {
  809. msg := "No result!"
  810. t.SendMsgToTgbot(chatId, msg)
  811. return
  812. }
  813. expiryTime := ""
  814. if traffic.ExpiryTime == 0 {
  815. expiryTime = "♾Unlimited"
  816. } else if traffic.ExpiryTime < 0 {
  817. expiryTime = fmt.Sprintf("%d days", traffic.ExpiryTime/-86400000)
  818. } else {
  819. expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
  820. }
  821. total := ""
  822. if traffic.Total == 0 {
  823. total = "♾Unlimited"
  824. } else {
  825. total = common.FormatTraffic((traffic.Total))
  826. }
  827. 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",
  828. traffic.Enable, traffic.Email, common.FormatTraffic(traffic.Up), common.FormatTraffic(traffic.Down), common.FormatTraffic((traffic.Up + traffic.Down)),
  829. total, expiryTime)
  830. t.SendMsgToTgbot(chatId, output)
  831. }
  832. func (t *Tgbot) getExhausted() string {
  833. trDiff := int64(0)
  834. exDiff := int64(0)
  835. now := time.Now().Unix() * 1000
  836. var exhaustedInbounds []model.Inbound
  837. var exhaustedClients []xray.ClientTraffic
  838. var disabledInbounds []model.Inbound
  839. var disabledClients []xray.ClientTraffic
  840. output := ""
  841. TrafficThreshold, err := t.settingService.GetTrafficDiff()
  842. if err == nil && TrafficThreshold > 0 {
  843. trDiff = int64(TrafficThreshold) * 1073741824
  844. }
  845. ExpireThreshold, err := t.settingService.GetExpireDiff()
  846. if err == nil && ExpireThreshold > 0 {
  847. exDiff = int64(ExpireThreshold) * 86400000
  848. }
  849. inbounds, err := t.inboundService.GetAllInbounds()
  850. if err != nil {
  851. logger.Warning("Unable to load Inbounds", err)
  852. }
  853. for _, inbound := range inbounds {
  854. if inbound.Enable {
  855. if (inbound.ExpiryTime > 0 && (inbound.ExpiryTime-now < exDiff)) ||
  856. (inbound.Total > 0 && (inbound.Total-(inbound.Up+inbound.Down) < trDiff)) {
  857. exhaustedInbounds = append(exhaustedInbounds, *inbound)
  858. }
  859. if len(inbound.ClientStats) > 0 {
  860. for _, client := range inbound.ClientStats {
  861. if client.Enable {
  862. if (client.ExpiryTime > 0 && (client.ExpiryTime-now < exDiff)) ||
  863. (client.Total > 0 && (client.Total-(client.Up+client.Down) < trDiff)) {
  864. exhaustedClients = append(exhaustedClients, client)
  865. }
  866. } else {
  867. disabledClients = append(disabledClients, client)
  868. }
  869. }
  870. }
  871. } else {
  872. disabledInbounds = append(disabledInbounds, *inbound)
  873. }
  874. }
  875. output += fmt.Sprintf("Exhausted Inbounds count:\r\n🛑 Disabled: %d\r\n🔜 Deplete soon: %d\r\n \r\n", len(disabledInbounds), len(exhaustedInbounds))
  876. if len(exhaustedInbounds) > 0 {
  877. output += "Exhausted Inbounds:\r\n"
  878. for _, inbound := range exhaustedInbounds {
  879. 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))
  880. if inbound.ExpiryTime == 0 {
  881. output += "Expire date: ♾Unlimited\r\n \r\n"
  882. } else {
  883. output += fmt.Sprintf("Expire date:%s\r\n \r\n", time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05"))
  884. }
  885. }
  886. }
  887. output += fmt.Sprintf("Exhausted Clients count:\r\n🛑 Exhausted: %d\r\n🔜 Deplete soon: %d\r\n \r\n", len(disabledClients), len(exhaustedClients))
  888. if len(exhaustedClients) > 0 {
  889. output += "Exhausted Clients:\r\n"
  890. for _, traffic := range exhaustedClients {
  891. expiryTime := ""
  892. if traffic.ExpiryTime == 0 {
  893. expiryTime = "♾Unlimited"
  894. } else if traffic.ExpiryTime < 0 {
  895. expiryTime += fmt.Sprintf("%d days", traffic.ExpiryTime/-86400000)
  896. } else {
  897. expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
  898. }
  899. total := ""
  900. if traffic.Total == 0 {
  901. total = "♾Unlimited"
  902. } else {
  903. total = common.FormatTraffic((traffic.Total))
  904. }
  905. 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",
  906. traffic.Enable, traffic.Email, common.FormatTraffic(traffic.Up), common.FormatTraffic(traffic.Down), common.FormatTraffic((traffic.Up + traffic.Down)),
  907. total, expiryTime)
  908. }
  909. }
  910. return output
  911. }
  912. func (t *Tgbot) sendBackup(chatId int64) {
  913. if !t.IsRunning() {
  914. return
  915. }
  916. sendingTime := time.Now().Format("2006-01-02 15:04:05")
  917. t.SendMsgToTgbot(chatId, "Backup time: "+sendingTime)
  918. file, err := os.Open(config.GetDBPath())
  919. if err != nil {
  920. logger.Warning("Error in opening db file for backup: ", err)
  921. }
  922. document := tu.Document(
  923. tu.ID(chatId),
  924. tu.File(file),
  925. )
  926. _, err = bot.SendDocument(document)
  927. if err != nil {
  928. logger.Warning("Error in uploading backup: ", err)
  929. }
  930. file, err = os.Open(xray.GetConfigPath())
  931. if err != nil {
  932. logger.Warning("Error in opening config.json file for backup: ", err)
  933. }
  934. document = tu.Document(
  935. tu.ID(chatId),
  936. tu.File(file),
  937. )
  938. _, err = bot.SendDocument(document)
  939. if err != nil {
  940. logger.Warning("Error in uploading config.json: ", err)
  941. }
  942. }
  943. func (t *Tgbot) sendCallbackAnswerTgBot(id string, message string) {
  944. params := telego.AnswerCallbackQueryParams{
  945. CallbackQueryID: id,
  946. Text: message,
  947. }
  948. if err := bot.AnswerCallbackQuery(&params); err != nil {
  949. logger.Warning(err)
  950. }
  951. }
  952. func (t *Tgbot) editMessageCallbackTgBot(chatId int64, messageID int, inlineKeyboard *telego.InlineKeyboardMarkup) {
  953. params := telego.EditMessageReplyMarkupParams{
  954. ChatID: tu.ID(chatId),
  955. MessageID: messageID,
  956. ReplyMarkup: inlineKeyboard,
  957. }
  958. if _, err := bot.EditMessageReplyMarkup(&params); err != nil {
  959. logger.Warning(err)
  960. }
  961. }
  962. func (t *Tgbot) editMessageTgBot(chatId int64, messageID int, text string, inlineKeyboard ...*telego.InlineKeyboardMarkup) {
  963. params := telego.EditMessageTextParams{
  964. ChatID: tu.ID(chatId),
  965. MessageID: messageID,
  966. Text: text,
  967. ParseMode: "HTML",
  968. }
  969. if len(inlineKeyboard) > 0 {
  970. params.ReplyMarkup = inlineKeyboard[0]
  971. }
  972. if _, err := bot.EditMessageText(&params); err != nil {
  973. logger.Warning(err)
  974. }
  975. }