tgbot.go 42 KB

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