tgbot.go 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702
  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. for _, sharedUser := range message.UsersShared.Users {
  173. userID := sharedUser.UserID
  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.getServerUsage(chatId)
  725. case "usage_refresh":
  726. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.successfulOperation"))
  727. t.getServerUsage(chatId, callbackQuery.Message.GetMessageID())
  728. case "inbounds":
  729. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.getInbounds"))
  730. t.SendMsgToTgbot(chatId, t.getInboundUsages())
  731. case "deplete_soon":
  732. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.depleteSoon"))
  733. t.getExhausted(chatId)
  734. case "get_backup":
  735. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.dbBackup"))
  736. t.sendBackup(chatId)
  737. case "get_banlogs":
  738. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.getBanLogs"))
  739. t.sendBanLogs(chatId, true)
  740. case "client_traffic":
  741. tgUserID := callbackQuery.From.ID
  742. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.clientUsage"))
  743. t.getClientUsage(chatId, tgUserID)
  744. case "client_commands":
  745. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.commands"))
  746. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.commands.helpClientCommands"))
  747. case "onlines":
  748. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.onlines"))
  749. t.onlineClients(chatId)
  750. case "onlines_refresh":
  751. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.successfulOperation"))
  752. t.onlineClients(chatId, callbackQuery.Message.GetMessageID())
  753. case "commands":
  754. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.commands"))
  755. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.commands.helpAdminCommands"))
  756. }
  757. }
  758. func checkAdmin(tgId int64) bool {
  759. for _, adminId := range adminIds {
  760. if adminId == tgId {
  761. return true
  762. }
  763. }
  764. return false
  765. }
  766. func (t *Tgbot) SendAnswer(chatId int64, msg string, isAdmin bool) {
  767. numericKeyboard := tu.InlineKeyboard(
  768. tu.InlineKeyboardRow(
  769. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.serverUsage")).WithCallbackData(t.encodeQuery("get_usage")),
  770. ),
  771. tu.InlineKeyboardRow(
  772. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.dbBackup")).WithCallbackData(t.encodeQuery("get_backup")),
  773. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.getBanLogs")).WithCallbackData(t.encodeQuery("get_banlogs")),
  774. ),
  775. tu.InlineKeyboardRow(
  776. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.getInbounds")).WithCallbackData(t.encodeQuery("inbounds")),
  777. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.depleteSoon")).WithCallbackData(t.encodeQuery("deplete_soon")),
  778. ),
  779. tu.InlineKeyboardRow(
  780. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.commands")).WithCallbackData(t.encodeQuery("commands")),
  781. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.onlines")).WithCallbackData(t.encodeQuery("onlines")),
  782. ),
  783. )
  784. numericKeyboardClient := tu.InlineKeyboard(
  785. tu.InlineKeyboardRow(
  786. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.clientUsage")).WithCallbackData(t.encodeQuery("client_traffic")),
  787. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.commands")).WithCallbackData(t.encodeQuery("client_commands")),
  788. ),
  789. )
  790. var ReplyMarkup telego.ReplyMarkup
  791. if isAdmin {
  792. ReplyMarkup = numericKeyboard
  793. } else {
  794. ReplyMarkup = numericKeyboardClient
  795. }
  796. t.SendMsgToTgbot(chatId, msg, ReplyMarkup)
  797. }
  798. func (t *Tgbot) SendMsgToTgbot(chatId int64, msg string, replyMarkup ...telego.ReplyMarkup) {
  799. if !isRunning {
  800. return
  801. }
  802. if msg == "" {
  803. logger.Info("[tgbot] message is empty!")
  804. return
  805. }
  806. var allMessages []string
  807. limit := 2000
  808. // paging message if it is big
  809. if len(msg) > limit {
  810. messages := strings.Split(msg, "\r\n\r\n")
  811. lastIndex := -1
  812. for _, message := range messages {
  813. if (len(allMessages) == 0) || (len(allMessages[lastIndex])+len(message) > limit) {
  814. allMessages = append(allMessages, message)
  815. lastIndex++
  816. } else {
  817. allMessages[lastIndex] += "\r\n\r\n" + message
  818. }
  819. }
  820. if strings.TrimSpace(allMessages[len(allMessages)-1]) == "" {
  821. allMessages = allMessages[:len(allMessages)-1]
  822. }
  823. } else {
  824. allMessages = append(allMessages, msg)
  825. }
  826. for n, message := range allMessages {
  827. params := telego.SendMessageParams{
  828. ChatID: tu.ID(chatId),
  829. Text: message,
  830. ParseMode: "HTML",
  831. }
  832. // only add replyMarkup to last message
  833. if len(replyMarkup) > 0 && n == (len(allMessages)-1) {
  834. params.ReplyMarkup = replyMarkup[0]
  835. }
  836. _, err := bot.SendMessage(&params)
  837. if err != nil {
  838. logger.Warning("Error sending telegram message :", err)
  839. }
  840. time.Sleep(500 * time.Millisecond)
  841. }
  842. }
  843. func (t *Tgbot) SendMsgToTgbotAdmins(msg string, replyMarkup ...telego.ReplyMarkup) {
  844. if len(replyMarkup) > 0 {
  845. for _, adminId := range adminIds {
  846. t.SendMsgToTgbot(adminId, msg, replyMarkup[0])
  847. }
  848. } else {
  849. for _, adminId := range adminIds {
  850. t.SendMsgToTgbot(adminId, msg)
  851. }
  852. }
  853. }
  854. func (t *Tgbot) SendReport() {
  855. runTime, err := t.settingService.GetTgbotRuntime()
  856. if err == nil && len(runTime) > 0 {
  857. msg := ""
  858. msg += t.I18nBot("tgbot.messages.report", "RunTime=="+runTime)
  859. msg += t.I18nBot("tgbot.messages.datetime", "DateTime=="+time.Now().Format("2006-01-02 15:04:05"))
  860. t.SendMsgToTgbotAdmins(msg)
  861. }
  862. info := t.sendServerUsage()
  863. t.SendMsgToTgbotAdmins(info)
  864. t.sendExhaustedToAdmins()
  865. t.notifyExhausted()
  866. backupEnable, err := t.settingService.GetTgBotBackup()
  867. if err == nil && backupEnable {
  868. t.SendBackupToAdmins()
  869. }
  870. }
  871. func (t *Tgbot) SendBackupToAdmins() {
  872. if !t.IsRunning() {
  873. return
  874. }
  875. for _, adminId := range adminIds {
  876. t.sendBackup(int64(adminId))
  877. }
  878. }
  879. func (t *Tgbot) sendExhaustedToAdmins() {
  880. if !t.IsRunning() {
  881. return
  882. }
  883. for _, adminId := range adminIds {
  884. t.getExhausted(int64(adminId))
  885. }
  886. }
  887. func (t *Tgbot) getServerUsage(chatId int64, messageID ...int) string {
  888. info := t.prepareServerUsageInfo()
  889. keyboard := tu.InlineKeyboard(tu.InlineKeyboardRow(
  890. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.refresh")).WithCallbackData(t.encodeQuery("usage_refresh"))))
  891. if len(messageID) > 0 {
  892. t.editMessageTgBot(chatId, messageID[0], info, keyboard)
  893. } else {
  894. t.SendMsgToTgbot(chatId, info, keyboard)
  895. }
  896. return info
  897. }
  898. // Send server usage without an inline keyborad
  899. func (t *Tgbot) sendServerUsage() string {
  900. info := t.prepareServerUsageInfo()
  901. return info
  902. }
  903. func (t *Tgbot) prepareServerUsageInfo() string {
  904. info, ipv4, ipv6 := "", "", ""
  905. // get latest status of server
  906. t.lastStatus = t.serverService.GetStatus(t.lastStatus)
  907. onlines := p.GetOnlineClients()
  908. info += t.I18nBot("tgbot.messages.hostname", "Hostname=="+hostname)
  909. info += t.I18nBot("tgbot.messages.version", "Version=="+config.GetVersion())
  910. info += t.I18nBot("tgbot.messages.xrayVersion", "XrayVersion=="+fmt.Sprint(t.lastStatus.Xray.Version))
  911. // get ip address
  912. netInterfaces, err := net.Interfaces()
  913. if err != nil {
  914. logger.Error("net.Interfaces failed, err: ", err.Error())
  915. info += t.I18nBot("tgbot.messages.ip", "IP=="+t.I18nBot("tgbot.unknown"))
  916. info += "\r\n"
  917. } else {
  918. for i := 0; i < len(netInterfaces); i++ {
  919. if (netInterfaces[i].Flags & net.FlagUp) != 0 {
  920. addrs, _ := netInterfaces[i].Addrs()
  921. for _, address := range addrs {
  922. if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
  923. if ipnet.IP.To4() != nil {
  924. ipv4 += ipnet.IP.String() + " "
  925. } else if ipnet.IP.To16() != nil && !ipnet.IP.IsLinkLocalUnicast() {
  926. ipv6 += ipnet.IP.String() + " "
  927. }
  928. }
  929. }
  930. }
  931. }
  932. info += t.I18nBot("tgbot.messages.ipv4", "IPv4=="+ipv4)
  933. info += t.I18nBot("tgbot.messages.ipv6", "IPv6=="+ipv6)
  934. }
  935. info += t.I18nBot("tgbot.messages.serverUpTime", "UpTime=="+strconv.FormatUint(t.lastStatus.Uptime/86400, 10), "Unit=="+t.I18nBot("tgbot.days"))
  936. 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))
  937. info += t.I18nBot("tgbot.messages.serverMemory", "Current=="+common.FormatTraffic(int64(t.lastStatus.Mem.Current)), "Total=="+common.FormatTraffic(int64(t.lastStatus.Mem.Total)))
  938. info += t.I18nBot("tgbot.messages.onlinesCount", "Count=="+fmt.Sprint(len(onlines)))
  939. info += t.I18nBot("tgbot.messages.tcpCount", "Count=="+strconv.Itoa(t.lastStatus.TcpCount))
  940. info += t.I18nBot("tgbot.messages.udpCount", "Count=="+strconv.Itoa(t.lastStatus.UdpCount))
  941. 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)))
  942. info += t.I18nBot("tgbot.messages.xrayStatus", "State=="+fmt.Sprint(t.lastStatus.Xray.State))
  943. return info
  944. }
  945. func (t *Tgbot) UserLoginNotify(username string, ip string, time string, status LoginStatus) {
  946. if !t.IsRunning() {
  947. return
  948. }
  949. if username == "" || ip == "" || time == "" {
  950. logger.Warning("UserLoginNotify failed, invalid info!")
  951. return
  952. }
  953. loginNotifyEnabled, err := t.settingService.GetTgBotLoginNotify()
  954. if err != nil || !loginNotifyEnabled {
  955. return
  956. }
  957. msg := ""
  958. if status == LoginSuccess {
  959. msg += t.I18nBot("tgbot.messages.loginSuccess")
  960. } else if status == LoginFail {
  961. msg += t.I18nBot("tgbot.messages.loginFailed")
  962. }
  963. msg += t.I18nBot("tgbot.messages.hostname", "Hostname=="+hostname)
  964. msg += t.I18nBot("tgbot.messages.username", "Username=="+username)
  965. msg += t.I18nBot("tgbot.messages.ip", "IP=="+ip)
  966. msg += t.I18nBot("tgbot.messages.time", "Time=="+time)
  967. t.SendMsgToTgbotAdmins(msg)
  968. }
  969. func (t *Tgbot) getInboundUsages() string {
  970. info := ""
  971. // get traffic
  972. inbouds, err := t.inboundService.GetAllInbounds()
  973. if err != nil {
  974. logger.Warning("GetAllInbounds run failed:", err)
  975. info += t.I18nBot("tgbot.answers.getInboundsFailed")
  976. } else {
  977. // NOTE:If there no any sessions here,need to notify here
  978. // TODO:Sub-node push, automatic conversion format
  979. for _, inbound := range inbouds {
  980. info += t.I18nBot("tgbot.messages.inbound", "Remark=="+inbound.Remark)
  981. info += t.I18nBot("tgbot.messages.port", "Port=="+strconv.Itoa(inbound.Port))
  982. info += t.I18nBot("tgbot.messages.traffic", "Total=="+common.FormatTraffic((inbound.Up+inbound.Down)), "Upload=="+common.FormatTraffic(inbound.Up), "Download=="+common.FormatTraffic(inbound.Down))
  983. if inbound.ExpiryTime == 0 {
  984. info += t.I18nBot("tgbot.messages.expire", "Time=="+t.I18nBot("tgbot.unlimited"))
  985. } else {
  986. info += t.I18nBot("tgbot.messages.expire", "Time=="+time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05"))
  987. }
  988. info += "\r\n"
  989. }
  990. }
  991. return info
  992. }
  993. func (t *Tgbot) clientInfoMsg(
  994. traffic *xray.ClientTraffic,
  995. printEnabled bool,
  996. printOnline bool,
  997. printActive bool,
  998. printDate bool,
  999. printTraffic bool,
  1000. printRefreshed bool,
  1001. ) string {
  1002. now := time.Now().Unix()
  1003. expiryTime := ""
  1004. flag := false
  1005. diff := traffic.ExpiryTime/1000 - now
  1006. if traffic.ExpiryTime == 0 {
  1007. expiryTime = t.I18nBot("tgbot.unlimited")
  1008. } else if diff > 172800 || !traffic.Enable {
  1009. expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
  1010. } else if traffic.ExpiryTime < 0 {
  1011. expiryTime = fmt.Sprintf("%d %s", traffic.ExpiryTime/-86400000, t.I18nBot("tgbot.days"))
  1012. flag = true
  1013. } else {
  1014. expiryTime = fmt.Sprintf("%d %s", diff/3600, t.I18nBot("tgbot.hours"))
  1015. flag = true
  1016. }
  1017. total := ""
  1018. if traffic.Total == 0 {
  1019. total = t.I18nBot("tgbot.unlimited")
  1020. } else {
  1021. total = common.FormatTraffic((traffic.Total))
  1022. }
  1023. enabled := ""
  1024. isEnabled, err := t.inboundService.checkIsEnabledByEmail(traffic.Email)
  1025. if err != nil {
  1026. logger.Warning(err)
  1027. enabled = t.I18nBot("tgbot.wentWrong")
  1028. } else if isEnabled {
  1029. enabled = t.I18nBot("tgbot.messages.yes")
  1030. } else {
  1031. enabled = t.I18nBot("tgbot.messages.no")
  1032. }
  1033. active := ""
  1034. if traffic.Enable {
  1035. active = t.I18nBot("tgbot.messages.yes")
  1036. } else {
  1037. active = t.I18nBot("tgbot.messages.no")
  1038. }
  1039. status := t.I18nBot("tgbot.offline")
  1040. if p.IsRunning() {
  1041. for _, online := range p.GetOnlineClients() {
  1042. if online == traffic.Email {
  1043. status = t.I18nBot("tgbot.online")
  1044. break
  1045. }
  1046. }
  1047. }
  1048. output := ""
  1049. output += t.I18nBot("tgbot.messages.email", "Email=="+traffic.Email)
  1050. if printEnabled {
  1051. output += t.I18nBot("tgbot.messages.enabled", "Enable=="+enabled)
  1052. }
  1053. if printOnline {
  1054. output += t.I18nBot("tgbot.messages.online", "Status=="+status)
  1055. }
  1056. if printActive {
  1057. output += t.I18nBot("tgbot.messages.active", "Enable=="+active)
  1058. }
  1059. if printDate {
  1060. if flag {
  1061. output += t.I18nBot("tgbot.messages.expireIn", "Time=="+expiryTime)
  1062. } else {
  1063. output += t.I18nBot("tgbot.messages.expire", "Time=="+expiryTime)
  1064. }
  1065. }
  1066. if printTraffic {
  1067. output += t.I18nBot("tgbot.messages.upload", "Upload=="+common.FormatTraffic(traffic.Up))
  1068. output += t.I18nBot("tgbot.messages.download", "Download=="+common.FormatTraffic(traffic.Down))
  1069. output += t.I18nBot("tgbot.messages.total", "UpDown=="+common.FormatTraffic((traffic.Up+traffic.Down)), "Total=="+total)
  1070. }
  1071. if printRefreshed {
  1072. output += t.I18nBot("tgbot.messages.refreshedOn", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
  1073. }
  1074. return output
  1075. }
  1076. func (t *Tgbot) getClientUsage(chatId int64, tgUserID int64, email ...string) {
  1077. traffics, err := t.inboundService.GetClientTrafficTgBot(tgUserID)
  1078. if err != nil {
  1079. logger.Warning(err)
  1080. msg := t.I18nBot("tgbot.wentWrong")
  1081. t.SendMsgToTgbot(chatId, msg)
  1082. return
  1083. }
  1084. if len(traffics) == 0 {
  1085. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.askToAddUserId", "TgUserID=="+strconv.FormatInt(tgUserID, 10)))
  1086. return
  1087. }
  1088. output := ""
  1089. if len(traffics) > 0 {
  1090. if len(email) > 0 {
  1091. for _, traffic := range traffics {
  1092. if traffic.Email == email[0] {
  1093. output := t.clientInfoMsg(traffic, true, true, true, true, true, true)
  1094. t.SendMsgToTgbot(chatId, output)
  1095. return
  1096. }
  1097. }
  1098. msg := t.I18nBot("tgbot.noResult")
  1099. t.SendMsgToTgbot(chatId, msg)
  1100. return
  1101. } else {
  1102. for _, traffic := range traffics {
  1103. output += t.clientInfoMsg(traffic, true, true, true, true, true, false)
  1104. output += "\r\n"
  1105. }
  1106. }
  1107. }
  1108. output += t.I18nBot("tgbot.messages.refreshedOn", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
  1109. t.SendMsgToTgbot(chatId, output)
  1110. output = t.I18nBot("tgbot.commands.pleaseChoose")
  1111. t.SendAnswer(chatId, output, false)
  1112. }
  1113. func (t *Tgbot) searchClientIps(chatId int64, email string, messageID ...int) {
  1114. ips, err := t.inboundService.GetInboundClientIps(email)
  1115. if err != nil || len(ips) == 0 {
  1116. ips = t.I18nBot("tgbot.noIpRecord")
  1117. }
  1118. output := ""
  1119. output += t.I18nBot("tgbot.messages.email", "Email=="+email)
  1120. output += t.I18nBot("tgbot.messages.ips", "IPs=="+ips)
  1121. output += t.I18nBot("tgbot.messages.refreshedOn", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
  1122. inlineKeyboard := tu.InlineKeyboard(
  1123. tu.InlineKeyboardRow(
  1124. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.refresh")).WithCallbackData(t.encodeQuery("ips_refresh "+email)),
  1125. ),
  1126. tu.InlineKeyboardRow(
  1127. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.clearIPs")).WithCallbackData(t.encodeQuery("clear_ips "+email)),
  1128. ),
  1129. )
  1130. if len(messageID) > 0 {
  1131. t.editMessageTgBot(chatId, messageID[0], output, inlineKeyboard)
  1132. } else {
  1133. t.SendMsgToTgbot(chatId, output, inlineKeyboard)
  1134. }
  1135. }
  1136. func (t *Tgbot) clientTelegramUserInfo(chatId int64, email string, messageID ...int) {
  1137. traffic, client, err := t.inboundService.GetClientByEmail(email)
  1138. if err != nil {
  1139. logger.Warning(err)
  1140. msg := t.I18nBot("tgbot.wentWrong")
  1141. t.SendMsgToTgbot(chatId, msg)
  1142. return
  1143. }
  1144. if client == nil {
  1145. msg := t.I18nBot("tgbot.noResult")
  1146. t.SendMsgToTgbot(chatId, msg)
  1147. return
  1148. }
  1149. tgId := "None"
  1150. if client.TgID != 0 {
  1151. tgId = strconv.FormatInt(client.TgID, 10)
  1152. }
  1153. output := ""
  1154. output += t.I18nBot("tgbot.messages.email", "Email=="+email)
  1155. output += t.I18nBot("tgbot.messages.TGUser", "TelegramID=="+tgId)
  1156. output += t.I18nBot("tgbot.messages.refreshedOn", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
  1157. inlineKeyboard := tu.InlineKeyboard(
  1158. tu.InlineKeyboardRow(
  1159. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.refresh")).WithCallbackData(t.encodeQuery("tgid_refresh "+email)),
  1160. ),
  1161. tu.InlineKeyboardRow(
  1162. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.removeTGUser")).WithCallbackData(t.encodeQuery("tgid_remove "+email)),
  1163. ),
  1164. )
  1165. if len(messageID) > 0 {
  1166. t.editMessageTgBot(chatId, messageID[0], output, inlineKeyboard)
  1167. } else {
  1168. t.SendMsgToTgbot(chatId, output, inlineKeyboard)
  1169. requestUser := telego.KeyboardButtonRequestUsers{
  1170. RequestID: int32(traffic.Id),
  1171. UserIsBot: new(bool),
  1172. }
  1173. keyboard := tu.Keyboard(
  1174. tu.KeyboardRow(
  1175. tu.KeyboardButton(t.I18nBot("tgbot.buttons.selectTGUser")).WithRequestUsers(&requestUser),
  1176. ),
  1177. tu.KeyboardRow(
  1178. tu.KeyboardButton(t.I18nBot("tgbot.buttons.closeKeyboard")),
  1179. ),
  1180. ).WithIsPersistent().WithResizeKeyboard()
  1181. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.buttons.selectOneTGUser"), keyboard)
  1182. }
  1183. }
  1184. func (t *Tgbot) searchClient(chatId int64, email string, messageID ...int) {
  1185. traffic, err := t.inboundService.GetClientTrafficByEmail(email)
  1186. if err != nil {
  1187. logger.Warning(err)
  1188. msg := t.I18nBot("tgbot.wentWrong")
  1189. t.SendMsgToTgbot(chatId, msg)
  1190. return
  1191. }
  1192. if traffic == nil {
  1193. msg := t.I18nBot("tgbot.noResult")
  1194. t.SendMsgToTgbot(chatId, msg)
  1195. return
  1196. }
  1197. output := t.clientInfoMsg(traffic, true, true, true, true, true, true)
  1198. inlineKeyboard := tu.InlineKeyboard(
  1199. tu.InlineKeyboardRow(
  1200. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.refresh")).WithCallbackData(t.encodeQuery("client_refresh "+email)),
  1201. ),
  1202. tu.InlineKeyboardRow(
  1203. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.resetTraffic")).WithCallbackData(t.encodeQuery("reset_traffic "+email)),
  1204. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.limitTraffic")).WithCallbackData(t.encodeQuery("limit_traffic "+email)),
  1205. ),
  1206. tu.InlineKeyboardRow(
  1207. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.resetExpire")).WithCallbackData(t.encodeQuery("reset_exp "+email)),
  1208. ),
  1209. tu.InlineKeyboardRow(
  1210. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.ipLog")).WithCallbackData(t.encodeQuery("ip_log "+email)),
  1211. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.ipLimit")).WithCallbackData(t.encodeQuery("ip_limit "+email)),
  1212. ),
  1213. tu.InlineKeyboardRow(
  1214. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.setTGUser")).WithCallbackData(t.encodeQuery("tg_user "+email)),
  1215. ),
  1216. tu.InlineKeyboardRow(
  1217. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.toggle")).WithCallbackData(t.encodeQuery("toggle_enable "+email)),
  1218. ),
  1219. )
  1220. if len(messageID) > 0 {
  1221. t.editMessageTgBot(chatId, messageID[0], output, inlineKeyboard)
  1222. } else {
  1223. t.SendMsgToTgbot(chatId, output, inlineKeyboard)
  1224. }
  1225. }
  1226. func (t *Tgbot) searchInbound(chatId int64, remark string) {
  1227. inbouds, err := t.inboundService.SearchInbounds(remark)
  1228. if err != nil {
  1229. logger.Warning(err)
  1230. msg := t.I18nBot("tgbot.wentWrong")
  1231. t.SendMsgToTgbot(chatId, msg)
  1232. return
  1233. }
  1234. if len(inbouds) == 0 {
  1235. msg := t.I18nBot("tgbot.noInbounds")
  1236. t.SendMsgToTgbot(chatId, msg)
  1237. return
  1238. }
  1239. for _, inbound := range inbouds {
  1240. info := ""
  1241. info += t.I18nBot("tgbot.messages.inbound", "Remark=="+inbound.Remark)
  1242. info += t.I18nBot("tgbot.messages.port", "Port=="+strconv.Itoa(inbound.Port))
  1243. info += t.I18nBot("tgbot.messages.traffic", "Total=="+common.FormatTraffic((inbound.Up+inbound.Down)), "Upload=="+common.FormatTraffic(inbound.Up), "Download=="+common.FormatTraffic(inbound.Down))
  1244. if inbound.ExpiryTime == 0 {
  1245. info += t.I18nBot("tgbot.messages.expire", "Time=="+t.I18nBot("tgbot.unlimited"))
  1246. } else {
  1247. info += t.I18nBot("tgbot.messages.expire", "Time=="+time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05"))
  1248. }
  1249. t.SendMsgToTgbot(chatId, info)
  1250. if len(inbound.ClientStats) > 0 {
  1251. output := ""
  1252. for _, traffic := range inbound.ClientStats {
  1253. output += t.clientInfoMsg(&traffic, true, true, true, true, true, true)
  1254. }
  1255. t.SendMsgToTgbot(chatId, output)
  1256. }
  1257. }
  1258. }
  1259. func (t *Tgbot) getExhausted(chatId int64) {
  1260. trDiff := int64(0)
  1261. exDiff := int64(0)
  1262. now := time.Now().Unix() * 1000
  1263. var exhaustedInbounds []model.Inbound
  1264. var exhaustedClients []xray.ClientTraffic
  1265. var disabledInbounds []model.Inbound
  1266. var disabledClients []xray.ClientTraffic
  1267. TrafficThreshold, err := t.settingService.GetTrafficDiff()
  1268. if err == nil && TrafficThreshold > 0 {
  1269. trDiff = int64(TrafficThreshold) * 1073741824
  1270. }
  1271. ExpireThreshold, err := t.settingService.GetExpireDiff()
  1272. if err == nil && ExpireThreshold > 0 {
  1273. exDiff = int64(ExpireThreshold) * 86400000
  1274. }
  1275. inbounds, err := t.inboundService.GetAllInbounds()
  1276. if err != nil {
  1277. logger.Warning("Unable to load Inbounds", err)
  1278. }
  1279. for _, inbound := range inbounds {
  1280. if inbound.Enable {
  1281. if (inbound.ExpiryTime > 0 && (inbound.ExpiryTime-now < exDiff)) ||
  1282. (inbound.Total > 0 && (inbound.Total-(inbound.Up+inbound.Down) < trDiff)) {
  1283. exhaustedInbounds = append(exhaustedInbounds, *inbound)
  1284. }
  1285. if len(inbound.ClientStats) > 0 {
  1286. for _, client := range inbound.ClientStats {
  1287. if client.Enable {
  1288. if (client.ExpiryTime > 0 && (client.ExpiryTime-now < exDiff)) ||
  1289. (client.Total > 0 && (client.Total-(client.Up+client.Down) < trDiff)) {
  1290. exhaustedClients = append(exhaustedClients, client)
  1291. }
  1292. } else {
  1293. disabledClients = append(disabledClients, client)
  1294. }
  1295. }
  1296. }
  1297. } else {
  1298. disabledInbounds = append(disabledInbounds, *inbound)
  1299. }
  1300. }
  1301. // Inbounds
  1302. output := ""
  1303. output += t.I18nBot("tgbot.messages.exhaustedCount", "Type=="+t.I18nBot("tgbot.inbounds"))
  1304. output += t.I18nBot("tgbot.messages.disabled", "Disabled=="+strconv.Itoa(len(disabledInbounds)))
  1305. output += t.I18nBot("tgbot.messages.depleteSoon", "Deplete=="+strconv.Itoa(len(exhaustedInbounds)))
  1306. if len(exhaustedInbounds) > 0 {
  1307. output += t.I18nBot("tgbot.messages.depleteSoon", "Deplete=="+t.I18nBot("tgbot.inbounds"))
  1308. for _, inbound := range exhaustedInbounds {
  1309. output += t.I18nBot("tgbot.messages.inbound", "Remark=="+inbound.Remark)
  1310. output += t.I18nBot("tgbot.messages.port", "Port=="+strconv.Itoa(inbound.Port))
  1311. output += t.I18nBot("tgbot.messages.traffic", "Total=="+common.FormatTraffic((inbound.Up+inbound.Down)), "Upload=="+common.FormatTraffic(inbound.Up), "Download=="+common.FormatTraffic(inbound.Down))
  1312. if inbound.ExpiryTime == 0 {
  1313. output += t.I18nBot("tgbot.messages.expire", "Time=="+t.I18nBot("tgbot.unlimited"))
  1314. } else {
  1315. output += t.I18nBot("tgbot.messages.expire", "Time=="+time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05"))
  1316. }
  1317. output += "\r\n"
  1318. }
  1319. }
  1320. // Clients
  1321. exhaustedCC := len(exhaustedClients)
  1322. output += t.I18nBot("tgbot.messages.exhaustedCount", "Type=="+t.I18nBot("tgbot.clients"))
  1323. output += t.I18nBot("tgbot.messages.disabled", "Disabled=="+strconv.Itoa(len(disabledClients)))
  1324. output += t.I18nBot("tgbot.messages.depleteSoon", "Deplete=="+strconv.Itoa(exhaustedCC))
  1325. if exhaustedCC > 0 {
  1326. output += t.I18nBot("tgbot.messages.depleteSoon", "Deplete=="+t.I18nBot("tgbot.clients"))
  1327. var buttons []telego.InlineKeyboardButton
  1328. for _, traffic := range exhaustedClients {
  1329. output += t.clientInfoMsg(&traffic, true, false, false, true, true, false)
  1330. output += "\r\n"
  1331. buttons = append(buttons, tu.InlineKeyboardButton(traffic.Email).WithCallbackData(t.encodeQuery("client_get_usage "+traffic.Email)))
  1332. }
  1333. cols := 0
  1334. if exhaustedCC < 11 {
  1335. cols = 1
  1336. } else {
  1337. cols = 2
  1338. }
  1339. output += t.I18nBot("tgbot.messages.refreshedOn", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
  1340. keyboard := tu.InlineKeyboardGrid(tu.InlineKeyboardCols(cols, buttons...))
  1341. t.SendMsgToTgbot(chatId, output, keyboard)
  1342. } else {
  1343. output += t.I18nBot("tgbot.messages.refreshedOn", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
  1344. t.SendMsgToTgbot(chatId, output)
  1345. }
  1346. }
  1347. func (t *Tgbot) notifyExhausted() {
  1348. trDiff := int64(0)
  1349. exDiff := int64(0)
  1350. now := time.Now().Unix() * 1000
  1351. TrafficThreshold, err := t.settingService.GetTrafficDiff()
  1352. if err == nil && TrafficThreshold > 0 {
  1353. trDiff = int64(TrafficThreshold) * 1073741824
  1354. }
  1355. ExpireThreshold, err := t.settingService.GetExpireDiff()
  1356. if err == nil && ExpireThreshold > 0 {
  1357. exDiff = int64(ExpireThreshold) * 86400000
  1358. }
  1359. inbounds, err := t.inboundService.GetAllInbounds()
  1360. if err != nil {
  1361. logger.Warning("Unable to load Inbounds", err)
  1362. }
  1363. var chatIDsDone []int64
  1364. for _, inbound := range inbounds {
  1365. if inbound.Enable {
  1366. if len(inbound.ClientStats) > 0 {
  1367. clients, err := t.inboundService.GetClients(inbound)
  1368. if err == nil {
  1369. for _, client := range clients {
  1370. if client.TgID != 0 {
  1371. chatID := client.TgID
  1372. if !int64Contains(chatIDsDone, chatID) && !checkAdmin(chatID) {
  1373. var disabledClients []xray.ClientTraffic
  1374. var exhaustedClients []xray.ClientTraffic
  1375. traffics, err := t.inboundService.GetClientTrafficTgBot(client.TgID)
  1376. if err == nil && len(traffics) > 0 {
  1377. output := t.I18nBot("tgbot.messages.exhaustedCount", "Type=="+t.I18nBot("tgbot.clients"))
  1378. for _, traffic := range traffics {
  1379. if traffic.Enable {
  1380. if (traffic.ExpiryTime > 0 && (traffic.ExpiryTime-now < exDiff)) ||
  1381. (traffic.Total > 0 && (traffic.Total-(traffic.Up+traffic.Down) < trDiff)) {
  1382. exhaustedClients = append(exhaustedClients, *traffic)
  1383. }
  1384. } else {
  1385. disabledClients = append(disabledClients, *traffic)
  1386. }
  1387. }
  1388. if len(exhaustedClients) > 0 {
  1389. output += t.I18nBot("tgbot.messages.disabled", "Disabled=="+strconv.Itoa(len(disabledClients)))
  1390. if len(disabledClients) > 0 {
  1391. output += t.I18nBot("tgbot.clients") + ":\r\n"
  1392. for _, traffic := range disabledClients {
  1393. output += " " + traffic.Email
  1394. }
  1395. output += "\r\n"
  1396. }
  1397. output += "\r\n"
  1398. output += t.I18nBot("tgbot.messages.depleteSoon", "Deplete=="+strconv.Itoa(len(exhaustedClients)))
  1399. for _, traffic := range exhaustedClients {
  1400. output += t.clientInfoMsg(&traffic, true, false, false, true, true, false)
  1401. output += "\r\n"
  1402. }
  1403. t.SendMsgToTgbot(chatID, output)
  1404. }
  1405. chatIDsDone = append(chatIDsDone, chatID)
  1406. }
  1407. }
  1408. }
  1409. }
  1410. }
  1411. }
  1412. }
  1413. }
  1414. }
  1415. func int64Contains(slice []int64, item int64) bool {
  1416. for _, s := range slice {
  1417. if s == item {
  1418. return true
  1419. }
  1420. }
  1421. return false
  1422. }
  1423. func (t *Tgbot) onlineClients(chatId int64, messageID ...int) {
  1424. if !p.IsRunning() {
  1425. return
  1426. }
  1427. onlines := p.GetOnlineClients()
  1428. onlinesCount := len(onlines)
  1429. output := t.I18nBot("tgbot.messages.onlinesCount", "Count=="+fmt.Sprint(onlinesCount))
  1430. keyboard := tu.InlineKeyboard(tu.InlineKeyboardRow(
  1431. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.refresh")).WithCallbackData(t.encodeQuery("onlines_refresh"))))
  1432. if onlinesCount > 0 {
  1433. var buttons []telego.InlineKeyboardButton
  1434. for _, online := range onlines {
  1435. buttons = append(buttons, tu.InlineKeyboardButton(online).WithCallbackData(t.encodeQuery("client_get_usage "+online)))
  1436. }
  1437. cols := 0
  1438. if onlinesCount < 21 {
  1439. cols = 2
  1440. } else if onlinesCount < 61 {
  1441. cols = 3
  1442. } else {
  1443. cols = 4
  1444. }
  1445. keyboard.InlineKeyboard = append(keyboard.InlineKeyboard, tu.InlineKeyboardCols(cols, buttons...)...)
  1446. }
  1447. if len(messageID) > 0 {
  1448. t.editMessageTgBot(chatId, messageID[0], output, keyboard)
  1449. } else {
  1450. t.SendMsgToTgbot(chatId, output, keyboard)
  1451. }
  1452. }
  1453. func (t *Tgbot) sendBackup(chatId int64) {
  1454. output := t.I18nBot("tgbot.messages.backupTime", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
  1455. t.SendMsgToTgbot(chatId, output)
  1456. // Update by manually trigger a checkpoint operation
  1457. err := database.Checkpoint()
  1458. if err != nil {
  1459. logger.Error("Error in trigger a checkpoint operation: ", err)
  1460. }
  1461. file, err := os.Open(config.GetDBPath())
  1462. if err == nil {
  1463. document := tu.Document(
  1464. tu.ID(chatId),
  1465. tu.File(file),
  1466. )
  1467. _, err = bot.SendDocument(document)
  1468. if err != nil {
  1469. logger.Error("Error in uploading backup: ", err)
  1470. }
  1471. } else {
  1472. logger.Error("Error in opening db file for backup: ", err)
  1473. }
  1474. file, err = os.Open(xray.GetConfigPath())
  1475. if err == nil {
  1476. document := tu.Document(
  1477. tu.ID(chatId),
  1478. tu.File(file),
  1479. )
  1480. _, err = bot.SendDocument(document)
  1481. if err != nil {
  1482. logger.Error("Error in uploading config.json: ", err)
  1483. }
  1484. } else {
  1485. logger.Error("Error in opening config.json file for backup: ", err)
  1486. }
  1487. }
  1488. func (t *Tgbot) sendBanLogs(chatId int64, dt bool) {
  1489. if dt {
  1490. output := t.I18nBot("tgbot.messages.datetime", "DateTime=="+time.Now().Format("2006-01-02 15:04:05"))
  1491. t.SendMsgToTgbot(chatId, output)
  1492. }
  1493. file, err := os.Open(xray.GetIPLimitBannedPrevLogPath())
  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 IPLimitBannedPrevLog: ", err)
  1505. }
  1506. } else {
  1507. logger.Warning("IPLimitBannedPrevLog file is empty, not uploading.")
  1508. }
  1509. file.Close()
  1510. } else {
  1511. logger.Error("Error in opening IPLimitBannedPrevLog file for backup: ", err)
  1512. }
  1513. file, err = os.Open(xray.GetIPLimitBannedLogPath())
  1514. if err == nil {
  1515. // Check if the file is non-empty before attempting to upload
  1516. fileInfo, _ := file.Stat()
  1517. if fileInfo.Size() > 0 {
  1518. document := tu.Document(
  1519. tu.ID(chatId),
  1520. tu.File(file),
  1521. )
  1522. _, err = bot.SendDocument(document)
  1523. if err != nil {
  1524. logger.Error("Error in uploading IPLimitBannedLog: ", err)
  1525. }
  1526. } else {
  1527. logger.Warning("IPLimitBannedLog file is empty, not uploading.")
  1528. }
  1529. file.Close()
  1530. } else {
  1531. logger.Error("Error in opening IPLimitBannedLog file for backup: ", err)
  1532. }
  1533. }
  1534. func (t *Tgbot) sendCallbackAnswerTgBot(id string, message string) {
  1535. params := telego.AnswerCallbackQueryParams{
  1536. CallbackQueryID: id,
  1537. Text: message,
  1538. }
  1539. if err := bot.AnswerCallbackQuery(&params); err != nil {
  1540. logger.Warning(err)
  1541. }
  1542. }
  1543. func (t *Tgbot) editMessageCallbackTgBot(chatId int64, messageID int, inlineKeyboard *telego.InlineKeyboardMarkup) {
  1544. params := telego.EditMessageReplyMarkupParams{
  1545. ChatID: tu.ID(chatId),
  1546. MessageID: messageID,
  1547. ReplyMarkup: inlineKeyboard,
  1548. }
  1549. if _, err := bot.EditMessageReplyMarkup(&params); err != nil {
  1550. logger.Warning(err)
  1551. }
  1552. }
  1553. func (t *Tgbot) editMessageTgBot(chatId int64, messageID int, text string, inlineKeyboard ...*telego.InlineKeyboardMarkup) {
  1554. params := telego.EditMessageTextParams{
  1555. ChatID: tu.ID(chatId),
  1556. MessageID: messageID,
  1557. Text: text,
  1558. ParseMode: "HTML",
  1559. }
  1560. if len(inlineKeyboard) > 0 {
  1561. params.ReplyMarkup = inlineKeyboard[0]
  1562. }
  1563. if _, err := bot.EditMessageText(&params); err != nil {
  1564. logger.Warning(err)
  1565. }
  1566. }