tgbot.go 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675
  1. package service
  2. import (
  3. "embed"
  4. "fmt"
  5. "net"
  6. "net/url"
  7. "os"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "x-ui/config"
  12. "x-ui/database"
  13. "x-ui/database/model"
  14. "x-ui/logger"
  15. "x-ui/util/common"
  16. "x-ui/web/global"
  17. "x-ui/web/locale"
  18. "x-ui/xray"
  19. "github.com/mymmrac/telego"
  20. th "github.com/mymmrac/telego/telegohandler"
  21. tu "github.com/mymmrac/telego/telegoutil"
  22. "github.com/valyala/fasthttp"
  23. "github.com/valyala/fasthttp/fasthttpproxy"
  24. )
  25. var (
  26. bot *telego.Bot
  27. botHandler *th.BotHandler
  28. adminIds []int64
  29. isRunning bool
  30. hostname string
  31. hashStorage *global.HashStorage
  32. )
  33. type LoginStatus byte
  34. const (
  35. LoginSuccess LoginStatus = 1
  36. LoginFail LoginStatus = 0
  37. EmptyTelegramUserID = int64(0)
  38. )
  39. type Tgbot struct {
  40. inboundService InboundService
  41. settingService SettingService
  42. serverService ServerService
  43. xrayService XrayService
  44. lastStatus *Status
  45. }
  46. func (t *Tgbot) NewTgbot() *Tgbot {
  47. return new(Tgbot)
  48. }
  49. func (t *Tgbot) I18nBot(name string, params ...string) string {
  50. return locale.I18n(locale.Bot, name, params...)
  51. }
  52. func (t *Tgbot) GetHashStorage() *global.HashStorage {
  53. return hashStorage
  54. }
  55. func (t *Tgbot) Start(i18nFS embed.FS) error {
  56. err := locale.InitLocalizer(i18nFS, &t.settingService)
  57. if err != nil {
  58. return err
  59. }
  60. // init hash storage => store callback queries
  61. hashStorage = global.NewHashStorage(20 * time.Minute)
  62. t.SetHostname()
  63. tgBottoken, err := t.settingService.GetTgBotToken()
  64. if err != nil || tgBottoken == "" {
  65. logger.Warning("Get TgBotToken failed:", err)
  66. return err
  67. }
  68. tgBotid, err := t.settingService.GetTgBotChatId()
  69. if err != nil {
  70. logger.Warning("Get GetTgBotChatId failed:", err)
  71. return err
  72. }
  73. if tgBotid != "" {
  74. for _, adminId := range strings.Split(tgBotid, ",") {
  75. id, err := strconv.Atoi(adminId)
  76. if err != nil {
  77. logger.Warning("Failed to get IDs from GetTgBotChatId:", err)
  78. return err
  79. }
  80. adminIds = append(adminIds, int64(id))
  81. }
  82. }
  83. tgBotProxy, err := t.settingService.GetTgBotProxy()
  84. if err != nil {
  85. logger.Warning("Failed to get ProxyUrl:", err)
  86. }
  87. bot, err = t.NewBot(tgBottoken, tgBotProxy)
  88. if err != nil {
  89. fmt.Println("Get tgbot's api error:", err)
  90. return err
  91. }
  92. // listen for TG bot income messages
  93. if !isRunning {
  94. logger.Info("Starting Telegram receiver ...")
  95. go t.OnReceive()
  96. isRunning = true
  97. }
  98. return nil
  99. }
  100. func (t *Tgbot) NewBot(token string, proxyUrl string) (*telego.Bot, error) {
  101. if proxyUrl == "" {
  102. // No proxy URL provided, use default instance
  103. return telego.NewBot(token)
  104. }
  105. if !strings.HasPrefix(proxyUrl, "socks5://") {
  106. logger.Warning("Invalid socks5 URL, starting with default")
  107. return telego.NewBot(token)
  108. }
  109. _, err := url.Parse(proxyUrl)
  110. if err != nil {
  111. logger.Warning("Can't parse proxy URL, using default instance for tgbot:", err)
  112. return telego.NewBot(token)
  113. }
  114. return telego.NewBot(token, telego.WithFastHTTPClient(&fasthttp.Client{
  115. Dial: fasthttpproxy.FasthttpSocksDialer(proxyUrl),
  116. }))
  117. }
  118. func (t *Tgbot) IsRunning() bool {
  119. return isRunning
  120. }
  121. func (t *Tgbot) SetHostname() {
  122. host, err := os.Hostname()
  123. if err != nil {
  124. logger.Error("get hostname error:", err)
  125. hostname = ""
  126. return
  127. }
  128. hostname = host
  129. }
  130. func (t *Tgbot) Stop() {
  131. botHandler.Stop()
  132. bot.StopLongPolling()
  133. logger.Info("Stop Telegram receiver ...")
  134. isRunning = false
  135. adminIds = nil
  136. }
  137. func (t *Tgbot) encodeQuery(query string) string {
  138. // NOTE: we only need to hash for more than 64 chars
  139. if len(query) <= 64 {
  140. return query
  141. }
  142. return hashStorage.SaveHash(query)
  143. }
  144. func (t *Tgbot) decodeQuery(query string) (string, error) {
  145. if !hashStorage.IsMD5(query) {
  146. return query, nil
  147. }
  148. decoded, exists := hashStorage.GetValue(query)
  149. if !exists {
  150. return "", common.NewError("hash not found in storage!")
  151. }
  152. return decoded, nil
  153. }
  154. func (t *Tgbot) OnReceive() {
  155. params := telego.GetUpdatesParams{
  156. Timeout: 10,
  157. }
  158. updates, _ := bot.UpdatesViaLongPolling(&params)
  159. botHandler, _ = th.NewBotHandler(bot, updates)
  160. botHandler.HandleMessage(func(_ *telego.Bot, message telego.Message) {
  161. t.SendMsgToTgbot(message.Chat.ID, t.I18nBot("tgbot.keyboardClosed"), tu.ReplyKeyboardRemove())
  162. }, th.TextEqual(t.I18nBot("tgbot.buttons.closeKeyboard")))
  163. botHandler.HandleMessage(func(_ *telego.Bot, message telego.Message) {
  164. t.answerCommand(&message, message.Chat.ID, checkAdmin(message.From.ID))
  165. }, th.AnyCommand())
  166. botHandler.HandleCallbackQuery(func(_ *telego.Bot, query telego.CallbackQuery) {
  167. t.asnwerCallback(&query, checkAdmin(query.From.ID))
  168. }, th.AnyCallbackQueryWithMessage())
  169. botHandler.HandleMessage(func(_ *telego.Bot, message telego.Message) {
  170. if message.UsersShared != nil {
  171. if checkAdmin(message.From.ID) {
  172. userIDs := message.UsersShared.UserIDs
  173. for _, userID := range userIDs {
  174. needRestart, err := t.inboundService.SetClientTelegramUserID(message.UsersShared.RequestID, userID)
  175. if needRestart {
  176. t.xrayService.SetToNeedRestart()
  177. }
  178. output := ""
  179. if err != nil {
  180. output += t.I18nBot("tgbot.messages.selectUserFailed")
  181. } else {
  182. output += t.I18nBot("tgbot.messages.userSaved")
  183. }
  184. t.SendMsgToTgbot(message.Chat.ID, output, tu.ReplyKeyboardRemove())
  185. }
  186. } else {
  187. t.SendMsgToTgbot(message.Chat.ID, t.I18nBot("tgbot.noResult"), tu.ReplyKeyboardRemove())
  188. }
  189. }
  190. }, th.AnyMessage())
  191. botHandler.Start()
  192. }
  193. func (t *Tgbot) answerCommand(message *telego.Message, chatId int64, isAdmin bool) {
  194. msg, onlyMessage := "", false
  195. command, _, commandArgs := tu.ParseCommand(message.Text)
  196. // Extract the command from the Message.
  197. switch command {
  198. case "help":
  199. msg += t.I18nBot("tgbot.commands.help")
  200. msg += t.I18nBot("tgbot.commands.pleaseChoose")
  201. case "start":
  202. msg += t.I18nBot("tgbot.commands.start", "Firstname=="+message.From.FirstName)
  203. if isAdmin {
  204. msg += t.I18nBot("tgbot.commands.welcome", "Hostname=="+hostname)
  205. }
  206. msg += "\n\n" + t.I18nBot("tgbot.commands.pleaseChoose")
  207. case "status":
  208. onlyMessage = true
  209. msg += t.I18nBot("tgbot.commands.status")
  210. case "id":
  211. onlyMessage = true
  212. msg += t.I18nBot("tgbot.commands.getID", "ID=="+strconv.FormatInt(message.From.ID, 10))
  213. case "usage":
  214. onlyMessage = true
  215. if len(commandArgs) > 0 {
  216. if isAdmin {
  217. t.searchClient(chatId, commandArgs[0])
  218. } else {
  219. // Convert message.From.ID to int64
  220. fromID := int64(message.From.ID)
  221. t.getClientUsage(chatId, fromID, commandArgs[0])
  222. }
  223. } else {
  224. msg += t.I18nBot("tgbot.commands.usage")
  225. }
  226. case "inbound":
  227. onlyMessage = true
  228. if isAdmin && len(commandArgs) > 0 {
  229. t.searchInbound(chatId, commandArgs[0])
  230. } else {
  231. msg += t.I18nBot("tgbot.commands.unknown")
  232. }
  233. default:
  234. msg += t.I18nBot("tgbot.commands.unknown")
  235. }
  236. if msg != "" {
  237. if onlyMessage {
  238. t.SendMsgToTgbot(chatId, msg)
  239. return
  240. } else {
  241. t.SendAnswer(chatId, msg, isAdmin)
  242. }
  243. }
  244. }
  245. func (t *Tgbot) asnwerCallback(callbackQuery *telego.CallbackQuery, isAdmin bool) {
  246. chatId := callbackQuery.Message.GetChat().ID
  247. if isAdmin {
  248. // get query from hash storage
  249. decodedQuery, err := t.decodeQuery(callbackQuery.Data)
  250. if err != nil {
  251. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.noQuery"))
  252. return
  253. }
  254. dataArray := strings.Split(decodedQuery, " ")
  255. if len(dataArray) >= 2 && len(dataArray[1]) > 0 {
  256. email := dataArray[1]
  257. switch dataArray[0] {
  258. case "client_get_usage":
  259. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.messages.email", "Email=="+email))
  260. t.searchClient(chatId, email)
  261. case "client_refresh":
  262. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.clientRefreshSuccess", "Email=="+email))
  263. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  264. case "client_cancel":
  265. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.canceled", "Email=="+email))
  266. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  267. case "ips_refresh":
  268. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.IpRefreshSuccess", "Email=="+email))
  269. t.searchClientIps(chatId, email, callbackQuery.Message.GetMessageID())
  270. case "ips_cancel":
  271. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.canceled", "Email=="+email))
  272. t.searchClientIps(chatId, email, callbackQuery.Message.GetMessageID())
  273. case "tgid_refresh":
  274. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.TGIdRefreshSuccess", "Email=="+email))
  275. t.clientTelegramUserInfo(chatId, email, callbackQuery.Message.GetMessageID())
  276. case "tgid_cancel":
  277. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.canceled", "Email=="+email))
  278. t.clientTelegramUserInfo(chatId, email, callbackQuery.Message.GetMessageID())
  279. case "reset_traffic":
  280. inlineKeyboard := tu.InlineKeyboard(
  281. tu.InlineKeyboardRow(
  282. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancelReset")).WithCallbackData(t.encodeQuery("client_cancel "+email)),
  283. ),
  284. tu.InlineKeyboardRow(
  285. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmResetTraffic")).WithCallbackData(t.encodeQuery("reset_traffic_c "+email)),
  286. ),
  287. )
  288. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  289. case "reset_traffic_c":
  290. err := t.inboundService.ResetClientTrafficByEmail(email)
  291. if err == nil {
  292. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.resetTrafficSuccess", "Email=="+email))
  293. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  294. } else {
  295. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  296. }
  297. case "limit_traffic":
  298. inlineKeyboard := tu.InlineKeyboard(
  299. tu.InlineKeyboardRow(
  300. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("client_cancel "+email)),
  301. ),
  302. tu.InlineKeyboardRow(
  303. tu.InlineKeyboardButton(t.I18nBot("tgbot.unlimited")).WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 0")),
  304. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.custom")).WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" 0")),
  305. ),
  306. tu.InlineKeyboardRow(
  307. tu.InlineKeyboardButton("1 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 1")),
  308. tu.InlineKeyboardButton("5 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 5")),
  309. tu.InlineKeyboardButton("10 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 10")),
  310. ),
  311. tu.InlineKeyboardRow(
  312. tu.InlineKeyboardButton("20 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 20")),
  313. tu.InlineKeyboardButton("30 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 30")),
  314. tu.InlineKeyboardButton("40 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 40")),
  315. ),
  316. tu.InlineKeyboardRow(
  317. tu.InlineKeyboardButton("50 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 50")),
  318. tu.InlineKeyboardButton("60 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 60")),
  319. tu.InlineKeyboardButton("80 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 80")),
  320. ),
  321. tu.InlineKeyboardRow(
  322. tu.InlineKeyboardButton("100 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 100")),
  323. tu.InlineKeyboardButton("150 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 150")),
  324. tu.InlineKeyboardButton("200 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 200")),
  325. ),
  326. )
  327. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  328. case "limit_traffic_c":
  329. if len(dataArray) == 3 {
  330. limitTraffic, err := strconv.Atoi(dataArray[2])
  331. if err == nil {
  332. needRestart, err := t.inboundService.ResetClientTrafficLimitByEmail(email, limitTraffic)
  333. if needRestart {
  334. t.xrayService.SetToNeedRestart()
  335. }
  336. if err == nil {
  337. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.setTrafficLimitSuccess", "Email=="+email))
  338. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  339. return
  340. }
  341. }
  342. }
  343. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  344. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  345. case "limit_traffic_in":
  346. if len(dataArray) >= 3 {
  347. oldInputNumber, err := strconv.Atoi(dataArray[2])
  348. inputNumber := oldInputNumber
  349. if err == nil {
  350. if len(dataArray) == 4 {
  351. num, err := strconv.Atoi(dataArray[3])
  352. if err == nil {
  353. if num == -2 {
  354. inputNumber = 0
  355. } else if num == -1 {
  356. if inputNumber > 0 {
  357. inputNumber = (inputNumber / 10)
  358. }
  359. } else {
  360. inputNumber = (inputNumber * 10) + num
  361. }
  362. }
  363. if inputNumber == oldInputNumber {
  364. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.successfulOperation"))
  365. return
  366. }
  367. if inputNumber >= 999999 {
  368. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  369. return
  370. }
  371. }
  372. inlineKeyboard := tu.InlineKeyboard(
  373. tu.InlineKeyboardRow(
  374. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("client_cancel "+email)),
  375. ),
  376. tu.InlineKeyboardRow(
  377. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmNumberAdd", "Num=="+strconv.Itoa(inputNumber))).WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" "+strconv.Itoa(inputNumber))),
  378. ),
  379. tu.InlineKeyboardRow(
  380. tu.InlineKeyboardButton("1").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 1")),
  381. tu.InlineKeyboardButton("2").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 2")),
  382. tu.InlineKeyboardButton("3").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 3")),
  383. ),
  384. tu.InlineKeyboardRow(
  385. tu.InlineKeyboardButton("4").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 4")),
  386. tu.InlineKeyboardButton("5").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 5")),
  387. tu.InlineKeyboardButton("6").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 6")),
  388. ),
  389. tu.InlineKeyboardRow(
  390. tu.InlineKeyboardButton("7").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 7")),
  391. tu.InlineKeyboardButton("8").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 8")),
  392. tu.InlineKeyboardButton("9").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 9")),
  393. ),
  394. tu.InlineKeyboardRow(
  395. tu.InlineKeyboardButton("🔄").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" -2")),
  396. tu.InlineKeyboardButton("0").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 0")),
  397. tu.InlineKeyboardButton("⬅️").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" -1")),
  398. ),
  399. )
  400. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  401. return
  402. }
  403. }
  404. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  405. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  406. case "reset_exp":
  407. inlineKeyboard := tu.InlineKeyboard(
  408. tu.InlineKeyboardRow(
  409. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancelReset")).WithCallbackData(t.encodeQuery("client_cancel "+email)),
  410. ),
  411. tu.InlineKeyboardRow(
  412. tu.InlineKeyboardButton(t.I18nBot("tgbot.unlimited")).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" 0")),
  413. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.custom")).WithCallbackData(t.encodeQuery("reset_exp_in "+email+" 0")),
  414. ),
  415. tu.InlineKeyboardRow(
  416. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 7 "+t.I18nBot("tgbot.days")).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" 7")),
  417. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 10 "+t.I18nBot("tgbot.days")).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" 10")),
  418. ),
  419. tu.InlineKeyboardRow(
  420. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 14 "+t.I18nBot("tgbot.days")).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" 14")),
  421. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 20 "+t.I18nBot("tgbot.days")).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" 20")),
  422. ),
  423. tu.InlineKeyboardRow(
  424. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 1 "+t.I18nBot("tgbot.month")).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" 30")),
  425. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 3 "+t.I18nBot("tgbot.months")).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" 90")),
  426. ),
  427. tu.InlineKeyboardRow(
  428. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 6 "+t.I18nBot("tgbot.months")).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" 180")),
  429. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 12 "+t.I18nBot("tgbot.months")).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" 365")),
  430. ),
  431. )
  432. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  433. case "reset_exp_c":
  434. if len(dataArray) == 3 {
  435. days, err := strconv.Atoi(dataArray[2])
  436. if err == nil {
  437. var date int64 = 0
  438. if days > 0 {
  439. traffic, err := t.inboundService.GetClientTrafficByEmail(email)
  440. if err != nil {
  441. logger.Warning(err)
  442. msg := t.I18nBot("tgbot.wentWrong")
  443. t.SendMsgToTgbot(chatId, msg)
  444. return
  445. }
  446. if traffic == nil {
  447. msg := t.I18nBot("tgbot.noResult")
  448. t.SendMsgToTgbot(chatId, msg)
  449. return
  450. }
  451. if traffic.ExpiryTime > 0 {
  452. if traffic.ExpiryTime-time.Now().Unix()*1000 < 0 {
  453. date = -int64(days * 24 * 60 * 60000)
  454. } else {
  455. date = traffic.ExpiryTime + int64(days*24*60*60000)
  456. }
  457. } else {
  458. date = traffic.ExpiryTime - int64(days*24*60*60000)
  459. }
  460. }
  461. needRestart, err := t.inboundService.ResetClientExpiryTimeByEmail(email, date)
  462. if needRestart {
  463. t.xrayService.SetToNeedRestart()
  464. }
  465. if err == nil {
  466. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.expireResetSuccess", "Email=="+email))
  467. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  468. return
  469. }
  470. }
  471. }
  472. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  473. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  474. case "reset_exp_in":
  475. if len(dataArray) >= 3 {
  476. oldInputNumber, err := strconv.Atoi(dataArray[2])
  477. inputNumber := oldInputNumber
  478. if err == nil {
  479. if len(dataArray) == 4 {
  480. num, err := strconv.Atoi(dataArray[3])
  481. if err == nil {
  482. if num == -2 {
  483. inputNumber = 0
  484. } else if num == -1 {
  485. if inputNumber > 0 {
  486. inputNumber = (inputNumber / 10)
  487. }
  488. } else {
  489. inputNumber = (inputNumber * 10) + num
  490. }
  491. }
  492. if inputNumber == oldInputNumber {
  493. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.successfulOperation"))
  494. return
  495. }
  496. if inputNumber >= 999999 {
  497. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  498. return
  499. }
  500. }
  501. inlineKeyboard := tu.InlineKeyboard(
  502. tu.InlineKeyboardRow(
  503. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("client_cancel "+email)),
  504. ),
  505. tu.InlineKeyboardRow(
  506. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmNumber", "Num=="+strconv.Itoa(inputNumber))).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" "+strconv.Itoa(inputNumber))),
  507. ),
  508. tu.InlineKeyboardRow(
  509. tu.InlineKeyboardButton("1").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 1")),
  510. tu.InlineKeyboardButton("2").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 2")),
  511. tu.InlineKeyboardButton("3").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 3")),
  512. ),
  513. tu.InlineKeyboardRow(
  514. tu.InlineKeyboardButton("4").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 4")),
  515. tu.InlineKeyboardButton("5").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 5")),
  516. tu.InlineKeyboardButton("6").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 6")),
  517. ),
  518. tu.InlineKeyboardRow(
  519. tu.InlineKeyboardButton("7").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 7")),
  520. tu.InlineKeyboardButton("8").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 8")),
  521. tu.InlineKeyboardButton("9").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 9")),
  522. ),
  523. tu.InlineKeyboardRow(
  524. tu.InlineKeyboardButton("🔄").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" -2")),
  525. tu.InlineKeyboardButton("0").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 0")),
  526. tu.InlineKeyboardButton("⬅️").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" -1")),
  527. ),
  528. )
  529. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  530. return
  531. }
  532. }
  533. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  534. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  535. case "ip_limit":
  536. inlineKeyboard := tu.InlineKeyboard(
  537. tu.InlineKeyboardRow(
  538. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancelIpLimit")).WithCallbackData(t.encodeQuery("client_cancel "+email)),
  539. ),
  540. tu.InlineKeyboardRow(
  541. tu.InlineKeyboardButton(t.I18nBot("tgbot.unlimited")).WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 0")),
  542. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.custom")).WithCallbackData(t.encodeQuery("ip_limit_in "+email+" 0")),
  543. ),
  544. tu.InlineKeyboardRow(
  545. tu.InlineKeyboardButton("1").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 1")),
  546. tu.InlineKeyboardButton("2").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 2")),
  547. ),
  548. tu.InlineKeyboardRow(
  549. tu.InlineKeyboardButton("3").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 3")),
  550. tu.InlineKeyboardButton("4").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 4")),
  551. ),
  552. tu.InlineKeyboardRow(
  553. tu.InlineKeyboardButton("5").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 5")),
  554. tu.InlineKeyboardButton("6").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 6")),
  555. tu.InlineKeyboardButton("7").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 7")),
  556. ),
  557. tu.InlineKeyboardRow(
  558. tu.InlineKeyboardButton("8").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 8")),
  559. tu.InlineKeyboardButton("9").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 9")),
  560. tu.InlineKeyboardButton("10").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 10")),
  561. ),
  562. )
  563. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  564. case "ip_limit_c":
  565. if len(dataArray) == 3 {
  566. count, err := strconv.Atoi(dataArray[2])
  567. if err == nil {
  568. needRestart, err := t.inboundService.ResetClientIpLimitByEmail(email, count)
  569. if needRestart {
  570. t.xrayService.SetToNeedRestart()
  571. }
  572. if err == nil {
  573. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.resetIpSuccess", "Email=="+email, "Count=="+strconv.Itoa(count)))
  574. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  575. return
  576. }
  577. }
  578. }
  579. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  580. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  581. case "ip_limit_in":
  582. if len(dataArray) >= 3 {
  583. oldInputNumber, err := strconv.Atoi(dataArray[2])
  584. inputNumber := oldInputNumber
  585. if err == nil {
  586. if len(dataArray) == 4 {
  587. num, err := strconv.Atoi(dataArray[3])
  588. if err == nil {
  589. if num == -2 {
  590. inputNumber = 0
  591. } else if num == -1 {
  592. if inputNumber > 0 {
  593. inputNumber = (inputNumber / 10)
  594. }
  595. } else {
  596. inputNumber = (inputNumber * 10) + num
  597. }
  598. }
  599. if inputNumber == oldInputNumber {
  600. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.successfulOperation"))
  601. return
  602. }
  603. if inputNumber >= 999999 {
  604. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  605. return
  606. }
  607. }
  608. inlineKeyboard := tu.InlineKeyboard(
  609. tu.InlineKeyboardRow(
  610. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("client_cancel "+email)),
  611. ),
  612. tu.InlineKeyboardRow(
  613. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmNumber", "Num=="+strconv.Itoa(inputNumber))).WithCallbackData(t.encodeQuery("ip_limit_c "+email+" "+strconv.Itoa(inputNumber))),
  614. ),
  615. tu.InlineKeyboardRow(
  616. tu.InlineKeyboardButton("1").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 1")),
  617. tu.InlineKeyboardButton("2").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 2")),
  618. tu.InlineKeyboardButton("3").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 3")),
  619. ),
  620. tu.InlineKeyboardRow(
  621. tu.InlineKeyboardButton("4").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 4")),
  622. tu.InlineKeyboardButton("5").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 5")),
  623. tu.InlineKeyboardButton("6").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 6")),
  624. ),
  625. tu.InlineKeyboardRow(
  626. tu.InlineKeyboardButton("7").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 7")),
  627. tu.InlineKeyboardButton("8").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 8")),
  628. tu.InlineKeyboardButton("9").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 9")),
  629. ),
  630. tu.InlineKeyboardRow(
  631. tu.InlineKeyboardButton("🔄").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" -2")),
  632. tu.InlineKeyboardButton("0").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 0")),
  633. tu.InlineKeyboardButton("⬅️").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" -1")),
  634. ),
  635. )
  636. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  637. return
  638. }
  639. }
  640. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  641. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  642. case "clear_ips":
  643. inlineKeyboard := tu.InlineKeyboard(
  644. tu.InlineKeyboardRow(
  645. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("ips_cancel "+email)),
  646. ),
  647. tu.InlineKeyboardRow(
  648. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmClearIps")).WithCallbackData(t.encodeQuery("clear_ips_c "+email)),
  649. ),
  650. )
  651. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  652. case "clear_ips_c":
  653. err := t.inboundService.ClearClientIps(email)
  654. if err == nil {
  655. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.clearIpSuccess", "Email=="+email))
  656. t.searchClientIps(chatId, email, callbackQuery.Message.GetMessageID())
  657. } else {
  658. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  659. }
  660. case "ip_log":
  661. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.getIpLog", "Email=="+email))
  662. t.searchClientIps(chatId, email)
  663. case "tg_user":
  664. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.getUserInfo", "Email=="+email))
  665. t.clientTelegramUserInfo(chatId, email)
  666. case "tgid_remove":
  667. inlineKeyboard := tu.InlineKeyboard(
  668. tu.InlineKeyboardRow(
  669. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("tgid_cancel "+email)),
  670. ),
  671. tu.InlineKeyboardRow(
  672. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmRemoveTGUser")).WithCallbackData(t.encodeQuery("tgid_remove_c "+email)),
  673. ),
  674. )
  675. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  676. case "tgid_remove_c":
  677. traffic, err := t.inboundService.GetClientTrafficByEmail(email)
  678. if err != nil || traffic == nil {
  679. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  680. return
  681. }
  682. needRestart, err := t.inboundService.SetClientTelegramUserID(traffic.Id, EmptyTelegramUserID)
  683. if needRestart {
  684. t.xrayService.SetToNeedRestart()
  685. }
  686. if err == nil {
  687. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.removedTGUserSuccess", "Email=="+email))
  688. t.clientTelegramUserInfo(chatId, email, callbackQuery.Message.GetMessageID())
  689. } else {
  690. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  691. }
  692. case "toggle_enable":
  693. inlineKeyboard := tu.InlineKeyboard(
  694. tu.InlineKeyboardRow(
  695. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("client_cancel "+email)),
  696. ),
  697. tu.InlineKeyboardRow(
  698. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmToggle")).WithCallbackData(t.encodeQuery("toggle_enable_c "+email)),
  699. ),
  700. )
  701. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  702. case "toggle_enable_c":
  703. enabled, needRestart, err := t.inboundService.ToggleClientEnableByEmail(email)
  704. if needRestart {
  705. t.xrayService.SetToNeedRestart()
  706. }
  707. if err == nil {
  708. if enabled {
  709. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.enableSuccess", "Email=="+email))
  710. } else {
  711. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.disableSuccess", "Email=="+email))
  712. }
  713. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  714. } else {
  715. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  716. }
  717. }
  718. return
  719. }
  720. }
  721. switch callbackQuery.Data {
  722. case "get_usage":
  723. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.serverUsage"))
  724. t.SendMsgToTgbot(chatId, t.getServerUsage())
  725. case "inbounds":
  726. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.getInbounds"))
  727. t.SendMsgToTgbot(chatId, t.getInboundUsages())
  728. case "deplete_soon":
  729. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.depleteSoon"))
  730. t.getExhausted(chatId)
  731. case "get_backup":
  732. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.dbBackup"))
  733. t.sendBackup(chatId)
  734. case "get_banlogs":
  735. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.getBanLogs"))
  736. t.sendBanLogs(chatId, true)
  737. case "client_traffic":
  738. tgUserID := callbackQuery.From.ID
  739. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.clientUsage"))
  740. t.getClientUsage(chatId, tgUserID)
  741. case "client_commands":
  742. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.commands"))
  743. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.commands.helpClientCommands"))
  744. case "onlines":
  745. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.onlines"))
  746. t.onlineClients(chatId)
  747. case "onlines_refresh":
  748. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.successfulOperation"))
  749. t.onlineClients(chatId, callbackQuery.Message.GetMessageID())
  750. case "commands":
  751. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.commands"))
  752. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.commands.helpAdminCommands"))
  753. }
  754. }
  755. func checkAdmin(tgId int64) bool {
  756. for _, adminId := range adminIds {
  757. if adminId == tgId {
  758. return true
  759. }
  760. }
  761. return false
  762. }
  763. func (t *Tgbot) SendAnswer(chatId int64, msg string, isAdmin bool) {
  764. numericKeyboard := tu.InlineKeyboard(
  765. tu.InlineKeyboardRow(
  766. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.serverUsage")).WithCallbackData(t.encodeQuery("get_usage")),
  767. ),
  768. tu.InlineKeyboardRow(
  769. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.dbBackup")).WithCallbackData(t.encodeQuery("get_backup")),
  770. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.getBanLogs")).WithCallbackData(t.encodeQuery("get_banlogs")),
  771. ),
  772. tu.InlineKeyboardRow(
  773. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.getInbounds")).WithCallbackData(t.encodeQuery("inbounds")),
  774. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.depleteSoon")).WithCallbackData(t.encodeQuery("deplete_soon")),
  775. ),
  776. tu.InlineKeyboardRow(
  777. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.commands")).WithCallbackData(t.encodeQuery("commands")),
  778. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.onlines")).WithCallbackData(t.encodeQuery("onlines")),
  779. ),
  780. )
  781. numericKeyboardClient := tu.InlineKeyboard(
  782. tu.InlineKeyboardRow(
  783. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.clientUsage")).WithCallbackData(t.encodeQuery("client_traffic")),
  784. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.commands")).WithCallbackData(t.encodeQuery("client_commands")),
  785. ),
  786. )
  787. var ReplyMarkup telego.ReplyMarkup
  788. if isAdmin {
  789. ReplyMarkup = numericKeyboard
  790. } else {
  791. ReplyMarkup = numericKeyboardClient
  792. }
  793. t.SendMsgToTgbot(chatId, msg, ReplyMarkup)
  794. }
  795. func (t *Tgbot) SendMsgToTgbot(chatId int64, msg string, replyMarkup ...telego.ReplyMarkup) {
  796. if !isRunning {
  797. return
  798. }
  799. if msg == "" {
  800. logger.Info("[tgbot] message is empty!")
  801. return
  802. }
  803. var allMessages []string
  804. limit := 2000
  805. // paging message if it is big
  806. if len(msg) > limit {
  807. messages := strings.Split(msg, "\r\n\r\n")
  808. lastIndex := -1
  809. for _, message := range messages {
  810. if (len(allMessages) == 0) || (len(allMessages[lastIndex])+len(message) > limit) {
  811. allMessages = append(allMessages, message)
  812. lastIndex++
  813. } else {
  814. allMessages[lastIndex] += "\r\n\r\n" + message
  815. }
  816. }
  817. if strings.TrimSpace(allMessages[len(allMessages)-1]) == "" {
  818. allMessages = allMessages[:len(allMessages)-1]
  819. }
  820. } else {
  821. allMessages = append(allMessages, msg)
  822. }
  823. for n, message := range allMessages {
  824. params := telego.SendMessageParams{
  825. ChatID: tu.ID(chatId),
  826. Text: message,
  827. ParseMode: "HTML",
  828. }
  829. // only add replyMarkup to last message
  830. if len(replyMarkup) > 0 && n == (len(allMessages)-1) {
  831. params.ReplyMarkup = replyMarkup[0]
  832. }
  833. _, err := bot.SendMessage(&params)
  834. if err != nil {
  835. logger.Warning("Error sending telegram message :", err)
  836. }
  837. time.Sleep(500 * time.Millisecond)
  838. }
  839. }
  840. func (t *Tgbot) SendMsgToTgbotAdmins(msg string, replyMarkup ...telego.ReplyMarkup) {
  841. if len(replyMarkup) > 0 {
  842. for _, adminId := range adminIds {
  843. t.SendMsgToTgbot(adminId, msg, replyMarkup[0])
  844. }
  845. } else {
  846. for _, adminId := range adminIds {
  847. t.SendMsgToTgbot(adminId, msg)
  848. }
  849. }
  850. }
  851. func (t *Tgbot) SendReport() {
  852. runTime, err := t.settingService.GetTgbotRuntime()
  853. if err == nil && len(runTime) > 0 {
  854. msg := ""
  855. msg += t.I18nBot("tgbot.messages.report", "RunTime=="+runTime)
  856. msg += t.I18nBot("tgbot.messages.datetime", "DateTime=="+time.Now().Format("2006-01-02 15:04:05"))
  857. t.SendMsgToTgbotAdmins(msg)
  858. }
  859. info := t.getServerUsage()
  860. t.SendMsgToTgbotAdmins(info)
  861. t.sendExhaustedToAdmins()
  862. t.notifyExhausted()
  863. backupEnable, err := t.settingService.GetTgBotBackup()
  864. if err == nil && backupEnable {
  865. t.SendBackupToAdmins()
  866. }
  867. }
  868. func (t *Tgbot) SendBackupToAdmins() {
  869. if !t.IsRunning() {
  870. return
  871. }
  872. for _, adminId := range adminIds {
  873. t.sendBackup(int64(adminId))
  874. }
  875. }
  876. func (t *Tgbot) sendExhaustedToAdmins() {
  877. if !t.IsRunning() {
  878. return
  879. }
  880. for _, adminId := range adminIds {
  881. t.getExhausted(int64(adminId))
  882. }
  883. }
  884. func (t *Tgbot) getServerUsage() string {
  885. info, ipv4, ipv6 := "", "", ""
  886. info += t.I18nBot("tgbot.messages.hostname", "Hostname=="+hostname)
  887. info += t.I18nBot("tgbot.messages.version", "Version=="+config.GetVersion())
  888. // get ip address
  889. netInterfaces, err := net.Interfaces()
  890. if err != nil {
  891. logger.Error("net.Interfaces failed, err: ", err.Error())
  892. info += t.I18nBot("tgbot.messages.ip", "IP=="+t.I18nBot("tgbot.unknown"))
  893. info += "\r\n"
  894. } else {
  895. for i := 0; i < len(netInterfaces); i++ {
  896. if (netInterfaces[i].Flags & net.FlagUp) != 0 {
  897. addrs, _ := netInterfaces[i].Addrs()
  898. for _, address := range addrs {
  899. if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
  900. if ipnet.IP.To4() != nil {
  901. ipv4 += ipnet.IP.String() + " "
  902. } else if ipnet.IP.To16() != nil && !ipnet.IP.IsLinkLocalUnicast() {
  903. ipv6 += ipnet.IP.String() + " "
  904. }
  905. }
  906. }
  907. }
  908. }
  909. info += t.I18nBot("tgbot.messages.ipv4", "IPv4=="+ipv4)
  910. info += t.I18nBot("tgbot.messages.ipv6", "IPv6=="+ipv6)
  911. }
  912. // get latest status of server
  913. t.lastStatus = t.serverService.GetStatus(t.lastStatus)
  914. onlines := p.GetOnlineClients()
  915. info += t.I18nBot("tgbot.messages.serverUpTime", "UpTime=="+strconv.FormatUint(t.lastStatus.Uptime/86400, 10), "Unit=="+t.I18nBot("tgbot.days"))
  916. 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))
  917. info += t.I18nBot("tgbot.messages.serverMemory", "Current=="+common.FormatTraffic(int64(t.lastStatus.Mem.Current)), "Total=="+common.FormatTraffic(int64(t.lastStatus.Mem.Total)))
  918. info += t.I18nBot("tgbot.messages.onlinesCount", "Count=="+fmt.Sprint(len(onlines)))
  919. info += t.I18nBot("tgbot.messages.tcpCount", "Count=="+strconv.Itoa(t.lastStatus.TcpCount))
  920. info += t.I18nBot("tgbot.messages.udpCount", "Count=="+strconv.Itoa(t.lastStatus.UdpCount))
  921. 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)))
  922. info += t.I18nBot("tgbot.messages.xrayStatus", "State=="+fmt.Sprint(t.lastStatus.Xray.State))
  923. return info
  924. }
  925. func (t *Tgbot) UserLoginNotify(username string, ip string, time string, status LoginStatus) {
  926. if !t.IsRunning() {
  927. return
  928. }
  929. if username == "" || ip == "" || time == "" {
  930. logger.Warning("UserLoginNotify failed, invalid info!")
  931. return
  932. }
  933. loginNotifyEnabled, err := t.settingService.GetTgBotLoginNotify()
  934. if err != nil || !loginNotifyEnabled {
  935. return
  936. }
  937. msg := ""
  938. if status == LoginSuccess {
  939. msg += t.I18nBot("tgbot.messages.loginSuccess")
  940. } else if status == LoginFail {
  941. msg += t.I18nBot("tgbot.messages.loginFailed")
  942. }
  943. msg += t.I18nBot("tgbot.messages.hostname", "Hostname=="+hostname)
  944. msg += t.I18nBot("tgbot.messages.username", "Username=="+username)
  945. msg += t.I18nBot("tgbot.messages.ip", "IP=="+ip)
  946. msg += t.I18nBot("tgbot.messages.time", "Time=="+time)
  947. t.SendMsgToTgbotAdmins(msg)
  948. }
  949. func (t *Tgbot) getInboundUsages() string {
  950. info := ""
  951. // get traffic
  952. inbouds, err := t.inboundService.GetAllInbounds()
  953. if err != nil {
  954. logger.Warning("GetAllInbounds run failed:", err)
  955. info += t.I18nBot("tgbot.answers.getInboundsFailed")
  956. } else {
  957. // NOTE:If there no any sessions here,need to notify here
  958. // TODO:Sub-node push, automatic conversion format
  959. for _, inbound := range inbouds {
  960. info += t.I18nBot("tgbot.messages.inbound", "Remark=="+inbound.Remark)
  961. info += t.I18nBot("tgbot.messages.port", "Port=="+strconv.Itoa(inbound.Port))
  962. info += t.I18nBot("tgbot.messages.traffic", "Total=="+common.FormatTraffic((inbound.Up+inbound.Down)), "Upload=="+common.FormatTraffic(inbound.Up), "Download=="+common.FormatTraffic(inbound.Down))
  963. if inbound.ExpiryTime == 0 {
  964. info += t.I18nBot("tgbot.messages.expire", "Time=="+t.I18nBot("tgbot.unlimited"))
  965. } else {
  966. info += t.I18nBot("tgbot.messages.expire", "Time=="+time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05"))
  967. }
  968. info += "\r\n"
  969. }
  970. }
  971. return info
  972. }
  973. func (t *Tgbot) clientInfoMsg(
  974. traffic *xray.ClientTraffic,
  975. printEnabled bool,
  976. printOnline bool,
  977. printActive bool,
  978. printDate bool,
  979. printTraffic bool,
  980. printRefreshed bool,
  981. ) string {
  982. now := time.Now().Unix()
  983. expiryTime := ""
  984. flag := false
  985. diff := traffic.ExpiryTime/1000 - now
  986. if traffic.ExpiryTime == 0 {
  987. expiryTime = t.I18nBot("tgbot.unlimited")
  988. } else if diff > 172800 || !traffic.Enable {
  989. expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
  990. } else if traffic.ExpiryTime < 0 {
  991. expiryTime = fmt.Sprintf("%d %s", traffic.ExpiryTime/-86400000, t.I18nBot("tgbot.days"))
  992. flag = true
  993. } else {
  994. expiryTime = fmt.Sprintf("%d %s", diff/3600, t.I18nBot("tgbot.hours"))
  995. flag = true
  996. }
  997. total := ""
  998. if traffic.Total == 0 {
  999. total = t.I18nBot("tgbot.unlimited")
  1000. } else {
  1001. total = common.FormatTraffic((traffic.Total))
  1002. }
  1003. enabled := ""
  1004. isEnabled, err := t.inboundService.checkIsEnabledByEmail(traffic.Email)
  1005. if err != nil {
  1006. logger.Warning(err)
  1007. enabled = t.I18nBot("tgbot.wentWrong")
  1008. } else if isEnabled {
  1009. enabled = t.I18nBot("tgbot.messages.yes")
  1010. } else {
  1011. enabled = t.I18nBot("tgbot.messages.no")
  1012. }
  1013. active := ""
  1014. if traffic.Enable {
  1015. active = t.I18nBot("tgbot.messages.yes")
  1016. } else {
  1017. active = t.I18nBot("tgbot.messages.no")
  1018. }
  1019. status := t.I18nBot("tgbot.offline")
  1020. if p.IsRunning() {
  1021. for _, online := range p.GetOnlineClients() {
  1022. if online == traffic.Email {
  1023. status = t.I18nBot("tgbot.online")
  1024. break
  1025. }
  1026. }
  1027. }
  1028. output := ""
  1029. output += t.I18nBot("tgbot.messages.email", "Email=="+traffic.Email)
  1030. if printEnabled {
  1031. output += t.I18nBot("tgbot.messages.enabled", "Enable=="+enabled)
  1032. }
  1033. if printOnline {
  1034. output += t.I18nBot("tgbot.messages.online", "Status=="+status)
  1035. }
  1036. if printActive {
  1037. output += t.I18nBot("tgbot.messages.active", "Enable=="+active)
  1038. }
  1039. if printDate {
  1040. if flag {
  1041. output += t.I18nBot("tgbot.messages.expireIn", "Time=="+expiryTime)
  1042. } else {
  1043. output += t.I18nBot("tgbot.messages.expire", "Time=="+expiryTime)
  1044. }
  1045. }
  1046. if printTraffic {
  1047. output += t.I18nBot("tgbot.messages.upload", "Upload=="+common.FormatTraffic(traffic.Up))
  1048. output += t.I18nBot("tgbot.messages.download", "Download=="+common.FormatTraffic(traffic.Down))
  1049. output += t.I18nBot("tgbot.messages.total", "UpDown=="+common.FormatTraffic((traffic.Up+traffic.Down)), "Total=="+total)
  1050. }
  1051. if printRefreshed {
  1052. output += t.I18nBot("tgbot.messages.refreshedOn", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
  1053. }
  1054. return output
  1055. }
  1056. func (t *Tgbot) getClientUsage(chatId int64, tgUserID int64, email ...string) {
  1057. traffics, err := t.inboundService.GetClientTrafficTgBot(tgUserID)
  1058. if err != nil {
  1059. logger.Warning(err)
  1060. msg := t.I18nBot("tgbot.wentWrong")
  1061. t.SendMsgToTgbot(chatId, msg)
  1062. return
  1063. }
  1064. if len(traffics) == 0 {
  1065. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.askToAddUserId", "TgUserID=="+strconv.FormatInt(tgUserID, 10)))
  1066. return
  1067. }
  1068. output := ""
  1069. if len(traffics) > 0 {
  1070. if len(email) > 0 {
  1071. for _, traffic := range traffics {
  1072. if traffic.Email == email[0] {
  1073. output := t.clientInfoMsg(traffic, true, true, true, true, true, true)
  1074. t.SendMsgToTgbot(chatId, output)
  1075. return
  1076. }
  1077. }
  1078. msg := t.I18nBot("tgbot.noResult")
  1079. t.SendMsgToTgbot(chatId, msg)
  1080. return
  1081. } else {
  1082. for _, traffic := range traffics {
  1083. output += t.clientInfoMsg(traffic, true, true, true, true, true, false)
  1084. output += "\r\n"
  1085. }
  1086. }
  1087. }
  1088. output += t.I18nBot("tgbot.messages.refreshedOn", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
  1089. t.SendMsgToTgbot(chatId, output)
  1090. output = t.I18nBot("tgbot.commands.pleaseChoose")
  1091. t.SendAnswer(chatId, output, false)
  1092. }
  1093. func (t *Tgbot) searchClientIps(chatId int64, email string, messageID ...int) {
  1094. ips, err := t.inboundService.GetInboundClientIps(email)
  1095. if err != nil || len(ips) == 0 {
  1096. ips = t.I18nBot("tgbot.noIpRecord")
  1097. }
  1098. output := ""
  1099. output += t.I18nBot("tgbot.messages.email", "Email=="+email)
  1100. output += t.I18nBot("tgbot.messages.ips", "IPs=="+ips)
  1101. output += t.I18nBot("tgbot.messages.refreshedOn", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
  1102. inlineKeyboard := tu.InlineKeyboard(
  1103. tu.InlineKeyboardRow(
  1104. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.refresh")).WithCallbackData(t.encodeQuery("ips_refresh "+email)),
  1105. ),
  1106. tu.InlineKeyboardRow(
  1107. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.clearIPs")).WithCallbackData(t.encodeQuery("clear_ips "+email)),
  1108. ),
  1109. )
  1110. if len(messageID) > 0 {
  1111. t.editMessageTgBot(chatId, messageID[0], output, inlineKeyboard)
  1112. } else {
  1113. t.SendMsgToTgbot(chatId, output, inlineKeyboard)
  1114. }
  1115. }
  1116. func (t *Tgbot) clientTelegramUserInfo(chatId int64, email string, messageID ...int) {
  1117. traffic, client, err := t.inboundService.GetClientByEmail(email)
  1118. if err != nil {
  1119. logger.Warning(err)
  1120. msg := t.I18nBot("tgbot.wentWrong")
  1121. t.SendMsgToTgbot(chatId, msg)
  1122. return
  1123. }
  1124. if client == nil {
  1125. msg := t.I18nBot("tgbot.noResult")
  1126. t.SendMsgToTgbot(chatId, msg)
  1127. return
  1128. }
  1129. tgId := "None"
  1130. if client.TgID != 0 {
  1131. tgId = strconv.FormatInt(client.TgID, 10)
  1132. }
  1133. output := ""
  1134. output += t.I18nBot("tgbot.messages.email", "Email=="+email)
  1135. output += t.I18nBot("tgbot.messages.TGUser", "TelegramID=="+tgId)
  1136. output += t.I18nBot("tgbot.messages.refreshedOn", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
  1137. inlineKeyboard := tu.InlineKeyboard(
  1138. tu.InlineKeyboardRow(
  1139. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.refresh")).WithCallbackData(t.encodeQuery("tgid_refresh "+email)),
  1140. ),
  1141. tu.InlineKeyboardRow(
  1142. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.removeTGUser")).WithCallbackData(t.encodeQuery("tgid_remove "+email)),
  1143. ),
  1144. )
  1145. if len(messageID) > 0 {
  1146. t.editMessageTgBot(chatId, messageID[0], output, inlineKeyboard)
  1147. } else {
  1148. t.SendMsgToTgbot(chatId, output, inlineKeyboard)
  1149. requestUser := telego.KeyboardButtonRequestUsers{
  1150. RequestID: int32(traffic.Id),
  1151. UserIsBot: new(bool),
  1152. }
  1153. keyboard := tu.Keyboard(
  1154. tu.KeyboardRow(
  1155. tu.KeyboardButton(t.I18nBot("tgbot.buttons.selectTGUser")).WithRequestUsers(&requestUser),
  1156. ),
  1157. tu.KeyboardRow(
  1158. tu.KeyboardButton(t.I18nBot("tgbot.buttons.closeKeyboard")),
  1159. ),
  1160. ).WithIsPersistent().WithResizeKeyboard()
  1161. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.buttons.selectOneTGUser"), keyboard)
  1162. }
  1163. }
  1164. func (t *Tgbot) searchClient(chatId int64, email string, messageID ...int) {
  1165. traffic, err := t.inboundService.GetClientTrafficByEmail(email)
  1166. if err != nil {
  1167. logger.Warning(err)
  1168. msg := t.I18nBot("tgbot.wentWrong")
  1169. t.SendMsgToTgbot(chatId, msg)
  1170. return
  1171. }
  1172. if traffic == nil {
  1173. msg := t.I18nBot("tgbot.noResult")
  1174. t.SendMsgToTgbot(chatId, msg)
  1175. return
  1176. }
  1177. output := t.clientInfoMsg(traffic, true, true, true, true, true, true)
  1178. inlineKeyboard := tu.InlineKeyboard(
  1179. tu.InlineKeyboardRow(
  1180. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.refresh")).WithCallbackData(t.encodeQuery("client_refresh "+email)),
  1181. ),
  1182. tu.InlineKeyboardRow(
  1183. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.resetTraffic")).WithCallbackData(t.encodeQuery("reset_traffic "+email)),
  1184. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.limitTraffic")).WithCallbackData(t.encodeQuery("limit_traffic "+email)),
  1185. ),
  1186. tu.InlineKeyboardRow(
  1187. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.resetExpire")).WithCallbackData(t.encodeQuery("reset_exp "+email)),
  1188. ),
  1189. tu.InlineKeyboardRow(
  1190. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.ipLog")).WithCallbackData(t.encodeQuery("ip_log "+email)),
  1191. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.ipLimit")).WithCallbackData(t.encodeQuery("ip_limit "+email)),
  1192. ),
  1193. tu.InlineKeyboardRow(
  1194. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.setTGUser")).WithCallbackData(t.encodeQuery("tg_user "+email)),
  1195. ),
  1196. tu.InlineKeyboardRow(
  1197. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.toggle")).WithCallbackData(t.encodeQuery("toggle_enable "+email)),
  1198. ),
  1199. )
  1200. if len(messageID) > 0 {
  1201. t.editMessageTgBot(chatId, messageID[0], output, inlineKeyboard)
  1202. } else {
  1203. t.SendMsgToTgbot(chatId, output, inlineKeyboard)
  1204. }
  1205. }
  1206. func (t *Tgbot) searchInbound(chatId int64, remark string) {
  1207. inbouds, err := t.inboundService.SearchInbounds(remark)
  1208. if err != nil {
  1209. logger.Warning(err)
  1210. msg := t.I18nBot("tgbot.wentWrong")
  1211. t.SendMsgToTgbot(chatId, msg)
  1212. return
  1213. }
  1214. if len(inbouds) == 0 {
  1215. msg := t.I18nBot("tgbot.noInbounds")
  1216. t.SendMsgToTgbot(chatId, msg)
  1217. return
  1218. }
  1219. for _, inbound := range inbouds {
  1220. info := ""
  1221. info += t.I18nBot("tgbot.messages.inbound", "Remark=="+inbound.Remark)
  1222. info += t.I18nBot("tgbot.messages.port", "Port=="+strconv.Itoa(inbound.Port))
  1223. info += t.I18nBot("tgbot.messages.traffic", "Total=="+common.FormatTraffic((inbound.Up+inbound.Down)), "Upload=="+common.FormatTraffic(inbound.Up), "Download=="+common.FormatTraffic(inbound.Down))
  1224. if inbound.ExpiryTime == 0 {
  1225. info += t.I18nBot("tgbot.messages.expire", "Time=="+t.I18nBot("tgbot.unlimited"))
  1226. } else {
  1227. info += t.I18nBot("tgbot.messages.expire", "Time=="+time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05"))
  1228. }
  1229. t.SendMsgToTgbot(chatId, info)
  1230. if len(inbound.ClientStats) > 0 {
  1231. output := ""
  1232. for _, traffic := range inbound.ClientStats {
  1233. output += t.clientInfoMsg(&traffic, true, true, true, true, true, true)
  1234. }
  1235. t.SendMsgToTgbot(chatId, output)
  1236. }
  1237. }
  1238. }
  1239. func (t *Tgbot) getExhausted(chatId int64) {
  1240. trDiff := int64(0)
  1241. exDiff := int64(0)
  1242. now := time.Now().Unix() * 1000
  1243. var exhaustedInbounds []model.Inbound
  1244. var exhaustedClients []xray.ClientTraffic
  1245. var disabledInbounds []model.Inbound
  1246. var disabledClients []xray.ClientTraffic
  1247. TrafficThreshold, err := t.settingService.GetTrafficDiff()
  1248. if err == nil && TrafficThreshold > 0 {
  1249. trDiff = int64(TrafficThreshold) * 1073741824
  1250. }
  1251. ExpireThreshold, err := t.settingService.GetExpireDiff()
  1252. if err == nil && ExpireThreshold > 0 {
  1253. exDiff = int64(ExpireThreshold) * 86400000
  1254. }
  1255. inbounds, err := t.inboundService.GetAllInbounds()
  1256. if err != nil {
  1257. logger.Warning("Unable to load Inbounds", err)
  1258. }
  1259. for _, inbound := range inbounds {
  1260. if inbound.Enable {
  1261. if (inbound.ExpiryTime > 0 && (inbound.ExpiryTime-now < exDiff)) ||
  1262. (inbound.Total > 0 && (inbound.Total-(inbound.Up+inbound.Down) < trDiff)) {
  1263. exhaustedInbounds = append(exhaustedInbounds, *inbound)
  1264. }
  1265. if len(inbound.ClientStats) > 0 {
  1266. for _, client := range inbound.ClientStats {
  1267. if client.Enable {
  1268. if (client.ExpiryTime > 0 && (client.ExpiryTime-now < exDiff)) ||
  1269. (client.Total > 0 && (client.Total-(client.Up+client.Down) < trDiff)) {
  1270. exhaustedClients = append(exhaustedClients, client)
  1271. }
  1272. } else {
  1273. disabledClients = append(disabledClients, client)
  1274. }
  1275. }
  1276. }
  1277. } else {
  1278. disabledInbounds = append(disabledInbounds, *inbound)
  1279. }
  1280. }
  1281. // Inbounds
  1282. output := ""
  1283. output += t.I18nBot("tgbot.messages.exhaustedCount", "Type=="+t.I18nBot("tgbot.inbounds"))
  1284. output += t.I18nBot("tgbot.messages.disabled", "Disabled=="+strconv.Itoa(len(disabledInbounds)))
  1285. output += t.I18nBot("tgbot.messages.depleteSoon", "Deplete=="+strconv.Itoa(len(exhaustedInbounds)))
  1286. if len(exhaustedInbounds) > 0 {
  1287. output += t.I18nBot("tgbot.messages.depleteSoon", "Deplete=="+t.I18nBot("tgbot.inbounds"))
  1288. for _, inbound := range exhaustedInbounds {
  1289. output += t.I18nBot("tgbot.messages.inbound", "Remark=="+inbound.Remark)
  1290. output += t.I18nBot("tgbot.messages.port", "Port=="+strconv.Itoa(inbound.Port))
  1291. output += t.I18nBot("tgbot.messages.traffic", "Total=="+common.FormatTraffic((inbound.Up+inbound.Down)), "Upload=="+common.FormatTraffic(inbound.Up), "Download=="+common.FormatTraffic(inbound.Down))
  1292. if inbound.ExpiryTime == 0 {
  1293. output += t.I18nBot("tgbot.messages.expire", "Time=="+t.I18nBot("tgbot.unlimited"))
  1294. } else {
  1295. output += t.I18nBot("tgbot.messages.expire", "Time=="+time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05"))
  1296. }
  1297. output += "\r\n"
  1298. }
  1299. }
  1300. // Clients
  1301. exhaustedCC := len(exhaustedClients)
  1302. output += t.I18nBot("tgbot.messages.exhaustedCount", "Type=="+t.I18nBot("tgbot.clients"))
  1303. output += t.I18nBot("tgbot.messages.disabled", "Disabled=="+strconv.Itoa(len(disabledClients)))
  1304. output += t.I18nBot("tgbot.messages.depleteSoon", "Deplete=="+strconv.Itoa(exhaustedCC))
  1305. if exhaustedCC > 0 {
  1306. output += t.I18nBot("tgbot.messages.depleteSoon", "Deplete=="+t.I18nBot("tgbot.clients"))
  1307. var buttons []telego.InlineKeyboardButton
  1308. for _, traffic := range exhaustedClients {
  1309. output += t.clientInfoMsg(&traffic, true, false, false, true, true, false)
  1310. output += "\r\n"
  1311. buttons = append(buttons, tu.InlineKeyboardButton(traffic.Email).WithCallbackData(t.encodeQuery("client_get_usage "+traffic.Email)))
  1312. }
  1313. cols := 0
  1314. if exhaustedCC < 11 {
  1315. cols = 1
  1316. } else {
  1317. cols = 2
  1318. }
  1319. output += t.I18nBot("tgbot.messages.refreshedOn", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
  1320. keyboard := tu.InlineKeyboardGrid(tu.InlineKeyboardCols(cols, buttons...))
  1321. t.SendMsgToTgbot(chatId, output, keyboard)
  1322. } else {
  1323. output += t.I18nBot("tgbot.messages.refreshedOn", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
  1324. t.SendMsgToTgbot(chatId, output)
  1325. }
  1326. }
  1327. func (t *Tgbot) notifyExhausted() {
  1328. trDiff := int64(0)
  1329. exDiff := int64(0)
  1330. now := time.Now().Unix() * 1000
  1331. TrafficThreshold, err := t.settingService.GetTrafficDiff()
  1332. if err == nil && TrafficThreshold > 0 {
  1333. trDiff = int64(TrafficThreshold) * 1073741824
  1334. }
  1335. ExpireThreshold, err := t.settingService.GetExpireDiff()
  1336. if err == nil && ExpireThreshold > 0 {
  1337. exDiff = int64(ExpireThreshold) * 86400000
  1338. }
  1339. inbounds, err := t.inboundService.GetAllInbounds()
  1340. if err != nil {
  1341. logger.Warning("Unable to load Inbounds", err)
  1342. }
  1343. var chatIDsDone []int64
  1344. for _, inbound := range inbounds {
  1345. if inbound.Enable {
  1346. if len(inbound.ClientStats) > 0 {
  1347. clients, err := t.inboundService.GetClients(inbound)
  1348. if err == nil {
  1349. for _, client := range clients {
  1350. if client.TgID != 0 {
  1351. chatID := client.TgID
  1352. if !int64Contains(chatIDsDone, chatID) && !checkAdmin(chatID) {
  1353. var disabledClients []xray.ClientTraffic
  1354. var exhaustedClients []xray.ClientTraffic
  1355. traffics, err := t.inboundService.GetClientTrafficTgBot(client.TgID)
  1356. if err == nil && len(traffics) > 0 {
  1357. output := t.I18nBot("tgbot.messages.exhaustedCount", "Type=="+t.I18nBot("tgbot.clients"))
  1358. for _, traffic := range traffics {
  1359. if traffic.Enable {
  1360. if (traffic.ExpiryTime > 0 && (traffic.ExpiryTime-now < exDiff)) ||
  1361. (traffic.Total > 0 && (traffic.Total-(traffic.Up+traffic.Down) < trDiff)) {
  1362. exhaustedClients = append(exhaustedClients, *traffic)
  1363. }
  1364. } else {
  1365. disabledClients = append(disabledClients, *traffic)
  1366. }
  1367. }
  1368. if len(exhaustedClients) > 0 {
  1369. output += t.I18nBot("tgbot.messages.disabled", "Disabled=="+strconv.Itoa(len(disabledClients)))
  1370. if len(disabledClients) > 0 {
  1371. output += t.I18nBot("tgbot.clients") + ":\r\n"
  1372. for _, traffic := range disabledClients {
  1373. output += " " + traffic.Email
  1374. }
  1375. output += "\r\n"
  1376. }
  1377. output += "\r\n"
  1378. output += t.I18nBot("tgbot.messages.depleteSoon", "Deplete=="+strconv.Itoa(len(exhaustedClients)))
  1379. for _, traffic := range exhaustedClients {
  1380. output += t.clientInfoMsg(&traffic, true, false, false, true, true, false)
  1381. output += "\r\n"
  1382. }
  1383. t.SendMsgToTgbot(chatID, output)
  1384. }
  1385. chatIDsDone = append(chatIDsDone, chatID)
  1386. }
  1387. }
  1388. }
  1389. }
  1390. }
  1391. }
  1392. }
  1393. }
  1394. }
  1395. func int64Contains(slice []int64, item int64) bool {
  1396. for _, s := range slice {
  1397. if s == item {
  1398. return true
  1399. }
  1400. }
  1401. return false
  1402. }
  1403. func (t *Tgbot) onlineClients(chatId int64, messageID ...int) {
  1404. if !p.IsRunning() {
  1405. return
  1406. }
  1407. onlines := p.GetOnlineClients()
  1408. onlinesCount := len(onlines)
  1409. output := t.I18nBot("tgbot.messages.onlinesCount", "Count=="+fmt.Sprint(onlinesCount))
  1410. keyboard := tu.InlineKeyboard(tu.InlineKeyboardRow(
  1411. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.refresh")).WithCallbackData(t.encodeQuery("onlines_refresh"))))
  1412. if onlinesCount > 0 {
  1413. var buttons []telego.InlineKeyboardButton
  1414. for _, online := range onlines {
  1415. buttons = append(buttons, tu.InlineKeyboardButton(online).WithCallbackData(t.encodeQuery("client_get_usage "+online)))
  1416. }
  1417. cols := 0
  1418. if onlinesCount < 21 {
  1419. cols = 2
  1420. } else if onlinesCount < 61 {
  1421. cols = 3
  1422. } else {
  1423. cols = 4
  1424. }
  1425. keyboard.InlineKeyboard = append(keyboard.InlineKeyboard, tu.InlineKeyboardCols(cols, buttons...)...)
  1426. }
  1427. if len(messageID) > 0 {
  1428. t.editMessageTgBot(chatId, messageID[0], output, keyboard)
  1429. } else {
  1430. t.SendMsgToTgbot(chatId, output, keyboard)
  1431. }
  1432. }
  1433. func (t *Tgbot) sendBackup(chatId int64) {
  1434. output := t.I18nBot("tgbot.messages.backupTime", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
  1435. t.SendMsgToTgbot(chatId, output)
  1436. // Update by manually trigger a checkpoint operation
  1437. err := database.Checkpoint()
  1438. if err != nil {
  1439. logger.Error("Error in trigger a checkpoint operation: ", err)
  1440. }
  1441. file, err := os.Open(config.GetDBPath())
  1442. if err == nil {
  1443. document := tu.Document(
  1444. tu.ID(chatId),
  1445. tu.File(file),
  1446. )
  1447. _, err = bot.SendDocument(document)
  1448. if err != nil {
  1449. logger.Error("Error in uploading backup: ", err)
  1450. }
  1451. } else {
  1452. logger.Error("Error in opening db file for backup: ", err)
  1453. }
  1454. file, err = os.Open(xray.GetConfigPath())
  1455. if err == nil {
  1456. document := tu.Document(
  1457. tu.ID(chatId),
  1458. tu.File(file),
  1459. )
  1460. _, err = bot.SendDocument(document)
  1461. if err != nil {
  1462. logger.Error("Error in uploading config.json: ", err)
  1463. }
  1464. } else {
  1465. logger.Error("Error in opening config.json file for backup: ", err)
  1466. }
  1467. }
  1468. func (t *Tgbot) sendBanLogs(chatId int64, dt bool) {
  1469. if dt {
  1470. output := t.I18nBot("tgbot.messages.datetime", "DateTime=="+time.Now().Format("2006-01-02 15:04:05"))
  1471. t.SendMsgToTgbot(chatId, output)
  1472. }
  1473. file, err := os.Open(xray.GetIPLimitBannedPrevLogPath())
  1474. if err == nil {
  1475. // Check if the file is non-empty before attempting to upload
  1476. fileInfo, _ := file.Stat()
  1477. if fileInfo.Size() > 0 {
  1478. document := tu.Document(
  1479. tu.ID(chatId),
  1480. tu.File(file),
  1481. )
  1482. _, err = bot.SendDocument(document)
  1483. if err != nil {
  1484. logger.Error("Error in uploading IPLimitBannedPrevLog: ", err)
  1485. }
  1486. } else {
  1487. logger.Warning("IPLimitBannedPrevLog file is empty, not uploading.")
  1488. }
  1489. file.Close()
  1490. } else {
  1491. logger.Error("Error in opening IPLimitBannedPrevLog file for backup: ", err)
  1492. }
  1493. file, err = os.Open(xray.GetIPLimitBannedLogPath())
  1494. if err == nil {
  1495. // Check if the file is non-empty before attempting to upload
  1496. fileInfo, _ := file.Stat()
  1497. if fileInfo.Size() > 0 {
  1498. document := tu.Document(
  1499. tu.ID(chatId),
  1500. tu.File(file),
  1501. )
  1502. _, err = bot.SendDocument(document)
  1503. if err != nil {
  1504. logger.Error("Error in uploading IPLimitBannedLog: ", err)
  1505. }
  1506. } else {
  1507. logger.Warning("IPLimitBannedLog file is empty, not uploading.")
  1508. }
  1509. file.Close()
  1510. } else {
  1511. logger.Error("Error in opening IPLimitBannedLog file for backup: ", err)
  1512. }
  1513. }
  1514. func (t *Tgbot) sendCallbackAnswerTgBot(id string, message string) {
  1515. params := telego.AnswerCallbackQueryParams{
  1516. CallbackQueryID: id,
  1517. Text: message,
  1518. }
  1519. if err := bot.AnswerCallbackQuery(&params); err != nil {
  1520. logger.Warning(err)
  1521. }
  1522. }
  1523. func (t *Tgbot) editMessageCallbackTgBot(chatId int64, messageID int, inlineKeyboard *telego.InlineKeyboardMarkup) {
  1524. params := telego.EditMessageReplyMarkupParams{
  1525. ChatID: tu.ID(chatId),
  1526. MessageID: messageID,
  1527. ReplyMarkup: inlineKeyboard,
  1528. }
  1529. if _, err := bot.EditMessageReplyMarkup(&params); err != nil {
  1530. logger.Warning(err)
  1531. }
  1532. }
  1533. func (t *Tgbot) editMessageTgBot(chatId int64, messageID int, text string, inlineKeyboard ...*telego.InlineKeyboardMarkup) {
  1534. params := telego.EditMessageTextParams{
  1535. ChatID: tu.ID(chatId),
  1536. MessageID: messageID,
  1537. Text: text,
  1538. ParseMode: "HTML",
  1539. }
  1540. if len(inlineKeyboard) > 0 {
  1541. params.ReplyMarkup = inlineKeyboard[0]
  1542. }
  1543. if _, err := bot.EditMessageText(&params); err != nil {
  1544. logger.Warning(err)
  1545. }
  1546. }