tgbot.go 40 KB

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