tgbot.go 65 KB

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