tgbot.go 59 KB

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