tgbot.go 40 KB

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