tgbot.go 60 KB

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