1
0

tgbot.go 42 KB

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