tgbot.go 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  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) IsRunnging() 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(bot *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(bot *telego.Bot, message telego.Message) {
  90. t.answerCommand(&message, message.Chat.ID, checkAdmin(message.From.ID))
  91. }, th.AnyCommand())
  92. botHandler.HandleCallbackQuery(func(bot *telego.Bot, query telego.CallbackQuery) {
  93. t.asnwerCallback(&query, checkAdmin(query.From.ID))
  94. }, th.AnyCallbackQueryWithMessage())
  95. botHandler.HandleMessage(func(bot *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. params := telego.SendMessageParams{
  395. ChatID: tu.ID(chatId),
  396. Text: msg,
  397. ParseMode: "HTML",
  398. }
  399. if isAdmin {
  400. params.ReplyMarkup = numericKeyboard
  401. } else {
  402. params.ReplyMarkup = numericKeyboardClient
  403. }
  404. _, err := bot.SendMessage(&params)
  405. if err != nil {
  406. logger.Warning("Error sending telegram message :", err)
  407. }
  408. }
  409. func (t *Tgbot) SendMsgToTgbot(chatId int64, msg string, replyMarkup ...telego.ReplyMarkup) {
  410. if !isRunning {
  411. return
  412. }
  413. var allMessages []string
  414. limit := 2000
  415. // paging message if it is big
  416. if len(msg) > limit {
  417. messages := strings.Split(msg, "\r\n \r\n")
  418. lastIndex := -1
  419. for _, message := range messages {
  420. if (len(allMessages) == 0) || (len(allMessages[lastIndex])+len(message) > limit) {
  421. allMessages = append(allMessages, message)
  422. lastIndex++
  423. } else {
  424. allMessages[lastIndex] += "\r\n \r\n" + message
  425. }
  426. }
  427. } else {
  428. allMessages = append(allMessages, msg)
  429. }
  430. for _, message := range allMessages {
  431. params := telego.SendMessageParams{
  432. ChatID: tu.ID(chatId),
  433. Text: message,
  434. ParseMode: "HTML",
  435. }
  436. if len(replyMarkup) > 0 {
  437. params.ReplyMarkup = replyMarkup[0]
  438. }
  439. _, err := bot.SendMessage(&params)
  440. if err != nil {
  441. logger.Warning("Error sending telegram message :", err)
  442. }
  443. time.Sleep(500 * time.Millisecond)
  444. }
  445. }
  446. func (t *Tgbot) SendMsgToTgbotAdmins(msg string) {
  447. for _, adminId := range adminIds {
  448. t.SendMsgToTgbot(adminId, msg)
  449. }
  450. }
  451. func (t *Tgbot) SendReport() {
  452. runTime, err := t.settingService.GetTgbotRuntime()
  453. if err == nil && len(runTime) > 0 {
  454. t.SendMsgToTgbotAdmins("🕰 Scheduled reports: " + runTime + "\r\nDate-Time: " + time.Now().Format("2006-01-02 15:04:05"))
  455. }
  456. info := t.getServerUsage()
  457. t.SendMsgToTgbotAdmins(info)
  458. exhausted := t.getExhausted()
  459. t.SendMsgToTgbotAdmins(exhausted)
  460. backupEnable, err := t.settingService.GetTgBotBackup()
  461. if err == nil && backupEnable {
  462. for _, adminId := range adminIds {
  463. t.sendBackup(int64(adminId))
  464. }
  465. }
  466. }
  467. func (t *Tgbot) SendBackUP(c *gin.Context) {
  468. for _, adminId := range adminIds {
  469. t.sendBackup(int64(adminId))
  470. }
  471. }
  472. func (t *Tgbot) getServerUsage() string {
  473. var info string
  474. //get hostname
  475. name, err := os.Hostname()
  476. if err != nil {
  477. logger.Error("get hostname error:", err)
  478. name = ""
  479. }
  480. info = fmt.Sprintf("💻 Hostname: %s\r\n", name)
  481. info += fmt.Sprintf("🚀X-UI Version: %s\r\n", config.GetVersion())
  482. //get ip address
  483. var ip string
  484. var ipv6 string
  485. netInterfaces, err := net.Interfaces()
  486. if err != nil {
  487. logger.Error("net.Interfaces failed, err:", err.Error())
  488. info += "🌐 IP: Unknown\r\n \r\n"
  489. } else {
  490. for i := 0; i < len(netInterfaces); i++ {
  491. if (netInterfaces[i].Flags & net.FlagUp) != 0 {
  492. addrs, _ := netInterfaces[i].Addrs()
  493. for _, address := range addrs {
  494. if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
  495. if ipnet.IP.To4() != nil {
  496. ip += ipnet.IP.String() + " "
  497. } else if ipnet.IP.To16() != nil && !ipnet.IP.IsLinkLocalUnicast() {
  498. ipv6 += ipnet.IP.String() + " "
  499. }
  500. }
  501. }
  502. }
  503. }
  504. info += fmt.Sprintf("🌐IP: %s\r\n🌐IPv6: %s\r\n", ip, ipv6)
  505. }
  506. // get latest status of server
  507. t.lastStatus = t.serverService.GetStatus(t.lastStatus)
  508. info += fmt.Sprintf("🔌Server Uptime: %d days\r\n", int(t.lastStatus.Uptime/86400))
  509. info += fmt.Sprintf("📈Server Load: %.1f, %.1f, %.1f\r\n", t.lastStatus.Loads[0], t.lastStatus.Loads[1], t.lastStatus.Loads[2])
  510. info += fmt.Sprintf("📋Server Memory: %s/%s\r\n", common.FormatTraffic(int64(t.lastStatus.Mem.Current)), common.FormatTraffic(int64(t.lastStatus.Mem.Total)))
  511. info += fmt.Sprintf("🔹TcpCount: %d\r\n", t.lastStatus.TcpCount)
  512. info += fmt.Sprintf("🔸UdpCount: %d\r\n", t.lastStatus.UdpCount)
  513. 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)))
  514. info += fmt.Sprintf("ℹXray status: %s", t.lastStatus.Xray.State)
  515. return info
  516. }
  517. func (t *Tgbot) UserLoginNotify(username string, ip string, time string, status LoginStatus) {
  518. if username == "" || ip == "" || time == "" {
  519. logger.Warning("UserLoginNotify failed,invalid info")
  520. return
  521. }
  522. var msg string
  523. // Get hostname
  524. name, err := os.Hostname()
  525. if err != nil {
  526. logger.Warning("get hostname error:", err)
  527. return
  528. }
  529. if status == LoginSuccess {
  530. msg = fmt.Sprintf("✅ Successfully logged-in to the panel\r\nHostname:%s\r\n", name)
  531. } else if status == LoginFail {
  532. msg = fmt.Sprintf("❗ Login to the panel was unsuccessful\r\nHostname:%s\r\n", name)
  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. tdId := "None"
  644. if len(client.TgID) > 0 {
  645. tdId = client.TgID
  646. }
  647. output := fmt.Sprintf("📧 Email: %s\r\n👤 Telegram User: %s\r\n", email, tdId)
  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. for _, inbound := range inbouds {
  741. info := ""
  742. info += fmt.Sprintf("📍Inbound:%s\r\nPort:%d\r\n", inbound.Remark, inbound.Port)
  743. info += fmt.Sprintf("Traffic: %s (↑%s,↓%s)\r\n", common.FormatTraffic((inbound.Up + inbound.Down)), common.FormatTraffic(inbound.Up), common.FormatTraffic(inbound.Down))
  744. if inbound.ExpiryTime == 0 {
  745. info += "Expire date: ♾ Unlimited\r\n \r\n"
  746. } else {
  747. info += fmt.Sprintf("Expire date:%s\r\n \r\n", time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05"))
  748. }
  749. t.SendMsgToTgbot(chatId, info)
  750. for _, traffic := range inbound.ClientStats {
  751. expiryTime := ""
  752. if traffic.ExpiryTime == 0 {
  753. expiryTime = "♾Unlimited"
  754. } else if traffic.ExpiryTime < 0 {
  755. expiryTime = fmt.Sprintf("%d days", traffic.ExpiryTime/-86400000)
  756. } else {
  757. expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
  758. }
  759. total := ""
  760. if traffic.Total == 0 {
  761. total = "♾Unlimited"
  762. } else {
  763. total = common.FormatTraffic((traffic.Total))
  764. }
  765. 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",
  766. traffic.Enable, traffic.Email, common.FormatTraffic(traffic.Up), common.FormatTraffic(traffic.Down), common.FormatTraffic((traffic.Up + traffic.Down)),
  767. total, expiryTime)
  768. t.SendMsgToTgbot(chatId, output)
  769. }
  770. }
  771. }
  772. func (t *Tgbot) searchForClient(chatId int64, query string) {
  773. traffic, err := t.inboundService.SearchClientTraffic(query)
  774. if err != nil {
  775. logger.Warning(err)
  776. msg := "❌ Something went wrong!"
  777. t.SendMsgToTgbot(chatId, msg)
  778. return
  779. }
  780. if traffic == nil {
  781. msg := "No result!"
  782. t.SendMsgToTgbot(chatId, msg)
  783. return
  784. }
  785. expiryTime := ""
  786. if traffic.ExpiryTime == 0 {
  787. expiryTime = "♾Unlimited"
  788. } else if traffic.ExpiryTime < 0 {
  789. expiryTime = fmt.Sprintf("%d days", traffic.ExpiryTime/-86400000)
  790. } else {
  791. expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
  792. }
  793. total := ""
  794. if traffic.Total == 0 {
  795. total = "♾Unlimited"
  796. } else {
  797. total = common.FormatTraffic((traffic.Total))
  798. }
  799. 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",
  800. traffic.Enable, traffic.Email, common.FormatTraffic(traffic.Up), common.FormatTraffic(traffic.Down), common.FormatTraffic((traffic.Up + traffic.Down)),
  801. total, expiryTime)
  802. t.SendMsgToTgbot(chatId, output)
  803. }
  804. func (t *Tgbot) getExhausted() string {
  805. trDiff := int64(0)
  806. exDiff := int64(0)
  807. now := time.Now().Unix() * 1000
  808. var exhaustedInbounds []model.Inbound
  809. var exhaustedClients []xray.ClientTraffic
  810. var disabledInbounds []model.Inbound
  811. var disabledClients []xray.ClientTraffic
  812. output := ""
  813. TrafficThreshold, err := t.settingService.GetTrafficDiff()
  814. if err == nil && TrafficThreshold > 0 {
  815. trDiff = int64(TrafficThreshold) * 1073741824
  816. }
  817. ExpireThreshold, err := t.settingService.GetExpireDiff()
  818. if err == nil && ExpireThreshold > 0 {
  819. exDiff = int64(ExpireThreshold) * 86400000
  820. }
  821. inbounds, err := t.inboundService.GetAllInbounds()
  822. if err != nil {
  823. logger.Warning("Unable to load Inbounds", err)
  824. }
  825. for _, inbound := range inbounds {
  826. if inbound.Enable {
  827. if (inbound.ExpiryTime > 0 && (inbound.ExpiryTime-now < exDiff)) ||
  828. (inbound.Total > 0 && (inbound.Total-(inbound.Up+inbound.Down) < trDiff)) {
  829. exhaustedInbounds = append(exhaustedInbounds, *inbound)
  830. }
  831. if len(inbound.ClientStats) > 0 {
  832. for _, client := range inbound.ClientStats {
  833. if client.Enable {
  834. if (client.ExpiryTime > 0 && (client.ExpiryTime-now < exDiff)) ||
  835. (client.Total > 0 && (client.Total-(client.Up+client.Down) < trDiff)) {
  836. exhaustedClients = append(exhaustedClients, client)
  837. }
  838. } else {
  839. disabledClients = append(disabledClients, client)
  840. }
  841. }
  842. }
  843. } else {
  844. disabledInbounds = append(disabledInbounds, *inbound)
  845. }
  846. }
  847. output += fmt.Sprintf("Exhausted Inbounds count:\r\n🛑 Disabled: %d\r\n🔜 Deplete soon: %d\r\n \r\n", len(disabledInbounds), len(exhaustedInbounds))
  848. if len(exhaustedInbounds) > 0 {
  849. output += "Exhausted Inbounds:\r\n"
  850. for _, inbound := range exhaustedInbounds {
  851. 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))
  852. if inbound.ExpiryTime == 0 {
  853. output += "Expire date: ♾Unlimited\r\n \r\n"
  854. } else {
  855. output += fmt.Sprintf("Expire date:%s\r\n \r\n", time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05"))
  856. }
  857. }
  858. }
  859. output += fmt.Sprintf("Exhausted Clients count:\r\n🛑 Exhausted: %d\r\n🔜 Deplete soon: %d\r\n \r\n", len(disabledClients), len(exhaustedClients))
  860. if len(exhaustedClients) > 0 {
  861. output += "Exhausted Clients:\r\n"
  862. for _, traffic := range exhaustedClients {
  863. expiryTime := ""
  864. if traffic.ExpiryTime == 0 {
  865. expiryTime = "♾Unlimited"
  866. } else if traffic.ExpiryTime < 0 {
  867. expiryTime += fmt.Sprintf("%d days", traffic.ExpiryTime/-86400000)
  868. } else {
  869. expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
  870. }
  871. total := ""
  872. if traffic.Total == 0 {
  873. total = "♾Unlimited"
  874. } else {
  875. total = common.FormatTraffic((traffic.Total))
  876. }
  877. 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",
  878. traffic.Enable, traffic.Email, common.FormatTraffic(traffic.Up), common.FormatTraffic(traffic.Down), common.FormatTraffic((traffic.Up + traffic.Down)),
  879. total, expiryTime)
  880. }
  881. }
  882. return output
  883. }
  884. func (t *Tgbot) sendBackup(chatId int64) {
  885. sendingTime := time.Now().Format("2006-01-02 15:04:05")
  886. t.SendMsgToTgbot(chatId, "Backup time: "+sendingTime)
  887. file, err := os.Open(config.GetDBPath())
  888. if err != nil {
  889. logger.Warning("Error in opening db file for backup: ", err)
  890. }
  891. document := tu.Document(
  892. tu.ID(chatId),
  893. tu.File(file),
  894. )
  895. _, err = bot.SendDocument(document)
  896. if err != nil {
  897. logger.Warning("Error in uploading backup: ", err)
  898. }
  899. file, err = os.Open(xray.GetConfigPath())
  900. if err != nil {
  901. logger.Warning("Error in opening config.json file for backup: ", err)
  902. }
  903. document = tu.Document(
  904. tu.ID(chatId),
  905. tu.File(file),
  906. )
  907. _, err = bot.SendDocument(document)
  908. if err != nil {
  909. logger.Warning("Error in uploading config.json: ", err)
  910. }
  911. }
  912. func (t *Tgbot) sendCallbackAnswerTgBot(id string, message string) {
  913. params := telego.AnswerCallbackQueryParams{
  914. CallbackQueryID: id,
  915. Text: message,
  916. }
  917. if err := bot.AnswerCallbackQuery(&params); err != nil {
  918. logger.Warning(err)
  919. }
  920. }
  921. func (t *Tgbot) editMessageCallbackTgBot(chatId int64, messageID int, inlineKeyboard *telego.InlineKeyboardMarkup) {
  922. params := telego.EditMessageReplyMarkupParams{
  923. ChatID: tu.ID(chatId),
  924. MessageID: messageID,
  925. ReplyMarkup: inlineKeyboard,
  926. }
  927. if _, err := bot.EditMessageReplyMarkup(&params); err != nil {
  928. logger.Warning(err)
  929. }
  930. }
  931. func (t *Tgbot) editMessageTgBot(chatId int64, messageID int, text string, inlineKeyboard ...*telego.InlineKeyboardMarkup) {
  932. params := telego.EditMessageTextParams{
  933. ChatID: tu.ID(chatId),
  934. MessageID: messageID,
  935. Text: text,
  936. ParseMode: "HTML",
  937. }
  938. if len(inlineKeyboard) > 0 {
  939. params.ReplyMarkup = inlineKeyboard[0]
  940. }
  941. if _, err := bot.EditMessageText(&params); err != nil {
  942. logger.Warning(err)
  943. }
  944. }
  945. func fromChat(u *telego.Update) *telego.Chat {
  946. switch {
  947. case u.Message != nil:
  948. return &u.Message.Chat
  949. case u.EditedMessage != nil:
  950. return &u.EditedMessage.Chat
  951. case u.ChannelPost != nil:
  952. return &u.ChannelPost.Chat
  953. case u.EditedChannelPost != nil:
  954. return &u.EditedChannelPost.Chat
  955. case u.CallbackQuery != nil:
  956. return &u.CallbackQuery.Message.Chat
  957. default:
  958. return nil
  959. }
  960. }