tgbot.go 60 KB

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