tgbot.go 39 KB

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