tgbot.go 55 KB

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