tgbot.go 55 KB

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