tgbot.go 34 KB

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