tgbot.go 60 KB

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