tgbot.go 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055
  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/gin-gonic/gin"
  18. "github.com/mymmrac/telego"
  19. th "github.com/mymmrac/telego/telegohandler"
  20. tu "github.com/mymmrac/telego/telegoutil"
  21. )
  22. var bot *telego.Bot
  23. var botHandler *th.BotHandler
  24. var adminIds []int64
  25. var isRunning bool
  26. type LoginStatus byte
  27. const (
  28. LoginSuccess LoginStatus = 1
  29. LoginFail LoginStatus = 0
  30. )
  31. type Tgbot struct {
  32. inboundService InboundService
  33. settingService SettingService
  34. serverService ServerService
  35. xrayService XrayService
  36. lastStatus *Status
  37. hashStorage *global.HashStorage
  38. }
  39. func (t *Tgbot) NewTgbot() *Tgbot {
  40. return new(Tgbot)
  41. }
  42. func (t *Tgbot) BotI18n(name string, params ...string) string {
  43. return locale.I18n(locale.Bot, name, params...)
  44. }
  45. func (t *Tgbot) GetHashStorage() *global.HashStorage {
  46. return t.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
  54. t.hashStorage = global.NewHashStorage(5*time.Minute, false)
  55. tgBottoken, err := t.settingService.GetTgBotToken()
  56. if err != nil || tgBottoken == "" {
  57. logger.Warning("Get TgBotToken failed:", err)
  58. return err
  59. }
  60. tgBotid, err := t.settingService.GetTgBotChatId()
  61. if err != nil {
  62. logger.Warning("Get GetTgBotChatId failed:", err)
  63. return err
  64. }
  65. for _, adminId := range strings.Split(tgBotid, ",") {
  66. id, err := strconv.Atoi(adminId)
  67. if err != nil {
  68. logger.Warning("Failed to get IDs from GetTgBotChatId:", err)
  69. return err
  70. }
  71. adminIds = append(adminIds, int64(id))
  72. }
  73. bot, err = telego.NewBot(tgBottoken)
  74. if err != nil {
  75. fmt.Println("Get tgbot's api error:", err)
  76. return err
  77. }
  78. // listen for TG bot income messages
  79. if !isRunning {
  80. logger.Info("Starting Telegram receiver ...")
  81. go t.OnReceive()
  82. isRunning = true
  83. }
  84. return nil
  85. }
  86. func (t *Tgbot) IsRunning() bool {
  87. return isRunning
  88. }
  89. func (t *Tgbot) Stop() {
  90. botHandler.Stop()
  91. bot.StopLongPolling()
  92. logger.Info("Stop Telegram receiver ...")
  93. isRunning = false
  94. adminIds = nil
  95. }
  96. func (t *Tgbot) OnReceive() {
  97. params := telego.GetUpdatesParams{
  98. Timeout: 10,
  99. }
  100. updates, _ := bot.UpdatesViaLongPolling(&params)
  101. botHandler, _ = th.NewBotHandler(bot, updates)
  102. botHandler.HandleMessage(func(_ *telego.Bot, message telego.Message) {
  103. t.SendMsgToTgbot(message.Chat.ID, "Custom Keyboard Closed!", tu.ReplyKeyboardRemove())
  104. }, th.TextEqual("❌ Close Keyboard"))
  105. botHandler.HandleMessage(func(_ *telego.Bot, message telego.Message) {
  106. t.answerCommand(&message, message.Chat.ID, checkAdmin(message.From.ID))
  107. }, th.AnyCommand())
  108. botHandler.HandleCallbackQuery(func(_ *telego.Bot, query telego.CallbackQuery) {
  109. t.asnwerCallback(&query, checkAdmin(query.From.ID))
  110. }, th.AnyCallbackQueryWithMessage())
  111. botHandler.HandleMessage(func(_ *telego.Bot, message telego.Message) {
  112. if message.UserShared != nil {
  113. if checkAdmin(message.From.ID) {
  114. err := t.inboundService.SetClientTelegramUserID(message.UserShared.RequestID, strconv.FormatInt(message.UserShared.UserID, 10))
  115. var output string
  116. if err != nil {
  117. output = "❌ Error in user selection!"
  118. } else {
  119. output = "✅ Telegram User saved."
  120. }
  121. t.SendMsgToTgbot(message.Chat.ID, output, tu.ReplyKeyboardRemove())
  122. } else {
  123. t.SendMsgToTgbot(message.Chat.ID, "No result!", tu.ReplyKeyboardRemove())
  124. }
  125. }
  126. }, th.AnyMessage())
  127. botHandler.Start()
  128. }
  129. func (t *Tgbot) answerCommand(message *telego.Message, chatId int64, isAdmin bool) {
  130. msg := ""
  131. command, commandArgs := tu.ParseCommand(message.Text)
  132. // Extract the command from the Message.
  133. switch command {
  134. case "help":
  135. msg = "This bot is providing you some specefic data from the server.\n\n Please choose:"
  136. case "start":
  137. msg = "Hello <i>" + message.From.FirstName + "</i> 👋"
  138. if isAdmin {
  139. hostname, _ := os.Hostname()
  140. msg += "\nWelcome to <b>" + hostname + "</b> management bot"
  141. }
  142. msg += "\n\nI can do some magics for you, please choose:"
  143. case "status":
  144. msg = "bot is ok ✅"
  145. case "usage":
  146. if len(commandArgs) > 0 {
  147. if isAdmin {
  148. t.searchClient(chatId, commandArgs[0])
  149. } else {
  150. t.searchForClient(chatId, commandArgs[0])
  151. }
  152. } else {
  153. msg = "❗Please provide a text for search!"
  154. }
  155. case "inbound":
  156. if isAdmin && len(commandArgs) > 0 {
  157. t.searchInbound(chatId, commandArgs[0])
  158. } else {
  159. msg = "❗ Unknown command"
  160. }
  161. default:
  162. msg = "❗ Unknown command"
  163. }
  164. t.SendAnswer(chatId, msg, isAdmin)
  165. }
  166. func (t *Tgbot) asnwerCallback(callbackQuery *telego.CallbackQuery, isAdmin bool) {
  167. chatId := callbackQuery.Message.Chat.ID
  168. if isAdmin {
  169. // get query from hash storage (if the query was <= 64 chars hash storage dont save the hash and return data itself)
  170. decodedQuery := t.hashStorage.GetValue(callbackQuery.Data)
  171. dataArray := strings.Split(decodedQuery, " ")
  172. if len(dataArray) >= 2 && len(dataArray[1]) > 0 {
  173. email := dataArray[1]
  174. switch dataArray[0] {
  175. case "client_refresh":
  176. t.sendCallbackAnswerTgBot(callbackQuery.ID, fmt.Sprintf("✅ %s : Client refreshed successfully.", email))
  177. t.searchClient(chatId, email, callbackQuery.Message.MessageID)
  178. case "client_cancel":
  179. t.sendCallbackAnswerTgBot(callbackQuery.ID, fmt.Sprintf("❌ %s : Operation canceled.", email))
  180. t.searchClient(chatId, email, callbackQuery.Message.MessageID)
  181. case "ips_refresh":
  182. t.sendCallbackAnswerTgBot(callbackQuery.ID, fmt.Sprintf("✅ %s : IPs refreshed successfully.", email))
  183. t.searchClientIps(chatId, email, callbackQuery.Message.MessageID)
  184. case "ips_cancel":
  185. t.sendCallbackAnswerTgBot(callbackQuery.ID, fmt.Sprintf("❌ %s : Operation canceled.", email))
  186. t.searchClientIps(chatId, email, callbackQuery.Message.MessageID)
  187. case "tgid_refresh":
  188. t.sendCallbackAnswerTgBot(callbackQuery.ID, fmt.Sprintf("✅ %s : Client's Telegram User refreshed successfully.", email))
  189. t.clientTelegramUserInfo(chatId, email, callbackQuery.Message.MessageID)
  190. case "tgid_cancel":
  191. t.sendCallbackAnswerTgBot(callbackQuery.ID, fmt.Sprintf("❌ %s : Operation canceled.", email))
  192. t.clientTelegramUserInfo(chatId, email, callbackQuery.Message.MessageID)
  193. case "reset_traffic":
  194. inlineKeyboard := tu.InlineKeyboard(
  195. tu.InlineKeyboardRow(
  196. tu.InlineKeyboardButton("❌ Cancel Reset").WithCallbackData(t.hashStorage.AddHash("client_cancel "+email)),
  197. ),
  198. tu.InlineKeyboardRow(
  199. tu.InlineKeyboardButton("✅ Confirm Reset Traffic?").WithCallbackData(t.hashStorage.AddHash("reset_traffic_c "+email)),
  200. ),
  201. )
  202. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.MessageID, inlineKeyboard)
  203. case "reset_traffic_c":
  204. err := t.inboundService.ResetClientTrafficByEmail(email)
  205. if err == nil {
  206. t.xrayService.SetToNeedRestart()
  207. t.sendCallbackAnswerTgBot(callbackQuery.ID, fmt.Sprintf("✅ %s : Traffic reset successfully.", email))
  208. t.searchClient(chatId, email, callbackQuery.Message.MessageID)
  209. } else {
  210. t.sendCallbackAnswerTgBot(callbackQuery.ID, "❗ Error in Operation.")
  211. }
  212. case "reset_exp":
  213. var inlineKeyboard = tu.InlineKeyboard(
  214. tu.InlineKeyboardRow(
  215. tu.InlineKeyboardButton("❌ Cancel Reset").WithCallbackData(t.hashStorage.AddHash("client_cancel "+email)),
  216. ),
  217. tu.InlineKeyboardRow(
  218. tu.InlineKeyboardButton("♾ Unlimited").WithCallbackData(t.hashStorage.AddHash("reset_exp_c "+email+" 0")),
  219. ),
  220. tu.InlineKeyboardRow(
  221. tu.InlineKeyboardButton("1 Month").WithCallbackData(t.hashStorage.AddHash("reset_exp_c "+email+" 30")),
  222. tu.InlineKeyboardButton("2 Months").WithCallbackData(t.hashStorage.AddHash("reset_exp_c "+email+" 60")),
  223. ),
  224. tu.InlineKeyboardRow(
  225. tu.InlineKeyboardButton("3 Months").WithCallbackData(t.hashStorage.AddHash("reset_exp_c "+email+" 90")),
  226. tu.InlineKeyboardButton("6 Months").WithCallbackData(t.hashStorage.AddHash("reset_exp_c "+email+" 180")),
  227. ),
  228. tu.InlineKeyboardRow(
  229. tu.InlineKeyboardButton("9 Months").WithCallbackData(t.hashStorage.AddHash("reset_exp_c "+email+" 270")),
  230. tu.InlineKeyboardButton("12 Months").WithCallbackData(t.hashStorage.AddHash("reset_exp_c "+email+" 360")),
  231. ),
  232. tu.InlineKeyboardRow(
  233. tu.InlineKeyboardButton("10 Days").WithCallbackData(t.hashStorage.AddHash("reset_exp_c "+email+" 10")),
  234. tu.InlineKeyboardButton("20 Days").WithCallbackData(t.hashStorage.AddHash("reset_exp_c "+email+" 20")),
  235. ),
  236. )
  237. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.MessageID, inlineKeyboard)
  238. case "reset_exp_c":
  239. if len(dataArray) == 3 {
  240. days, err := strconv.Atoi(dataArray[2])
  241. if err == nil {
  242. var date int64 = 0
  243. if days > 0 {
  244. date = int64(-(days * 24 * 60 * 60000))
  245. }
  246. err := t.inboundService.ResetClientExpiryTimeByEmail(email, date)
  247. if err == nil {
  248. t.xrayService.SetToNeedRestart()
  249. t.sendCallbackAnswerTgBot(callbackQuery.ID, fmt.Sprintf("✅ %s : Expire days reset successfully.", email))
  250. t.searchClient(chatId, email, callbackQuery.Message.MessageID)
  251. return
  252. }
  253. }
  254. }
  255. t.sendCallbackAnswerTgBot(callbackQuery.ID, "❗ Error in Operation.")
  256. t.searchClient(chatId, email, callbackQuery.Message.MessageID)
  257. case "ip_limit":
  258. inlineKeyboard := tu.InlineKeyboard(
  259. tu.InlineKeyboardRow(
  260. tu.InlineKeyboardButton("❌ Cancel IP Limit").WithCallbackData(t.hashStorage.AddHash("client_cancel "+email)),
  261. ),
  262. tu.InlineKeyboardRow(
  263. tu.InlineKeyboardButton("♾ Unlimited").WithCallbackData(t.hashStorage.AddHash("ip_limit_c "+email+" 0")),
  264. ),
  265. tu.InlineKeyboardRow(
  266. tu.InlineKeyboardButton("1").WithCallbackData(t.hashStorage.AddHash("ip_limit_c "+email+" 1")),
  267. tu.InlineKeyboardButton("2").WithCallbackData(t.hashStorage.AddHash("ip_limit_c "+email+" 2")),
  268. ),
  269. tu.InlineKeyboardRow(
  270. tu.InlineKeyboardButton("3").WithCallbackData(t.hashStorage.AddHash("ip_limit_c "+email+" 3")),
  271. tu.InlineKeyboardButton("4").WithCallbackData(t.hashStorage.AddHash("ip_limit_c "+email+" 4")),
  272. ),
  273. tu.InlineKeyboardRow(
  274. tu.InlineKeyboardButton("5").WithCallbackData(t.hashStorage.AddHash("ip_limit_c "+email+" 5")),
  275. tu.InlineKeyboardButton("6").WithCallbackData(t.hashStorage.AddHash("ip_limit_c "+email+" 6")),
  276. tu.InlineKeyboardButton("7").WithCallbackData(t.hashStorage.AddHash("ip_limit_c "+email+" 7")),
  277. ),
  278. tu.InlineKeyboardRow(
  279. tu.InlineKeyboardButton("8").WithCallbackData(t.hashStorage.AddHash("ip_limit_c "+email+" 8")),
  280. tu.InlineKeyboardButton("9").WithCallbackData(t.hashStorage.AddHash("ip_limit_c "+email+" 9")),
  281. tu.InlineKeyboardButton("10").WithCallbackData(t.hashStorage.AddHash("ip_limit_c "+email+" 10")),
  282. ),
  283. )
  284. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.MessageID, inlineKeyboard)
  285. case "ip_limit_c":
  286. if len(dataArray) == 3 {
  287. count, err := strconv.Atoi(dataArray[2])
  288. if err == nil {
  289. err := t.inboundService.ResetClientIpLimitByEmail(email, count)
  290. if err == nil {
  291. t.xrayService.SetToNeedRestart()
  292. t.sendCallbackAnswerTgBot(callbackQuery.ID, fmt.Sprintf("✅ %s : IP limit %d saved successfully.", email, count))
  293. t.searchClient(chatId, email, callbackQuery.Message.MessageID)
  294. return
  295. }
  296. }
  297. }
  298. t.sendCallbackAnswerTgBot(callbackQuery.ID, "❗ Error in Operation.")
  299. t.searchClient(chatId, email, callbackQuery.Message.MessageID)
  300. case "clear_ips":
  301. inlineKeyboard := tu.InlineKeyboard(
  302. tu.InlineKeyboardRow(
  303. tu.InlineKeyboardButton("❌ Cancel").WithCallbackData(t.hashStorage.AddHash("ips_cancel "+email)),
  304. ),
  305. tu.InlineKeyboardRow(
  306. tu.InlineKeyboardButton("✅ Confirm Clear IPs?").WithCallbackData(t.hashStorage.AddHash("clear_ips_c "+email)),
  307. ),
  308. )
  309. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.MessageID, inlineKeyboard)
  310. case "clear_ips_c":
  311. err := t.inboundService.ClearClientIps(email)
  312. if err == nil {
  313. t.sendCallbackAnswerTgBot(callbackQuery.ID, fmt.Sprintf("✅ %s : IPs cleared successfully.", email))
  314. t.searchClientIps(chatId, email, callbackQuery.Message.MessageID)
  315. } else {
  316. t.sendCallbackAnswerTgBot(callbackQuery.ID, "❗ Error in Operation.")
  317. }
  318. case "ip_log":
  319. t.sendCallbackAnswerTgBot(callbackQuery.ID, fmt.Sprintf("✅ %s : Get IP Log.", email))
  320. t.searchClientIps(chatId, email)
  321. case "tg_user":
  322. t.sendCallbackAnswerTgBot(callbackQuery.ID, fmt.Sprintf("✅ %s : Get Telegram User Info.", email))
  323. t.clientTelegramUserInfo(chatId, email)
  324. case "tgid_remove":
  325. inlineKeyboard := tu.InlineKeyboard(
  326. tu.InlineKeyboardRow(
  327. tu.InlineKeyboardButton("❌ Cancel").WithCallbackData(t.hashStorage.AddHash("tgid_cancel "+email)),
  328. ),
  329. tu.InlineKeyboardRow(
  330. tu.InlineKeyboardButton("✅ Confirm Remove Telegram User?").WithCallbackData(t.hashStorage.AddHash("tgid_remove_c "+email)),
  331. ),
  332. )
  333. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.MessageID, inlineKeyboard)
  334. case "tgid_remove_c":
  335. traffic, err := t.inboundService.GetClientTrafficByEmail(email)
  336. if err != nil || traffic == nil {
  337. t.sendCallbackAnswerTgBot(callbackQuery.ID, "❗ Error in Operation.")
  338. return
  339. }
  340. err = t.inboundService.SetClientTelegramUserID(traffic.Id, "")
  341. if err == nil {
  342. t.sendCallbackAnswerTgBot(callbackQuery.ID, fmt.Sprintf("✅ %s : Telegram User removed successfully.", email))
  343. t.clientTelegramUserInfo(chatId, email, callbackQuery.Message.MessageID)
  344. } else {
  345. t.sendCallbackAnswerTgBot(callbackQuery.ID, "❗ Error in Operation.")
  346. }
  347. case "toggle_enable":
  348. enabled, err := t.inboundService.ToggleClientEnableByEmail(email)
  349. if err == nil {
  350. t.xrayService.SetToNeedRestart()
  351. if enabled {
  352. t.sendCallbackAnswerTgBot(callbackQuery.ID, fmt.Sprintf("✅ %s : Enabled successfully.", email))
  353. } else {
  354. t.sendCallbackAnswerTgBot(callbackQuery.ID, fmt.Sprintf("✅ %s : Disabled successfully.", email))
  355. }
  356. t.searchClient(chatId, email, callbackQuery.Message.MessageID)
  357. } else {
  358. t.sendCallbackAnswerTgBot(callbackQuery.ID, "❗ Error in Operation.")
  359. }
  360. }
  361. return
  362. }
  363. }
  364. // Respond to the callback query, telling Telegram to show the user
  365. // a message with the data received.
  366. t.sendCallbackAnswerTgBot(callbackQuery.ID, callbackQuery.Data)
  367. switch callbackQuery.Data {
  368. case "get_usage":
  369. t.SendMsgToTgbot(chatId, t.getServerUsage())
  370. case "inbounds":
  371. t.SendMsgToTgbot(chatId, t.getInboundUsages())
  372. case "deplete_soon":
  373. t.SendMsgToTgbot(chatId, t.getExhausted())
  374. case "get_backup":
  375. t.sendBackup(chatId)
  376. case "client_traffic":
  377. t.getClientUsage(chatId, callbackQuery.From.Username, strconv.FormatInt(callbackQuery.From.ID, 10))
  378. case "client_commands":
  379. t.SendMsgToTgbot(chatId, "To search for statistics, just use folowing command:\r\n \r\n<code>/usage [UID|Password]</code>\r\n \r\nUse UID for vmess/vless and Password for Trojan.")
  380. case "commands":
  381. t.SendMsgToTgbot(chatId, "Search for a client email:\r\n<code>/usage email</code>\r\n \r\nSearch for inbounds (with client stats):\r\n<code>/inbound [remark]</code>")
  382. }
  383. }
  384. func checkAdmin(tgId int64) bool {
  385. for _, adminId := range adminIds {
  386. if adminId == tgId {
  387. return true
  388. }
  389. }
  390. return false
  391. }
  392. func (t *Tgbot) SendAnswer(chatId int64, msg string, isAdmin bool) {
  393. numericKeyboard := tu.InlineKeyboard(
  394. tu.InlineKeyboardRow(
  395. tu.InlineKeyboardButton("Server Usage").WithCallbackData(t.hashStorage.AddHash("get_usage")),
  396. tu.InlineKeyboardButton("Get DB Backup").WithCallbackData(t.hashStorage.AddHash("get_backup")),
  397. ),
  398. tu.InlineKeyboardRow(
  399. tu.InlineKeyboardButton("Get Inbounds").WithCallbackData(t.hashStorage.AddHash("inbounds")),
  400. tu.InlineKeyboardButton("Deplete soon").WithCallbackData(t.hashStorage.AddHash("deplete_soon")),
  401. ),
  402. tu.InlineKeyboardRow(
  403. tu.InlineKeyboardButton("Commands").WithCallbackData(t.hashStorage.AddHash("commands")),
  404. ),
  405. )
  406. numericKeyboardClient := tu.InlineKeyboard(
  407. tu.InlineKeyboardRow(
  408. tu.InlineKeyboardButton("Get Usage").WithCallbackData(t.hashStorage.AddHash("client_traffic")),
  409. tu.InlineKeyboardButton("Commands").WithCallbackData(t.hashStorage.AddHash("client_commands")),
  410. ),
  411. )
  412. var ReplyMarkup telego.ReplyMarkup
  413. if isAdmin {
  414. ReplyMarkup = numericKeyboard
  415. } else {
  416. ReplyMarkup = numericKeyboardClient
  417. }
  418. t.SendMsgToTgbot(chatId, msg, ReplyMarkup)
  419. }
  420. func (t *Tgbot) SendMsgToTgbot(chatId int64, msg string, replyMarkup ...telego.ReplyMarkup) {
  421. if !isRunning {
  422. return
  423. }
  424. if msg == "" {
  425. logger.Info("[tgbot] message is empty!")
  426. return
  427. }
  428. var allMessages []string
  429. limit := 2000
  430. // paging message if it is big
  431. if len(msg) > limit {
  432. messages := strings.Split(msg, "\r\n \r\n")
  433. lastIndex := -1
  434. for _, message := range messages {
  435. if (len(allMessages) == 0) || (len(allMessages[lastIndex])+len(message) > limit) {
  436. allMessages = append(allMessages, message)
  437. lastIndex++
  438. } else {
  439. allMessages[lastIndex] += "\r\n \r\n" + message
  440. }
  441. }
  442. } else {
  443. allMessages = append(allMessages, msg)
  444. }
  445. for _, message := range allMessages {
  446. params := telego.SendMessageParams{
  447. ChatID: tu.ID(chatId),
  448. Text: message,
  449. ParseMode: "HTML",
  450. }
  451. if len(replyMarkup) > 0 {
  452. params.ReplyMarkup = replyMarkup[0]
  453. }
  454. _, err := bot.SendMessage(&params)
  455. if err != nil {
  456. logger.Warning("Error sending telegram message :", err)
  457. }
  458. time.Sleep(500 * time.Millisecond)
  459. }
  460. }
  461. func (t *Tgbot) SendMsgToTgbotAdmins(msg string) {
  462. for _, adminId := range adminIds {
  463. t.SendMsgToTgbot(adminId, msg)
  464. }
  465. }
  466. func (t *Tgbot) SendReport() {
  467. runTime, err := t.settingService.GetTgbotRuntime()
  468. if err == nil && len(runTime) > 0 {
  469. t.SendMsgToTgbotAdmins("🕰 Scheduled reports: " + runTime + "\r\nDate-Time: " + time.Now().Format("2006-01-02 15:04:05"))
  470. }
  471. info := t.getServerUsage()
  472. t.SendMsgToTgbotAdmins(info)
  473. exhausted := t.getExhausted()
  474. t.SendMsgToTgbotAdmins(exhausted)
  475. backupEnable, err := t.settingService.GetTgBotBackup()
  476. if err == nil && backupEnable {
  477. for _, adminId := range adminIds {
  478. t.sendBackup(int64(adminId))
  479. }
  480. }
  481. }
  482. func (t *Tgbot) SendBackUP(c *gin.Context) {
  483. for _, adminId := range adminIds {
  484. t.sendBackup(int64(adminId))
  485. }
  486. }
  487. func (t *Tgbot) getServerUsage() string {
  488. var info string
  489. //get hostname
  490. hostname, err := os.Hostname()
  491. if err != nil {
  492. logger.Error("get hostname error:", err)
  493. hostname = ""
  494. }
  495. info = fmt.Sprintf("💻 Hostname: %s\r\n", hostname)
  496. info += fmt.Sprintf("🚀X-UI Version: %s\r\n", config.GetVersion())
  497. //get ip address
  498. var ip string
  499. var ipv6 string
  500. netInterfaces, err := net.Interfaces()
  501. if err != nil {
  502. logger.Error("net.Interfaces failed, err:", err.Error())
  503. info += "🌐 IP: Unknown\r\n \r\n"
  504. } else {
  505. for i := 0; i < len(netInterfaces); i++ {
  506. if (netInterfaces[i].Flags & net.FlagUp) != 0 {
  507. addrs, _ := netInterfaces[i].Addrs()
  508. for _, address := range addrs {
  509. if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
  510. if ipnet.IP.To4() != nil {
  511. ip += ipnet.IP.String() + " "
  512. } else if ipnet.IP.To16() != nil && !ipnet.IP.IsLinkLocalUnicast() {
  513. ipv6 += ipnet.IP.String() + " "
  514. }
  515. }
  516. }
  517. }
  518. }
  519. info += fmt.Sprintf("🌐IP: %s\r\n🌐IPv6: %s\r\n", ip, ipv6)
  520. }
  521. // get latest status of server
  522. t.lastStatus = t.serverService.GetStatus(t.lastStatus)
  523. info += fmt.Sprintf("🔌Server Uptime: %d days\r\n", int(t.lastStatus.Uptime/86400))
  524. info += fmt.Sprintf("📈Server Load: %.1f, %.1f, %.1f\r\n", t.lastStatus.Loads[0], t.lastStatus.Loads[1], t.lastStatus.Loads[2])
  525. info += fmt.Sprintf("📋Server Memory: %s/%s\r\n", common.FormatTraffic(int64(t.lastStatus.Mem.Current)), common.FormatTraffic(int64(t.lastStatus.Mem.Total)))
  526. info += fmt.Sprintf("🔹TcpCount: %d\r\n", t.lastStatus.TcpCount)
  527. info += fmt.Sprintf("🔸UdpCount: %d\r\n", t.lastStatus.UdpCount)
  528. info += fmt.Sprintf("🚦Traffic: %s (↑%s,↓%s)\r\n", common.FormatTraffic(int64(t.lastStatus.NetTraffic.Sent+t.lastStatus.NetTraffic.Recv)), common.FormatTraffic(int64(t.lastStatus.NetTraffic.Sent)), common.FormatTraffic(int64(t.lastStatus.NetTraffic.Recv)))
  529. info += fmt.Sprintf("ℹXray status: %s", t.lastStatus.Xray.State)
  530. return info
  531. }
  532. func (t *Tgbot) UserLoginNotify(username string, ip string, time string, status LoginStatus) {
  533. if !t.IsRunning() {
  534. return
  535. }
  536. if username == "" || ip == "" || time == "" {
  537. logger.Warning("UserLoginNotify failed, invalid info!")
  538. return
  539. }
  540. // Get hostname
  541. hostname, err := os.Hostname()
  542. if err != nil {
  543. logger.Warning("get hostname error:", err)
  544. return
  545. }
  546. msg := ""
  547. if status == LoginSuccess {
  548. msg = fmt.Sprintf("✅ Successfully logged-in to the panel\r\nHostname:%s\r\n", hostname)
  549. } else if status == LoginFail {
  550. msg = fmt.Sprintf("❗ Login to the panel was unsuccessful\r\nHostname:%s\r\n", hostname)
  551. }
  552. msg += fmt.Sprintf("⏰ Time:%s\r\n", time)
  553. msg += fmt.Sprintf("🆔 Username:%s\r\n", username)
  554. msg += fmt.Sprintf("🌐 IP:%s\r\n", ip)
  555. t.SendMsgToTgbotAdmins(msg)
  556. }
  557. func (t *Tgbot) getInboundUsages() string {
  558. info := ""
  559. // get traffic
  560. inbouds, err := t.inboundService.GetAllInbounds()
  561. if err != nil {
  562. logger.Warning("GetAllInbounds run failed:", err)
  563. info += "❌ Failed to get inbounds"
  564. } else {
  565. // NOTE:If there no any sessions here,need to notify here
  566. // TODO:Sub-node push, automatic conversion format
  567. for _, inbound := range inbouds {
  568. info += fmt.Sprintf("📍Inbound:%s\r\nPort:%d\r\n", inbound.Remark, inbound.Port)
  569. info += fmt.Sprintf("Traffic: %s (↑%s,↓%s)\r\n", common.FormatTraffic((inbound.Up + inbound.Down)), common.FormatTraffic(inbound.Up), common.FormatTraffic(inbound.Down))
  570. if inbound.ExpiryTime == 0 {
  571. info += "Expire date: ♾ Unlimited\r\n \r\n"
  572. } else {
  573. info += fmt.Sprintf("Expire date:%s\r\n \r\n", time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05"))
  574. }
  575. }
  576. }
  577. return info
  578. }
  579. func (t *Tgbot) getClientUsage(chatId int64, tgUserName string, tgUserID string) {
  580. traffics, err := t.inboundService.GetClientTrafficTgBot(tgUserID)
  581. if err != nil {
  582. logger.Warning(err)
  583. msg := "❌ Something went wrong!"
  584. t.SendMsgToTgbot(chatId, msg)
  585. return
  586. }
  587. if len(traffics) == 0 {
  588. if len(tgUserName) == 0 {
  589. msg := "Your configuration is not found!\nPlease ask your Admin to use your telegram user id in your configuration(s).\n\nYour user id: <b>" + tgUserID + "</b>"
  590. t.SendMsgToTgbot(chatId, msg)
  591. return
  592. }
  593. traffics, err = t.inboundService.GetClientTrafficTgBot(tgUserName)
  594. }
  595. if err != nil {
  596. logger.Warning(err)
  597. msg := "❌ Something went wrong!"
  598. t.SendMsgToTgbot(chatId, msg)
  599. return
  600. }
  601. if len(traffics) == 0 {
  602. msg := "Your configuration is not found!\nPlease ask your Admin to use your telegram username or user id in your configuration(s).\n\nYour username: <b>@" + tgUserName + "</b>\n\nYour user id: <b>" + tgUserID + "</b>"
  603. t.SendMsgToTgbot(chatId, msg)
  604. return
  605. }
  606. for _, traffic := range traffics {
  607. expiryTime := ""
  608. if traffic.ExpiryTime == 0 {
  609. expiryTime = "♾Unlimited"
  610. } else if traffic.ExpiryTime < 0 {
  611. expiryTime = fmt.Sprintf("%d days", traffic.ExpiryTime/-86400000)
  612. } else {
  613. expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
  614. }
  615. total := ""
  616. if traffic.Total == 0 {
  617. total = "♾Unlimited"
  618. } else {
  619. total = common.FormatTraffic((traffic.Total))
  620. }
  621. output := fmt.Sprintf("💡 Active: %t\r\n📧 Email: %s\r\n🔼 Upload↑: %s\r\n🔽 Download↓: %s\r\n🔄 Total: %s / %s\r\n📅 Expire in: %s\r\n",
  622. traffic.Enable, traffic.Email, common.FormatTraffic(traffic.Up), common.FormatTraffic(traffic.Down), common.FormatTraffic((traffic.Up + traffic.Down)),
  623. total, expiryTime)
  624. t.SendMsgToTgbot(chatId, output)
  625. }
  626. t.SendAnswer(chatId, "Please choose:", false)
  627. }
  628. func (t *Tgbot) searchClientIps(chatId int64, email string, messageID ...int) {
  629. ips, err := t.inboundService.GetInboundClientIps(email)
  630. if err != nil || len(ips) == 0 {
  631. ips = "No IP Record"
  632. }
  633. output := fmt.Sprintf("📧 Email: %s\r\n🔢 IPs: \r\n%s\r\n", email, ips)
  634. inlineKeyboard := tu.InlineKeyboard(
  635. tu.InlineKeyboardRow(
  636. tu.InlineKeyboardButton("🔄 Refresh").WithCallbackData(t.hashStorage.AddHash("ips_refresh "+email)),
  637. ),
  638. tu.InlineKeyboardRow(
  639. tu.InlineKeyboardButton("❌ Clear IPs").WithCallbackData(t.hashStorage.AddHash("clear_ips "+email)),
  640. ),
  641. )
  642. if len(messageID) > 0 {
  643. t.editMessageTgBot(chatId, messageID[0], output, inlineKeyboard)
  644. } else {
  645. t.SendMsgToTgbot(chatId, output, inlineKeyboard)
  646. }
  647. }
  648. func (t *Tgbot) clientTelegramUserInfo(chatId int64, email string, messageID ...int) {
  649. traffic, client, err := t.inboundService.GetClientByEmail(email)
  650. if err != nil {
  651. logger.Warning(err)
  652. msg := "❌ Something went wrong!"
  653. t.SendMsgToTgbot(chatId, msg)
  654. return
  655. }
  656. if client == nil {
  657. msg := "No result!"
  658. t.SendMsgToTgbot(chatId, msg)
  659. return
  660. }
  661. tgId := "None"
  662. if len(client.TgID) > 0 {
  663. tgId = client.TgID
  664. }
  665. output := fmt.Sprintf("📧 Email: %s\r\n👤 Telegram User: %s\r\n", email, tgId)
  666. inlineKeyboard := tu.InlineKeyboard(
  667. tu.InlineKeyboardRow(
  668. tu.InlineKeyboardButton("🔄 Refresh").WithCallbackData(t.hashStorage.AddHash("tgid_refresh "+email)),
  669. ),
  670. tu.InlineKeyboardRow(
  671. tu.InlineKeyboardButton("❌ Remove Telegram User").WithCallbackData(t.hashStorage.AddHash("tgid_remove "+email)),
  672. ),
  673. )
  674. if len(messageID) > 0 {
  675. t.editMessageTgBot(chatId, messageID[0], output, inlineKeyboard)
  676. } else {
  677. t.SendMsgToTgbot(chatId, output, inlineKeyboard)
  678. requestUser := telego.KeyboardButtonRequestUser{
  679. RequestID: int32(traffic.Id),
  680. UserIsBot: false,
  681. }
  682. keyboard := tu.Keyboard(
  683. tu.KeyboardRow(
  684. tu.KeyboardButton("👤 Select Telegram User").WithRequestUser(&requestUser),
  685. ),
  686. tu.KeyboardRow(
  687. tu.KeyboardButton("❌ Close Keyboard"),
  688. ),
  689. ).WithIsPersistent().WithResizeKeyboard()
  690. t.SendMsgToTgbot(chatId, "👤 Select a telegram user:", keyboard)
  691. }
  692. }
  693. func (t *Tgbot) searchClient(chatId int64, email string, messageID ...int) {
  694. traffic, err := t.inboundService.GetClientTrafficByEmail(email)
  695. if err != nil {
  696. logger.Warning(err)
  697. msg := "❌ Something went wrong!"
  698. t.SendMsgToTgbot(chatId, msg)
  699. return
  700. }
  701. if traffic == nil {
  702. msg := "No result!"
  703. t.SendMsgToTgbot(chatId, msg)
  704. return
  705. }
  706. expiryTime := ""
  707. if traffic.ExpiryTime == 0 {
  708. expiryTime = "♾Unlimited"
  709. } else if traffic.ExpiryTime < 0 {
  710. expiryTime = fmt.Sprintf("%d days", traffic.ExpiryTime/-86400000)
  711. } else {
  712. expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
  713. }
  714. total := ""
  715. if traffic.Total == 0 {
  716. total = "♾Unlimited"
  717. } else {
  718. total = common.FormatTraffic((traffic.Total))
  719. }
  720. output := fmt.Sprintf("💡 Active: %t\r\n📧 Email: %s\r\n🔼 Upload↑: %s\r\n🔽 Download↓: %s\r\n🔄 Total: %s / %s\r\n📅 Expire in: %s\r\n",
  721. traffic.Enable, traffic.Email, common.FormatTraffic(traffic.Up), common.FormatTraffic(traffic.Down), common.FormatTraffic((traffic.Up + traffic.Down)),
  722. total, expiryTime)
  723. inlineKeyboard := tu.InlineKeyboard(
  724. tu.InlineKeyboardRow(
  725. tu.InlineKeyboardButton("🔄 Refresh").WithCallbackData(t.hashStorage.AddHash("client_refresh "+email)),
  726. ),
  727. tu.InlineKeyboardRow(
  728. tu.InlineKeyboardButton("📈 Reset Traffic").WithCallbackData(t.hashStorage.AddHash("reset_traffic "+email)),
  729. ),
  730. tu.InlineKeyboardRow(
  731. tu.InlineKeyboardButton("📅 Reset Expire Days").WithCallbackData(t.hashStorage.AddHash("reset_exp "+email)),
  732. ),
  733. tu.InlineKeyboardRow(
  734. tu.InlineKeyboardButton("🔢 IP Log").WithCallbackData(t.hashStorage.AddHash("ip_log "+email)),
  735. tu.InlineKeyboardButton("🔢 IP Limit").WithCallbackData(t.hashStorage.AddHash("ip_limit "+email)),
  736. ),
  737. tu.InlineKeyboardRow(
  738. tu.InlineKeyboardButton("👤 Set Telegram User").WithCallbackData(t.hashStorage.AddHash("tg_user "+email)),
  739. ),
  740. tu.InlineKeyboardRow(
  741. tu.InlineKeyboardButton("🔘 Enable / Disable").WithCallbackData(t.hashStorage.AddHash("toggle_enable "+email)),
  742. ),
  743. )
  744. if len(messageID) > 0 {
  745. t.editMessageTgBot(chatId, messageID[0], output, inlineKeyboard)
  746. } else {
  747. t.SendMsgToTgbot(chatId, output, inlineKeyboard)
  748. }
  749. }
  750. func (t *Tgbot) searchInbound(chatId int64, remark string) {
  751. inbouds, err := t.inboundService.SearchInbounds(remark)
  752. if err != nil {
  753. logger.Warning(err)
  754. msg := "❌ Something went wrong!"
  755. t.SendMsgToTgbot(chatId, msg)
  756. return
  757. }
  758. if len(inbouds) == 0 {
  759. msg := "❌ No inbounds found!"
  760. t.SendMsgToTgbot(chatId, msg)
  761. return
  762. }
  763. for _, inbound := range inbouds {
  764. info := ""
  765. info += fmt.Sprintf("📍Inbound:%s\r\nPort:%d\r\n", inbound.Remark, inbound.Port)
  766. info += fmt.Sprintf("Traffic: %s (↑%s,↓%s)\r\n", common.FormatTraffic((inbound.Up + inbound.Down)), common.FormatTraffic(inbound.Up), common.FormatTraffic(inbound.Down))
  767. if inbound.ExpiryTime == 0 {
  768. info += "Expire date: ♾ Unlimited\r\n \r\n"
  769. } else {
  770. info += fmt.Sprintf("Expire date:%s\r\n \r\n", time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05"))
  771. }
  772. t.SendMsgToTgbot(chatId, info)
  773. for _, traffic := range inbound.ClientStats {
  774. expiryTime := ""
  775. if traffic.ExpiryTime == 0 {
  776. expiryTime = "♾Unlimited"
  777. } else if traffic.ExpiryTime < 0 {
  778. expiryTime = fmt.Sprintf("%d days", traffic.ExpiryTime/-86400000)
  779. } else {
  780. expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
  781. }
  782. total := ""
  783. if traffic.Total == 0 {
  784. total = "♾Unlimited"
  785. } else {
  786. total = common.FormatTraffic((traffic.Total))
  787. }
  788. output := fmt.Sprintf("💡 Active: %t\r\n📧 Email: %s\r\n🔼 Upload↑: %s\r\n🔽 Download↓: %s\r\n🔄 Total: %s / %s\r\n📅 Expire in: %s\r\n",
  789. traffic.Enable, traffic.Email, common.FormatTraffic(traffic.Up), common.FormatTraffic(traffic.Down), common.FormatTraffic((traffic.Up + traffic.Down)),
  790. total, expiryTime)
  791. t.SendMsgToTgbot(chatId, output)
  792. }
  793. }
  794. }
  795. func (t *Tgbot) searchForClient(chatId int64, query string) {
  796. traffic, err := t.inboundService.SearchClientTraffic(query)
  797. if err != nil {
  798. logger.Warning(err)
  799. msg := "❌ Something went wrong!"
  800. t.SendMsgToTgbot(chatId, msg)
  801. return
  802. }
  803. if traffic == nil {
  804. msg := "No result!"
  805. t.SendMsgToTgbot(chatId, msg)
  806. return
  807. }
  808. expiryTime := ""
  809. if traffic.ExpiryTime == 0 {
  810. expiryTime = "♾Unlimited"
  811. } else if traffic.ExpiryTime < 0 {
  812. expiryTime = fmt.Sprintf("%d days", traffic.ExpiryTime/-86400000)
  813. } else {
  814. expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
  815. }
  816. total := ""
  817. if traffic.Total == 0 {
  818. total = "♾Unlimited"
  819. } else {
  820. total = common.FormatTraffic((traffic.Total))
  821. }
  822. output := fmt.Sprintf("💡 Active: %t\r\n📧 Email: %s\r\n🔼 Upload↑: %s\r\n🔽 Download↓: %s\r\n🔄 Total: %s / %s\r\n📅 Expire in: %s\r\n",
  823. traffic.Enable, traffic.Email, common.FormatTraffic(traffic.Up), common.FormatTraffic(traffic.Down), common.FormatTraffic((traffic.Up + traffic.Down)),
  824. total, expiryTime)
  825. t.SendMsgToTgbot(chatId, output)
  826. }
  827. func (t *Tgbot) getExhausted() string {
  828. trDiff := int64(0)
  829. exDiff := int64(0)
  830. now := time.Now().Unix() * 1000
  831. var exhaustedInbounds []model.Inbound
  832. var exhaustedClients []xray.ClientTraffic
  833. var disabledInbounds []model.Inbound
  834. var disabledClients []xray.ClientTraffic
  835. output := ""
  836. TrafficThreshold, err := t.settingService.GetTrafficDiff()
  837. if err == nil && TrafficThreshold > 0 {
  838. trDiff = int64(TrafficThreshold) * 1073741824
  839. }
  840. ExpireThreshold, err := t.settingService.GetExpireDiff()
  841. if err == nil && ExpireThreshold > 0 {
  842. exDiff = int64(ExpireThreshold) * 86400000
  843. }
  844. inbounds, err := t.inboundService.GetAllInbounds()
  845. if err != nil {
  846. logger.Warning("Unable to load Inbounds", err)
  847. }
  848. for _, inbound := range inbounds {
  849. if inbound.Enable {
  850. if (inbound.ExpiryTime > 0 && (inbound.ExpiryTime-now < exDiff)) ||
  851. (inbound.Total > 0 && (inbound.Total-(inbound.Up+inbound.Down) < trDiff)) {
  852. exhaustedInbounds = append(exhaustedInbounds, *inbound)
  853. }
  854. if len(inbound.ClientStats) > 0 {
  855. for _, client := range inbound.ClientStats {
  856. if client.Enable {
  857. if (client.ExpiryTime > 0 && (client.ExpiryTime-now < exDiff)) ||
  858. (client.Total > 0 && (client.Total-(client.Up+client.Down) < trDiff)) {
  859. exhaustedClients = append(exhaustedClients, client)
  860. }
  861. } else {
  862. disabledClients = append(disabledClients, client)
  863. }
  864. }
  865. }
  866. } else {
  867. disabledInbounds = append(disabledInbounds, *inbound)
  868. }
  869. }
  870. output += fmt.Sprintf("Exhausted Inbounds count:\r\n🛑 Disabled: %d\r\n🔜 Deplete soon: %d\r\n \r\n", len(disabledInbounds), len(exhaustedInbounds))
  871. if len(exhaustedInbounds) > 0 {
  872. output += "Exhausted Inbounds:\r\n"
  873. for _, inbound := range exhaustedInbounds {
  874. output += fmt.Sprintf("📍Inbound:%s\r\nPort:%d\r\nTraffic: %s (↑%s,↓%s)\r\n", inbound.Remark, inbound.Port, common.FormatTraffic((inbound.Up + inbound.Down)), common.FormatTraffic(inbound.Up), common.FormatTraffic(inbound.Down))
  875. if inbound.ExpiryTime == 0 {
  876. output += "Expire date: ♾Unlimited\r\n \r\n"
  877. } else {
  878. output += fmt.Sprintf("Expire date:%s\r\n \r\n", time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05"))
  879. }
  880. }
  881. }
  882. output += fmt.Sprintf("Exhausted Clients count:\r\n🛑 Exhausted: %d\r\n🔜 Deplete soon: %d\r\n \r\n", len(disabledClients), len(exhaustedClients))
  883. if len(exhaustedClients) > 0 {
  884. output += "Exhausted Clients:\r\n"
  885. for _, traffic := range exhaustedClients {
  886. expiryTime := ""
  887. if traffic.ExpiryTime == 0 {
  888. expiryTime = "♾Unlimited"
  889. } else if traffic.ExpiryTime < 0 {
  890. expiryTime += fmt.Sprintf("%d days", traffic.ExpiryTime/-86400000)
  891. } else {
  892. expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
  893. }
  894. total := ""
  895. if traffic.Total == 0 {
  896. total = "♾Unlimited"
  897. } else {
  898. total = common.FormatTraffic((traffic.Total))
  899. }
  900. output += fmt.Sprintf("💡 Active: %t\r\n📧 Email: %s\r\n🔼 Upload↑: %s\r\n🔽 Download↓: %s\r\n🔄 Total: %s / %s\r\n📅 Expire date: %s\r\n \r\n",
  901. traffic.Enable, traffic.Email, common.FormatTraffic(traffic.Up), common.FormatTraffic(traffic.Down), common.FormatTraffic((traffic.Up + traffic.Down)),
  902. total, expiryTime)
  903. }
  904. }
  905. return output
  906. }
  907. func (t *Tgbot) sendBackup(chatId int64) {
  908. if !t.IsRunning() {
  909. return
  910. }
  911. sendingTime := time.Now().Format("2006-01-02 15:04:05")
  912. t.SendMsgToTgbot(chatId, "Backup time: "+sendingTime)
  913. file, err := os.Open(config.GetDBPath())
  914. if err != nil {
  915. logger.Warning("Error in opening db file for backup: ", err)
  916. }
  917. document := tu.Document(
  918. tu.ID(chatId),
  919. tu.File(file),
  920. )
  921. _, err = bot.SendDocument(document)
  922. if err != nil {
  923. logger.Warning("Error in uploading backup: ", err)
  924. }
  925. file, err = os.Open(xray.GetConfigPath())
  926. if err != nil {
  927. logger.Warning("Error in opening config.json file for backup: ", err)
  928. }
  929. document = tu.Document(
  930. tu.ID(chatId),
  931. tu.File(file),
  932. )
  933. _, err = bot.SendDocument(document)
  934. if err != nil {
  935. logger.Warning("Error in uploading config.json: ", err)
  936. }
  937. }
  938. func (t *Tgbot) sendCallbackAnswerTgBot(id string, message string) {
  939. params := telego.AnswerCallbackQueryParams{
  940. CallbackQueryID: id,
  941. Text: message,
  942. }
  943. if err := bot.AnswerCallbackQuery(&params); err != nil {
  944. logger.Warning(err)
  945. }
  946. }
  947. func (t *Tgbot) editMessageCallbackTgBot(chatId int64, messageID int, inlineKeyboard *telego.InlineKeyboardMarkup) {
  948. params := telego.EditMessageReplyMarkupParams{
  949. ChatID: tu.ID(chatId),
  950. MessageID: messageID,
  951. ReplyMarkup: inlineKeyboard,
  952. }
  953. if _, err := bot.EditMessageReplyMarkup(&params); err != nil {
  954. logger.Warning(err)
  955. }
  956. }
  957. func (t *Tgbot) editMessageTgBot(chatId int64, messageID int, text string, inlineKeyboard ...*telego.InlineKeyboardMarkup) {
  958. params := telego.EditMessageTextParams{
  959. ChatID: tu.ID(chatId),
  960. MessageID: messageID,
  961. Text: text,
  962. ParseMode: "HTML",
  963. }
  964. if len(inlineKeyboard) > 0 {
  965. params.ReplyMarkup = inlineKeyboard[0]
  966. }
  967. if _, err := bot.EditMessageText(&params); err != nil {
  968. logger.Warning(err)
  969. }
  970. }