1
0

tgbot.go 60 KB

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