tgbot.go 42 KB

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