tgbot.go 34 KB

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