tgbot.go 102 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710
  1. package service
  2. import (
  3. "crypto/rand"
  4. "embed"
  5. "encoding/base64"
  6. "errors"
  7. "fmt"
  8. "math/big"
  9. "net"
  10. "net/url"
  11. "os"
  12. "regexp"
  13. "strconv"
  14. "strings"
  15. "time"
  16. "x-ui/config"
  17. "x-ui/database"
  18. "x-ui/database/model"
  19. "x-ui/logger"
  20. "x-ui/util/common"
  21. "x-ui/web/global"
  22. "x-ui/web/locale"
  23. "x-ui/xray"
  24. "github.com/google/uuid"
  25. "github.com/mymmrac/telego"
  26. th "github.com/mymmrac/telego/telegohandler"
  27. tu "github.com/mymmrac/telego/telegoutil"
  28. "github.com/valyala/fasthttp"
  29. "github.com/valyala/fasthttp/fasthttpproxy"
  30. )
  31. var (
  32. bot *telego.Bot
  33. botHandler *th.BotHandler
  34. adminIds []int64
  35. isRunning bool
  36. hostname string
  37. hashStorage *global.HashStorage
  38. handler *th.Handler
  39. // clients data to adding new client
  40. receiver_inbound_ID int
  41. client_Id string
  42. client_Flow string
  43. client_Email string
  44. client_LimitIP int
  45. client_TotalGB int64
  46. client_ExpiryTime int64
  47. client_Enable bool
  48. client_TgID string
  49. client_SubID string
  50. client_Comment string
  51. client_Reset int
  52. client_Security string
  53. client_ShPassword string
  54. client_TrPassword string
  55. client_Method string
  56. )
  57. var userStates = make(map[int64]string)
  58. type LoginStatus byte
  59. const (
  60. LoginSuccess LoginStatus = 1
  61. LoginFail LoginStatus = 0
  62. EmptyTelegramUserID = int64(0)
  63. )
  64. type Tgbot struct {
  65. inboundService InboundService
  66. settingService SettingService
  67. serverService ServerService
  68. xrayService XrayService
  69. lastStatus *Status
  70. }
  71. func (t *Tgbot) NewTgbot() *Tgbot {
  72. return new(Tgbot)
  73. }
  74. func (t *Tgbot) I18nBot(name string, params ...string) string {
  75. return locale.I18n(locale.Bot, name, params...)
  76. }
  77. func (t *Tgbot) GetHashStorage() *global.HashStorage {
  78. return hashStorage
  79. }
  80. func (t *Tgbot) Start(i18nFS embed.FS) error {
  81. // Initialize localizer
  82. err := locale.InitLocalizer(i18nFS, &t.settingService)
  83. if err != nil {
  84. return err
  85. }
  86. // Initialize hash storage to store callback queries
  87. hashStorage = global.NewHashStorage(20 * time.Minute)
  88. t.SetHostname()
  89. // Get Telegram bot token
  90. tgBotToken, err := t.settingService.GetTgBotToken()
  91. if err != nil || tgBotToken == "" {
  92. logger.Warning("Failed to get Telegram bot token:", err)
  93. return err
  94. }
  95. // Get Telegram bot chat ID(s)
  96. tgBotID, err := t.settingService.GetTgBotChatId()
  97. if err != nil {
  98. logger.Warning("Failed to get Telegram bot chat ID:", err)
  99. return err
  100. }
  101. // Parse admin IDs from comma-separated string
  102. if tgBotID != "" {
  103. for _, adminID := range strings.Split(tgBotID, ",") {
  104. id, err := strconv.Atoi(adminID)
  105. if err != nil {
  106. logger.Warning("Failed to parse admin ID from Telegram bot chat ID:", err)
  107. return err
  108. }
  109. adminIds = append(adminIds, int64(id))
  110. }
  111. }
  112. // Get Telegram bot proxy URL
  113. tgBotProxy, err := t.settingService.GetTgBotProxy()
  114. if err != nil {
  115. logger.Warning("Failed to get Telegram bot proxy URL:", err)
  116. }
  117. // Get Telegram bot API server URL
  118. tgBotAPIServer, err := t.settingService.GetTgBotAPIServer()
  119. if err != nil {
  120. logger.Warning("Failed to get Telegram bot API server URL:", err)
  121. }
  122. // Create new Telegram bot instance
  123. bot, err = t.NewBot(tgBotToken, tgBotProxy, tgBotAPIServer)
  124. if err != nil {
  125. logger.Error("Failed to initialize Telegram bot API:", err)
  126. return err
  127. }
  128. // Start receiving Telegram bot messages
  129. if !isRunning {
  130. logger.Info("Telegram bot receiver started")
  131. go t.OnReceive()
  132. isRunning = true
  133. }
  134. return nil
  135. }
  136. func (t *Tgbot) NewBot(token string, proxyUrl string, apiServerUrl string) (*telego.Bot, error) {
  137. if proxyUrl == "" && apiServerUrl == "" {
  138. return telego.NewBot(token)
  139. }
  140. if proxyUrl != "" {
  141. if !strings.HasPrefix(proxyUrl, "socks5://") {
  142. logger.Warning("Invalid socks5 URL, using default")
  143. return telego.NewBot(token)
  144. }
  145. _, err := url.Parse(proxyUrl)
  146. if err != nil {
  147. logger.Warningf("Can't parse proxy URL, using default instance for tgbot: %v", err)
  148. return telego.NewBot(token)
  149. }
  150. return telego.NewBot(token, telego.WithFastHTTPClient(&fasthttp.Client{
  151. Dial: fasthttpproxy.FasthttpSocksDialer(proxyUrl),
  152. }))
  153. }
  154. if !strings.HasPrefix(apiServerUrl, "http") {
  155. logger.Warning("Invalid http(s) URL, using default")
  156. return telego.NewBot(token)
  157. }
  158. _, err := url.Parse(apiServerUrl)
  159. if err != nil {
  160. logger.Warningf("Can't parse API server URL, using default instance for tgbot: %v", err)
  161. return telego.NewBot(token)
  162. }
  163. return telego.NewBot(token, telego.WithAPIServer(apiServerUrl))
  164. }
  165. func (t *Tgbot) IsRunning() bool {
  166. return isRunning
  167. }
  168. func (t *Tgbot) SetHostname() {
  169. host, err := os.Hostname()
  170. if err != nil {
  171. logger.Error("get hostname error:", err)
  172. hostname = ""
  173. return
  174. }
  175. hostname = host
  176. }
  177. func (t *Tgbot) Stop() {
  178. botHandler.Stop()
  179. bot.StopLongPolling()
  180. logger.Info("Stop Telegram receiver ...")
  181. isRunning = false
  182. adminIds = nil
  183. }
  184. func (t *Tgbot) encodeQuery(query string) string {
  185. // NOTE: we only need to hash for more than 64 chars
  186. if len(query) <= 64 {
  187. return query
  188. }
  189. return hashStorage.SaveHash(query)
  190. }
  191. func (t *Tgbot) decodeQuery(query string) (string, error) {
  192. if !hashStorage.IsMD5(query) {
  193. return query, nil
  194. }
  195. decoded, exists := hashStorage.GetValue(query)
  196. if !exists {
  197. return "", common.NewError("hash not found in storage!")
  198. }
  199. return decoded, nil
  200. }
  201. func (t *Tgbot) OnReceive() {
  202. params := telego.GetUpdatesParams{
  203. Timeout: 10,
  204. }
  205. updates, _ := bot.UpdatesViaLongPolling(&params)
  206. botHandler, _ = th.NewBotHandler(bot, updates)
  207. botHandler.HandleMessage(func(_ *telego.Bot, message telego.Message) {
  208. delete(userStates, message.Chat.ID)
  209. t.SendMsgToTgbot(message.Chat.ID, t.I18nBot("tgbot.keyboardClosed"), tu.ReplyKeyboardRemove())
  210. }, th.TextEqual(t.I18nBot("tgbot.buttons.closeKeyboard")))
  211. botHandler.HandleMessage(func(_ *telego.Bot, message telego.Message) {
  212. delete(userStates, message.Chat.ID)
  213. t.answerCommand(&message, message.Chat.ID, checkAdmin(message.From.ID))
  214. }, th.AnyCommand())
  215. botHandler.HandleCallbackQuery(func(_ *telego.Bot, query telego.CallbackQuery) {
  216. delete(userStates, query.Message.GetChat().ID)
  217. t.answerCallback(&query, checkAdmin(query.From.ID))
  218. }, th.AnyCallbackQueryWithMessage())
  219. botHandler.HandleMessage(func(_ *telego.Bot, message telego.Message) {
  220. if userState, exists := userStates[message.Chat.ID]; exists {
  221. switch userState {
  222. case "awaiting_id":
  223. if client_Id == strings.TrimSpace(message.Text) {
  224. t.SendMsgToTgbotDeleteAfter(message.Chat.ID, t.I18nBot("tgbot.messages.using_default_value"), 3, tu.ReplyKeyboardRemove())
  225. delete(userStates, message.Chat.ID)
  226. inbound, _ := t.inboundService.GetInbound(receiver_inbound_ID)
  227. message_text, _ := t.BuildInboundClientDataMessage(inbound.Remark, inbound.Protocol)
  228. t.addClient(message.Chat.ID, message_text)
  229. return
  230. }
  231. client_Id = strings.TrimSpace(message.Text)
  232. if t.isSingleWord(client_Id) {
  233. userStates[message.Chat.ID] = "awaiting_id"
  234. cancel_btn_markup := tu.InlineKeyboard(
  235. tu.InlineKeyboardRow(
  236. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.use_default")).WithCallbackData("add_client_default_info"),
  237. ),
  238. )
  239. t.SendMsgToTgbot(message.Chat.ID, t.I18nBot("tgbot.messages.incorrect_input"), cancel_btn_markup)
  240. } else {
  241. t.SendMsgToTgbotDeleteAfter(message.Chat.ID, t.I18nBot("tgbot.messages.received_id"), 3, tu.ReplyKeyboardRemove())
  242. delete(userStates, message.Chat.ID)
  243. inbound, _ := t.inboundService.GetInbound(receiver_inbound_ID)
  244. message_text, _ := t.BuildInboundClientDataMessage(inbound.Remark, inbound.Protocol)
  245. t.addClient(message.Chat.ID, message_text)
  246. }
  247. case "awaiting_password_tr":
  248. if client_TrPassword == strings.TrimSpace(message.Text) {
  249. t.SendMsgToTgbotDeleteAfter(message.Chat.ID, t.I18nBot("tgbot.messages.using_default_value"), 3, tu.ReplyKeyboardRemove())
  250. delete(userStates, message.Chat.ID)
  251. return
  252. }
  253. client_TrPassword = strings.TrimSpace(message.Text)
  254. if t.isSingleWord(client_TrPassword) {
  255. userStates[message.Chat.ID] = "awaiting_password_tr"
  256. cancel_btn_markup := tu.InlineKeyboard(
  257. tu.InlineKeyboardRow(
  258. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.use_default")).WithCallbackData("add_client_default_info"),
  259. ),
  260. )
  261. t.SendMsgToTgbot(message.Chat.ID, t.I18nBot("tgbot.messages.incorrect_input"), cancel_btn_markup)
  262. } else {
  263. t.SendMsgToTgbotDeleteAfter(message.Chat.ID, t.I18nBot("tgbot.messages.received_password"), 3, tu.ReplyKeyboardRemove())
  264. delete(userStates, message.Chat.ID)
  265. inbound, _ := t.inboundService.GetInbound(receiver_inbound_ID)
  266. message_text, _ := t.BuildInboundClientDataMessage(inbound.Remark, inbound.Protocol)
  267. t.addClient(message.Chat.ID, message_text)
  268. }
  269. case "awaiting_password_sh":
  270. if client_ShPassword == strings.TrimSpace(message.Text) {
  271. t.SendMsgToTgbotDeleteAfter(message.Chat.ID, t.I18nBot("tgbot.messages.using_default_value"), 3, tu.ReplyKeyboardRemove())
  272. delete(userStates, message.Chat.ID)
  273. return
  274. }
  275. client_ShPassword = strings.TrimSpace(message.Text)
  276. if t.isSingleWord(client_ShPassword) {
  277. userStates[message.Chat.ID] = "awaiting_password_sh"
  278. cancel_btn_markup := tu.InlineKeyboard(
  279. tu.InlineKeyboardRow(
  280. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.use_default")).WithCallbackData("add_client_default_info"),
  281. ),
  282. )
  283. t.SendMsgToTgbot(message.Chat.ID, t.I18nBot("tgbot.messages.incorrect_input"), cancel_btn_markup)
  284. } else {
  285. t.SendMsgToTgbotDeleteAfter(message.Chat.ID, t.I18nBot("tgbot.messages.received_password"), 3, tu.ReplyKeyboardRemove())
  286. delete(userStates, message.Chat.ID)
  287. inbound, _ := t.inboundService.GetInbound(receiver_inbound_ID)
  288. message_text, _ := t.BuildInboundClientDataMessage(inbound.Remark, inbound.Protocol)
  289. t.addClient(message.Chat.ID, message_text)
  290. }
  291. case "awaiting_email":
  292. if client_Email == strings.TrimSpace(message.Text) {
  293. t.SendMsgToTgbotDeleteAfter(message.Chat.ID, t.I18nBot("tgbot.messages.using_default_value"), 3, tu.ReplyKeyboardRemove())
  294. delete(userStates, message.Chat.ID)
  295. return
  296. }
  297. client_Email = strings.TrimSpace(message.Text)
  298. if t.isSingleWord(client_Email) {
  299. userStates[message.Chat.ID] = "awaiting_email"
  300. cancel_btn_markup := tu.InlineKeyboard(
  301. tu.InlineKeyboardRow(
  302. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.use_default")).WithCallbackData("add_client_default_info"),
  303. ),
  304. )
  305. t.SendMsgToTgbot(message.Chat.ID, t.I18nBot("tgbot.messages.incorrect_input"), cancel_btn_markup)
  306. } else {
  307. t.SendMsgToTgbotDeleteAfter(message.Chat.ID, t.I18nBot("tgbot.messages.received_email"), 3, tu.ReplyKeyboardRemove())
  308. delete(userStates, message.Chat.ID)
  309. inbound, _ := t.inboundService.GetInbound(receiver_inbound_ID)
  310. message_text, _ := t.BuildInboundClientDataMessage(inbound.Remark, inbound.Protocol)
  311. t.addClient(message.Chat.ID, message_text)
  312. }
  313. case "awaiting_comment":
  314. if client_Comment == strings.TrimSpace(message.Text) {
  315. t.SendMsgToTgbotDeleteAfter(message.Chat.ID, t.I18nBot("tgbot.messages.using_default_value"), 3, tu.ReplyKeyboardRemove())
  316. delete(userStates, message.Chat.ID)
  317. return
  318. }
  319. client_Comment = strings.TrimSpace(message.Text)
  320. t.SendMsgToTgbotDeleteAfter(message.Chat.ID, t.I18nBot("tgbot.messages.received_comment"), 3, tu.ReplyKeyboardRemove())
  321. delete(userStates, message.Chat.ID)
  322. inbound, _ := t.inboundService.GetInbound(receiver_inbound_ID)
  323. message_text, _ := t.BuildInboundClientDataMessage(inbound.Remark, inbound.Protocol)
  324. t.addClient(message.Chat.ID, message_text)
  325. }
  326. } else {
  327. if message.UsersShared != nil {
  328. if checkAdmin(message.From.ID) {
  329. for _, sharedUser := range message.UsersShared.Users {
  330. userID := sharedUser.UserID
  331. needRestart, err := t.inboundService.SetClientTelegramUserID(message.UsersShared.RequestID, userID)
  332. if needRestart {
  333. t.xrayService.SetToNeedRestart()
  334. }
  335. output := ""
  336. if err != nil {
  337. output += t.I18nBot("tgbot.messages.selectUserFailed")
  338. } else {
  339. output += t.I18nBot("tgbot.messages.userSaved")
  340. }
  341. t.SendMsgToTgbot(message.Chat.ID, output, tu.ReplyKeyboardRemove())
  342. }
  343. } else {
  344. t.SendMsgToTgbot(message.Chat.ID, t.I18nBot("tgbot.noResult"), tu.ReplyKeyboardRemove())
  345. }
  346. }
  347. }
  348. }, th.AnyMessage())
  349. botHandler.Start()
  350. }
  351. func (t *Tgbot) answerCommand(message *telego.Message, chatId int64, isAdmin bool) {
  352. msg, onlyMessage := "", false
  353. command, _, commandArgs := tu.ParseCommand(message.Text)
  354. // Helper function to handle unknown commands.
  355. handleUnknownCommand := func() {
  356. msg += t.I18nBot("tgbot.commands.unknown")
  357. }
  358. // Handle the command.
  359. switch command {
  360. case "help":
  361. msg += t.I18nBot("tgbot.commands.help")
  362. msg += t.I18nBot("tgbot.commands.pleaseChoose")
  363. case "start":
  364. msg += t.I18nBot("tgbot.commands.start", "Firstname=="+message.From.FirstName)
  365. if isAdmin {
  366. msg += t.I18nBot("tgbot.commands.welcome", "Hostname=="+hostname)
  367. }
  368. msg += "\n\n" + t.I18nBot("tgbot.commands.pleaseChoose")
  369. case "status":
  370. onlyMessage = true
  371. msg += t.I18nBot("tgbot.commands.status")
  372. case "id":
  373. onlyMessage = true
  374. msg += t.I18nBot("tgbot.commands.getID", "ID=="+strconv.FormatInt(message.From.ID, 10))
  375. case "usage":
  376. onlyMessage = true
  377. if len(commandArgs) > 0 {
  378. if isAdmin {
  379. t.searchClient(chatId, commandArgs[0])
  380. } else {
  381. t.getClientUsage(chatId, int64(message.From.ID), commandArgs[0])
  382. }
  383. } else {
  384. msg += t.I18nBot("tgbot.commands.usage")
  385. }
  386. case "inbound":
  387. onlyMessage = true
  388. if isAdmin && len(commandArgs) > 0 {
  389. t.searchInbound(chatId, commandArgs[0])
  390. } else {
  391. handleUnknownCommand()
  392. }
  393. case "restart":
  394. onlyMessage = true
  395. if isAdmin {
  396. if len(commandArgs) == 0 {
  397. if t.xrayService.IsXrayRunning() {
  398. err := t.xrayService.RestartXray(true)
  399. if err != nil {
  400. msg += t.I18nBot("tgbot.commands.restartFailed", "Error=="+err.Error())
  401. } else {
  402. msg += t.I18nBot("tgbot.commands.restartSuccess")
  403. }
  404. } else {
  405. msg += t.I18nBot("tgbot.commands.xrayNotRunning")
  406. }
  407. } else {
  408. handleUnknownCommand()
  409. msg += t.I18nBot("tgbot.commands.restartUsage")
  410. }
  411. } else {
  412. handleUnknownCommand()
  413. }
  414. default:
  415. handleUnknownCommand()
  416. }
  417. if msg != "" {
  418. t.sendResponse(chatId, msg, onlyMessage, isAdmin)
  419. }
  420. }
  421. // Helper function to send the message based on onlyMessage flag.
  422. func (t *Tgbot) sendResponse(chatId int64, msg string, onlyMessage, isAdmin bool) {
  423. if onlyMessage {
  424. t.SendMsgToTgbot(chatId, msg)
  425. } else {
  426. t.SendAnswer(chatId, msg, isAdmin)
  427. }
  428. }
  429. func (t *Tgbot) randomLowerAndNum(length int) string {
  430. charset := "abcdefghijklmnopqrstuvwxyz0123456789"
  431. bytes := make([]byte, length)
  432. for i := range bytes {
  433. randomIndex, _ := rand.Int(rand.Reader, big.NewInt(int64(len(charset))))
  434. bytes[i] = charset[randomIndex.Int64()]
  435. }
  436. return string(bytes)
  437. }
  438. func (t *Tgbot) randomShadowSocksPassword() string {
  439. array := make([]byte, 32)
  440. _, err := rand.Read(array)
  441. if err != nil {
  442. return t.randomLowerAndNum(32)
  443. }
  444. return base64.StdEncoding.EncodeToString(array)
  445. }
  446. func (t *Tgbot) answerCallback(callbackQuery *telego.CallbackQuery, isAdmin bool) {
  447. chatId := callbackQuery.Message.GetChat().ID
  448. if isAdmin {
  449. // get query from hash storage
  450. decodedQuery, err := t.decodeQuery(callbackQuery.Data)
  451. if err != nil {
  452. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.noQuery"))
  453. return
  454. }
  455. dataArray := strings.Split(decodedQuery, " ")
  456. if len(dataArray) >= 2 && len(dataArray[1]) > 0 {
  457. email := dataArray[1]
  458. switch dataArray[0] {
  459. case "client_get_usage":
  460. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.messages.email", "Email=="+email))
  461. t.searchClient(chatId, email)
  462. case "client_refresh":
  463. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.clientRefreshSuccess", "Email=="+email))
  464. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  465. case "client_cancel":
  466. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.canceled", "Email=="+email))
  467. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  468. case "ips_refresh":
  469. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.IpRefreshSuccess", "Email=="+email))
  470. t.searchClientIps(chatId, email, callbackQuery.Message.GetMessageID())
  471. case "ips_cancel":
  472. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.canceled", "Email=="+email))
  473. t.searchClientIps(chatId, email, callbackQuery.Message.GetMessageID())
  474. case "tgid_refresh":
  475. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.TGIdRefreshSuccess", "Email=="+email))
  476. t.clientTelegramUserInfo(chatId, email, callbackQuery.Message.GetMessageID())
  477. case "tgid_cancel":
  478. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.canceled", "Email=="+email))
  479. t.clientTelegramUserInfo(chatId, email, callbackQuery.Message.GetMessageID())
  480. case "reset_traffic":
  481. inlineKeyboard := tu.InlineKeyboard(
  482. tu.InlineKeyboardRow(
  483. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancelReset")).WithCallbackData(t.encodeQuery("client_cancel "+email)),
  484. ),
  485. tu.InlineKeyboardRow(
  486. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmResetTraffic")).WithCallbackData(t.encodeQuery("reset_traffic_c "+email)),
  487. ),
  488. )
  489. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  490. case "reset_traffic_c":
  491. err := t.inboundService.ResetClientTrafficByEmail(email)
  492. if err == nil {
  493. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.resetTrafficSuccess", "Email=="+email))
  494. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  495. } else {
  496. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  497. }
  498. case "limit_traffic":
  499. inlineKeyboard := tu.InlineKeyboard(
  500. tu.InlineKeyboardRow(
  501. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("client_cancel "+email)),
  502. ),
  503. tu.InlineKeyboardRow(
  504. tu.InlineKeyboardButton(t.I18nBot("tgbot.unlimited")).WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 0")),
  505. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.custom")).WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" 0")),
  506. ),
  507. tu.InlineKeyboardRow(
  508. tu.InlineKeyboardButton("1 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 1")),
  509. tu.InlineKeyboardButton("5 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 5")),
  510. tu.InlineKeyboardButton("10 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 10")),
  511. ),
  512. tu.InlineKeyboardRow(
  513. tu.InlineKeyboardButton("20 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 20")),
  514. tu.InlineKeyboardButton("30 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 30")),
  515. tu.InlineKeyboardButton("40 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 40")),
  516. ),
  517. tu.InlineKeyboardRow(
  518. tu.InlineKeyboardButton("50 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 50")),
  519. tu.InlineKeyboardButton("60 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 60")),
  520. tu.InlineKeyboardButton("80 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 80")),
  521. ),
  522. tu.InlineKeyboardRow(
  523. tu.InlineKeyboardButton("100 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 100")),
  524. tu.InlineKeyboardButton("150 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 150")),
  525. tu.InlineKeyboardButton("200 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 200")),
  526. ),
  527. )
  528. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  529. case "limit_traffic_c":
  530. if len(dataArray) == 3 {
  531. limitTraffic, err := strconv.Atoi(dataArray[2])
  532. if err == nil {
  533. needRestart, err := t.inboundService.ResetClientTrafficLimitByEmail(email, limitTraffic)
  534. if needRestart {
  535. t.xrayService.SetToNeedRestart()
  536. }
  537. if err == nil {
  538. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.setTrafficLimitSuccess", "Email=="+email))
  539. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  540. return
  541. }
  542. }
  543. }
  544. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  545. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  546. case "limit_traffic_in":
  547. if len(dataArray) >= 3 {
  548. oldInputNumber, err := strconv.Atoi(dataArray[2])
  549. inputNumber := oldInputNumber
  550. if err == nil {
  551. if len(dataArray) == 4 {
  552. num, err := strconv.Atoi(dataArray[3])
  553. if err == nil {
  554. if num == -2 {
  555. inputNumber = 0
  556. } else if num == -1 {
  557. if inputNumber > 0 {
  558. inputNumber = (inputNumber / 10)
  559. }
  560. } else {
  561. inputNumber = (inputNumber * 10) + num
  562. }
  563. }
  564. if inputNumber == oldInputNumber {
  565. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.successfulOperation"))
  566. return
  567. }
  568. if inputNumber >= 999999 {
  569. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  570. return
  571. }
  572. }
  573. inlineKeyboard := tu.InlineKeyboard(
  574. tu.InlineKeyboardRow(
  575. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("client_cancel "+email)),
  576. ),
  577. tu.InlineKeyboardRow(
  578. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmNumberAdd", "Num=="+strconv.Itoa(inputNumber))).WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" "+strconv.Itoa(inputNumber))),
  579. ),
  580. tu.InlineKeyboardRow(
  581. tu.InlineKeyboardButton("1").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 1")),
  582. tu.InlineKeyboardButton("2").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 2")),
  583. tu.InlineKeyboardButton("3").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 3")),
  584. ),
  585. tu.InlineKeyboardRow(
  586. tu.InlineKeyboardButton("4").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 4")),
  587. tu.InlineKeyboardButton("5").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 5")),
  588. tu.InlineKeyboardButton("6").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 6")),
  589. ),
  590. tu.InlineKeyboardRow(
  591. tu.InlineKeyboardButton("7").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 7")),
  592. tu.InlineKeyboardButton("8").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 8")),
  593. tu.InlineKeyboardButton("9").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 9")),
  594. ),
  595. tu.InlineKeyboardRow(
  596. tu.InlineKeyboardButton("🔄").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" -2")),
  597. tu.InlineKeyboardButton("0").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 0")),
  598. tu.InlineKeyboardButton("⬅️").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" -1")),
  599. ),
  600. )
  601. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  602. return
  603. }
  604. }
  605. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  606. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  607. case "add_client_limit_traffic_c":
  608. limitTraffic, _ := strconv.Atoi(dataArray[1])
  609. client_TotalGB = int64(limitTraffic) * 1024 * 1024 * 1024
  610. messageId := callbackQuery.Message.GetMessageID()
  611. inbound, err := t.inboundService.GetInbound(receiver_inbound_ID)
  612. if err != nil {
  613. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  614. return
  615. }
  616. message_text, err := t.BuildInboundClientDataMessage(inbound.Remark, inbound.Protocol)
  617. t.addClient(chatId, message_text, messageId)
  618. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.successfulOperation"))
  619. case "add_client_limit_traffic_in":
  620. if len(dataArray) >= 2 {
  621. oldInputNumber, err := strconv.Atoi(dataArray[1])
  622. inputNumber := oldInputNumber
  623. if err == nil {
  624. if len(dataArray) == 3 {
  625. num, err := strconv.Atoi(dataArray[2])
  626. if err == nil {
  627. if num == -2 {
  628. inputNumber = 0
  629. } else if num == -1 {
  630. if inputNumber > 0 {
  631. inputNumber = (inputNumber / 10)
  632. }
  633. } else {
  634. inputNumber = (inputNumber * 10) + num
  635. }
  636. }
  637. if inputNumber == oldInputNumber {
  638. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.successfulOperation"))
  639. return
  640. }
  641. if inputNumber >= 999999 {
  642. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  643. return
  644. }
  645. }
  646. inlineKeyboard := tu.InlineKeyboard(
  647. tu.InlineKeyboardRow(
  648. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("add_client_default_traffic_exp")),
  649. ),
  650. tu.InlineKeyboardRow(
  651. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmNumberAdd", "Num=="+strconv.Itoa(inputNumber))).WithCallbackData(t.encodeQuery("add_client_limit_traffic_c "+strconv.Itoa(inputNumber))),
  652. ),
  653. tu.InlineKeyboardRow(
  654. tu.InlineKeyboardButton("1").WithCallbackData(t.encodeQuery("add_client_limit_traffic_in "+strconv.Itoa(inputNumber)+" 1")),
  655. tu.InlineKeyboardButton("2").WithCallbackData(t.encodeQuery("add_client_limit_traffic_in "+strconv.Itoa(inputNumber)+" 2")),
  656. tu.InlineKeyboardButton("3").WithCallbackData(t.encodeQuery("add_client_limit_traffic_in "+strconv.Itoa(inputNumber)+" 3")),
  657. ),
  658. tu.InlineKeyboardRow(
  659. tu.InlineKeyboardButton("4").WithCallbackData(t.encodeQuery("add_client_limit_traffic_in "+strconv.Itoa(inputNumber)+" 4")),
  660. tu.InlineKeyboardButton("5").WithCallbackData(t.encodeQuery("add_client_limit_traffic_in "+strconv.Itoa(inputNumber)+" 5")),
  661. tu.InlineKeyboardButton("6").WithCallbackData(t.encodeQuery("add_client_limit_traffic_in "+strconv.Itoa(inputNumber)+" 6")),
  662. ),
  663. tu.InlineKeyboardRow(
  664. tu.InlineKeyboardButton("7").WithCallbackData(t.encodeQuery("add_client_limit_traffic_in "+strconv.Itoa(inputNumber)+" 7")),
  665. tu.InlineKeyboardButton("8").WithCallbackData(t.encodeQuery("add_client_limit_traffic_in "+strconv.Itoa(inputNumber)+" 8")),
  666. tu.InlineKeyboardButton("9").WithCallbackData(t.encodeQuery("add_client_limit_traffic_in "+strconv.Itoa(inputNumber)+" 9")),
  667. ),
  668. tu.InlineKeyboardRow(
  669. tu.InlineKeyboardButton("🔄").WithCallbackData(t.encodeQuery("add_client_limit_traffic_in "+strconv.Itoa(inputNumber)+" -2")),
  670. tu.InlineKeyboardButton("0").WithCallbackData(t.encodeQuery("add_client_limit_traffic_in "+strconv.Itoa(inputNumber)+" 0")),
  671. tu.InlineKeyboardButton("⬅️").WithCallbackData(t.encodeQuery("add_client_limit_traffic_in "+strconv.Itoa(inputNumber)+" -1")),
  672. ),
  673. )
  674. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  675. return
  676. }
  677. }
  678. case "reset_exp":
  679. inlineKeyboard := tu.InlineKeyboard(
  680. tu.InlineKeyboardRow(
  681. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancelReset")).WithCallbackData(t.encodeQuery("client_cancel "+email)),
  682. ),
  683. tu.InlineKeyboardRow(
  684. tu.InlineKeyboardButton(t.I18nBot("tgbot.unlimited")).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" 0")),
  685. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.custom")).WithCallbackData(t.encodeQuery("reset_exp_in "+email+" 0")),
  686. ),
  687. tu.InlineKeyboardRow(
  688. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 7 "+t.I18nBot("tgbot.days")).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" 7")),
  689. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 10 "+t.I18nBot("tgbot.days")).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" 10")),
  690. ),
  691. tu.InlineKeyboardRow(
  692. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 14 "+t.I18nBot("tgbot.days")).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" 14")),
  693. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 20 "+t.I18nBot("tgbot.days")).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" 20")),
  694. ),
  695. tu.InlineKeyboardRow(
  696. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 1 "+t.I18nBot("tgbot.month")).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" 30")),
  697. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 3 "+t.I18nBot("tgbot.months")).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" 90")),
  698. ),
  699. tu.InlineKeyboardRow(
  700. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 6 "+t.I18nBot("tgbot.months")).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" 180")),
  701. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 12 "+t.I18nBot("tgbot.months")).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" 365")),
  702. ),
  703. )
  704. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  705. case "reset_exp_c":
  706. if len(dataArray) == 3 {
  707. days, err := strconv.Atoi(dataArray[2])
  708. if err == nil {
  709. var date int64 = 0
  710. if days > 0 {
  711. traffic, err := t.inboundService.GetClientTrafficByEmail(email)
  712. if err != nil {
  713. logger.Warning(err)
  714. msg := t.I18nBot("tgbot.wentWrong")
  715. t.SendMsgToTgbot(chatId, msg)
  716. return
  717. }
  718. if traffic == nil {
  719. msg := t.I18nBot("tgbot.noResult")
  720. t.SendMsgToTgbot(chatId, msg)
  721. return
  722. }
  723. if traffic.ExpiryTime > 0 {
  724. if traffic.ExpiryTime-time.Now().Unix()*1000 < 0 {
  725. date = -int64(days * 24 * 60 * 60000)
  726. } else {
  727. date = traffic.ExpiryTime + int64(days*24*60*60000)
  728. }
  729. } else {
  730. date = traffic.ExpiryTime - int64(days*24*60*60000)
  731. }
  732. }
  733. needRestart, err := t.inboundService.ResetClientExpiryTimeByEmail(email, date)
  734. if needRestart {
  735. t.xrayService.SetToNeedRestart()
  736. }
  737. if err == nil {
  738. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.expireResetSuccess", "Email=="+email))
  739. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  740. return
  741. }
  742. }
  743. }
  744. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  745. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  746. case "reset_exp_in":
  747. if len(dataArray) >= 3 {
  748. oldInputNumber, err := strconv.Atoi(dataArray[2])
  749. inputNumber := oldInputNumber
  750. if err == nil {
  751. if len(dataArray) == 4 {
  752. num, err := strconv.Atoi(dataArray[3])
  753. if err == nil {
  754. if num == -2 {
  755. inputNumber = 0
  756. } else if num == -1 {
  757. if inputNumber > 0 {
  758. inputNumber = (inputNumber / 10)
  759. }
  760. } else {
  761. inputNumber = (inputNumber * 10) + num
  762. }
  763. }
  764. if inputNumber == oldInputNumber {
  765. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.successfulOperation"))
  766. return
  767. }
  768. if inputNumber >= 999999 {
  769. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  770. return
  771. }
  772. }
  773. inlineKeyboard := tu.InlineKeyboard(
  774. tu.InlineKeyboardRow(
  775. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("client_cancel "+email)),
  776. ),
  777. tu.InlineKeyboardRow(
  778. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmNumber", "Num=="+strconv.Itoa(inputNumber))).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" "+strconv.Itoa(inputNumber))),
  779. ),
  780. tu.InlineKeyboardRow(
  781. tu.InlineKeyboardButton("1").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 1")),
  782. tu.InlineKeyboardButton("2").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 2")),
  783. tu.InlineKeyboardButton("3").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 3")),
  784. ),
  785. tu.InlineKeyboardRow(
  786. tu.InlineKeyboardButton("4").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 4")),
  787. tu.InlineKeyboardButton("5").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 5")),
  788. tu.InlineKeyboardButton("6").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 6")),
  789. ),
  790. tu.InlineKeyboardRow(
  791. tu.InlineKeyboardButton("7").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 7")),
  792. tu.InlineKeyboardButton("8").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 8")),
  793. tu.InlineKeyboardButton("9").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 9")),
  794. ),
  795. tu.InlineKeyboardRow(
  796. tu.InlineKeyboardButton("🔄").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" -2")),
  797. tu.InlineKeyboardButton("0").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 0")),
  798. tu.InlineKeyboardButton("⬅️").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" -1")),
  799. ),
  800. )
  801. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  802. return
  803. }
  804. }
  805. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  806. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  807. case "add_client_reset_exp_c":
  808. client_ExpiryTime = 0
  809. days, _ := strconv.Atoi(dataArray[1])
  810. var date int64 = 0
  811. if client_ExpiryTime > 0 {
  812. if client_ExpiryTime-time.Now().Unix()*1000 < 0 {
  813. date = -int64(days * 24 * 60 * 60000)
  814. } else {
  815. date = client_ExpiryTime + int64(days*24*60*60000)
  816. }
  817. } else {
  818. date = client_ExpiryTime - int64(days*24*60*60000)
  819. }
  820. client_ExpiryTime = date
  821. messageId := callbackQuery.Message.GetMessageID()
  822. inbound, err := t.inboundService.GetInbound(receiver_inbound_ID)
  823. if err != nil {
  824. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  825. return
  826. }
  827. message_text, err := t.BuildInboundClientDataMessage(inbound.Remark, inbound.Protocol)
  828. t.addClient(chatId, message_text, messageId)
  829. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.successfulOperation"))
  830. case "add_client_reset_exp_in":
  831. if len(dataArray) >= 2 {
  832. oldInputNumber, err := strconv.Atoi(dataArray[1])
  833. inputNumber := oldInputNumber
  834. if err == nil {
  835. if len(dataArray) == 3 {
  836. num, err := strconv.Atoi(dataArray[2])
  837. if err == nil {
  838. if num == -2 {
  839. inputNumber = 0
  840. } else if num == -1 {
  841. if inputNumber > 0 {
  842. inputNumber = (inputNumber / 10)
  843. }
  844. } else {
  845. inputNumber = (inputNumber * 10) + num
  846. }
  847. }
  848. if inputNumber == oldInputNumber {
  849. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.successfulOperation"))
  850. return
  851. }
  852. if inputNumber >= 999999 {
  853. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  854. return
  855. }
  856. }
  857. inlineKeyboard := tu.InlineKeyboard(
  858. tu.InlineKeyboardRow(
  859. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("add_client_default_traffic_exp")),
  860. ),
  861. tu.InlineKeyboardRow(
  862. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmNumber", "Num=="+strconv.Itoa(inputNumber))).WithCallbackData(t.encodeQuery("add_client_reset_exp_c "+strconv.Itoa(inputNumber))),
  863. ),
  864. tu.InlineKeyboardRow(
  865. tu.InlineKeyboardButton("1").WithCallbackData(t.encodeQuery("add_client_reset_exp_in "+strconv.Itoa(inputNumber)+" 1")),
  866. tu.InlineKeyboardButton("2").WithCallbackData(t.encodeQuery("add_client_reset_exp_in "+strconv.Itoa(inputNumber)+" 2")),
  867. tu.InlineKeyboardButton("3").WithCallbackData(t.encodeQuery("add_client_reset_exp_in "+strconv.Itoa(inputNumber)+" 3")),
  868. ),
  869. tu.InlineKeyboardRow(
  870. tu.InlineKeyboardButton("4").WithCallbackData(t.encodeQuery("add_client_reset_exp_in "+strconv.Itoa(inputNumber)+" 4")),
  871. tu.InlineKeyboardButton("5").WithCallbackData(t.encodeQuery("add_client_reset_exp_in "+strconv.Itoa(inputNumber)+" 5")),
  872. tu.InlineKeyboardButton("6").WithCallbackData(t.encodeQuery("add_client_reset_exp_in "+strconv.Itoa(inputNumber)+" 6")),
  873. ),
  874. tu.InlineKeyboardRow(
  875. tu.InlineKeyboardButton("7").WithCallbackData(t.encodeQuery("add_client_reset_exp_in "+strconv.Itoa(inputNumber)+" 7")),
  876. tu.InlineKeyboardButton("8").WithCallbackData(t.encodeQuery("add_client_reset_exp_in "+strconv.Itoa(inputNumber)+" 8")),
  877. tu.InlineKeyboardButton("9").WithCallbackData(t.encodeQuery("add_client_reset_exp_in "+strconv.Itoa(inputNumber)+" 9")),
  878. ),
  879. tu.InlineKeyboardRow(
  880. tu.InlineKeyboardButton("🔄").WithCallbackData(t.encodeQuery("add_client_reset_exp_in "+strconv.Itoa(inputNumber)+" -2")),
  881. tu.InlineKeyboardButton("0").WithCallbackData(t.encodeQuery("add_client_reset_exp_in "+strconv.Itoa(inputNumber)+" 0")),
  882. tu.InlineKeyboardButton("⬅️").WithCallbackData(t.encodeQuery("add_client_reset_exp_in "+strconv.Itoa(inputNumber)+" -1")),
  883. ),
  884. )
  885. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  886. return
  887. }
  888. }
  889. case "ip_limit":
  890. inlineKeyboard := tu.InlineKeyboard(
  891. tu.InlineKeyboardRow(
  892. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancelIpLimit")).WithCallbackData(t.encodeQuery("client_cancel "+email)),
  893. ),
  894. tu.InlineKeyboardRow(
  895. tu.InlineKeyboardButton(t.I18nBot("tgbot.unlimited")).WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 0")),
  896. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.custom")).WithCallbackData(t.encodeQuery("ip_limit_in "+email+" 0")),
  897. ),
  898. tu.InlineKeyboardRow(
  899. tu.InlineKeyboardButton("1").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 1")),
  900. tu.InlineKeyboardButton("2").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 2")),
  901. ),
  902. tu.InlineKeyboardRow(
  903. tu.InlineKeyboardButton("3").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 3")),
  904. tu.InlineKeyboardButton("4").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 4")),
  905. ),
  906. tu.InlineKeyboardRow(
  907. tu.InlineKeyboardButton("5").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 5")),
  908. tu.InlineKeyboardButton("6").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 6")),
  909. tu.InlineKeyboardButton("7").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 7")),
  910. ),
  911. tu.InlineKeyboardRow(
  912. tu.InlineKeyboardButton("8").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 8")),
  913. tu.InlineKeyboardButton("9").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 9")),
  914. tu.InlineKeyboardButton("10").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 10")),
  915. ),
  916. )
  917. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  918. case "ip_limit_c":
  919. if len(dataArray) == 3 {
  920. count, err := strconv.Atoi(dataArray[2])
  921. if err == nil {
  922. needRestart, err := t.inboundService.ResetClientIpLimitByEmail(email, count)
  923. if needRestart {
  924. t.xrayService.SetToNeedRestart()
  925. }
  926. if err == nil {
  927. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.resetIpSuccess", "Email=="+email, "Count=="+strconv.Itoa(count)))
  928. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  929. return
  930. }
  931. }
  932. }
  933. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  934. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  935. case "ip_limit_in":
  936. if len(dataArray) >= 3 {
  937. oldInputNumber, err := strconv.Atoi(dataArray[2])
  938. inputNumber := oldInputNumber
  939. if err == nil {
  940. if len(dataArray) == 4 {
  941. num, err := strconv.Atoi(dataArray[3])
  942. if err == nil {
  943. if num == -2 {
  944. inputNumber = 0
  945. } else if num == -1 {
  946. if inputNumber > 0 {
  947. inputNumber = (inputNumber / 10)
  948. }
  949. } else {
  950. inputNumber = (inputNumber * 10) + num
  951. }
  952. }
  953. if inputNumber == oldInputNumber {
  954. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.successfulOperation"))
  955. return
  956. }
  957. if inputNumber >= 999999 {
  958. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  959. return
  960. }
  961. }
  962. inlineKeyboard := tu.InlineKeyboard(
  963. tu.InlineKeyboardRow(
  964. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("client_cancel "+email)),
  965. ),
  966. tu.InlineKeyboardRow(
  967. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmNumber", "Num=="+strconv.Itoa(inputNumber))).WithCallbackData(t.encodeQuery("ip_limit_c "+email+" "+strconv.Itoa(inputNumber))),
  968. ),
  969. tu.InlineKeyboardRow(
  970. tu.InlineKeyboardButton("1").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 1")),
  971. tu.InlineKeyboardButton("2").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 2")),
  972. tu.InlineKeyboardButton("3").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 3")),
  973. ),
  974. tu.InlineKeyboardRow(
  975. tu.InlineKeyboardButton("4").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 4")),
  976. tu.InlineKeyboardButton("5").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 5")),
  977. tu.InlineKeyboardButton("6").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 6")),
  978. ),
  979. tu.InlineKeyboardRow(
  980. tu.InlineKeyboardButton("7").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 7")),
  981. tu.InlineKeyboardButton("8").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 8")),
  982. tu.InlineKeyboardButton("9").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 9")),
  983. ),
  984. tu.InlineKeyboardRow(
  985. tu.InlineKeyboardButton("🔄").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" -2")),
  986. tu.InlineKeyboardButton("0").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 0")),
  987. tu.InlineKeyboardButton("⬅️").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" -1")),
  988. ),
  989. )
  990. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  991. return
  992. }
  993. }
  994. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  995. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  996. case "clear_ips":
  997. inlineKeyboard := tu.InlineKeyboard(
  998. tu.InlineKeyboardRow(
  999. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("ips_cancel "+email)),
  1000. ),
  1001. tu.InlineKeyboardRow(
  1002. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmClearIps")).WithCallbackData(t.encodeQuery("clear_ips_c "+email)),
  1003. ),
  1004. )
  1005. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  1006. case "clear_ips_c":
  1007. err := t.inboundService.ClearClientIps(email)
  1008. if err == nil {
  1009. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.clearIpSuccess", "Email=="+email))
  1010. t.searchClientIps(chatId, email, callbackQuery.Message.GetMessageID())
  1011. } else {
  1012. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  1013. }
  1014. case "ip_log":
  1015. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.getIpLog", "Email=="+email))
  1016. t.searchClientIps(chatId, email)
  1017. case "tg_user":
  1018. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.getUserInfo", "Email=="+email))
  1019. t.clientTelegramUserInfo(chatId, email)
  1020. case "tgid_remove":
  1021. inlineKeyboard := tu.InlineKeyboard(
  1022. tu.InlineKeyboardRow(
  1023. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("tgid_cancel "+email)),
  1024. ),
  1025. tu.InlineKeyboardRow(
  1026. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmRemoveTGUser")).WithCallbackData(t.encodeQuery("tgid_remove_c "+email)),
  1027. ),
  1028. )
  1029. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  1030. case "tgid_remove_c":
  1031. traffic, err := t.inboundService.GetClientTrafficByEmail(email)
  1032. if err != nil || traffic == nil {
  1033. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  1034. return
  1035. }
  1036. needRestart, err := t.inboundService.SetClientTelegramUserID(traffic.Id, EmptyTelegramUserID)
  1037. if needRestart {
  1038. t.xrayService.SetToNeedRestart()
  1039. }
  1040. if err == nil {
  1041. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.removedTGUserSuccess", "Email=="+email))
  1042. t.clientTelegramUserInfo(chatId, email, callbackQuery.Message.GetMessageID())
  1043. } else {
  1044. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  1045. }
  1046. case "toggle_enable":
  1047. inlineKeyboard := tu.InlineKeyboard(
  1048. tu.InlineKeyboardRow(
  1049. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("client_cancel "+email)),
  1050. ),
  1051. tu.InlineKeyboardRow(
  1052. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmToggle")).WithCallbackData(t.encodeQuery("toggle_enable_c "+email)),
  1053. ),
  1054. )
  1055. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  1056. case "toggle_enable_c":
  1057. enabled, needRestart, err := t.inboundService.ToggleClientEnableByEmail(email)
  1058. if needRestart {
  1059. t.xrayService.SetToNeedRestart()
  1060. }
  1061. if err == nil {
  1062. if enabled {
  1063. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.enableSuccess", "Email=="+email))
  1064. } else {
  1065. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.disableSuccess", "Email=="+email))
  1066. }
  1067. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  1068. } else {
  1069. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  1070. }
  1071. case "get_clients":
  1072. inboundId := dataArray[1]
  1073. inboundIdInt, err := strconv.Atoi(inboundId)
  1074. if err != nil {
  1075. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1076. return
  1077. }
  1078. inbound, err := t.inboundService.GetInbound(inboundIdInt)
  1079. if err != nil {
  1080. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1081. return
  1082. }
  1083. clients, err := t.getInboundClients(inboundIdInt)
  1084. if err != nil {
  1085. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1086. return
  1087. }
  1088. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.chooseClient", "Inbound=="+inbound.Remark), clients)
  1089. case "add_client_to":
  1090. // assign default values to clients variables
  1091. client_Id = uuid.New().String()
  1092. client_Flow = ""
  1093. client_Email = t.randomLowerAndNum(8)
  1094. client_LimitIP = 0
  1095. client_TotalGB = 0
  1096. client_ExpiryTime = 0
  1097. client_Enable = true
  1098. client_TgID = ""
  1099. client_SubID = t.randomLowerAndNum(16)
  1100. client_Comment = ""
  1101. client_Reset = 0
  1102. client_Security = "auto"
  1103. client_ShPassword = t.randomShadowSocksPassword()
  1104. client_TrPassword = t.randomLowerAndNum(10)
  1105. client_Method = ""
  1106. inboundId := dataArray[1]
  1107. inboundIdInt, err := strconv.Atoi(inboundId)
  1108. if err != nil {
  1109. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1110. return
  1111. }
  1112. receiver_inbound_ID = inboundIdInt
  1113. inbound, err := t.inboundService.GetInbound(inboundIdInt)
  1114. if err != nil {
  1115. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1116. return
  1117. }
  1118. message_text, err := t.BuildInboundClientDataMessage(inbound.Remark, inbound.Protocol)
  1119. t.addClient(chatId, message_text)
  1120. }
  1121. return
  1122. } else {
  1123. switch callbackQuery.Data {
  1124. case "get_inbounds":
  1125. inbounds, err := t.getInbounds()
  1126. if err != nil {
  1127. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1128. return
  1129. }
  1130. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.allClients"))
  1131. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.chooseInbound"), inbounds)
  1132. }
  1133. }
  1134. }
  1135. switch callbackQuery.Data {
  1136. case "get_usage":
  1137. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.serverUsage"))
  1138. t.getServerUsage(chatId)
  1139. case "usage_refresh":
  1140. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.successfulOperation"))
  1141. t.getServerUsage(chatId, callbackQuery.Message.GetMessageID())
  1142. case "inbounds":
  1143. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.getInbounds"))
  1144. t.SendMsgToTgbot(chatId, t.getInboundUsages())
  1145. case "deplete_soon":
  1146. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.depleteSoon"))
  1147. t.getExhausted(chatId)
  1148. case "get_backup":
  1149. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.dbBackup"))
  1150. t.sendBackup(chatId)
  1151. case "get_banlogs":
  1152. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.getBanLogs"))
  1153. t.sendBanLogs(chatId, true)
  1154. case "client_traffic":
  1155. tgUserID := callbackQuery.From.ID
  1156. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.clientUsage"))
  1157. t.getClientUsage(chatId, tgUserID)
  1158. case "client_commands":
  1159. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.commands"))
  1160. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.commands.helpClientCommands"))
  1161. case "onlines":
  1162. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.onlines"))
  1163. t.onlineClients(chatId)
  1164. case "onlines_refresh":
  1165. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.successfulOperation"))
  1166. t.onlineClients(chatId, callbackQuery.Message.GetMessageID())
  1167. case "commands":
  1168. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.commands"))
  1169. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.commands.helpAdminCommands"))
  1170. case "add_client":
  1171. // assign default values to clients variables
  1172. client_Id = uuid.New().String()
  1173. client_Flow = ""
  1174. client_Email = t.randomLowerAndNum(8)
  1175. client_LimitIP = 0
  1176. client_TotalGB = 0
  1177. client_ExpiryTime = 0
  1178. client_Enable = true
  1179. client_TgID = ""
  1180. client_SubID = t.randomLowerAndNum(16)
  1181. client_Comment = ""
  1182. client_Reset = 0
  1183. client_Security = "auto"
  1184. client_ShPassword = t.randomShadowSocksPassword()
  1185. client_TrPassword = t.randomLowerAndNum(10)
  1186. client_Method = ""
  1187. inbounds, err := t.getInboundsAddClient()
  1188. if err != nil {
  1189. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1190. return
  1191. }
  1192. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.addClient"))
  1193. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.chooseInbound"), inbounds)
  1194. case "add_client_ch_default_email":
  1195. t.deleteMessageTgBot(chatId, callbackQuery.Message.GetMessageID())
  1196. userStates[chatId] = "awaiting_email"
  1197. cancel_btn_markup := tu.InlineKeyboard(
  1198. tu.InlineKeyboardRow(
  1199. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.use_default")).WithCallbackData("add_client_default_info"),
  1200. ),
  1201. )
  1202. prompt_message := t.I18nBot("tgbot.messages.email_prompt", "ClientEmail=="+client_Email)
  1203. t.SendMsgToTgbot(chatId, prompt_message, cancel_btn_markup)
  1204. case "add_client_ch_default_id":
  1205. t.deleteMessageTgBot(chatId, callbackQuery.Message.GetMessageID())
  1206. userStates[chatId] = "awaiting_id"
  1207. cancel_btn_markup := tu.InlineKeyboard(
  1208. tu.InlineKeyboardRow(
  1209. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.use_default")).WithCallbackData("add_client_default_info"),
  1210. ),
  1211. )
  1212. prompt_message := t.I18nBot("tgbot.messages.id_prompt", "ClientId=="+client_Id)
  1213. t.SendMsgToTgbot(chatId, prompt_message, cancel_btn_markup)
  1214. case "add_client_ch_default_pass_tr":
  1215. t.deleteMessageTgBot(chatId, callbackQuery.Message.GetMessageID())
  1216. userStates[chatId] = "awaiting_password_tr"
  1217. cancel_btn_markup := tu.InlineKeyboard(
  1218. tu.InlineKeyboardRow(
  1219. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.use_default")).WithCallbackData("add_client_default_info"),
  1220. ),
  1221. )
  1222. prompt_message := t.I18nBot("tgbot.messages.pass_prompt", "ClientPassword=="+client_TrPassword)
  1223. t.SendMsgToTgbot(chatId, prompt_message, cancel_btn_markup)
  1224. case "add_client_ch_default_pass_sh":
  1225. t.deleteMessageTgBot(chatId, callbackQuery.Message.GetMessageID())
  1226. userStates[chatId] = "awaiting_password_sh"
  1227. cancel_btn_markup := tu.InlineKeyboard(
  1228. tu.InlineKeyboardRow(
  1229. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.use_default")).WithCallbackData("add_client_default_info"),
  1230. ),
  1231. )
  1232. prompt_message := t.I18nBot("tgbot.messages.pass_prompt", "ClientPassword=="+client_ShPassword)
  1233. t.SendMsgToTgbot(chatId, prompt_message, cancel_btn_markup)
  1234. case "add_client_ch_default_comment":
  1235. t.deleteMessageTgBot(chatId, callbackQuery.Message.GetMessageID())
  1236. userStates[chatId] = "awaiting_comment"
  1237. cancel_btn_markup := tu.InlineKeyboard(
  1238. tu.InlineKeyboardRow(
  1239. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.use_default")).WithCallbackData("add_client_default_info"),
  1240. ),
  1241. )
  1242. prompt_message := t.I18nBot("tgbot.messages.comment_prompt", "ClientComment=="+client_Comment)
  1243. t.SendMsgToTgbot(chatId, prompt_message, cancel_btn_markup)
  1244. case "add_client_ch_default_traffic":
  1245. inlineKeyboard := tu.InlineKeyboard(
  1246. tu.InlineKeyboardRow(
  1247. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("add_client_default_traffic_exp")),
  1248. ),
  1249. tu.InlineKeyboardRow(
  1250. tu.InlineKeyboardButton(t.I18nBot("tgbot.unlimited")).WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 0")),
  1251. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.custom")).WithCallbackData(t.encodeQuery("add_client_limit_traffic_in 0")),
  1252. ),
  1253. tu.InlineKeyboardRow(
  1254. tu.InlineKeyboardButton("1 GB").WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 1")),
  1255. tu.InlineKeyboardButton("5 GB").WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 5")),
  1256. tu.InlineKeyboardButton("10 GB").WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 10")),
  1257. ),
  1258. tu.InlineKeyboardRow(
  1259. tu.InlineKeyboardButton("20 GB").WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 20")),
  1260. tu.InlineKeyboardButton("30 GB").WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 30")),
  1261. tu.InlineKeyboardButton("40 GB").WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 40")),
  1262. ),
  1263. tu.InlineKeyboardRow(
  1264. tu.InlineKeyboardButton("50 GB").WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 50")),
  1265. tu.InlineKeyboardButton("60 GB").WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 60")),
  1266. tu.InlineKeyboardButton("80 GB").WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 80")),
  1267. ),
  1268. tu.InlineKeyboardRow(
  1269. tu.InlineKeyboardButton("100 GB").WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 100")),
  1270. tu.InlineKeyboardButton("150 GB").WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 150")),
  1271. tu.InlineKeyboardButton("200 GB").WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 200")),
  1272. ),
  1273. )
  1274. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  1275. case "add_client_ch_default_exp":
  1276. inlineKeyboard := tu.InlineKeyboard(
  1277. tu.InlineKeyboardRow(
  1278. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("add_client_default_traffic_exp")),
  1279. ),
  1280. tu.InlineKeyboardRow(
  1281. tu.InlineKeyboardButton(t.I18nBot("tgbot.unlimited")).WithCallbackData(t.encodeQuery("add_client_reset_exp_c 0")),
  1282. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.custom")).WithCallbackData(t.encodeQuery("add_client_reset_exp_in 0")),
  1283. ),
  1284. tu.InlineKeyboardRow(
  1285. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 7 "+t.I18nBot("tgbot.days")).WithCallbackData(t.encodeQuery("add_client_reset_exp_c 7")),
  1286. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 10 "+t.I18nBot("tgbot.days")).WithCallbackData(t.encodeQuery("add_client_reset_exp_c 10")),
  1287. ),
  1288. tu.InlineKeyboardRow(
  1289. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 14 "+t.I18nBot("tgbot.days")).WithCallbackData(t.encodeQuery("add_client_reset_exp_c 14")),
  1290. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 20 "+t.I18nBot("tgbot.days")).WithCallbackData(t.encodeQuery("add_client_reset_exp_c 20")),
  1291. ),
  1292. tu.InlineKeyboardRow(
  1293. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 1 "+t.I18nBot("tgbot.month")).WithCallbackData(t.encodeQuery("add_client_reset_exp_c 30")),
  1294. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 3 "+t.I18nBot("tgbot.months")).WithCallbackData(t.encodeQuery("add_client_reset_exp_c 90")),
  1295. ),
  1296. tu.InlineKeyboardRow(
  1297. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 6 "+t.I18nBot("tgbot.months")).WithCallbackData(t.encodeQuery("add_client_reset_exp_c 180")),
  1298. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 12 "+t.I18nBot("tgbot.months")).WithCallbackData(t.encodeQuery("add_client_reset_exp_c 365")),
  1299. ),
  1300. )
  1301. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  1302. case "add_client_default_info":
  1303. t.deleteMessageTgBot(chatId, callbackQuery.Message.GetMessageID())
  1304. t.SendMsgToTgbotDeleteAfter(chatId, t.I18nBot("tgbot.messages.using_default_value"), 3, tu.ReplyKeyboardRemove())
  1305. delete(userStates, chatId)
  1306. inbound, _ := t.inboundService.GetInbound(receiver_inbound_ID)
  1307. message_text, _ := t.BuildInboundClientDataMessage(inbound.Remark, inbound.Protocol)
  1308. t.addClient(chatId, message_text)
  1309. case "add_client_cancel":
  1310. delete(userStates, chatId)
  1311. t.deleteMessageTgBot(chatId, callbackQuery.Message.GetMessageID())
  1312. t.SendMsgToTgbotDeleteAfter(chatId, t.I18nBot("tgbot.messages.cancel"), 3, tu.ReplyKeyboardRemove())
  1313. case "add_client_default_traffic_exp":
  1314. messageId := callbackQuery.Message.GetMessageID()
  1315. inbound, err := t.inboundService.GetInbound(receiver_inbound_ID)
  1316. if err != nil {
  1317. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1318. return
  1319. }
  1320. message_text, err := t.BuildInboundClientDataMessage(inbound.Remark, inbound.Protocol)
  1321. t.addClient(chatId, message_text, messageId)
  1322. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.canceled", "Email=="+client_Email))
  1323. case "add_client_submit_disable":
  1324. client_Enable = false
  1325. _, err := t.SubmitAddClient()
  1326. if err != nil {
  1327. errorMessage := fmt.Sprintf("%v", err)
  1328. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.messages.error_add_client", "error=="+errorMessage), tu.ReplyKeyboardRemove())
  1329. } else {
  1330. t.deleteMessageTgBot(chatId, callbackQuery.Message.GetMessageID())
  1331. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.successfulOperation"), tu.ReplyKeyboardRemove())
  1332. }
  1333. case "add_client_submit_enable":
  1334. client_Enable = true
  1335. _, err := t.SubmitAddClient()
  1336. if err != nil {
  1337. errorMessage := fmt.Sprintf("%v", err)
  1338. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.messages.error_add_client", "error=="+errorMessage), tu.ReplyKeyboardRemove())
  1339. } else {
  1340. t.deleteMessageTgBot(chatId, callbackQuery.Message.GetMessageID())
  1341. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.successfulOperation"), tu.ReplyKeyboardRemove())
  1342. }
  1343. }
  1344. }
  1345. func (t *Tgbot) BuildInboundClientDataMessage(inbound_remark string, protocol model.Protocol) (string, error) {
  1346. var message string
  1347. currentTime := time.Now()
  1348. timestampMillis := currentTime.UnixNano() / int64(time.Millisecond)
  1349. expiryTime := ""
  1350. diff := client_ExpiryTime/1000 - timestampMillis
  1351. if client_ExpiryTime == 0 {
  1352. expiryTime = t.I18nBot("tgbot.unlimited")
  1353. } else if diff > 172800 {
  1354. expiryTime = time.Unix((client_ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
  1355. } else if client_ExpiryTime < 0 {
  1356. expiryTime = fmt.Sprintf("%d %s", client_ExpiryTime/-86400000, t.I18nBot("tgbot.days"))
  1357. } else {
  1358. expiryTime = fmt.Sprintf("%d %s", diff/3600, t.I18nBot("tgbot.hours"))
  1359. }
  1360. traffic_value := ""
  1361. if client_TotalGB == 0 {
  1362. traffic_value = "♾️ Unlimited(Reset)"
  1363. } else {
  1364. traffic_value = common.FormatTraffic(client_TotalGB)
  1365. }
  1366. switch protocol {
  1367. case model.VMESS, model.VLESS:
  1368. message = t.I18nBot("tgbot.messages.inbound_client_data_id", "InboundRemark=="+inbound_remark, "ClientId=="+client_Id, "ClientEmail=="+client_Email, "ClientTraffic=="+traffic_value, "ClientExp=="+expiryTime, "ClientComment=="+client_Comment)
  1369. case model.Trojan:
  1370. message = t.I18nBot("tgbot.messages.inbound_client_data_pass", "InboundRemark=="+inbound_remark, "ClientPass=="+client_TrPassword, "ClientEmail=="+client_Email, "ClientTraffic=="+traffic_value, "ClientExp=="+expiryTime, "ClientComment=="+client_Comment)
  1371. case model.Shadowsocks:
  1372. message = t.I18nBot("tgbot.messages.inbound_client_data_pass", "InboundRemark=="+inbound_remark, "ClientPass=="+client_ShPassword, "ClientEmail=="+client_Email, "ClientTraffic=="+traffic_value, "ClientExp=="+expiryTime, "ClientComment=="+client_Comment)
  1373. default:
  1374. return "", errors.New("unknown protocol")
  1375. }
  1376. return message, nil
  1377. }
  1378. func (t *Tgbot) BuildJSONForProtocol(protocol model.Protocol) (string, error) {
  1379. var jsonString string
  1380. switch protocol {
  1381. case model.VMESS:
  1382. jsonString = fmt.Sprintf(`{
  1383. "clients": [{
  1384. "id": "%s",
  1385. "security": "%s",
  1386. "email": "%s",
  1387. "limitIp": %d,
  1388. "totalGB": %d,
  1389. "expiryTime": %d,
  1390. "enable": %t,
  1391. "tgId": "%s",
  1392. "subId": "%s",
  1393. "comment": "%s",
  1394. "reset": %d
  1395. }]
  1396. }`, client_Id, client_Security, client_Email, client_LimitIP, client_TotalGB, client_ExpiryTime, client_Enable, client_TgID, client_SubID, client_Comment, client_Reset)
  1397. case model.VLESS:
  1398. jsonString = fmt.Sprintf(`{
  1399. "clients": [{
  1400. "id": "%s",
  1401. "flow": "%s",
  1402. "email": "%s",
  1403. "limitIp": %d,
  1404. "totalGB": %d,
  1405. "expiryTime": %d,
  1406. "enable": %t,
  1407. "tgId": "%s",
  1408. "subId": "%s",
  1409. "comment": "%s",
  1410. "reset": %d
  1411. }]
  1412. }`, client_Id, client_Flow, client_Email, client_LimitIP, client_TotalGB, client_ExpiryTime, client_Enable, client_TgID, client_SubID, client_Comment, client_Reset)
  1413. case model.Trojan:
  1414. jsonString = fmt.Sprintf(`{
  1415. "clients": [{
  1416. "password": "%s",
  1417. "email": "%s",
  1418. "limitIp": %d,
  1419. "totalGB": %d,
  1420. "expiryTime": %d,
  1421. "enable": %t,
  1422. "tgId": "%s",
  1423. "subId": "%s",
  1424. "comment": "%s",
  1425. "reset": %d
  1426. }]
  1427. }`, client_TrPassword, client_Email, client_LimitIP, client_TotalGB, client_ExpiryTime, client_Enable, client_TgID, client_SubID, client_Comment, client_Reset)
  1428. case model.Shadowsocks:
  1429. jsonString = fmt.Sprintf(`{
  1430. "clients": [{
  1431. "method": "%s",
  1432. "password": "%s",
  1433. "email": "%s",
  1434. "limitIp": %d,
  1435. "totalGB": %d,
  1436. "expiryTime": %d,
  1437. "enable": %t,
  1438. "tgId": "%s",
  1439. "subId": "%s",
  1440. "comment": "%s",
  1441. "reset": %d
  1442. }]
  1443. }`, client_Method, client_ShPassword, client_Email, client_LimitIP, client_TotalGB, client_ExpiryTime, client_Enable, client_TgID, client_SubID, client_Comment, client_Reset)
  1444. default:
  1445. return "", errors.New("unknown protocol")
  1446. }
  1447. return jsonString, nil
  1448. }
  1449. func (t *Tgbot) SubmitAddClient() (bool, error) {
  1450. inbound, err := t.inboundService.GetInbound(receiver_inbound_ID)
  1451. if err != nil {
  1452. logger.Warning("getIboundClients run failed:", err)
  1453. return false, errors.New(t.I18nBot("tgbot.answers.getInboundsFailed"))
  1454. }
  1455. jsonString, err := t.BuildJSONForProtocol(inbound.Protocol)
  1456. newInbound := &model.Inbound{
  1457. Id: receiver_inbound_ID,
  1458. Settings: jsonString,
  1459. }
  1460. return t.inboundService.AddInboundClient(newInbound)
  1461. }
  1462. func checkAdmin(tgId int64) bool {
  1463. for _, adminId := range adminIds {
  1464. if adminId == tgId {
  1465. return true
  1466. }
  1467. }
  1468. return false
  1469. }
  1470. func (t *Tgbot) SendAnswer(chatId int64, msg string, isAdmin bool) {
  1471. numericKeyboard := tu.InlineKeyboard(
  1472. tu.InlineKeyboardRow(
  1473. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.serverUsage")).WithCallbackData(t.encodeQuery("get_usage")),
  1474. ),
  1475. tu.InlineKeyboardRow(
  1476. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.dbBackup")).WithCallbackData(t.encodeQuery("get_backup")),
  1477. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.getBanLogs")).WithCallbackData(t.encodeQuery("get_banlogs")),
  1478. ),
  1479. tu.InlineKeyboardRow(
  1480. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.getInbounds")).WithCallbackData(t.encodeQuery("inbounds")),
  1481. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.depleteSoon")).WithCallbackData(t.encodeQuery("deplete_soon")),
  1482. ),
  1483. tu.InlineKeyboardRow(
  1484. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.commands")).WithCallbackData(t.encodeQuery("commands")),
  1485. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.onlines")).WithCallbackData(t.encodeQuery("onlines")),
  1486. ),
  1487. tu.InlineKeyboardRow(
  1488. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.allClients")).WithCallbackData(t.encodeQuery("get_inbounds")),
  1489. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.addClient")).WithCallbackData(t.encodeQuery("add_client")),
  1490. ),
  1491. // TODOOOOOOOOOOOOOO: Add restart button here.
  1492. )
  1493. numericKeyboardClient := tu.InlineKeyboard(
  1494. tu.InlineKeyboardRow(
  1495. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.clientUsage")).WithCallbackData(t.encodeQuery("client_traffic")),
  1496. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.commands")).WithCallbackData(t.encodeQuery("client_commands")),
  1497. ),
  1498. )
  1499. var ReplyMarkup telego.ReplyMarkup
  1500. if isAdmin {
  1501. ReplyMarkup = numericKeyboard
  1502. } else {
  1503. ReplyMarkup = numericKeyboardClient
  1504. }
  1505. t.SendMsgToTgbot(chatId, msg, ReplyMarkup)
  1506. }
  1507. func (t *Tgbot) SendMsgToTgbot(chatId int64, msg string, replyMarkup ...telego.ReplyMarkup) {
  1508. if !isRunning {
  1509. return
  1510. }
  1511. if msg == "" {
  1512. logger.Info("[tgbot] message is empty!")
  1513. return
  1514. }
  1515. var allMessages []string
  1516. limit := 2000
  1517. // paging message if it is big
  1518. if len(msg) > limit {
  1519. messages := strings.Split(msg, "\r\n\r\n")
  1520. lastIndex := -1
  1521. for _, message := range messages {
  1522. if (len(allMessages) == 0) || (len(allMessages[lastIndex])+len(message) > limit) {
  1523. allMessages = append(allMessages, message)
  1524. lastIndex++
  1525. } else {
  1526. allMessages[lastIndex] += "\r\n\r\n" + message
  1527. }
  1528. }
  1529. if strings.TrimSpace(allMessages[len(allMessages)-1]) == "" {
  1530. allMessages = allMessages[:len(allMessages)-1]
  1531. }
  1532. } else {
  1533. allMessages = append(allMessages, msg)
  1534. }
  1535. for n, message := range allMessages {
  1536. params := telego.SendMessageParams{
  1537. ChatID: tu.ID(chatId),
  1538. Text: message,
  1539. ParseMode: "HTML",
  1540. }
  1541. // only add replyMarkup to last message
  1542. if len(replyMarkup) > 0 && n == (len(allMessages)-1) {
  1543. params.ReplyMarkup = replyMarkup[0]
  1544. }
  1545. _, err := bot.SendMessage(&params)
  1546. if err != nil {
  1547. logger.Warning("Error sending telegram message :", err)
  1548. }
  1549. time.Sleep(500 * time.Millisecond)
  1550. }
  1551. }
  1552. func (t *Tgbot) SendMsgToTgbotAdmins(msg string, replyMarkup ...telego.ReplyMarkup) {
  1553. if len(replyMarkup) > 0 {
  1554. for _, adminId := range adminIds {
  1555. t.SendMsgToTgbot(adminId, msg, replyMarkup[0])
  1556. }
  1557. } else {
  1558. for _, adminId := range adminIds {
  1559. t.SendMsgToTgbot(adminId, msg)
  1560. }
  1561. }
  1562. }
  1563. func (t *Tgbot) SendReport() {
  1564. runTime, err := t.settingService.GetTgbotRuntime()
  1565. if err == nil && len(runTime) > 0 {
  1566. msg := ""
  1567. msg += t.I18nBot("tgbot.messages.report", "RunTime=="+runTime)
  1568. msg += t.I18nBot("tgbot.messages.datetime", "DateTime=="+time.Now().Format("2006-01-02 15:04:05"))
  1569. t.SendMsgToTgbotAdmins(msg)
  1570. }
  1571. info := t.sendServerUsage()
  1572. t.SendMsgToTgbotAdmins(info)
  1573. t.sendExhaustedToAdmins()
  1574. t.notifyExhausted()
  1575. backupEnable, err := t.settingService.GetTgBotBackup()
  1576. if err == nil && backupEnable {
  1577. t.SendBackupToAdmins()
  1578. }
  1579. }
  1580. func (t *Tgbot) SendBackupToAdmins() {
  1581. if !t.IsRunning() {
  1582. return
  1583. }
  1584. for _, adminId := range adminIds {
  1585. t.sendBackup(int64(adminId))
  1586. }
  1587. }
  1588. func (t *Tgbot) sendExhaustedToAdmins() {
  1589. if !t.IsRunning() {
  1590. return
  1591. }
  1592. for _, adminId := range adminIds {
  1593. t.getExhausted(int64(adminId))
  1594. }
  1595. }
  1596. func (t *Tgbot) getServerUsage(chatId int64, messageID ...int) string {
  1597. info := t.prepareServerUsageInfo()
  1598. keyboard := tu.InlineKeyboard(tu.InlineKeyboardRow(
  1599. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.refresh")).WithCallbackData(t.encodeQuery("usage_refresh"))))
  1600. if len(messageID) > 0 {
  1601. t.editMessageTgBot(chatId, messageID[0], info, keyboard)
  1602. } else {
  1603. t.SendMsgToTgbot(chatId, info, keyboard)
  1604. }
  1605. return info
  1606. }
  1607. // Send server usage without an inline keyboard
  1608. func (t *Tgbot) sendServerUsage() string {
  1609. info := t.prepareServerUsageInfo()
  1610. return info
  1611. }
  1612. func (t *Tgbot) prepareServerUsageInfo() string {
  1613. info, ipv4, ipv6 := "", "", ""
  1614. // get latest status of server
  1615. t.lastStatus = t.serverService.GetStatus(t.lastStatus)
  1616. onlines := p.GetOnlineClients()
  1617. info += t.I18nBot("tgbot.messages.hostname", "Hostname=="+hostname)
  1618. info += t.I18nBot("tgbot.messages.version", "Version=="+config.GetVersion())
  1619. info += t.I18nBot("tgbot.messages.xrayVersion", "XrayVersion=="+fmt.Sprint(t.lastStatus.Xray.Version))
  1620. // get ip address
  1621. netInterfaces, err := net.Interfaces()
  1622. if err != nil {
  1623. logger.Error("net.Interfaces failed, err: ", err.Error())
  1624. info += t.I18nBot("tgbot.messages.ip", "IP=="+t.I18nBot("tgbot.unknown"))
  1625. info += "\r\n"
  1626. } else {
  1627. for i := 0; i < len(netInterfaces); i++ {
  1628. if (netInterfaces[i].Flags & net.FlagUp) != 0 {
  1629. addrs, _ := netInterfaces[i].Addrs()
  1630. for _, address := range addrs {
  1631. if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
  1632. if ipnet.IP.To4() != nil {
  1633. ipv4 += ipnet.IP.String() + " "
  1634. } else if ipnet.IP.To16() != nil && !ipnet.IP.IsLinkLocalUnicast() {
  1635. ipv6 += ipnet.IP.String() + " "
  1636. }
  1637. }
  1638. }
  1639. }
  1640. }
  1641. info += t.I18nBot("tgbot.messages.ipv4", "IPv4=="+ipv4)
  1642. info += t.I18nBot("tgbot.messages.ipv6", "IPv6=="+ipv6)
  1643. }
  1644. info += t.I18nBot("tgbot.messages.serverUpTime", "UpTime=="+strconv.FormatUint(t.lastStatus.Uptime/86400, 10), "Unit=="+t.I18nBot("tgbot.days"))
  1645. info += t.I18nBot("tgbot.messages.serverLoad", "Load1=="+strconv.FormatFloat(t.lastStatus.Loads[0], 'f', 2, 64), "Load2=="+strconv.FormatFloat(t.lastStatus.Loads[1], 'f', 2, 64), "Load3=="+strconv.FormatFloat(t.lastStatus.Loads[2], 'f', 2, 64))
  1646. info += t.I18nBot("tgbot.messages.serverMemory", "Current=="+common.FormatTraffic(int64(t.lastStatus.Mem.Current)), "Total=="+common.FormatTraffic(int64(t.lastStatus.Mem.Total)))
  1647. info += t.I18nBot("tgbot.messages.onlinesCount", "Count=="+fmt.Sprint(len(onlines)))
  1648. info += t.I18nBot("tgbot.messages.tcpCount", "Count=="+strconv.Itoa(t.lastStatus.TcpCount))
  1649. info += t.I18nBot("tgbot.messages.udpCount", "Count=="+strconv.Itoa(t.lastStatus.UdpCount))
  1650. info += t.I18nBot("tgbot.messages.traffic", "Total=="+common.FormatTraffic(int64(t.lastStatus.NetTraffic.Sent+t.lastStatus.NetTraffic.Recv)), "Upload=="+common.FormatTraffic(int64(t.lastStatus.NetTraffic.Sent)), "Download=="+common.FormatTraffic(int64(t.lastStatus.NetTraffic.Recv)))
  1651. info += t.I18nBot("tgbot.messages.xrayStatus", "State=="+fmt.Sprint(t.lastStatus.Xray.State))
  1652. return info
  1653. }
  1654. func (t *Tgbot) UserLoginNotify(username string, password string, ip string, time string, status LoginStatus) {
  1655. if !t.IsRunning() {
  1656. return
  1657. }
  1658. if username == "" || ip == "" || time == "" {
  1659. logger.Warning("UserLoginNotify failed, invalid info!")
  1660. return
  1661. }
  1662. loginNotifyEnabled, err := t.settingService.GetTgBotLoginNotify()
  1663. if err != nil || !loginNotifyEnabled {
  1664. return
  1665. }
  1666. msg := ""
  1667. if status == LoginSuccess {
  1668. msg += t.I18nBot("tgbot.messages.loginSuccess")
  1669. msg += t.I18nBot("tgbot.messages.hostname", "Hostname=="+hostname)
  1670. } else if status == LoginFail {
  1671. msg += t.I18nBot("tgbot.messages.loginFailed")
  1672. msg += t.I18nBot("tgbot.messages.hostname", "Hostname=="+hostname)
  1673. msg += t.I18nBot("tgbot.messages.password", "Password=="+password)
  1674. }
  1675. msg += t.I18nBot("tgbot.messages.username", "Username=="+username)
  1676. msg += t.I18nBot("tgbot.messages.ip", "IP=="+ip)
  1677. msg += t.I18nBot("tgbot.messages.time", "Time=="+time)
  1678. t.SendMsgToTgbotAdmins(msg)
  1679. }
  1680. func (t *Tgbot) getInboundUsages() string {
  1681. info := ""
  1682. // get traffic
  1683. inbounds, err := t.inboundService.GetAllInbounds()
  1684. if err != nil {
  1685. logger.Warning("GetAllInbounds run failed:", err)
  1686. info += t.I18nBot("tgbot.answers.getInboundsFailed")
  1687. } else {
  1688. // NOTE:If there no any sessions here,need to notify here
  1689. // TODO:Sub-node push, automatic conversion format
  1690. for _, inbound := range inbounds {
  1691. info += t.I18nBot("tgbot.messages.inbound", "Remark=="+inbound.Remark)
  1692. info += t.I18nBot("tgbot.messages.port", "Port=="+strconv.Itoa(inbound.Port))
  1693. info += t.I18nBot("tgbot.messages.traffic", "Total=="+common.FormatTraffic((inbound.Up+inbound.Down)), "Upload=="+common.FormatTraffic(inbound.Up), "Download=="+common.FormatTraffic(inbound.Down))
  1694. if inbound.ExpiryTime == 0 {
  1695. info += t.I18nBot("tgbot.messages.expire", "Time=="+t.I18nBot("tgbot.unlimited"))
  1696. } else {
  1697. info += t.I18nBot("tgbot.messages.expire", "Time=="+time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05"))
  1698. }
  1699. info += "\r\n"
  1700. }
  1701. }
  1702. return info
  1703. }
  1704. func (t *Tgbot) getInbounds() (*telego.InlineKeyboardMarkup, error) {
  1705. inbounds, err := t.inboundService.GetAllInbounds()
  1706. if err != nil {
  1707. logger.Warning("GetAllInbounds run failed:", err)
  1708. return nil, errors.New(t.I18nBot("tgbot.answers.getInboundsFailed"))
  1709. }
  1710. if len(inbounds) == 0 {
  1711. logger.Warning("No inbounds found")
  1712. return nil, errors.New(t.I18nBot("tgbot.answers.getInboundsFailed"))
  1713. }
  1714. var buttons []telego.InlineKeyboardButton
  1715. for _, inbound := range inbounds {
  1716. status := "❌"
  1717. if inbound.Enable {
  1718. status = "✅"
  1719. }
  1720. callbackData := t.encodeQuery(fmt.Sprintf("%s %d", "get_clients", inbound.Id))
  1721. buttons = append(buttons, tu.InlineKeyboardButton(fmt.Sprintf("%v - %v", inbound.Remark, status)).WithCallbackData(callbackData))
  1722. }
  1723. cols := 1
  1724. if len(buttons) >= 6 {
  1725. cols = 2
  1726. }
  1727. keyboard := tu.InlineKeyboardGrid(tu.InlineKeyboardCols(cols, buttons...))
  1728. return keyboard, nil
  1729. }
  1730. func (t *Tgbot) getInboundsAddClient() (*telego.InlineKeyboardMarkup, error) {
  1731. inbounds, err := t.inboundService.GetAllInbounds()
  1732. if err != nil {
  1733. logger.Warning("GetAllInbounds run failed:", err)
  1734. return nil, errors.New(t.I18nBot("tgbot.answers.getInboundsFailed"))
  1735. }
  1736. if len(inbounds) == 0 {
  1737. logger.Warning("No inbounds found")
  1738. return nil, errors.New(t.I18nBot("tgbot.answers.getInboundsFailed"))
  1739. }
  1740. excludedProtocols := map[model.Protocol]bool{
  1741. model.DOKODEMO: true,
  1742. model.Socks: true,
  1743. model.WireGuard: true,
  1744. model.HTTP: true,
  1745. }
  1746. var buttons []telego.InlineKeyboardButton
  1747. for _, inbound := range inbounds {
  1748. if excludedProtocols[inbound.Protocol] {
  1749. continue
  1750. }
  1751. status := "❌"
  1752. if inbound.Enable {
  1753. status = "✅"
  1754. }
  1755. callbackData := t.encodeQuery(fmt.Sprintf("%s %d", "add_client_to", inbound.Id))
  1756. buttons = append(buttons, tu.InlineKeyboardButton(fmt.Sprintf("%v - %v", inbound.Remark, status)).WithCallbackData(callbackData))
  1757. }
  1758. cols := 1
  1759. if len(buttons) >= 6 {
  1760. cols = 2
  1761. }
  1762. keyboard := tu.InlineKeyboardGrid(tu.InlineKeyboardCols(cols, buttons...))
  1763. return keyboard, nil
  1764. }
  1765. func (t *Tgbot) getInboundClients(id int) (*telego.InlineKeyboardMarkup, error) {
  1766. inbound, err := t.inboundService.GetInbound(id)
  1767. if err != nil {
  1768. logger.Warning("getIboundClients run failed:", err)
  1769. return nil, errors.New(t.I18nBot("tgbot.answers.getInboundsFailed"))
  1770. }
  1771. clients, err := t.inboundService.GetClients(inbound)
  1772. var buttons []telego.InlineKeyboardButton
  1773. if err != nil {
  1774. logger.Warning("GetInboundClients run failed:", err)
  1775. return nil, errors.New(t.I18nBot("tgbot.answers.getInboundsFailed"))
  1776. } else {
  1777. if len(clients) > 0 {
  1778. for _, client := range clients {
  1779. buttons = append(buttons, tu.InlineKeyboardButton(client.Email).WithCallbackData(t.encodeQuery("client_get_usage "+client.Email)))
  1780. }
  1781. } else {
  1782. return nil, errors.New(t.I18nBot("tgbot.answers.getClientsFailed"))
  1783. }
  1784. }
  1785. cols := 0
  1786. if len(buttons) < 6 {
  1787. cols = 3
  1788. } else {
  1789. cols = 2
  1790. }
  1791. keyboard := tu.InlineKeyboardGrid(tu.InlineKeyboardCols(cols, buttons...))
  1792. return keyboard, nil
  1793. }
  1794. func (t *Tgbot) clientInfoMsg(
  1795. traffic *xray.ClientTraffic,
  1796. printEnabled bool,
  1797. printOnline bool,
  1798. printActive bool,
  1799. printDate bool,
  1800. printTraffic bool,
  1801. printRefreshed bool,
  1802. ) string {
  1803. now := time.Now().Unix()
  1804. expiryTime := ""
  1805. flag := false
  1806. diff := traffic.ExpiryTime/1000 - now
  1807. if traffic.ExpiryTime == 0 {
  1808. expiryTime = t.I18nBot("tgbot.unlimited")
  1809. } else if diff > 172800 || !traffic.Enable {
  1810. expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
  1811. } else if traffic.ExpiryTime < 0 {
  1812. expiryTime = fmt.Sprintf("%d %s", traffic.ExpiryTime/-86400000, t.I18nBot("tgbot.days"))
  1813. flag = true
  1814. } else {
  1815. expiryTime = fmt.Sprintf("%d %s", diff/3600, t.I18nBot("tgbot.hours"))
  1816. flag = true
  1817. }
  1818. total := ""
  1819. if traffic.Total == 0 {
  1820. total = t.I18nBot("tgbot.unlimited")
  1821. } else {
  1822. total = common.FormatTraffic((traffic.Total))
  1823. }
  1824. enabled := ""
  1825. isEnabled, err := t.inboundService.checkIsEnabledByEmail(traffic.Email)
  1826. if err != nil {
  1827. logger.Warning(err)
  1828. enabled = t.I18nBot("tgbot.wentWrong")
  1829. } else if isEnabled {
  1830. enabled = t.I18nBot("tgbot.messages.yes")
  1831. } else {
  1832. enabled = t.I18nBot("tgbot.messages.no")
  1833. }
  1834. active := ""
  1835. if traffic.Enable {
  1836. active = t.I18nBot("tgbot.messages.yes")
  1837. } else {
  1838. active = t.I18nBot("tgbot.messages.no")
  1839. }
  1840. status := t.I18nBot("tgbot.offline")
  1841. if p.IsRunning() {
  1842. for _, online := range p.GetOnlineClients() {
  1843. if online == traffic.Email {
  1844. status = t.I18nBot("tgbot.online")
  1845. break
  1846. }
  1847. }
  1848. }
  1849. output := ""
  1850. output += t.I18nBot("tgbot.messages.email", "Email=="+traffic.Email)
  1851. if printEnabled {
  1852. output += t.I18nBot("tgbot.messages.enabled", "Enable=="+enabled)
  1853. }
  1854. if printOnline {
  1855. output += t.I18nBot("tgbot.messages.online", "Status=="+status)
  1856. }
  1857. if printActive {
  1858. output += t.I18nBot("tgbot.messages.active", "Enable=="+active)
  1859. }
  1860. if printDate {
  1861. if flag {
  1862. output += t.I18nBot("tgbot.messages.expireIn", "Time=="+expiryTime)
  1863. } else {
  1864. output += t.I18nBot("tgbot.messages.expire", "Time=="+expiryTime)
  1865. }
  1866. }
  1867. if printTraffic {
  1868. output += t.I18nBot("tgbot.messages.upload", "Upload=="+common.FormatTraffic(traffic.Up))
  1869. output += t.I18nBot("tgbot.messages.download", "Download=="+common.FormatTraffic(traffic.Down))
  1870. output += t.I18nBot("tgbot.messages.total", "UpDown=="+common.FormatTraffic((traffic.Up+traffic.Down)), "Total=="+total)
  1871. }
  1872. if printRefreshed {
  1873. output += t.I18nBot("tgbot.messages.refreshedOn", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
  1874. }
  1875. return output
  1876. }
  1877. func (t *Tgbot) getClientUsage(chatId int64, tgUserID int64, email ...string) {
  1878. traffics, err := t.inboundService.GetClientTrafficTgBot(tgUserID)
  1879. if err != nil {
  1880. logger.Warning(err)
  1881. msg := t.I18nBot("tgbot.wentWrong")
  1882. t.SendMsgToTgbot(chatId, msg)
  1883. return
  1884. }
  1885. if len(traffics) == 0 {
  1886. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.askToAddUserId", "TgUserID=="+strconv.FormatInt(tgUserID, 10)))
  1887. return
  1888. }
  1889. output := ""
  1890. if len(traffics) > 0 {
  1891. if len(email) > 0 {
  1892. for _, traffic := range traffics {
  1893. if traffic.Email == email[0] {
  1894. output := t.clientInfoMsg(traffic, true, true, true, true, true, true)
  1895. t.SendMsgToTgbot(chatId, output)
  1896. return
  1897. }
  1898. }
  1899. msg := t.I18nBot("tgbot.noResult")
  1900. t.SendMsgToTgbot(chatId, msg)
  1901. return
  1902. } else {
  1903. for _, traffic := range traffics {
  1904. output += t.clientInfoMsg(traffic, true, true, true, true, true, false)
  1905. output += "\r\n"
  1906. }
  1907. }
  1908. }
  1909. output += t.I18nBot("tgbot.messages.refreshedOn", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
  1910. t.SendMsgToTgbot(chatId, output)
  1911. output = t.I18nBot("tgbot.commands.pleaseChoose")
  1912. t.SendAnswer(chatId, output, false)
  1913. }
  1914. func (t *Tgbot) searchClientIps(chatId int64, email string, messageID ...int) {
  1915. ips, err := t.inboundService.GetInboundClientIps(email)
  1916. if err != nil || len(ips) == 0 {
  1917. ips = t.I18nBot("tgbot.noIpRecord")
  1918. }
  1919. output := ""
  1920. output += t.I18nBot("tgbot.messages.email", "Email=="+email)
  1921. output += t.I18nBot("tgbot.messages.ips", "IPs=="+ips)
  1922. output += t.I18nBot("tgbot.messages.refreshedOn", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
  1923. inlineKeyboard := tu.InlineKeyboard(
  1924. tu.InlineKeyboardRow(
  1925. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.refresh")).WithCallbackData(t.encodeQuery("ips_refresh "+email)),
  1926. ),
  1927. tu.InlineKeyboardRow(
  1928. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.clearIPs")).WithCallbackData(t.encodeQuery("clear_ips "+email)),
  1929. ),
  1930. )
  1931. if len(messageID) > 0 {
  1932. t.editMessageTgBot(chatId, messageID[0], output, inlineKeyboard)
  1933. } else {
  1934. t.SendMsgToTgbot(chatId, output, inlineKeyboard)
  1935. }
  1936. }
  1937. func (t *Tgbot) clientTelegramUserInfo(chatId int64, email string, messageID ...int) {
  1938. traffic, client, err := t.inboundService.GetClientByEmail(email)
  1939. if err != nil {
  1940. logger.Warning(err)
  1941. msg := t.I18nBot("tgbot.wentWrong")
  1942. t.SendMsgToTgbot(chatId, msg)
  1943. return
  1944. }
  1945. if client == nil {
  1946. msg := t.I18nBot("tgbot.noResult")
  1947. t.SendMsgToTgbot(chatId, msg)
  1948. return
  1949. }
  1950. tgId := "None"
  1951. if client.TgID != 0 {
  1952. tgId = strconv.FormatInt(client.TgID, 10)
  1953. }
  1954. output := ""
  1955. output += t.I18nBot("tgbot.messages.email", "Email=="+email)
  1956. output += t.I18nBot("tgbot.messages.TGUser", "TelegramID=="+tgId)
  1957. output += t.I18nBot("tgbot.messages.refreshedOn", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
  1958. inlineKeyboard := tu.InlineKeyboard(
  1959. tu.InlineKeyboardRow(
  1960. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.refresh")).WithCallbackData(t.encodeQuery("tgid_refresh "+email)),
  1961. ),
  1962. tu.InlineKeyboardRow(
  1963. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.removeTGUser")).WithCallbackData(t.encodeQuery("tgid_remove "+email)),
  1964. ),
  1965. )
  1966. if len(messageID) > 0 {
  1967. t.editMessageTgBot(chatId, messageID[0], output, inlineKeyboard)
  1968. } else {
  1969. t.SendMsgToTgbot(chatId, output, inlineKeyboard)
  1970. requestUser := telego.KeyboardButtonRequestUsers{
  1971. RequestID: int32(traffic.Id),
  1972. UserIsBot: new(bool),
  1973. }
  1974. keyboard := tu.Keyboard(
  1975. tu.KeyboardRow(
  1976. tu.KeyboardButton(t.I18nBot("tgbot.buttons.selectTGUser")).WithRequestUsers(&requestUser),
  1977. ),
  1978. tu.KeyboardRow(
  1979. tu.KeyboardButton(t.I18nBot("tgbot.buttons.closeKeyboard")),
  1980. ),
  1981. ).WithIsPersistent().WithResizeKeyboard()
  1982. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.buttons.selectOneTGUser"), keyboard)
  1983. }
  1984. }
  1985. func (t *Tgbot) searchClient(chatId int64, email string, messageID ...int) {
  1986. traffic, err := t.inboundService.GetClientTrafficByEmail(email)
  1987. if err != nil {
  1988. logger.Warning(err)
  1989. msg := t.I18nBot("tgbot.wentWrong")
  1990. t.SendMsgToTgbot(chatId, msg)
  1991. return
  1992. }
  1993. if traffic == nil {
  1994. msg := t.I18nBot("tgbot.noResult")
  1995. t.SendMsgToTgbot(chatId, msg)
  1996. return
  1997. }
  1998. output := t.clientInfoMsg(traffic, true, true, true, true, true, true)
  1999. inlineKeyboard := tu.InlineKeyboard(
  2000. tu.InlineKeyboardRow(
  2001. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.refresh")).WithCallbackData(t.encodeQuery("client_refresh "+email)),
  2002. ),
  2003. tu.InlineKeyboardRow(
  2004. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.resetTraffic")).WithCallbackData(t.encodeQuery("reset_traffic "+email)),
  2005. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.limitTraffic")).WithCallbackData(t.encodeQuery("limit_traffic "+email)),
  2006. ),
  2007. tu.InlineKeyboardRow(
  2008. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.resetExpire")).WithCallbackData(t.encodeQuery("reset_exp "+email)),
  2009. ),
  2010. tu.InlineKeyboardRow(
  2011. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.ipLog")).WithCallbackData(t.encodeQuery("ip_log "+email)),
  2012. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.ipLimit")).WithCallbackData(t.encodeQuery("ip_limit "+email)),
  2013. ),
  2014. tu.InlineKeyboardRow(
  2015. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.setTGUser")).WithCallbackData(t.encodeQuery("tg_user "+email)),
  2016. ),
  2017. tu.InlineKeyboardRow(
  2018. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.toggle")).WithCallbackData(t.encodeQuery("toggle_enable "+email)),
  2019. ),
  2020. )
  2021. if len(messageID) > 0 {
  2022. t.editMessageTgBot(chatId, messageID[0], output, inlineKeyboard)
  2023. } else {
  2024. t.SendMsgToTgbot(chatId, output, inlineKeyboard)
  2025. }
  2026. }
  2027. func (t *Tgbot) addClient(chatId int64, msg string, messageID ...int) {
  2028. inbound, err := t.inboundService.GetInbound(receiver_inbound_ID)
  2029. if err != nil {
  2030. t.SendMsgToTgbot(chatId, err.Error())
  2031. return
  2032. }
  2033. protocol := inbound.Protocol
  2034. switch protocol {
  2035. case model.VMESS, model.VLESS:
  2036. inlineKeyboard := tu.InlineKeyboard(
  2037. tu.InlineKeyboardRow(
  2038. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.change_email")).WithCallbackData("add_client_ch_default_email"),
  2039. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.change_id")).WithCallbackData("add_client_ch_default_id"),
  2040. ),
  2041. tu.InlineKeyboardRow(
  2042. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.limitTraffic")).WithCallbackData("add_client_ch_default_traffic"),
  2043. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.resetExpire")).WithCallbackData("add_client_ch_default_exp"),
  2044. ),
  2045. tu.InlineKeyboardRow(
  2046. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.change_comment")).WithCallbackData("add_client_ch_default_comment"),
  2047. ),
  2048. tu.InlineKeyboardRow(
  2049. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.submitDisable")).WithCallbackData("add_client_submit_disable"),
  2050. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.submitEnable")).WithCallbackData("add_client_submit_enable"),
  2051. ),
  2052. tu.InlineKeyboardRow(
  2053. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData("add_client_cancel"),
  2054. ),
  2055. )
  2056. if len(messageID) > 0 {
  2057. t.editMessageTgBot(chatId, messageID[0], msg, inlineKeyboard)
  2058. } else {
  2059. t.SendMsgToTgbot(chatId, msg, inlineKeyboard)
  2060. }
  2061. case model.Trojan:
  2062. inlineKeyboard := tu.InlineKeyboard(
  2063. tu.InlineKeyboardRow(
  2064. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.change_email")).WithCallbackData("add_client_ch_default_email"),
  2065. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.change_password")).WithCallbackData("add_client_ch_default_pass_tr"),
  2066. ),
  2067. tu.InlineKeyboardRow(
  2068. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.limitTraffic")).WithCallbackData("add_client_ch_default_traffic"),
  2069. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.resetExpire")).WithCallbackData("add_client_ch_default_exp"),
  2070. ),
  2071. tu.InlineKeyboardRow(
  2072. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.change_comment")).WithCallbackData("add_client_ch_default_comment"),
  2073. ),
  2074. tu.InlineKeyboardRow(
  2075. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.submitDisable")).WithCallbackData("add_client_submit_disable"),
  2076. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.submitEnable")).WithCallbackData("add_client_submit_enable"),
  2077. ),
  2078. tu.InlineKeyboardRow(
  2079. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData("add_client_cancel"),
  2080. ),
  2081. )
  2082. if len(messageID) > 0 {
  2083. t.editMessageTgBot(chatId, messageID[0], msg, inlineKeyboard)
  2084. } else {
  2085. t.SendMsgToTgbot(chatId, msg, inlineKeyboard)
  2086. }
  2087. case model.Shadowsocks:
  2088. inlineKeyboard := tu.InlineKeyboard(
  2089. tu.InlineKeyboardRow(
  2090. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.change_email")).WithCallbackData("add_client_ch_default_email"),
  2091. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.change_password")).WithCallbackData("add_client_ch_default_pass_sh"),
  2092. ),
  2093. tu.InlineKeyboardRow(
  2094. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.limitTraffic")).WithCallbackData("add_client_ch_default_traffic"),
  2095. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.resetExpire")).WithCallbackData("add_client_ch_default_exp"),
  2096. ),
  2097. tu.InlineKeyboardRow(
  2098. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.change_comment")).WithCallbackData("add_client_ch_default_comment"),
  2099. ),
  2100. tu.InlineKeyboardRow(
  2101. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.submitDisable")).WithCallbackData("add_client_submit_disable"),
  2102. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.submitEnable")).WithCallbackData("add_client_submit_enable"),
  2103. ),
  2104. tu.InlineKeyboardRow(
  2105. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData("add_client_cancel"),
  2106. ),
  2107. )
  2108. if len(messageID) > 0 {
  2109. t.editMessageTgBot(chatId, messageID[0], msg, inlineKeyboard)
  2110. } else {
  2111. t.SendMsgToTgbot(chatId, msg, inlineKeyboard)
  2112. }
  2113. }
  2114. }
  2115. func (t *Tgbot) searchInbound(chatId int64, remark string) {
  2116. inbounds, err := t.inboundService.SearchInbounds(remark)
  2117. if err != nil {
  2118. logger.Warning(err)
  2119. msg := t.I18nBot("tgbot.wentWrong")
  2120. t.SendMsgToTgbot(chatId, msg)
  2121. return
  2122. }
  2123. if len(inbounds) == 0 {
  2124. msg := t.I18nBot("tgbot.noInbounds")
  2125. t.SendMsgToTgbot(chatId, msg)
  2126. return
  2127. }
  2128. for _, inbound := range inbounds {
  2129. info := ""
  2130. info += t.I18nBot("tgbot.messages.inbound", "Remark=="+inbound.Remark)
  2131. info += t.I18nBot("tgbot.messages.port", "Port=="+strconv.Itoa(inbound.Port))
  2132. info += t.I18nBot("tgbot.messages.traffic", "Total=="+common.FormatTraffic((inbound.Up+inbound.Down)), "Upload=="+common.FormatTraffic(inbound.Up), "Download=="+common.FormatTraffic(inbound.Down))
  2133. if inbound.ExpiryTime == 0 {
  2134. info += t.I18nBot("tgbot.messages.expire", "Time=="+t.I18nBot("tgbot.unlimited"))
  2135. } else {
  2136. info += t.I18nBot("tgbot.messages.expire", "Time=="+time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05"))
  2137. }
  2138. t.SendMsgToTgbot(chatId, info)
  2139. if len(inbound.ClientStats) > 0 {
  2140. output := ""
  2141. for _, traffic := range inbound.ClientStats {
  2142. output += t.clientInfoMsg(&traffic, true, true, true, true, true, true)
  2143. }
  2144. t.SendMsgToTgbot(chatId, output)
  2145. }
  2146. }
  2147. }
  2148. func (t *Tgbot) getExhausted(chatId int64) {
  2149. trDiff := int64(0)
  2150. exDiff := int64(0)
  2151. now := time.Now().Unix() * 1000
  2152. var exhaustedInbounds []model.Inbound
  2153. var exhaustedClients []xray.ClientTraffic
  2154. var disabledInbounds []model.Inbound
  2155. var disabledClients []xray.ClientTraffic
  2156. TrafficThreshold, err := t.settingService.GetTrafficDiff()
  2157. if err == nil && TrafficThreshold > 0 {
  2158. trDiff = int64(TrafficThreshold) * 1073741824
  2159. }
  2160. ExpireThreshold, err := t.settingService.GetExpireDiff()
  2161. if err == nil && ExpireThreshold > 0 {
  2162. exDiff = int64(ExpireThreshold) * 86400000
  2163. }
  2164. inbounds, err := t.inboundService.GetAllInbounds()
  2165. if err != nil {
  2166. logger.Warning("Unable to load Inbounds", err)
  2167. }
  2168. for _, inbound := range inbounds {
  2169. if inbound.Enable {
  2170. if (inbound.ExpiryTime > 0 && (inbound.ExpiryTime-now < exDiff)) ||
  2171. (inbound.Total > 0 && (inbound.Total-(inbound.Up+inbound.Down) < trDiff)) {
  2172. exhaustedInbounds = append(exhaustedInbounds, *inbound)
  2173. }
  2174. if len(inbound.ClientStats) > 0 {
  2175. for _, client := range inbound.ClientStats {
  2176. if client.Enable {
  2177. if (client.ExpiryTime > 0 && (client.ExpiryTime-now < exDiff)) ||
  2178. (client.Total > 0 && (client.Total-(client.Up+client.Down) < trDiff)) {
  2179. exhaustedClients = append(exhaustedClients, client)
  2180. }
  2181. } else {
  2182. disabledClients = append(disabledClients, client)
  2183. }
  2184. }
  2185. }
  2186. } else {
  2187. disabledInbounds = append(disabledInbounds, *inbound)
  2188. }
  2189. }
  2190. // Inbounds
  2191. output := ""
  2192. output += t.I18nBot("tgbot.messages.exhaustedCount", "Type=="+t.I18nBot("tgbot.inbounds"))
  2193. output += t.I18nBot("tgbot.messages.disabled", "Disabled=="+strconv.Itoa(len(disabledInbounds)))
  2194. output += t.I18nBot("tgbot.messages.depleteSoon", "Deplete=="+strconv.Itoa(len(exhaustedInbounds)))
  2195. if len(exhaustedInbounds) > 0 {
  2196. output += t.I18nBot("tgbot.messages.depleteSoon", "Deplete=="+t.I18nBot("tgbot.inbounds"))
  2197. for _, inbound := range exhaustedInbounds {
  2198. output += t.I18nBot("tgbot.messages.inbound", "Remark=="+inbound.Remark)
  2199. output += t.I18nBot("tgbot.messages.port", "Port=="+strconv.Itoa(inbound.Port))
  2200. output += t.I18nBot("tgbot.messages.traffic", "Total=="+common.FormatTraffic((inbound.Up+inbound.Down)), "Upload=="+common.FormatTraffic(inbound.Up), "Download=="+common.FormatTraffic(inbound.Down))
  2201. if inbound.ExpiryTime == 0 {
  2202. output += t.I18nBot("tgbot.messages.expire", "Time=="+t.I18nBot("tgbot.unlimited"))
  2203. } else {
  2204. output += t.I18nBot("tgbot.messages.expire", "Time=="+time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05"))
  2205. }
  2206. output += "\r\n"
  2207. }
  2208. }
  2209. // Clients
  2210. exhaustedCC := len(exhaustedClients)
  2211. output += t.I18nBot("tgbot.messages.exhaustedCount", "Type=="+t.I18nBot("tgbot.clients"))
  2212. output += t.I18nBot("tgbot.messages.disabled", "Disabled=="+strconv.Itoa(len(disabledClients)))
  2213. output += t.I18nBot("tgbot.messages.depleteSoon", "Deplete=="+strconv.Itoa(exhaustedCC))
  2214. if exhaustedCC > 0 {
  2215. output += t.I18nBot("tgbot.messages.depleteSoon", "Deplete=="+t.I18nBot("tgbot.clients"))
  2216. var buttons []telego.InlineKeyboardButton
  2217. for _, traffic := range exhaustedClients {
  2218. output += t.clientInfoMsg(&traffic, true, false, false, true, true, false)
  2219. output += "\r\n"
  2220. buttons = append(buttons, tu.InlineKeyboardButton(traffic.Email).WithCallbackData(t.encodeQuery("client_get_usage "+traffic.Email)))
  2221. }
  2222. cols := 0
  2223. if exhaustedCC < 11 {
  2224. cols = 1
  2225. } else {
  2226. cols = 2
  2227. }
  2228. output += t.I18nBot("tgbot.messages.refreshedOn", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
  2229. keyboard := tu.InlineKeyboardGrid(tu.InlineKeyboardCols(cols, buttons...))
  2230. t.SendMsgToTgbot(chatId, output, keyboard)
  2231. } else {
  2232. output += t.I18nBot("tgbot.messages.refreshedOn", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
  2233. t.SendMsgToTgbot(chatId, output)
  2234. }
  2235. }
  2236. func (t *Tgbot) notifyExhausted() {
  2237. trDiff := int64(0)
  2238. exDiff := int64(0)
  2239. now := time.Now().Unix() * 1000
  2240. TrafficThreshold, err := t.settingService.GetTrafficDiff()
  2241. if err == nil && TrafficThreshold > 0 {
  2242. trDiff = int64(TrafficThreshold) * 1073741824
  2243. }
  2244. ExpireThreshold, err := t.settingService.GetExpireDiff()
  2245. if err == nil && ExpireThreshold > 0 {
  2246. exDiff = int64(ExpireThreshold) * 86400000
  2247. }
  2248. inbounds, err := t.inboundService.GetAllInbounds()
  2249. if err != nil {
  2250. logger.Warning("Unable to load Inbounds", err)
  2251. }
  2252. var chatIDsDone []int64
  2253. for _, inbound := range inbounds {
  2254. if inbound.Enable {
  2255. if len(inbound.ClientStats) > 0 {
  2256. clients, err := t.inboundService.GetClients(inbound)
  2257. if err == nil {
  2258. for _, client := range clients {
  2259. if client.TgID != 0 {
  2260. chatID := client.TgID
  2261. if !int64Contains(chatIDsDone, chatID) && !checkAdmin(chatID) {
  2262. var disabledClients []xray.ClientTraffic
  2263. var exhaustedClients []xray.ClientTraffic
  2264. traffics, err := t.inboundService.GetClientTrafficTgBot(client.TgID)
  2265. if err == nil && len(traffics) > 0 {
  2266. output := t.I18nBot("tgbot.messages.exhaustedCount", "Type=="+t.I18nBot("tgbot.clients"))
  2267. for _, traffic := range traffics {
  2268. if traffic.Enable {
  2269. if (traffic.ExpiryTime > 0 && (traffic.ExpiryTime-now < exDiff)) ||
  2270. (traffic.Total > 0 && (traffic.Total-(traffic.Up+traffic.Down) < trDiff)) {
  2271. exhaustedClients = append(exhaustedClients, *traffic)
  2272. }
  2273. } else {
  2274. disabledClients = append(disabledClients, *traffic)
  2275. }
  2276. }
  2277. if len(exhaustedClients) > 0 {
  2278. output += t.I18nBot("tgbot.messages.disabled", "Disabled=="+strconv.Itoa(len(disabledClients)))
  2279. if len(disabledClients) > 0 {
  2280. output += t.I18nBot("tgbot.clients") + ":\r\n"
  2281. for _, traffic := range disabledClients {
  2282. output += " " + traffic.Email
  2283. }
  2284. output += "\r\n"
  2285. }
  2286. output += "\r\n"
  2287. output += t.I18nBot("tgbot.messages.depleteSoon", "Deplete=="+strconv.Itoa(len(exhaustedClients)))
  2288. for _, traffic := range exhaustedClients {
  2289. output += t.clientInfoMsg(&traffic, true, false, false, true, true, false)
  2290. output += "\r\n"
  2291. }
  2292. t.SendMsgToTgbot(chatID, output)
  2293. }
  2294. chatIDsDone = append(chatIDsDone, chatID)
  2295. }
  2296. }
  2297. }
  2298. }
  2299. }
  2300. }
  2301. }
  2302. }
  2303. }
  2304. func int64Contains(slice []int64, item int64) bool {
  2305. for _, s := range slice {
  2306. if s == item {
  2307. return true
  2308. }
  2309. }
  2310. return false
  2311. }
  2312. func (t *Tgbot) onlineClients(chatId int64, messageID ...int) {
  2313. if !p.IsRunning() {
  2314. return
  2315. }
  2316. onlines := p.GetOnlineClients()
  2317. onlinesCount := len(onlines)
  2318. output := t.I18nBot("tgbot.messages.onlinesCount", "Count=="+fmt.Sprint(onlinesCount))
  2319. keyboard := tu.InlineKeyboard(tu.InlineKeyboardRow(
  2320. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.refresh")).WithCallbackData(t.encodeQuery("onlines_refresh"))))
  2321. if onlinesCount > 0 {
  2322. var buttons []telego.InlineKeyboardButton
  2323. for _, online := range onlines {
  2324. buttons = append(buttons, tu.InlineKeyboardButton(online).WithCallbackData(t.encodeQuery("client_get_usage "+online)))
  2325. }
  2326. cols := 0
  2327. if onlinesCount < 21 {
  2328. cols = 2
  2329. } else if onlinesCount < 61 {
  2330. cols = 3
  2331. } else {
  2332. cols = 4
  2333. }
  2334. keyboard.InlineKeyboard = append(keyboard.InlineKeyboard, tu.InlineKeyboardCols(cols, buttons...)...)
  2335. }
  2336. if len(messageID) > 0 {
  2337. t.editMessageTgBot(chatId, messageID[0], output, keyboard)
  2338. } else {
  2339. t.SendMsgToTgbot(chatId, output, keyboard)
  2340. }
  2341. }
  2342. func (t *Tgbot) sendBackup(chatId int64) {
  2343. output := t.I18nBot("tgbot.messages.backupTime", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
  2344. t.SendMsgToTgbot(chatId, output)
  2345. // Update by manually trigger a checkpoint operation
  2346. err := database.Checkpoint()
  2347. if err != nil {
  2348. logger.Error("Error in trigger a checkpoint operation: ", err)
  2349. }
  2350. file, err := os.Open(config.GetDBPath())
  2351. if err == nil {
  2352. document := tu.Document(
  2353. tu.ID(chatId),
  2354. tu.File(file),
  2355. )
  2356. _, err = bot.SendDocument(document)
  2357. if err != nil {
  2358. logger.Error("Error in uploading backup: ", err)
  2359. }
  2360. } else {
  2361. logger.Error("Error in opening db file for backup: ", err)
  2362. }
  2363. file, err = os.Open(xray.GetConfigPath())
  2364. if err == nil {
  2365. document := tu.Document(
  2366. tu.ID(chatId),
  2367. tu.File(file),
  2368. )
  2369. _, err = bot.SendDocument(document)
  2370. if err != nil {
  2371. logger.Error("Error in uploading config.json: ", err)
  2372. }
  2373. } else {
  2374. logger.Error("Error in opening config.json file for backup: ", err)
  2375. }
  2376. }
  2377. func (t *Tgbot) sendBanLogs(chatId int64, dt bool) {
  2378. if dt {
  2379. output := t.I18nBot("tgbot.messages.datetime", "DateTime=="+time.Now().Format("2006-01-02 15:04:05"))
  2380. t.SendMsgToTgbot(chatId, output)
  2381. }
  2382. file, err := os.Open(xray.GetIPLimitBannedPrevLogPath())
  2383. if err == nil {
  2384. // Check if the file is non-empty before attempting to upload
  2385. fileInfo, _ := file.Stat()
  2386. if fileInfo.Size() > 0 {
  2387. document := tu.Document(
  2388. tu.ID(chatId),
  2389. tu.File(file),
  2390. )
  2391. _, err = bot.SendDocument(document)
  2392. if err != nil {
  2393. logger.Error("Error in uploading IPLimitBannedPrevLog: ", err)
  2394. }
  2395. } else {
  2396. logger.Warning("IPLimitBannedPrevLog file is empty, not uploading.")
  2397. }
  2398. file.Close()
  2399. } else {
  2400. logger.Error("Error in opening IPLimitBannedPrevLog file for backup: ", err)
  2401. }
  2402. file, err = os.Open(xray.GetIPLimitBannedLogPath())
  2403. if err == nil {
  2404. // Check if the file is non-empty before attempting to upload
  2405. fileInfo, _ := file.Stat()
  2406. if fileInfo.Size() > 0 {
  2407. document := tu.Document(
  2408. tu.ID(chatId),
  2409. tu.File(file),
  2410. )
  2411. _, err = bot.SendDocument(document)
  2412. if err != nil {
  2413. logger.Error("Error in uploading IPLimitBannedLog: ", err)
  2414. }
  2415. } else {
  2416. logger.Warning("IPLimitBannedLog file is empty, not uploading.")
  2417. }
  2418. file.Close()
  2419. } else {
  2420. logger.Error("Error in opening IPLimitBannedLog file for backup: ", err)
  2421. }
  2422. }
  2423. func (t *Tgbot) sendCallbackAnswerTgBot(id string, message string) {
  2424. params := telego.AnswerCallbackQueryParams{
  2425. CallbackQueryID: id,
  2426. Text: message,
  2427. }
  2428. if err := bot.AnswerCallbackQuery(&params); err != nil {
  2429. logger.Warning(err)
  2430. }
  2431. }
  2432. func (t *Tgbot) editMessageCallbackTgBot(chatId int64, messageID int, inlineKeyboard *telego.InlineKeyboardMarkup) {
  2433. params := telego.EditMessageReplyMarkupParams{
  2434. ChatID: tu.ID(chatId),
  2435. MessageID: messageID,
  2436. ReplyMarkup: inlineKeyboard,
  2437. }
  2438. if _, err := bot.EditMessageReplyMarkup(&params); err != nil {
  2439. logger.Warning(err)
  2440. }
  2441. }
  2442. func (t *Tgbot) editMessageTgBot(chatId int64, messageID int, text string, inlineKeyboard ...*telego.InlineKeyboardMarkup) {
  2443. params := telego.EditMessageTextParams{
  2444. ChatID: tu.ID(chatId),
  2445. MessageID: messageID,
  2446. Text: text,
  2447. ParseMode: "HTML",
  2448. }
  2449. if len(inlineKeyboard) > 0 {
  2450. params.ReplyMarkup = inlineKeyboard[0]
  2451. }
  2452. if _, err := bot.EditMessageText(&params); err != nil {
  2453. logger.Warning(err)
  2454. }
  2455. }
  2456. func (t *Tgbot) SendMsgToTgbotDeleteAfter(chatId int64, msg string, delayInSeconds int, replyMarkup ...telego.ReplyMarkup) {
  2457. // Determine if replyMarkup was passed; otherwise, set it to nil
  2458. var replyMarkupParam telego.ReplyMarkup
  2459. if len(replyMarkup) > 0 {
  2460. replyMarkupParam = replyMarkup[0] // Use the first element
  2461. }
  2462. // Send the message
  2463. sentMsg, err := bot.SendMessage(&telego.SendMessageParams{
  2464. ChatID: tu.ID(chatId),
  2465. Text: msg,
  2466. ReplyMarkup: replyMarkupParam, // Use the correct replyMarkup value
  2467. })
  2468. if err != nil {
  2469. logger.Warning("Failed to send message:", err)
  2470. return
  2471. }
  2472. // Delete the sent message after the specified number of seconds
  2473. go func() {
  2474. time.Sleep(time.Duration(delayInSeconds) * time.Second) // Wait for the specified delay
  2475. t.deleteMessageTgBot(chatId, sentMsg.MessageID) // Delete the message
  2476. delete(userStates, chatId)
  2477. }()
  2478. }
  2479. func (t *Tgbot) deleteMessageTgBot(chatId int64, messageID int) {
  2480. params := telego.DeleteMessageParams{
  2481. ChatID: tu.ID(chatId),
  2482. MessageID: messageID,
  2483. }
  2484. if err := bot.DeleteMessage(&params); err != nil {
  2485. logger.Warning("Failed to delete message:", err)
  2486. } else {
  2487. logger.Info("Message deleted successfully")
  2488. }
  2489. }
  2490. func (t *Tgbot) isSingleWord(text string) bool {
  2491. text = strings.TrimSpace(text)
  2492. re := regexp.MustCompile(`\s+`)
  2493. return re.MatchString(text)
  2494. }