tgbot.go 58 KB

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