1
0

tgbot.go 42 KB

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