tgbot.go 61 KB

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