tgbot.go 137 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634
  1. package service
  2. import (
  3. "context"
  4. "crypto/rand"
  5. "embed"
  6. "encoding/base64"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "math/big"
  11. "net"
  12. "net/http"
  13. "net/url"
  14. "os"
  15. "regexp"
  16. "strconv"
  17. "strings"
  18. "sync"
  19. "time"
  20. "github.com/mhsanaei/3x-ui/v2/config"
  21. "github.com/mhsanaei/3x-ui/v2/database"
  22. "github.com/mhsanaei/3x-ui/v2/database/model"
  23. "github.com/mhsanaei/3x-ui/v2/logger"
  24. "github.com/mhsanaei/3x-ui/v2/util/common"
  25. "github.com/mhsanaei/3x-ui/v2/web/global"
  26. "github.com/mhsanaei/3x-ui/v2/web/locale"
  27. "github.com/mhsanaei/3x-ui/v2/xray"
  28. "github.com/google/uuid"
  29. "github.com/mymmrac/telego"
  30. th "github.com/mymmrac/telego/telegohandler"
  31. tu "github.com/mymmrac/telego/telegoutil"
  32. "github.com/skip2/go-qrcode"
  33. "github.com/valyala/fasthttp"
  34. "github.com/valyala/fasthttp/fasthttpproxy"
  35. )
  36. var (
  37. bot *telego.Bot
  38. botHandler *th.BotHandler
  39. adminIds []int64
  40. isRunning bool
  41. hostname string
  42. hashStorage *global.HashStorage
  43. // Performance improvements
  44. messageWorkerPool chan struct{} // Semaphore for limiting concurrent message processing
  45. optimizedHTTPClient *http.Client // HTTP client with connection pooling and timeouts
  46. // Simple cache for frequently accessed data
  47. statusCache struct {
  48. data *Status
  49. timestamp time.Time
  50. mutex sync.RWMutex
  51. }
  52. serverStatsCache struct {
  53. data string
  54. timestamp time.Time
  55. mutex sync.RWMutex
  56. }
  57. // clients data to adding new client
  58. receiver_inbound_ID int
  59. client_Id string
  60. client_Flow string
  61. client_Email string
  62. client_LimitIP int
  63. client_TotalGB int64
  64. client_ExpiryTime int64
  65. client_Enable bool
  66. client_TgID string
  67. client_SubID string
  68. client_Comment string
  69. client_Reset int
  70. client_Security string
  71. client_ShPassword string
  72. client_TrPassword string
  73. client_Method string
  74. )
  75. var userStates = make(map[int64]string)
  76. // LoginStatus represents the result of a login attempt.
  77. type LoginStatus byte
  78. // Login status constants
  79. const (
  80. LoginSuccess LoginStatus = 1 // Login was successful
  81. LoginFail LoginStatus = 0 // Login failed
  82. EmptyTelegramUserID = int64(0) // Default value for empty Telegram user ID
  83. )
  84. // Tgbot provides business logic for Telegram bot integration.
  85. // It handles bot commands, user interactions, and status reporting via Telegram.
  86. type Tgbot struct {
  87. inboundService InboundService
  88. settingService SettingService
  89. serverService ServerService
  90. xrayService XrayService
  91. lastStatus *Status
  92. }
  93. // NewTgbot creates a new Tgbot instance.
  94. func (t *Tgbot) NewTgbot() *Tgbot {
  95. return new(Tgbot)
  96. }
  97. // I18nBot retrieves a localized message for the bot interface.
  98. func (t *Tgbot) I18nBot(name string, params ...string) string {
  99. return locale.I18n(locale.Bot, name, params...)
  100. }
  101. // GetHashStorage returns the hash storage instance for callback queries.
  102. func (t *Tgbot) GetHashStorage() *global.HashStorage {
  103. return hashStorage
  104. }
  105. // getCachedStatus returns cached server status if it's fresh enough (less than 5 seconds old)
  106. func (t *Tgbot) getCachedStatus() (*Status, bool) {
  107. statusCache.mutex.RLock()
  108. defer statusCache.mutex.RUnlock()
  109. if statusCache.data != nil && time.Since(statusCache.timestamp) < 5*time.Second {
  110. return statusCache.data, true
  111. }
  112. return nil, false
  113. }
  114. // setCachedStatus updates the status cache
  115. func (t *Tgbot) setCachedStatus(status *Status) {
  116. statusCache.mutex.Lock()
  117. defer statusCache.mutex.Unlock()
  118. statusCache.data = status
  119. statusCache.timestamp = time.Now()
  120. }
  121. // getCachedServerStats returns cached server stats if it's fresh enough (less than 10 seconds old)
  122. func (t *Tgbot) getCachedServerStats() (string, bool) {
  123. serverStatsCache.mutex.RLock()
  124. defer serverStatsCache.mutex.RUnlock()
  125. if serverStatsCache.data != "" && time.Since(serverStatsCache.timestamp) < 10*time.Second {
  126. return serverStatsCache.data, true
  127. }
  128. return "", false
  129. }
  130. // setCachedServerStats updates the server stats cache
  131. func (t *Tgbot) setCachedServerStats(stats string) {
  132. serverStatsCache.mutex.Lock()
  133. defer serverStatsCache.mutex.Unlock()
  134. serverStatsCache.data = stats
  135. serverStatsCache.timestamp = time.Now()
  136. }
  137. // Start initializes and starts the Telegram bot with the provided translation files.
  138. func (t *Tgbot) Start(i18nFS embed.FS) error {
  139. // Initialize localizer
  140. err := locale.InitLocalizer(i18nFS, &t.settingService)
  141. if err != nil {
  142. return err
  143. }
  144. // Initialize hash storage to store callback queries
  145. hashStorage = global.NewHashStorage(20 * time.Minute)
  146. // Initialize worker pool for concurrent message processing (max 10 concurrent handlers)
  147. messageWorkerPool = make(chan struct{}, 10)
  148. // Initialize optimized HTTP client with connection pooling
  149. optimizedHTTPClient = &http.Client{
  150. Timeout: 15 * time.Second,
  151. Transport: &http.Transport{
  152. MaxIdleConns: 100,
  153. MaxIdleConnsPerHost: 10,
  154. IdleConnTimeout: 30 * time.Second,
  155. DisableKeepAlives: false,
  156. },
  157. }
  158. t.SetHostname()
  159. // Get Telegram bot token
  160. tgBotToken, err := t.settingService.GetTgBotToken()
  161. if err != nil || tgBotToken == "" {
  162. logger.Warning("Failed to get Telegram bot token:", err)
  163. return err
  164. }
  165. // Get Telegram bot chat ID(s)
  166. tgBotID, err := t.settingService.GetTgBotChatId()
  167. if err != nil {
  168. logger.Warning("Failed to get Telegram bot chat ID:", err)
  169. return err
  170. }
  171. // Parse admin IDs from comma-separated string
  172. if tgBotID != "" {
  173. for _, adminID := range strings.Split(tgBotID, ",") {
  174. id, err := strconv.Atoi(adminID)
  175. if err != nil {
  176. logger.Warning("Failed to parse admin ID from Telegram bot chat ID:", err)
  177. return err
  178. }
  179. adminIds = append(adminIds, int64(id))
  180. }
  181. }
  182. // Get Telegram bot proxy URL
  183. tgBotProxy, err := t.settingService.GetTgBotProxy()
  184. if err != nil {
  185. logger.Warning("Failed to get Telegram bot proxy URL:", err)
  186. }
  187. // Get Telegram bot API server URL
  188. tgBotAPIServer, err := t.settingService.GetTgBotAPIServer()
  189. if err != nil {
  190. logger.Warning("Failed to get Telegram bot API server URL:", err)
  191. }
  192. // Create new Telegram bot instance
  193. bot, err = t.NewBot(tgBotToken, tgBotProxy, tgBotAPIServer)
  194. if err != nil {
  195. logger.Error("Failed to initialize Telegram bot API:", err)
  196. return err
  197. }
  198. // After bot initialization, set up bot commands with localized descriptions
  199. err = bot.SetMyCommands(context.Background(), &telego.SetMyCommandsParams{
  200. Commands: []telego.BotCommand{
  201. {Command: "start", Description: t.I18nBot("tgbot.commands.startDesc")},
  202. {Command: "help", Description: t.I18nBot("tgbot.commands.helpDesc")},
  203. {Command: "status", Description: t.I18nBot("tgbot.commands.statusDesc")},
  204. {Command: "id", Description: t.I18nBot("tgbot.commands.idDesc")},
  205. },
  206. })
  207. if err != nil {
  208. logger.Warning("Failed to set bot commands:", err)
  209. }
  210. // Start receiving Telegram bot messages
  211. if !isRunning {
  212. logger.Info("Telegram bot receiver started")
  213. go t.OnReceive()
  214. isRunning = true
  215. }
  216. return nil
  217. }
  218. // NewBot creates a new Telegram bot instance with optional proxy and API server settings.
  219. func (t *Tgbot) NewBot(token string, proxyUrl string, apiServerUrl string) (*telego.Bot, error) {
  220. if proxyUrl == "" && apiServerUrl == "" {
  221. return telego.NewBot(token)
  222. }
  223. if proxyUrl != "" {
  224. if !strings.HasPrefix(proxyUrl, "socks5://") {
  225. logger.Warning("Invalid socks5 URL, using default")
  226. return telego.NewBot(token)
  227. }
  228. _, err := url.Parse(proxyUrl)
  229. if err != nil {
  230. logger.Warningf("Can't parse proxy URL, using default instance for tgbot: %v", err)
  231. return telego.NewBot(token)
  232. }
  233. return telego.NewBot(token, telego.WithFastHTTPClient(&fasthttp.Client{
  234. Dial: fasthttpproxy.FasthttpSocksDialer(proxyUrl),
  235. }))
  236. }
  237. if !strings.HasPrefix(apiServerUrl, "http") {
  238. logger.Warning("Invalid http(s) URL, using default")
  239. return telego.NewBot(token)
  240. }
  241. _, err := url.Parse(apiServerUrl)
  242. if err != nil {
  243. logger.Warningf("Can't parse API server URL, using default instance for tgbot: %v", err)
  244. return telego.NewBot(token)
  245. }
  246. return telego.NewBot(token, telego.WithAPIServer(apiServerUrl))
  247. }
  248. // IsRunning checks if the Telegram bot is currently running.
  249. func (t *Tgbot) IsRunning() bool {
  250. return isRunning
  251. }
  252. // SetHostname sets the hostname for the bot.
  253. func (t *Tgbot) SetHostname() {
  254. host, err := os.Hostname()
  255. if err != nil {
  256. logger.Error("get hostname error:", err)
  257. hostname = ""
  258. return
  259. }
  260. hostname = host
  261. }
  262. // Stop stops the Telegram bot and cleans up resources.
  263. func (t *Tgbot) Stop() {
  264. if botHandler != nil {
  265. botHandler.Stop()
  266. }
  267. logger.Info("Stop Telegram receiver ...")
  268. isRunning = false
  269. adminIds = nil
  270. }
  271. // encodeQuery encodes the query string if it's longer than 64 characters.
  272. func (t *Tgbot) encodeQuery(query string) string {
  273. // NOTE: we only need to hash for more than 64 chars
  274. if len(query) <= 64 {
  275. return query
  276. }
  277. return hashStorage.SaveHash(query)
  278. }
  279. // decodeQuery decodes a hashed query string back to its original form.
  280. func (t *Tgbot) decodeQuery(query string) (string, error) {
  281. if !hashStorage.IsMD5(query) {
  282. return query, nil
  283. }
  284. decoded, exists := hashStorage.GetValue(query)
  285. if !exists {
  286. return "", common.NewError("hash not found in storage!")
  287. }
  288. return decoded, nil
  289. }
  290. // OnReceive starts the message receiving loop for the Telegram bot.
  291. func (t *Tgbot) OnReceive() {
  292. params := telego.GetUpdatesParams{
  293. Timeout: 30, // Increased timeout to reduce API calls
  294. }
  295. updates, _ := bot.UpdatesViaLongPolling(context.Background(), &params)
  296. botHandler, _ = th.NewBotHandler(bot, updates)
  297. botHandler.HandleMessage(func(ctx *th.Context, message telego.Message) error {
  298. delete(userStates, message.Chat.ID)
  299. t.SendMsgToTgbot(message.Chat.ID, t.I18nBot("tgbot.keyboardClosed"), tu.ReplyKeyboardRemove())
  300. return nil
  301. }, th.TextEqual(t.I18nBot("tgbot.buttons.closeKeyboard")))
  302. botHandler.HandleMessage(func(ctx *th.Context, message telego.Message) error {
  303. // Use goroutine with worker pool for concurrent command processing
  304. go func() {
  305. messageWorkerPool <- struct{}{} // Acquire worker
  306. defer func() { <-messageWorkerPool }() // Release worker
  307. delete(userStates, message.Chat.ID)
  308. t.answerCommand(&message, message.Chat.ID, checkAdmin(message.From.ID))
  309. }()
  310. return nil
  311. }, th.AnyCommand())
  312. botHandler.HandleCallbackQuery(func(ctx *th.Context, query telego.CallbackQuery) error {
  313. // Use goroutine with worker pool for concurrent callback processing
  314. go func() {
  315. messageWorkerPool <- struct{}{} // Acquire worker
  316. defer func() { <-messageWorkerPool }() // Release worker
  317. delete(userStates, query.Message.GetChat().ID)
  318. t.answerCallback(&query, checkAdmin(query.From.ID))
  319. }()
  320. return nil
  321. }, th.AnyCallbackQueryWithMessage())
  322. botHandler.HandleMessage(func(ctx *th.Context, message telego.Message) error {
  323. if userState, exists := userStates[message.Chat.ID]; exists {
  324. switch userState {
  325. case "awaiting_id":
  326. if client_Id == strings.TrimSpace(message.Text) {
  327. t.SendMsgToTgbotDeleteAfter(message.Chat.ID, t.I18nBot("tgbot.messages.using_default_value"), 3, tu.ReplyKeyboardRemove())
  328. delete(userStates, message.Chat.ID)
  329. inbound, _ := t.inboundService.GetInbound(receiver_inbound_ID)
  330. message_text, _ := t.BuildInboundClientDataMessage(inbound.Remark, inbound.Protocol)
  331. t.addClient(message.Chat.ID, message_text)
  332. return nil
  333. }
  334. client_Id = strings.TrimSpace(message.Text)
  335. if t.isSingleWord(client_Id) {
  336. userStates[message.Chat.ID] = "awaiting_id"
  337. cancel_btn_markup := tu.InlineKeyboard(
  338. tu.InlineKeyboardRow(
  339. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.use_default")).WithCallbackData("add_client_default_info"),
  340. ),
  341. )
  342. t.SendMsgToTgbot(message.Chat.ID, t.I18nBot("tgbot.messages.incorrect_input"), cancel_btn_markup)
  343. } else {
  344. t.SendMsgToTgbotDeleteAfter(message.Chat.ID, t.I18nBot("tgbot.messages.received_id"), 3, tu.ReplyKeyboardRemove())
  345. delete(userStates, message.Chat.ID)
  346. inbound, _ := t.inboundService.GetInbound(receiver_inbound_ID)
  347. message_text, _ := t.BuildInboundClientDataMessage(inbound.Remark, inbound.Protocol)
  348. t.addClient(message.Chat.ID, message_text)
  349. }
  350. case "awaiting_password_tr":
  351. if client_TrPassword == strings.TrimSpace(message.Text) {
  352. t.SendMsgToTgbotDeleteAfter(message.Chat.ID, t.I18nBot("tgbot.messages.using_default_value"), 3, tu.ReplyKeyboardRemove())
  353. delete(userStates, message.Chat.ID)
  354. return nil
  355. }
  356. client_TrPassword = strings.TrimSpace(message.Text)
  357. if t.isSingleWord(client_TrPassword) {
  358. userStates[message.Chat.ID] = "awaiting_password_tr"
  359. cancel_btn_markup := tu.InlineKeyboard(
  360. tu.InlineKeyboardRow(
  361. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.use_default")).WithCallbackData("add_client_default_info"),
  362. ),
  363. )
  364. t.SendMsgToTgbot(message.Chat.ID, t.I18nBot("tgbot.messages.incorrect_input"), cancel_btn_markup)
  365. } else {
  366. t.SendMsgToTgbotDeleteAfter(message.Chat.ID, t.I18nBot("tgbot.messages.received_password"), 3, tu.ReplyKeyboardRemove())
  367. delete(userStates, message.Chat.ID)
  368. inbound, _ := t.inboundService.GetInbound(receiver_inbound_ID)
  369. message_text, _ := t.BuildInboundClientDataMessage(inbound.Remark, inbound.Protocol)
  370. t.addClient(message.Chat.ID, message_text)
  371. }
  372. case "awaiting_password_sh":
  373. if client_ShPassword == strings.TrimSpace(message.Text) {
  374. t.SendMsgToTgbotDeleteAfter(message.Chat.ID, t.I18nBot("tgbot.messages.using_default_value"), 3, tu.ReplyKeyboardRemove())
  375. delete(userStates, message.Chat.ID)
  376. return nil
  377. }
  378. client_ShPassword = strings.TrimSpace(message.Text)
  379. if t.isSingleWord(client_ShPassword) {
  380. userStates[message.Chat.ID] = "awaiting_password_sh"
  381. cancel_btn_markup := tu.InlineKeyboard(
  382. tu.InlineKeyboardRow(
  383. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.use_default")).WithCallbackData("add_client_default_info"),
  384. ),
  385. )
  386. t.SendMsgToTgbot(message.Chat.ID, t.I18nBot("tgbot.messages.incorrect_input"), cancel_btn_markup)
  387. } else {
  388. t.SendMsgToTgbotDeleteAfter(message.Chat.ID, t.I18nBot("tgbot.messages.received_password"), 3, tu.ReplyKeyboardRemove())
  389. delete(userStates, message.Chat.ID)
  390. inbound, _ := t.inboundService.GetInbound(receiver_inbound_ID)
  391. message_text, _ := t.BuildInboundClientDataMessage(inbound.Remark, inbound.Protocol)
  392. t.addClient(message.Chat.ID, message_text)
  393. }
  394. case "awaiting_email":
  395. if client_Email == strings.TrimSpace(message.Text) {
  396. t.SendMsgToTgbotDeleteAfter(message.Chat.ID, t.I18nBot("tgbot.messages.using_default_value"), 3, tu.ReplyKeyboardRemove())
  397. delete(userStates, message.Chat.ID)
  398. return nil
  399. }
  400. client_Email = strings.TrimSpace(message.Text)
  401. if t.isSingleWord(client_Email) {
  402. userStates[message.Chat.ID] = "awaiting_email"
  403. cancel_btn_markup := tu.InlineKeyboard(
  404. tu.InlineKeyboardRow(
  405. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.use_default")).WithCallbackData("add_client_default_info"),
  406. ),
  407. )
  408. t.SendMsgToTgbot(message.Chat.ID, t.I18nBot("tgbot.messages.incorrect_input"), cancel_btn_markup)
  409. } else {
  410. t.SendMsgToTgbotDeleteAfter(message.Chat.ID, t.I18nBot("tgbot.messages.received_email"), 3, tu.ReplyKeyboardRemove())
  411. delete(userStates, message.Chat.ID)
  412. inbound, _ := t.inboundService.GetInbound(receiver_inbound_ID)
  413. message_text, _ := t.BuildInboundClientDataMessage(inbound.Remark, inbound.Protocol)
  414. t.addClient(message.Chat.ID, message_text)
  415. }
  416. case "awaiting_comment":
  417. if client_Comment == strings.TrimSpace(message.Text) {
  418. t.SendMsgToTgbotDeleteAfter(message.Chat.ID, t.I18nBot("tgbot.messages.using_default_value"), 3, tu.ReplyKeyboardRemove())
  419. delete(userStates, message.Chat.ID)
  420. return nil
  421. }
  422. client_Comment = strings.TrimSpace(message.Text)
  423. t.SendMsgToTgbotDeleteAfter(message.Chat.ID, t.I18nBot("tgbot.messages.received_comment"), 3, tu.ReplyKeyboardRemove())
  424. delete(userStates, message.Chat.ID)
  425. inbound, _ := t.inboundService.GetInbound(receiver_inbound_ID)
  426. message_text, _ := t.BuildInboundClientDataMessage(inbound.Remark, inbound.Protocol)
  427. t.addClient(message.Chat.ID, message_text)
  428. }
  429. } else {
  430. if message.UsersShared != nil {
  431. if checkAdmin(message.From.ID) {
  432. for _, sharedUser := range message.UsersShared.Users {
  433. userID := sharedUser.UserID
  434. needRestart, err := t.inboundService.SetClientTelegramUserID(message.UsersShared.RequestID, userID)
  435. if needRestart {
  436. t.xrayService.SetToNeedRestart()
  437. }
  438. output := ""
  439. if err != nil {
  440. output += t.I18nBot("tgbot.messages.selectUserFailed")
  441. } else {
  442. output += t.I18nBot("tgbot.messages.userSaved")
  443. }
  444. t.SendMsgToTgbot(message.Chat.ID, output, tu.ReplyKeyboardRemove())
  445. }
  446. } else {
  447. t.SendMsgToTgbot(message.Chat.ID, t.I18nBot("tgbot.noResult"), tu.ReplyKeyboardRemove())
  448. }
  449. }
  450. }
  451. return nil
  452. }, th.AnyMessage())
  453. botHandler.Start()
  454. }
  455. // answerCommand processes incoming command messages from Telegram users.
  456. func (t *Tgbot) answerCommand(message *telego.Message, chatId int64, isAdmin bool) {
  457. msg, onlyMessage := "", false
  458. command, _, commandArgs := tu.ParseCommand(message.Text)
  459. // Helper function to handle unknown commands.
  460. handleUnknownCommand := func() {
  461. msg += t.I18nBot("tgbot.commands.unknown")
  462. }
  463. // Handle the command.
  464. switch command {
  465. case "help":
  466. msg += t.I18nBot("tgbot.commands.help")
  467. msg += t.I18nBot("tgbot.commands.pleaseChoose")
  468. case "start":
  469. msg += t.I18nBot("tgbot.commands.start", "Firstname=="+message.From.FirstName)
  470. if isAdmin {
  471. msg += t.I18nBot("tgbot.commands.welcome", "Hostname=="+hostname)
  472. }
  473. msg += "\n\n" + t.I18nBot("tgbot.commands.pleaseChoose")
  474. case "status":
  475. onlyMessage = true
  476. msg += t.I18nBot("tgbot.commands.status")
  477. case "id":
  478. onlyMessage = true
  479. msg += t.I18nBot("tgbot.commands.getID", "ID=="+strconv.FormatInt(message.From.ID, 10))
  480. case "usage":
  481. onlyMessage = true
  482. if len(commandArgs) > 0 {
  483. if isAdmin {
  484. t.searchClient(chatId, commandArgs[0])
  485. } else {
  486. t.getClientUsage(chatId, int64(message.From.ID), commandArgs[0])
  487. }
  488. } else {
  489. msg += t.I18nBot("tgbot.commands.usage")
  490. }
  491. case "inbound":
  492. onlyMessage = true
  493. if isAdmin && len(commandArgs) > 0 {
  494. t.searchInbound(chatId, commandArgs[0])
  495. } else {
  496. handleUnknownCommand()
  497. }
  498. case "restart":
  499. onlyMessage = true
  500. if isAdmin {
  501. if len(commandArgs) == 0 {
  502. if t.xrayService.IsXrayRunning() {
  503. err := t.xrayService.RestartXray(true)
  504. if err != nil {
  505. msg += t.I18nBot("tgbot.commands.restartFailed", "Error=="+err.Error())
  506. } else {
  507. msg += t.I18nBot("tgbot.commands.restartSuccess")
  508. }
  509. } else {
  510. msg += t.I18nBot("tgbot.commands.xrayNotRunning")
  511. }
  512. } else {
  513. handleUnknownCommand()
  514. msg += t.I18nBot("tgbot.commands.restartUsage")
  515. }
  516. } else {
  517. handleUnknownCommand()
  518. }
  519. default:
  520. handleUnknownCommand()
  521. }
  522. if msg != "" {
  523. t.sendResponse(chatId, msg, onlyMessage, isAdmin)
  524. }
  525. }
  526. // sendResponse sends the response message based on the onlyMessage flag.
  527. func (t *Tgbot) sendResponse(chatId int64, msg string, onlyMessage, isAdmin bool) {
  528. if onlyMessage {
  529. t.SendMsgToTgbot(chatId, msg)
  530. } else {
  531. t.SendAnswer(chatId, msg, isAdmin)
  532. }
  533. }
  534. // randomLowerAndNum generates a random string of lowercase letters and numbers.
  535. func (t *Tgbot) randomLowerAndNum(length int) string {
  536. charset := "abcdefghijklmnopqrstuvwxyz0123456789"
  537. bytes := make([]byte, length)
  538. for i := range bytes {
  539. randomIndex, _ := rand.Int(rand.Reader, big.NewInt(int64(len(charset))))
  540. bytes[i] = charset[randomIndex.Int64()]
  541. }
  542. return string(bytes)
  543. }
  544. // randomShadowSocksPassword generates a random password for Shadowsocks.
  545. func (t *Tgbot) randomShadowSocksPassword() string {
  546. array := make([]byte, 32)
  547. _, err := rand.Read(array)
  548. if err != nil {
  549. return t.randomLowerAndNum(32)
  550. }
  551. return base64.StdEncoding.EncodeToString(array)
  552. }
  553. // answerCallback processes callback queries from inline keyboards.
  554. func (t *Tgbot) answerCallback(callbackQuery *telego.CallbackQuery, isAdmin bool) {
  555. chatId := callbackQuery.Message.GetChat().ID
  556. if isAdmin {
  557. // get query from hash storage
  558. decodedQuery, err := t.decodeQuery(callbackQuery.Data)
  559. if err != nil {
  560. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.noQuery"))
  561. return
  562. }
  563. dataArray := strings.Split(decodedQuery, " ")
  564. if len(dataArray) >= 2 && len(dataArray[1]) > 0 {
  565. email := dataArray[1]
  566. switch dataArray[0] {
  567. case "get_clients_for_sub":
  568. inboundId := dataArray[1]
  569. inboundIdInt, err := strconv.Atoi(inboundId)
  570. if err != nil {
  571. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  572. return
  573. }
  574. clientsKB, err := t.getInboundClientsFor(inboundIdInt, "client_sub_links")
  575. if err != nil {
  576. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  577. return
  578. }
  579. inbound, _ := t.inboundService.GetInbound(inboundIdInt)
  580. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.chooseClient", "Inbound=="+inbound.Remark), clientsKB)
  581. case "get_clients_for_individual":
  582. inboundId := dataArray[1]
  583. inboundIdInt, err := strconv.Atoi(inboundId)
  584. if err != nil {
  585. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  586. return
  587. }
  588. clientsKB, err := t.getInboundClientsFor(inboundIdInt, "client_individual_links")
  589. if err != nil {
  590. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  591. return
  592. }
  593. inbound, _ := t.inboundService.GetInbound(inboundIdInt)
  594. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.chooseClient", "Inbound=="+inbound.Remark), clientsKB)
  595. case "get_clients_for_qr":
  596. inboundId := dataArray[1]
  597. inboundIdInt, err := strconv.Atoi(inboundId)
  598. if err != nil {
  599. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  600. return
  601. }
  602. clientsKB, err := t.getInboundClientsFor(inboundIdInt, "client_qr_links")
  603. if err != nil {
  604. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  605. return
  606. }
  607. inbound, _ := t.inboundService.GetInbound(inboundIdInt)
  608. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.chooseClient", "Inbound=="+inbound.Remark), clientsKB)
  609. case "client_sub_links":
  610. t.sendClientSubLinks(chatId, email)
  611. return
  612. case "client_individual_links":
  613. t.sendClientIndividualLinks(chatId, email)
  614. return
  615. case "client_qr_links":
  616. t.sendClientQRLinks(chatId, email)
  617. return
  618. case "client_get_usage":
  619. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.messages.email", "Email=="+email))
  620. t.searchClient(chatId, email)
  621. case "client_refresh":
  622. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.clientRefreshSuccess", "Email=="+email))
  623. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  624. case "client_cancel":
  625. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.canceled", "Email=="+email))
  626. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  627. case "ips_refresh":
  628. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.IpRefreshSuccess", "Email=="+email))
  629. t.searchClientIps(chatId, email, callbackQuery.Message.GetMessageID())
  630. case "ips_cancel":
  631. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.canceled", "Email=="+email))
  632. t.searchClientIps(chatId, email, callbackQuery.Message.GetMessageID())
  633. case "tgid_refresh":
  634. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.TGIdRefreshSuccess", "Email=="+email))
  635. t.clientTelegramUserInfo(chatId, email, callbackQuery.Message.GetMessageID())
  636. case "tgid_cancel":
  637. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.canceled", "Email=="+email))
  638. t.clientTelegramUserInfo(chatId, email, callbackQuery.Message.GetMessageID())
  639. case "reset_traffic":
  640. inlineKeyboard := tu.InlineKeyboard(
  641. tu.InlineKeyboardRow(
  642. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancelReset")).WithCallbackData(t.encodeQuery("client_cancel "+email)),
  643. ),
  644. tu.InlineKeyboardRow(
  645. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmResetTraffic")).WithCallbackData(t.encodeQuery("reset_traffic_c "+email)),
  646. ),
  647. )
  648. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  649. case "reset_traffic_c":
  650. err := t.inboundService.ResetClientTrafficByEmail(email)
  651. if err == nil {
  652. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.resetTrafficSuccess", "Email=="+email))
  653. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  654. } else {
  655. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  656. }
  657. case "limit_traffic":
  658. inlineKeyboard := tu.InlineKeyboard(
  659. tu.InlineKeyboardRow(
  660. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("client_cancel "+email)),
  661. ),
  662. tu.InlineKeyboardRow(
  663. tu.InlineKeyboardButton(t.I18nBot("tgbot.unlimited")).WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 0")),
  664. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.custom")).WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" 0")),
  665. ),
  666. tu.InlineKeyboardRow(
  667. tu.InlineKeyboardButton("1 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 1")),
  668. tu.InlineKeyboardButton("5 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 5")),
  669. tu.InlineKeyboardButton("10 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 10")),
  670. ),
  671. tu.InlineKeyboardRow(
  672. tu.InlineKeyboardButton("20 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 20")),
  673. tu.InlineKeyboardButton("30 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 30")),
  674. tu.InlineKeyboardButton("40 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 40")),
  675. ),
  676. tu.InlineKeyboardRow(
  677. tu.InlineKeyboardButton("50 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 50")),
  678. tu.InlineKeyboardButton("60 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 60")),
  679. tu.InlineKeyboardButton("80 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 80")),
  680. ),
  681. tu.InlineKeyboardRow(
  682. tu.InlineKeyboardButton("100 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 100")),
  683. tu.InlineKeyboardButton("150 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 150")),
  684. tu.InlineKeyboardButton("200 GB").WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" 200")),
  685. ),
  686. )
  687. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  688. case "limit_traffic_c":
  689. if len(dataArray) == 3 {
  690. limitTraffic, err := strconv.Atoi(dataArray[2])
  691. if err == nil {
  692. needRestart, err := t.inboundService.ResetClientTrafficLimitByEmail(email, limitTraffic)
  693. if needRestart {
  694. t.xrayService.SetToNeedRestart()
  695. }
  696. if err == nil {
  697. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.setTrafficLimitSuccess", "Email=="+email))
  698. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  699. return
  700. }
  701. }
  702. }
  703. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  704. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  705. case "limit_traffic_in":
  706. if len(dataArray) >= 3 {
  707. oldInputNumber, err := strconv.Atoi(dataArray[2])
  708. inputNumber := oldInputNumber
  709. if err == nil {
  710. if len(dataArray) == 4 {
  711. num, err := strconv.Atoi(dataArray[3])
  712. if err == nil {
  713. switch num {
  714. case -2:
  715. inputNumber = 0
  716. case -1:
  717. if inputNumber > 0 {
  718. inputNumber = (inputNumber / 10)
  719. }
  720. default:
  721. inputNumber = (inputNumber * 10) + num
  722. }
  723. }
  724. if inputNumber == oldInputNumber {
  725. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.successfulOperation"))
  726. return
  727. }
  728. if inputNumber >= 999999 {
  729. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  730. return
  731. }
  732. }
  733. inlineKeyboard := tu.InlineKeyboard(
  734. tu.InlineKeyboardRow(
  735. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("client_cancel "+email)),
  736. ),
  737. tu.InlineKeyboardRow(
  738. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmNumberAdd", "Num=="+strconv.Itoa(inputNumber))).WithCallbackData(t.encodeQuery("limit_traffic_c "+email+" "+strconv.Itoa(inputNumber))),
  739. ),
  740. tu.InlineKeyboardRow(
  741. tu.InlineKeyboardButton("1").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 1")),
  742. tu.InlineKeyboardButton("2").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 2")),
  743. tu.InlineKeyboardButton("3").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 3")),
  744. ),
  745. tu.InlineKeyboardRow(
  746. tu.InlineKeyboardButton("4").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 4")),
  747. tu.InlineKeyboardButton("5").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 5")),
  748. tu.InlineKeyboardButton("6").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 6")),
  749. ),
  750. tu.InlineKeyboardRow(
  751. tu.InlineKeyboardButton("7").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 7")),
  752. tu.InlineKeyboardButton("8").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 8")),
  753. tu.InlineKeyboardButton("9").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 9")),
  754. ),
  755. tu.InlineKeyboardRow(
  756. tu.InlineKeyboardButton("🔄").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" -2")),
  757. tu.InlineKeyboardButton("0").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" 0")),
  758. tu.InlineKeyboardButton("⬅️").WithCallbackData(t.encodeQuery("limit_traffic_in "+email+" "+strconv.Itoa(inputNumber)+" -1")),
  759. ),
  760. )
  761. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  762. return
  763. }
  764. }
  765. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  766. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  767. case "add_client_limit_traffic_c":
  768. limitTraffic, _ := strconv.Atoi(dataArray[1])
  769. client_TotalGB = int64(limitTraffic) * 1024 * 1024 * 1024
  770. messageId := callbackQuery.Message.GetMessageID()
  771. inbound, err := t.inboundService.GetInbound(receiver_inbound_ID)
  772. if err != nil {
  773. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  774. return
  775. }
  776. message_text, err := t.BuildInboundClientDataMessage(inbound.Remark, inbound.Protocol)
  777. if err != nil {
  778. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  779. return
  780. }
  781. t.addClient(callbackQuery.Message.GetChat().ID, message_text, messageId)
  782. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.successfulOperation"))
  783. case "add_client_limit_traffic_in":
  784. if len(dataArray) >= 2 {
  785. oldInputNumber, err := strconv.Atoi(dataArray[1])
  786. inputNumber := oldInputNumber
  787. if err == nil {
  788. if len(dataArray) == 3 {
  789. num, err := strconv.Atoi(dataArray[2])
  790. if err == nil {
  791. switch num {
  792. case -2:
  793. inputNumber = 0
  794. case -1:
  795. if inputNumber > 0 {
  796. inputNumber = (inputNumber / 10)
  797. }
  798. default:
  799. inputNumber = (inputNumber * 10) + num
  800. }
  801. }
  802. if inputNumber == oldInputNumber {
  803. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.successfulOperation"))
  804. return
  805. }
  806. if inputNumber >= 999999 {
  807. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  808. return
  809. }
  810. }
  811. inlineKeyboard := tu.InlineKeyboard(
  812. tu.InlineKeyboardRow(
  813. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("add_client_default_traffic_exp")),
  814. ),
  815. tu.InlineKeyboardRow(
  816. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmNumberAdd", "Num=="+strconv.Itoa(inputNumber))).WithCallbackData(t.encodeQuery("add_client_limit_traffic_c "+strconv.Itoa(inputNumber))),
  817. ),
  818. tu.InlineKeyboardRow(
  819. tu.InlineKeyboardButton("1").WithCallbackData(t.encodeQuery("add_client_limit_traffic_in "+strconv.Itoa(inputNumber)+" 1")),
  820. tu.InlineKeyboardButton("2").WithCallbackData(t.encodeQuery("add_client_limit_traffic_in "+strconv.Itoa(inputNumber)+" 2")),
  821. tu.InlineKeyboardButton("3").WithCallbackData(t.encodeQuery("add_client_limit_traffic_in "+strconv.Itoa(inputNumber)+" 3")),
  822. ),
  823. tu.InlineKeyboardRow(
  824. tu.InlineKeyboardButton("4").WithCallbackData(t.encodeQuery("add_client_limit_traffic_in "+strconv.Itoa(inputNumber)+" 4")),
  825. tu.InlineKeyboardButton("5").WithCallbackData(t.encodeQuery("add_client_limit_traffic_in "+strconv.Itoa(inputNumber)+" 5")),
  826. tu.InlineKeyboardButton("6").WithCallbackData(t.encodeQuery("add_client_limit_traffic_in "+strconv.Itoa(inputNumber)+" 6")),
  827. ),
  828. tu.InlineKeyboardRow(
  829. tu.InlineKeyboardButton("7").WithCallbackData(t.encodeQuery("add_client_limit_traffic_in "+strconv.Itoa(inputNumber)+" 7")),
  830. tu.InlineKeyboardButton("8").WithCallbackData(t.encodeQuery("add_client_limit_traffic_in "+strconv.Itoa(inputNumber)+" 8")),
  831. tu.InlineKeyboardButton("9").WithCallbackData(t.encodeQuery("add_client_limit_traffic_in "+strconv.Itoa(inputNumber)+" 9")),
  832. ),
  833. tu.InlineKeyboardRow(
  834. tu.InlineKeyboardButton("🔄").WithCallbackData(t.encodeQuery("add_client_limit_traffic_in "+strconv.Itoa(inputNumber)+" -2")),
  835. tu.InlineKeyboardButton("0").WithCallbackData(t.encodeQuery("add_client_limit_traffic_in "+strconv.Itoa(inputNumber)+" 0")),
  836. tu.InlineKeyboardButton("⬅️").WithCallbackData(t.encodeQuery("add_client_limit_traffic_in "+strconv.Itoa(inputNumber)+" -1")),
  837. ),
  838. )
  839. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  840. return
  841. }
  842. }
  843. case "reset_exp":
  844. inlineKeyboard := tu.InlineKeyboard(
  845. tu.InlineKeyboardRow(
  846. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancelReset")).WithCallbackData(t.encodeQuery("client_cancel "+email)),
  847. ),
  848. tu.InlineKeyboardRow(
  849. tu.InlineKeyboardButton(t.I18nBot("tgbot.unlimited")).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" 0")),
  850. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.custom")).WithCallbackData(t.encodeQuery("reset_exp_in "+email+" 0")),
  851. ),
  852. tu.InlineKeyboardRow(
  853. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 7 "+t.I18nBot("tgbot.days")).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" 7")),
  854. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 10 "+t.I18nBot("tgbot.days")).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" 10")),
  855. ),
  856. tu.InlineKeyboardRow(
  857. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 14 "+t.I18nBot("tgbot.days")).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" 14")),
  858. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 20 "+t.I18nBot("tgbot.days")).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" 20")),
  859. ),
  860. tu.InlineKeyboardRow(
  861. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 1 "+t.I18nBot("tgbot.month")).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" 30")),
  862. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 3 "+t.I18nBot("tgbot.months")).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" 90")),
  863. ),
  864. tu.InlineKeyboardRow(
  865. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 6 "+t.I18nBot("tgbot.months")).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" 180")),
  866. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 12 "+t.I18nBot("tgbot.months")).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" 365")),
  867. ),
  868. )
  869. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  870. case "reset_exp_c":
  871. if len(dataArray) == 3 {
  872. days, err := strconv.Atoi(dataArray[2])
  873. if err == nil {
  874. var date int64
  875. if days > 0 {
  876. traffic, err := t.inboundService.GetClientTrafficByEmail(email)
  877. if err != nil {
  878. logger.Warning(err)
  879. msg := t.I18nBot("tgbot.wentWrong")
  880. t.SendMsgToTgbot(chatId, msg)
  881. return
  882. }
  883. if traffic == nil {
  884. msg := t.I18nBot("tgbot.noResult")
  885. t.SendMsgToTgbot(chatId, msg)
  886. return
  887. }
  888. if traffic.ExpiryTime > 0 {
  889. if traffic.ExpiryTime-time.Now().Unix()*1000 < 0 {
  890. date = -int64(days * 24 * 60 * 60000)
  891. } else {
  892. date = traffic.ExpiryTime + int64(days*24*60*60000)
  893. }
  894. } else {
  895. date = traffic.ExpiryTime - int64(days*24*60*60000)
  896. }
  897. }
  898. needRestart, err := t.inboundService.ResetClientExpiryTimeByEmail(email, date)
  899. if needRestart {
  900. t.xrayService.SetToNeedRestart()
  901. }
  902. if err == nil {
  903. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.expireResetSuccess", "Email=="+email))
  904. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  905. return
  906. }
  907. }
  908. }
  909. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  910. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  911. case "reset_exp_in":
  912. if len(dataArray) >= 3 {
  913. oldInputNumber, err := strconv.Atoi(dataArray[2])
  914. inputNumber := oldInputNumber
  915. if err == nil {
  916. if len(dataArray) == 4 {
  917. num, err := strconv.Atoi(dataArray[3])
  918. if err == nil {
  919. switch num {
  920. case -2:
  921. inputNumber = 0
  922. case -1:
  923. if inputNumber > 0 {
  924. inputNumber = (inputNumber / 10)
  925. }
  926. default:
  927. inputNumber = (inputNumber * 10) + num
  928. }
  929. }
  930. if inputNumber == oldInputNumber {
  931. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.successfulOperation"))
  932. return
  933. }
  934. if inputNumber >= 999999 {
  935. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  936. return
  937. }
  938. }
  939. inlineKeyboard := tu.InlineKeyboard(
  940. tu.InlineKeyboardRow(
  941. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("client_cancel "+email)),
  942. ),
  943. tu.InlineKeyboardRow(
  944. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmNumber", "Num=="+strconv.Itoa(inputNumber))).WithCallbackData(t.encodeQuery("reset_exp_c "+email+" "+strconv.Itoa(inputNumber))),
  945. ),
  946. tu.InlineKeyboardRow(
  947. tu.InlineKeyboardButton("1").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 1")),
  948. tu.InlineKeyboardButton("2").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 2")),
  949. tu.InlineKeyboardButton("3").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 3")),
  950. ),
  951. tu.InlineKeyboardRow(
  952. tu.InlineKeyboardButton("4").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 4")),
  953. tu.InlineKeyboardButton("5").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 5")),
  954. tu.InlineKeyboardButton("6").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 6")),
  955. ),
  956. tu.InlineKeyboardRow(
  957. tu.InlineKeyboardButton("7").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 7")),
  958. tu.InlineKeyboardButton("8").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 8")),
  959. tu.InlineKeyboardButton("9").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 9")),
  960. ),
  961. tu.InlineKeyboardRow(
  962. tu.InlineKeyboardButton("🔄").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" -2")),
  963. tu.InlineKeyboardButton("0").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" 0")),
  964. tu.InlineKeyboardButton("⬅️").WithCallbackData(t.encodeQuery("reset_exp_in "+email+" "+strconv.Itoa(inputNumber)+" -1")),
  965. ),
  966. )
  967. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  968. return
  969. }
  970. }
  971. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  972. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  973. case "add_client_reset_exp_c":
  974. client_ExpiryTime = 0
  975. days, _ := strconv.Atoi(dataArray[1])
  976. var date int64
  977. if client_ExpiryTime > 0 {
  978. if client_ExpiryTime-time.Now().Unix()*1000 < 0 {
  979. date = -int64(days * 24 * 60 * 60000)
  980. } else {
  981. date = client_ExpiryTime + int64(days*24*60*60000)
  982. }
  983. } else {
  984. date = client_ExpiryTime - int64(days*24*60*60000)
  985. }
  986. client_ExpiryTime = date
  987. messageId := callbackQuery.Message.GetMessageID()
  988. inbound, err := t.inboundService.GetInbound(receiver_inbound_ID)
  989. if err != nil {
  990. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  991. return
  992. }
  993. message_text, err := t.BuildInboundClientDataMessage(inbound.Remark, inbound.Protocol)
  994. if err != nil {
  995. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  996. return
  997. }
  998. t.addClient(callbackQuery.Message.GetChat().ID, message_text, messageId)
  999. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.successfulOperation"))
  1000. case "add_client_reset_exp_in":
  1001. if len(dataArray) >= 2 {
  1002. oldInputNumber, err := strconv.Atoi(dataArray[1])
  1003. inputNumber := oldInputNumber
  1004. if err == nil {
  1005. if len(dataArray) == 3 {
  1006. num, err := strconv.Atoi(dataArray[2])
  1007. if err == nil {
  1008. switch num {
  1009. case -2:
  1010. inputNumber = 0
  1011. case -1:
  1012. if inputNumber > 0 {
  1013. inputNumber = (inputNumber / 10)
  1014. }
  1015. default:
  1016. inputNumber = (inputNumber * 10) + num
  1017. }
  1018. }
  1019. if inputNumber == oldInputNumber {
  1020. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.successfulOperation"))
  1021. return
  1022. }
  1023. if inputNumber >= 999999 {
  1024. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  1025. return
  1026. }
  1027. }
  1028. inlineKeyboard := tu.InlineKeyboard(
  1029. tu.InlineKeyboardRow(
  1030. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("add_client_default_traffic_exp")),
  1031. ),
  1032. tu.InlineKeyboardRow(
  1033. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmNumberAdd", "Num=="+strconv.Itoa(inputNumber))).WithCallbackData(t.encodeQuery("add_client_reset_exp_c "+strconv.Itoa(inputNumber))),
  1034. ),
  1035. tu.InlineKeyboardRow(
  1036. tu.InlineKeyboardButton("1").WithCallbackData(t.encodeQuery("add_client_reset_exp_in "+strconv.Itoa(inputNumber)+" 1")),
  1037. tu.InlineKeyboardButton("2").WithCallbackData(t.encodeQuery("add_client_reset_exp_in "+strconv.Itoa(inputNumber)+" 2")),
  1038. tu.InlineKeyboardButton("3").WithCallbackData(t.encodeQuery("add_client_reset_exp_in "+strconv.Itoa(inputNumber)+" 3")),
  1039. ),
  1040. tu.InlineKeyboardRow(
  1041. tu.InlineKeyboardButton("4").WithCallbackData(t.encodeQuery("add_client_reset_exp_in "+strconv.Itoa(inputNumber)+" 4")),
  1042. tu.InlineKeyboardButton("5").WithCallbackData(t.encodeQuery("add_client_reset_exp_in "+strconv.Itoa(inputNumber)+" 5")),
  1043. tu.InlineKeyboardButton("6").WithCallbackData(t.encodeQuery("add_client_reset_exp_in "+strconv.Itoa(inputNumber)+" 6")),
  1044. ),
  1045. tu.InlineKeyboardRow(
  1046. tu.InlineKeyboardButton("7").WithCallbackData(t.encodeQuery("add_client_reset_exp_in "+strconv.Itoa(inputNumber)+" 7")),
  1047. tu.InlineKeyboardButton("8").WithCallbackData(t.encodeQuery("add_client_reset_exp_in "+strconv.Itoa(inputNumber)+" 8")),
  1048. tu.InlineKeyboardButton("9").WithCallbackData(t.encodeQuery("add_client_reset_exp_in "+strconv.Itoa(inputNumber)+" 9")),
  1049. ),
  1050. tu.InlineKeyboardRow(
  1051. tu.InlineKeyboardButton("🔄").WithCallbackData(t.encodeQuery("add_client_reset_exp_in "+strconv.Itoa(inputNumber)+" -2")),
  1052. tu.InlineKeyboardButton("0").WithCallbackData(t.encodeQuery("add_client_reset_exp_in "+strconv.Itoa(inputNumber)+" 0")),
  1053. tu.InlineKeyboardButton("⬅️").WithCallbackData(t.encodeQuery("add_client_reset_exp_in "+strconv.Itoa(inputNumber)+" -1")),
  1054. ),
  1055. )
  1056. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  1057. return
  1058. }
  1059. }
  1060. case "ip_limit":
  1061. inlineKeyboard := tu.InlineKeyboard(
  1062. tu.InlineKeyboardRow(
  1063. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancelIpLimit")).WithCallbackData(t.encodeQuery("client_cancel "+email)),
  1064. ),
  1065. tu.InlineKeyboardRow(
  1066. tu.InlineKeyboardButton(t.I18nBot("tgbot.unlimited")).WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 0")),
  1067. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.custom")).WithCallbackData(t.encodeQuery("ip_limit_in "+email+" 0")),
  1068. ),
  1069. tu.InlineKeyboardRow(
  1070. tu.InlineKeyboardButton("1").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 1")),
  1071. tu.InlineKeyboardButton("2").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 2")),
  1072. ),
  1073. tu.InlineKeyboardRow(
  1074. tu.InlineKeyboardButton("3").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 3")),
  1075. tu.InlineKeyboardButton("4").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 4")),
  1076. ),
  1077. tu.InlineKeyboardRow(
  1078. tu.InlineKeyboardButton("5").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 5")),
  1079. tu.InlineKeyboardButton("6").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 6")),
  1080. tu.InlineKeyboardButton("7").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 7")),
  1081. ),
  1082. tu.InlineKeyboardRow(
  1083. tu.InlineKeyboardButton("8").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 8")),
  1084. tu.InlineKeyboardButton("9").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 9")),
  1085. tu.InlineKeyboardButton("10").WithCallbackData(t.encodeQuery("ip_limit_c "+email+" 10")),
  1086. ),
  1087. )
  1088. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  1089. case "ip_limit_c":
  1090. if len(dataArray) == 3 {
  1091. count, err := strconv.Atoi(dataArray[2])
  1092. if err == nil {
  1093. needRestart, err := t.inboundService.ResetClientIpLimitByEmail(email, count)
  1094. if needRestart {
  1095. t.xrayService.SetToNeedRestart()
  1096. }
  1097. if err == nil {
  1098. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.resetIpSuccess", "Email=="+email, "Count=="+strconv.Itoa(count)))
  1099. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  1100. return
  1101. }
  1102. }
  1103. }
  1104. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  1105. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  1106. case "ip_limit_in":
  1107. if len(dataArray) >= 3 {
  1108. oldInputNumber, err := strconv.Atoi(dataArray[2])
  1109. inputNumber := oldInputNumber
  1110. if err == nil {
  1111. if len(dataArray) == 4 {
  1112. num, err := strconv.Atoi(dataArray[3])
  1113. if err == nil {
  1114. switch num {
  1115. case -2:
  1116. inputNumber = 0
  1117. case -1:
  1118. if inputNumber > 0 {
  1119. inputNumber = (inputNumber / 10)
  1120. }
  1121. default:
  1122. inputNumber = (inputNumber * 10) + num
  1123. }
  1124. }
  1125. if inputNumber == oldInputNumber {
  1126. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.successfulOperation"))
  1127. return
  1128. }
  1129. if inputNumber >= 999999 {
  1130. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  1131. return
  1132. }
  1133. }
  1134. inlineKeyboard := tu.InlineKeyboard(
  1135. tu.InlineKeyboardRow(
  1136. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("client_cancel "+email)),
  1137. ),
  1138. tu.InlineKeyboardRow(
  1139. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmNumber", "Num=="+strconv.Itoa(inputNumber))).WithCallbackData(t.encodeQuery("ip_limit_c "+email+" "+strconv.Itoa(inputNumber))),
  1140. ),
  1141. tu.InlineKeyboardRow(
  1142. tu.InlineKeyboardButton("1").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 1")),
  1143. tu.InlineKeyboardButton("2").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 2")),
  1144. tu.InlineKeyboardButton("3").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 3")),
  1145. ),
  1146. tu.InlineKeyboardRow(
  1147. tu.InlineKeyboardButton("4").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 4")),
  1148. tu.InlineKeyboardButton("5").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 5")),
  1149. tu.InlineKeyboardButton("6").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 6")),
  1150. ),
  1151. tu.InlineKeyboardRow(
  1152. tu.InlineKeyboardButton("7").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 7")),
  1153. tu.InlineKeyboardButton("8").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 8")),
  1154. tu.InlineKeyboardButton("9").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 9")),
  1155. ),
  1156. tu.InlineKeyboardRow(
  1157. tu.InlineKeyboardButton("🔄").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" -2")),
  1158. tu.InlineKeyboardButton("0").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" 0")),
  1159. tu.InlineKeyboardButton("⬅️").WithCallbackData(t.encodeQuery("ip_limit_in "+email+" "+strconv.Itoa(inputNumber)+" -1")),
  1160. ),
  1161. )
  1162. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  1163. return
  1164. }
  1165. }
  1166. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  1167. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  1168. case "add_client_ip_limit_c":
  1169. if len(dataArray) == 2 {
  1170. count, _ := strconv.Atoi(dataArray[1])
  1171. client_LimitIP = count
  1172. }
  1173. messageId := callbackQuery.Message.GetMessageID()
  1174. inbound, err := t.inboundService.GetInbound(receiver_inbound_ID)
  1175. if err != nil {
  1176. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1177. return
  1178. }
  1179. message_text, err := t.BuildInboundClientDataMessage(inbound.Remark, inbound.Protocol)
  1180. if err != nil {
  1181. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1182. return
  1183. }
  1184. t.addClient(callbackQuery.Message.GetChat().ID, message_text, messageId)
  1185. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.successfulOperation"))
  1186. case "add_client_ip_limit_in":
  1187. if len(dataArray) >= 2 {
  1188. oldInputNumber, err := strconv.Atoi(dataArray[1])
  1189. inputNumber := oldInputNumber
  1190. if err == nil {
  1191. if len(dataArray) == 3 {
  1192. num, err := strconv.Atoi(dataArray[2])
  1193. if err == nil {
  1194. switch num {
  1195. case -2:
  1196. inputNumber = 0
  1197. case -1:
  1198. if inputNumber > 0 {
  1199. inputNumber = (inputNumber / 10)
  1200. }
  1201. default:
  1202. inputNumber = (inputNumber * 10) + num
  1203. }
  1204. }
  1205. if inputNumber == oldInputNumber {
  1206. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.successfulOperation"))
  1207. return
  1208. }
  1209. if inputNumber >= 999999 {
  1210. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  1211. return
  1212. }
  1213. }
  1214. inlineKeyboard := tu.InlineKeyboard(
  1215. tu.InlineKeyboardRow(
  1216. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("add_client_default_ip_limit")),
  1217. ),
  1218. tu.InlineKeyboardRow(
  1219. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmNumber", "Num=="+strconv.Itoa(inputNumber))).WithCallbackData(t.encodeQuery("add_client_ip_limit_c "+strconv.Itoa(inputNumber))),
  1220. ),
  1221. tu.InlineKeyboardRow(
  1222. tu.InlineKeyboardButton("1").WithCallbackData(t.encodeQuery("add_client_ip_limit_in "+strconv.Itoa(inputNumber)+" 1")),
  1223. tu.InlineKeyboardButton("2").WithCallbackData(t.encodeQuery("add_client_ip_limit_in "+strconv.Itoa(inputNumber)+" 2")),
  1224. tu.InlineKeyboardButton("3").WithCallbackData(t.encodeQuery("add_client_ip_limit_in "+strconv.Itoa(inputNumber)+" 3")),
  1225. ),
  1226. tu.InlineKeyboardRow(
  1227. tu.InlineKeyboardButton("4").WithCallbackData(t.encodeQuery("add_client_ip_limit_in "+strconv.Itoa(inputNumber)+" 4")),
  1228. tu.InlineKeyboardButton("5").WithCallbackData(t.encodeQuery("add_client_ip_limit_in "+strconv.Itoa(inputNumber)+" 5")),
  1229. tu.InlineKeyboardButton("6").WithCallbackData(t.encodeQuery("add_client_ip_limit_in "+strconv.Itoa(inputNumber)+" 6")),
  1230. ),
  1231. tu.InlineKeyboardRow(
  1232. tu.InlineKeyboardButton("7").WithCallbackData(t.encodeQuery("add_client_ip_limit_in "+strconv.Itoa(inputNumber)+" 7")),
  1233. tu.InlineKeyboardButton("8").WithCallbackData(t.encodeQuery("add_client_ip_limit_in "+strconv.Itoa(inputNumber)+" 8")),
  1234. tu.InlineKeyboardButton("9").WithCallbackData(t.encodeQuery("add_client_ip_limit_in "+strconv.Itoa(inputNumber)+" 9")),
  1235. ),
  1236. tu.InlineKeyboardRow(
  1237. tu.InlineKeyboardButton("🔄").WithCallbackData(t.encodeQuery("add_client_ip_limit_in "+strconv.Itoa(inputNumber)+" -2")),
  1238. tu.InlineKeyboardButton("0").WithCallbackData(t.encodeQuery("add_client_ip_limit_in "+strconv.Itoa(inputNumber)+" 0")),
  1239. tu.InlineKeyboardButton("⬅️").WithCallbackData(t.encodeQuery("add_client_ip_limit_in "+strconv.Itoa(inputNumber)+" -1")),
  1240. ),
  1241. )
  1242. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  1243. return
  1244. }
  1245. }
  1246. case "clear_ips":
  1247. inlineKeyboard := tu.InlineKeyboard(
  1248. tu.InlineKeyboardRow(
  1249. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("ips_cancel "+email)),
  1250. ),
  1251. tu.InlineKeyboardRow(
  1252. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmClearIps")).WithCallbackData(t.encodeQuery("clear_ips_c "+email)),
  1253. ),
  1254. )
  1255. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  1256. case "clear_ips_c":
  1257. err := t.inboundService.ClearClientIps(email)
  1258. if err == nil {
  1259. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.clearIpSuccess", "Email=="+email))
  1260. t.searchClientIps(chatId, email, callbackQuery.Message.GetMessageID())
  1261. } else {
  1262. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  1263. }
  1264. case "ip_log":
  1265. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.getIpLog", "Email=="+email))
  1266. t.searchClientIps(chatId, email)
  1267. case "tg_user":
  1268. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.getUserInfo", "Email=="+email))
  1269. t.clientTelegramUserInfo(chatId, email)
  1270. case "tgid_remove":
  1271. inlineKeyboard := tu.InlineKeyboard(
  1272. tu.InlineKeyboardRow(
  1273. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("tgid_cancel "+email)),
  1274. ),
  1275. tu.InlineKeyboardRow(
  1276. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmRemoveTGUser")).WithCallbackData(t.encodeQuery("tgid_remove_c "+email)),
  1277. ),
  1278. )
  1279. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  1280. case "tgid_remove_c":
  1281. traffic, err := t.inboundService.GetClientTrafficByEmail(email)
  1282. if err != nil || traffic == nil {
  1283. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  1284. return
  1285. }
  1286. needRestart, err := t.inboundService.SetClientTelegramUserID(traffic.Id, EmptyTelegramUserID)
  1287. if needRestart {
  1288. t.xrayService.SetToNeedRestart()
  1289. }
  1290. if err == nil {
  1291. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.removedTGUserSuccess", "Email=="+email))
  1292. t.clientTelegramUserInfo(chatId, email, callbackQuery.Message.GetMessageID())
  1293. } else {
  1294. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  1295. }
  1296. case "toggle_enable":
  1297. inlineKeyboard := tu.InlineKeyboard(
  1298. tu.InlineKeyboardRow(
  1299. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("client_cancel "+email)),
  1300. ),
  1301. tu.InlineKeyboardRow(
  1302. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmToggle")).WithCallbackData(t.encodeQuery("toggle_enable_c "+email)),
  1303. ),
  1304. )
  1305. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  1306. case "toggle_enable_c":
  1307. enabled, needRestart, err := t.inboundService.ToggleClientEnableByEmail(email)
  1308. if needRestart {
  1309. t.xrayService.SetToNeedRestart()
  1310. }
  1311. if err == nil {
  1312. if enabled {
  1313. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.enableSuccess", "Email=="+email))
  1314. } else {
  1315. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.disableSuccess", "Email=="+email))
  1316. }
  1317. t.searchClient(chatId, email, callbackQuery.Message.GetMessageID())
  1318. } else {
  1319. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
  1320. }
  1321. case "get_clients":
  1322. inboundId := dataArray[1]
  1323. inboundIdInt, err := strconv.Atoi(inboundId)
  1324. if err != nil {
  1325. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1326. return
  1327. }
  1328. inbound, err := t.inboundService.GetInbound(inboundIdInt)
  1329. if err != nil {
  1330. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1331. return
  1332. }
  1333. clients, err := t.getInboundClients(inboundIdInt)
  1334. if err != nil {
  1335. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1336. return
  1337. }
  1338. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.chooseClient", "Inbound=="+inbound.Remark), clients)
  1339. case "add_client_to":
  1340. // assign default values to clients variables
  1341. client_Id = uuid.New().String()
  1342. client_Flow = ""
  1343. client_Email = t.randomLowerAndNum(8)
  1344. client_LimitIP = 0
  1345. client_TotalGB = 0
  1346. client_ExpiryTime = 0
  1347. client_Enable = true
  1348. client_TgID = ""
  1349. client_SubID = t.randomLowerAndNum(16)
  1350. client_Comment = ""
  1351. client_Reset = 0
  1352. client_Security = "auto"
  1353. client_ShPassword = t.randomShadowSocksPassword()
  1354. client_TrPassword = t.randomLowerAndNum(10)
  1355. client_Method = ""
  1356. inboundId := dataArray[1]
  1357. inboundIdInt, err := strconv.Atoi(inboundId)
  1358. if err != nil {
  1359. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1360. return
  1361. }
  1362. receiver_inbound_ID = inboundIdInt
  1363. inbound, err := t.inboundService.GetInbound(inboundIdInt)
  1364. if err != nil {
  1365. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1366. return
  1367. }
  1368. message_text, err := t.BuildInboundClientDataMessage(inbound.Remark, inbound.Protocol)
  1369. if err != nil {
  1370. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1371. return
  1372. }
  1373. t.addClient(callbackQuery.Message.GetChat().ID, message_text)
  1374. }
  1375. return
  1376. } else {
  1377. switch callbackQuery.Data {
  1378. case "get_inbounds":
  1379. inbounds, err := t.getInbounds()
  1380. if err != nil {
  1381. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1382. return
  1383. }
  1384. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.allClients"))
  1385. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.chooseInbound"), inbounds)
  1386. case "admin_client_sub_links":
  1387. inbounds, err := t.getInboundsFor("get_clients_for_sub")
  1388. if err != nil {
  1389. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1390. return
  1391. }
  1392. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.chooseInbound"), inbounds)
  1393. case "admin_client_individual_links":
  1394. inbounds, err := t.getInboundsFor("get_clients_for_individual")
  1395. if err != nil {
  1396. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1397. return
  1398. }
  1399. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.chooseInbound"), inbounds)
  1400. case "admin_client_qr_links":
  1401. inbounds, err := t.getInboundsFor("get_clients_for_qr")
  1402. if err != nil {
  1403. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1404. return
  1405. }
  1406. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.chooseInbound"), inbounds)
  1407. }
  1408. }
  1409. }
  1410. switch callbackQuery.Data {
  1411. case "get_usage":
  1412. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.serverUsage"))
  1413. t.getServerUsage(chatId)
  1414. case "usage_refresh":
  1415. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.successfulOperation"))
  1416. t.getServerUsage(chatId, callbackQuery.Message.GetMessageID())
  1417. case "inbounds":
  1418. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.getInbounds"))
  1419. t.SendMsgToTgbot(chatId, t.getInboundUsages())
  1420. case "deplete_soon":
  1421. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.depleteSoon"))
  1422. t.getExhausted(chatId)
  1423. case "get_backup":
  1424. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.dbBackup"))
  1425. t.sendBackup(chatId)
  1426. case "get_banlogs":
  1427. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.getBanLogs"))
  1428. t.sendBanLogs(chatId, true)
  1429. case "client_traffic":
  1430. tgUserID := callbackQuery.From.ID
  1431. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.clientUsage"))
  1432. t.getClientUsage(chatId, tgUserID)
  1433. case "client_commands":
  1434. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.commands"))
  1435. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.commands.helpClientCommands"))
  1436. case "client_sub_links":
  1437. // show user's own clients to choose one for sub links
  1438. tgUserID := callbackQuery.From.ID
  1439. traffics, err := t.inboundService.GetClientTrafficTgBot(tgUserID)
  1440. if err != nil {
  1441. // fallback to message
  1442. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.errorOperation")+"\r\n"+err.Error())
  1443. return
  1444. }
  1445. if len(traffics) == 0 {
  1446. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.askToAddUserId", "TgUserID=="+strconv.FormatInt(tgUserID, 10)))
  1447. return
  1448. }
  1449. var buttons []telego.InlineKeyboardButton
  1450. for _, tr := range traffics {
  1451. buttons = append(buttons, tu.InlineKeyboardButton(tr.Email).WithCallbackData(t.encodeQuery("client_sub_links "+tr.Email)))
  1452. }
  1453. cols := 1
  1454. if len(buttons) >= 6 {
  1455. cols = 2
  1456. }
  1457. keyboard := tu.InlineKeyboardGrid(tu.InlineKeyboardCols(cols, buttons...))
  1458. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.commands.pleaseChoose"), keyboard)
  1459. case "client_individual_links":
  1460. // show user's clients to choose for individual links
  1461. tgUserID := callbackQuery.From.ID
  1462. traffics, err := t.inboundService.GetClientTrafficTgBot(tgUserID)
  1463. if err != nil {
  1464. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.errorOperation")+"\r\n"+err.Error())
  1465. return
  1466. }
  1467. if len(traffics) == 0 {
  1468. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.askToAddUserId", "TgUserID=="+strconv.FormatInt(tgUserID, 10)))
  1469. return
  1470. }
  1471. var buttons2 []telego.InlineKeyboardButton
  1472. for _, tr := range traffics {
  1473. buttons2 = append(buttons2, tu.InlineKeyboardButton(tr.Email).WithCallbackData(t.encodeQuery("client_individual_links "+tr.Email)))
  1474. }
  1475. cols2 := 1
  1476. if len(buttons2) >= 6 {
  1477. cols2 = 2
  1478. }
  1479. keyboard2 := tu.InlineKeyboardGrid(tu.InlineKeyboardCols(cols2, buttons2...))
  1480. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.commands.pleaseChoose"), keyboard2)
  1481. case "client_qr_links":
  1482. // show user's clients to choose for QR codes
  1483. tgUserID := callbackQuery.From.ID
  1484. traffics, err := t.inboundService.GetClientTrafficTgBot(tgUserID)
  1485. if err != nil {
  1486. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.errorOccurred")+"\r\n"+err.Error())
  1487. return
  1488. }
  1489. if len(traffics) == 0 {
  1490. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.askToAddUserId", "TgUserID=="+strconv.FormatInt(tgUserID, 10)))
  1491. return
  1492. }
  1493. var buttons3 []telego.InlineKeyboardButton
  1494. for _, tr := range traffics {
  1495. buttons3 = append(buttons3, tu.InlineKeyboardButton(tr.Email).WithCallbackData(t.encodeQuery("client_qr_links "+tr.Email)))
  1496. }
  1497. cols3 := 1
  1498. if len(buttons3) >= 6 {
  1499. cols3 = 2
  1500. }
  1501. keyboard3 := tu.InlineKeyboardGrid(tu.InlineKeyboardCols(cols3, buttons3...))
  1502. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.commands.pleaseChoose"), keyboard3)
  1503. case "onlines":
  1504. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.onlines"))
  1505. t.onlineClients(chatId)
  1506. case "onlines_refresh":
  1507. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.successfulOperation"))
  1508. t.onlineClients(chatId, callbackQuery.Message.GetMessageID())
  1509. case "commands":
  1510. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.commands"))
  1511. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.commands.helpAdminCommands"))
  1512. case "add_client":
  1513. // assign default values to clients variables
  1514. client_Id = uuid.New().String()
  1515. client_Flow = ""
  1516. client_Email = t.randomLowerAndNum(8)
  1517. client_LimitIP = 0
  1518. client_TotalGB = 0
  1519. client_ExpiryTime = 0
  1520. client_Enable = true
  1521. client_TgID = ""
  1522. client_SubID = t.randomLowerAndNum(16)
  1523. client_Comment = ""
  1524. client_Reset = 0
  1525. client_Security = "auto"
  1526. client_ShPassword = t.randomShadowSocksPassword()
  1527. client_TrPassword = t.randomLowerAndNum(10)
  1528. client_Method = ""
  1529. inbounds, err := t.getInboundsAddClient()
  1530. if err != nil {
  1531. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1532. return
  1533. }
  1534. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.addClient"))
  1535. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.chooseInbound"), inbounds)
  1536. case "add_client_ch_default_email":
  1537. t.deleteMessageTgBot(chatId, callbackQuery.Message.GetMessageID())
  1538. userStates[chatId] = "awaiting_email"
  1539. cancel_btn_markup := tu.InlineKeyboard(
  1540. tu.InlineKeyboardRow(
  1541. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.use_default")).WithCallbackData("add_client_default_info"),
  1542. ),
  1543. )
  1544. prompt_message := t.I18nBot("tgbot.messages.email_prompt", "ClientEmail=="+client_Email)
  1545. t.SendMsgToTgbot(chatId, prompt_message, cancel_btn_markup)
  1546. case "add_client_ch_default_id":
  1547. t.deleteMessageTgBot(chatId, callbackQuery.Message.GetMessageID())
  1548. userStates[chatId] = "awaiting_id"
  1549. cancel_btn_markup := tu.InlineKeyboard(
  1550. tu.InlineKeyboardRow(
  1551. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.use_default")).WithCallbackData("add_client_default_info"),
  1552. ),
  1553. )
  1554. prompt_message := t.I18nBot("tgbot.messages.id_prompt", "ClientId=="+client_Id)
  1555. t.SendMsgToTgbot(chatId, prompt_message, cancel_btn_markup)
  1556. case "add_client_ch_default_pass_tr":
  1557. t.deleteMessageTgBot(chatId, callbackQuery.Message.GetMessageID())
  1558. userStates[chatId] = "awaiting_password_tr"
  1559. cancel_btn_markup := tu.InlineKeyboard(
  1560. tu.InlineKeyboardRow(
  1561. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.use_default")).WithCallbackData("add_client_default_info"),
  1562. ),
  1563. )
  1564. prompt_message := t.I18nBot("tgbot.messages.pass_prompt", "ClientPassword=="+client_TrPassword)
  1565. t.SendMsgToTgbot(chatId, prompt_message, cancel_btn_markup)
  1566. case "add_client_ch_default_pass_sh":
  1567. t.deleteMessageTgBot(chatId, callbackQuery.Message.GetMessageID())
  1568. userStates[chatId] = "awaiting_password_sh"
  1569. cancel_btn_markup := tu.InlineKeyboard(
  1570. tu.InlineKeyboardRow(
  1571. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.use_default")).WithCallbackData("add_client_default_info"),
  1572. ),
  1573. )
  1574. prompt_message := t.I18nBot("tgbot.messages.pass_prompt", "ClientPassword=="+client_ShPassword)
  1575. t.SendMsgToTgbot(chatId, prompt_message, cancel_btn_markup)
  1576. case "add_client_ch_default_comment":
  1577. t.deleteMessageTgBot(chatId, callbackQuery.Message.GetMessageID())
  1578. userStates[chatId] = "awaiting_comment"
  1579. cancel_btn_markup := tu.InlineKeyboard(
  1580. tu.InlineKeyboardRow(
  1581. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.use_default")).WithCallbackData("add_client_default_info"),
  1582. ),
  1583. )
  1584. prompt_message := t.I18nBot("tgbot.messages.comment_prompt", "ClientComment=="+client_Comment)
  1585. t.SendMsgToTgbot(chatId, prompt_message, cancel_btn_markup)
  1586. case "add_client_ch_default_traffic":
  1587. inlineKeyboard := tu.InlineKeyboard(
  1588. tu.InlineKeyboardRow(
  1589. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("add_client_default_traffic_exp")),
  1590. ),
  1591. tu.InlineKeyboardRow(
  1592. tu.InlineKeyboardButton(t.I18nBot("tgbot.unlimited")).WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 0")),
  1593. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.custom")).WithCallbackData(t.encodeQuery("add_client_limit_traffic_in 0")),
  1594. ),
  1595. tu.InlineKeyboardRow(
  1596. tu.InlineKeyboardButton("1 GB").WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 1")),
  1597. tu.InlineKeyboardButton("5 GB").WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 5")),
  1598. tu.InlineKeyboardButton("10 GB").WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 10")),
  1599. ),
  1600. tu.InlineKeyboardRow(
  1601. tu.InlineKeyboardButton("20 GB").WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 20")),
  1602. tu.InlineKeyboardButton("30 GB").WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 30")),
  1603. tu.InlineKeyboardButton("40 GB").WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 40")),
  1604. ),
  1605. tu.InlineKeyboardRow(
  1606. tu.InlineKeyboardButton("50 GB").WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 50")),
  1607. tu.InlineKeyboardButton("60 GB").WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 60")),
  1608. tu.InlineKeyboardButton("80 GB").WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 80")),
  1609. ),
  1610. tu.InlineKeyboardRow(
  1611. tu.InlineKeyboardButton("100 GB").WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 100")),
  1612. tu.InlineKeyboardButton("150 GB").WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 150")),
  1613. tu.InlineKeyboardButton("200 GB").WithCallbackData(t.encodeQuery("add_client_limit_traffic_c 200")),
  1614. ),
  1615. )
  1616. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  1617. case "add_client_ch_default_exp":
  1618. inlineKeyboard := tu.InlineKeyboard(
  1619. tu.InlineKeyboardRow(
  1620. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("add_client_default_traffic_exp")),
  1621. ),
  1622. tu.InlineKeyboardRow(
  1623. tu.InlineKeyboardButton(t.I18nBot("tgbot.unlimited")).WithCallbackData(t.encodeQuery("add_client_reset_exp_c 0")),
  1624. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.custom")).WithCallbackData(t.encodeQuery("add_client_reset_exp_in 0")),
  1625. ),
  1626. tu.InlineKeyboardRow(
  1627. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 7 "+t.I18nBot("tgbot.days")).WithCallbackData(t.encodeQuery("add_client_reset_exp_c 7")),
  1628. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 10 "+t.I18nBot("tgbot.days")).WithCallbackData(t.encodeQuery("add_client_reset_exp_c 10")),
  1629. ),
  1630. tu.InlineKeyboardRow(
  1631. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 14 "+t.I18nBot("tgbot.days")).WithCallbackData(t.encodeQuery("add_client_reset_exp_c 14")),
  1632. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 20 "+t.I18nBot("tgbot.days")).WithCallbackData(t.encodeQuery("add_client_reset_exp_c 20")),
  1633. ),
  1634. tu.InlineKeyboardRow(
  1635. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 1 "+t.I18nBot("tgbot.month")).WithCallbackData(t.encodeQuery("add_client_reset_exp_c 30")),
  1636. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 3 "+t.I18nBot("tgbot.months")).WithCallbackData(t.encodeQuery("add_client_reset_exp_c 90")),
  1637. ),
  1638. tu.InlineKeyboardRow(
  1639. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 6 "+t.I18nBot("tgbot.months")).WithCallbackData(t.encodeQuery("add_client_reset_exp_c 180")),
  1640. tu.InlineKeyboardButton(t.I18nBot("tgbot.add")+" 12 "+t.I18nBot("tgbot.months")).WithCallbackData(t.encodeQuery("add_client_reset_exp_c 365")),
  1641. ),
  1642. )
  1643. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  1644. case "add_client_ch_default_ip_limit":
  1645. inlineKeyboard := tu.InlineKeyboard(
  1646. tu.InlineKeyboardRow(
  1647. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery("add_client_default_ip_limit")),
  1648. ),
  1649. tu.InlineKeyboardRow(
  1650. tu.InlineKeyboardButton(t.I18nBot("tgbot.unlimited")).WithCallbackData(t.encodeQuery("add_client_ip_limit_c 0")),
  1651. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.custom")).WithCallbackData(t.encodeQuery("add_client_ip_limit_in 0")),
  1652. ),
  1653. tu.InlineKeyboardRow(
  1654. tu.InlineKeyboardButton("1").WithCallbackData(t.encodeQuery("add_client_ip_limit_c 1")),
  1655. tu.InlineKeyboardButton("2").WithCallbackData(t.encodeQuery("add_client_ip_limit_c 2")),
  1656. ),
  1657. tu.InlineKeyboardRow(
  1658. tu.InlineKeyboardButton("3").WithCallbackData(t.encodeQuery("add_client_ip_limit_c 3")),
  1659. tu.InlineKeyboardButton("4").WithCallbackData(t.encodeQuery("add_client_ip_limit_c 4")),
  1660. ),
  1661. tu.InlineKeyboardRow(
  1662. tu.InlineKeyboardButton("5").WithCallbackData(t.encodeQuery("add_client_ip_limit_c 5")),
  1663. tu.InlineKeyboardButton("6").WithCallbackData(t.encodeQuery("add_client_ip_limit_c 6")),
  1664. tu.InlineKeyboardButton("7").WithCallbackData(t.encodeQuery("add_client_ip_limit_c 7")),
  1665. ),
  1666. tu.InlineKeyboardRow(
  1667. tu.InlineKeyboardButton("8").WithCallbackData(t.encodeQuery("add_client_ip_limit_c 8")),
  1668. tu.InlineKeyboardButton("9").WithCallbackData(t.encodeQuery("add_client_ip_limit_c 9")),
  1669. tu.InlineKeyboardButton("10").WithCallbackData(t.encodeQuery("add_client_ip_limit_c 10")),
  1670. ),
  1671. )
  1672. t.editMessageCallbackTgBot(chatId, callbackQuery.Message.GetMessageID(), inlineKeyboard)
  1673. case "add_client_default_info":
  1674. t.deleteMessageTgBot(chatId, callbackQuery.Message.GetMessageID())
  1675. t.SendMsgToTgbotDeleteAfter(chatId, t.I18nBot("tgbot.messages.using_default_value"), 3, tu.ReplyKeyboardRemove())
  1676. delete(userStates, chatId)
  1677. inbound, _ := t.inboundService.GetInbound(receiver_inbound_ID)
  1678. message_text, _ := t.BuildInboundClientDataMessage(inbound.Remark, inbound.Protocol)
  1679. t.addClient(chatId, message_text)
  1680. case "add_client_cancel":
  1681. delete(userStates, chatId)
  1682. t.deleteMessageTgBot(chatId, callbackQuery.Message.GetMessageID())
  1683. t.SendMsgToTgbotDeleteAfter(chatId, t.I18nBot("tgbot.messages.cancel"), 3, tu.ReplyKeyboardRemove())
  1684. case "add_client_default_traffic_exp":
  1685. messageId := callbackQuery.Message.GetMessageID()
  1686. inbound, err := t.inboundService.GetInbound(receiver_inbound_ID)
  1687. if err != nil {
  1688. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1689. return
  1690. }
  1691. message_text, err := t.BuildInboundClientDataMessage(inbound.Remark, inbound.Protocol)
  1692. if err != nil {
  1693. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1694. return
  1695. }
  1696. t.addClient(chatId, message_text, messageId)
  1697. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.canceled", "Email=="+client_Email))
  1698. case "add_client_default_ip_limit":
  1699. messageId := callbackQuery.Message.GetMessageID()
  1700. inbound, err := t.inboundService.GetInbound(receiver_inbound_ID)
  1701. if err != nil {
  1702. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1703. return
  1704. }
  1705. message_text, err := t.BuildInboundClientDataMessage(inbound.Remark, inbound.Protocol)
  1706. if err != nil {
  1707. t.sendCallbackAnswerTgBot(callbackQuery.ID, err.Error())
  1708. return
  1709. }
  1710. t.addClient(chatId, message_text, messageId)
  1711. t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.canceled", "Email=="+client_Email))
  1712. case "add_client_submit_disable":
  1713. client_Enable = false
  1714. _, err := t.SubmitAddClient()
  1715. if err != nil {
  1716. errorMessage := fmt.Sprintf("%v", err)
  1717. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.messages.error_add_client", "error=="+errorMessage), tu.ReplyKeyboardRemove())
  1718. } else {
  1719. t.deleteMessageTgBot(chatId, callbackQuery.Message.GetMessageID())
  1720. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.successfulOperation"), tu.ReplyKeyboardRemove())
  1721. }
  1722. case "add_client_submit_enable":
  1723. client_Enable = true
  1724. _, err := t.SubmitAddClient()
  1725. if err != nil {
  1726. errorMessage := fmt.Sprintf("%v", err)
  1727. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.messages.error_add_client", "error=="+errorMessage), tu.ReplyKeyboardRemove())
  1728. } else {
  1729. t.deleteMessageTgBot(chatId, callbackQuery.Message.GetMessageID())
  1730. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.successfulOperation"), tu.ReplyKeyboardRemove())
  1731. }
  1732. case "reset_all_traffics_cancel":
  1733. t.deleteMessageTgBot(chatId, callbackQuery.Message.GetMessageID())
  1734. t.SendMsgToTgbotDeleteAfter(chatId, t.I18nBot("tgbot.messages.cancel"), 1, tu.ReplyKeyboardRemove())
  1735. case "reset_all_traffics":
  1736. inlineKeyboard := tu.InlineKeyboard(
  1737. tu.InlineKeyboardRow(
  1738. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancelReset")).WithCallbackData(t.encodeQuery("reset_all_traffics_cancel")),
  1739. ),
  1740. tu.InlineKeyboardRow(
  1741. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmResetTraffic")).WithCallbackData(t.encodeQuery("reset_all_traffics_c")),
  1742. ),
  1743. )
  1744. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.messages.AreYouSure"), inlineKeyboard)
  1745. case "reset_all_traffics_c":
  1746. t.deleteMessageTgBot(chatId, callbackQuery.Message.GetMessageID())
  1747. emails, err := t.inboundService.getAllEmails()
  1748. if err != nil {
  1749. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.errorOperation"), tu.ReplyKeyboardRemove())
  1750. return
  1751. }
  1752. for _, email := range emails {
  1753. err := t.inboundService.ResetClientTrafficByEmail(email)
  1754. if err == nil {
  1755. msg := t.I18nBot("tgbot.messages.SuccessResetTraffic", "ClientEmail=="+email)
  1756. t.SendMsgToTgbot(chatId, msg, tu.ReplyKeyboardRemove())
  1757. } else {
  1758. msg := t.I18nBot("tgbot.messages.FailedResetTraffic", "ClientEmail=="+email, "ErrorMessage=="+err.Error())
  1759. t.SendMsgToTgbot(chatId, msg, tu.ReplyKeyboardRemove())
  1760. }
  1761. }
  1762. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.messages.FinishProcess"), tu.ReplyKeyboardRemove())
  1763. case "get_sorted_traffic_usage_report":
  1764. t.deleteMessageTgBot(chatId, callbackQuery.Message.GetMessageID())
  1765. emails, err := t.inboundService.getAllEmails()
  1766. if err != nil {
  1767. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.errorOperation"), tu.ReplyKeyboardRemove())
  1768. return
  1769. }
  1770. valid_emails, extra_emails, err := t.inboundService.FilterAndSortClientEmails(emails)
  1771. if err != nil {
  1772. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.errorOperation"), tu.ReplyKeyboardRemove())
  1773. return
  1774. }
  1775. for _, valid_emails := range valid_emails {
  1776. traffic, err := t.inboundService.GetClientTrafficByEmail(valid_emails)
  1777. if err != nil {
  1778. logger.Warning(err)
  1779. msg := t.I18nBot("tgbot.wentWrong")
  1780. t.SendMsgToTgbot(chatId, msg)
  1781. continue
  1782. }
  1783. if traffic == nil {
  1784. msg := t.I18nBot("tgbot.noResult")
  1785. t.SendMsgToTgbot(chatId, msg)
  1786. continue
  1787. }
  1788. output := t.clientInfoMsg(traffic, false, false, false, false, true, false)
  1789. t.SendMsgToTgbot(chatId, output, tu.ReplyKeyboardRemove())
  1790. }
  1791. for _, extra_emails := range extra_emails {
  1792. msg := fmt.Sprintf("📧 %s\n%s", extra_emails, t.I18nBot("tgbot.noResult"))
  1793. t.SendMsgToTgbot(chatId, msg, tu.ReplyKeyboardRemove())
  1794. }
  1795. default:
  1796. if after, ok := strings.CutPrefix(callbackQuery.Data, "client_sub_links "); ok {
  1797. email := after
  1798. t.sendClientSubLinks(chatId, email)
  1799. return
  1800. }
  1801. if after, ok := strings.CutPrefix(callbackQuery.Data, "client_individual_links "); ok {
  1802. email := after
  1803. t.sendClientIndividualLinks(chatId, email)
  1804. return
  1805. }
  1806. if after, ok := strings.CutPrefix(callbackQuery.Data, "client_qr_links "); ok {
  1807. email := after
  1808. t.sendClientQRLinks(chatId, email)
  1809. return
  1810. }
  1811. }
  1812. }
  1813. // BuildInboundClientDataMessage builds a message with client data for the given inbound and protocol.
  1814. func (t *Tgbot) BuildInboundClientDataMessage(inbound_remark string, protocol model.Protocol) (string, error) {
  1815. var message string
  1816. currentTime := time.Now()
  1817. timestampMillis := currentTime.UnixNano() / int64(time.Millisecond)
  1818. expiryTime := ""
  1819. diff := client_ExpiryTime/1000 - timestampMillis
  1820. if client_ExpiryTime == 0 {
  1821. expiryTime = t.I18nBot("tgbot.unlimited")
  1822. } else if diff > 172800 {
  1823. expiryTime = time.Unix((client_ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
  1824. } else if client_ExpiryTime < 0 {
  1825. expiryTime = fmt.Sprintf("%d %s", client_ExpiryTime/-86400000, t.I18nBot("tgbot.days"))
  1826. } else {
  1827. expiryTime = fmt.Sprintf("%d %s", diff/3600, t.I18nBot("tgbot.hours"))
  1828. }
  1829. traffic_value := ""
  1830. if client_TotalGB == 0 {
  1831. traffic_value = "♾️ Unlimited(Reset)"
  1832. } else {
  1833. traffic_value = common.FormatTraffic(client_TotalGB)
  1834. }
  1835. ip_limit := ""
  1836. if client_LimitIP == 0 {
  1837. ip_limit = "♾️ Unlimited(Reset)"
  1838. } else {
  1839. ip_limit = fmt.Sprint(client_LimitIP)
  1840. }
  1841. switch protocol {
  1842. case model.VMESS, model.VLESS:
  1843. message = t.I18nBot("tgbot.messages.inbound_client_data_id", "InboundRemark=="+inbound_remark, "ClientId=="+client_Id, "ClientEmail=="+client_Email, "ClientTraffic=="+traffic_value, "ClientExp=="+expiryTime, "IpLimit=="+ip_limit, "ClientComment=="+client_Comment)
  1844. case model.Trojan:
  1845. message = t.I18nBot("tgbot.messages.inbound_client_data_pass", "InboundRemark=="+inbound_remark, "ClientPass=="+client_TrPassword, "ClientEmail=="+client_Email, "ClientTraffic=="+traffic_value, "ClientExp=="+expiryTime, "IpLimit=="+ip_limit, "ClientComment=="+client_Comment)
  1846. case model.Shadowsocks:
  1847. message = t.I18nBot("tgbot.messages.inbound_client_data_pass", "InboundRemark=="+inbound_remark, "ClientPass=="+client_ShPassword, "ClientEmail=="+client_Email, "ClientTraffic=="+traffic_value, "ClientExp=="+expiryTime, "IpLimit=="+ip_limit, "ClientComment=="+client_Comment)
  1848. default:
  1849. return "", errors.New("unknown protocol")
  1850. }
  1851. return message, nil
  1852. }
  1853. // BuildJSONForProtocol builds a JSON string for the given protocol with client data.
  1854. func (t *Tgbot) BuildJSONForProtocol(protocol model.Protocol) (string, error) {
  1855. var jsonString string
  1856. switch protocol {
  1857. case model.VMESS:
  1858. jsonString = fmt.Sprintf(`{
  1859. "clients": [{
  1860. "id": "%s",
  1861. "security": "%s",
  1862. "email": "%s",
  1863. "limitIp": %d,
  1864. "totalGB": %d,
  1865. "expiryTime": %d,
  1866. "enable": %t,
  1867. "tgId": "%s",
  1868. "subId": "%s",
  1869. "comment": "%s",
  1870. "reset": %d
  1871. }]
  1872. }`, client_Id, client_Security, client_Email, client_LimitIP, client_TotalGB, client_ExpiryTime, client_Enable, client_TgID, client_SubID, client_Comment, client_Reset)
  1873. case model.VLESS:
  1874. jsonString = fmt.Sprintf(`{
  1875. "clients": [{
  1876. "id": "%s",
  1877. "flow": "%s",
  1878. "email": "%s",
  1879. "limitIp": %d,
  1880. "totalGB": %d,
  1881. "expiryTime": %d,
  1882. "enable": %t,
  1883. "tgId": "%s",
  1884. "subId": "%s",
  1885. "comment": "%s",
  1886. "reset": %d
  1887. }]
  1888. }`, client_Id, client_Flow, client_Email, client_LimitIP, client_TotalGB, client_ExpiryTime, client_Enable, client_TgID, client_SubID, client_Comment, client_Reset)
  1889. case model.Trojan:
  1890. jsonString = fmt.Sprintf(`{
  1891. "clients": [{
  1892. "password": "%s",
  1893. "email": "%s",
  1894. "limitIp": %d,
  1895. "totalGB": %d,
  1896. "expiryTime": %d,
  1897. "enable": %t,
  1898. "tgId": "%s",
  1899. "subId": "%s",
  1900. "comment": "%s",
  1901. "reset": %d
  1902. }]
  1903. }`, client_TrPassword, client_Email, client_LimitIP, client_TotalGB, client_ExpiryTime, client_Enable, client_TgID, client_SubID, client_Comment, client_Reset)
  1904. case model.Shadowsocks:
  1905. jsonString = fmt.Sprintf(`{
  1906. "clients": [{
  1907. "method": "%s",
  1908. "password": "%s",
  1909. "email": "%s",
  1910. "limitIp": %d,
  1911. "totalGB": %d,
  1912. "expiryTime": %d,
  1913. "enable": %t,
  1914. "tgId": "%s",
  1915. "subId": "%s",
  1916. "comment": "%s",
  1917. "reset": %d
  1918. }]
  1919. }`, client_Method, client_ShPassword, client_Email, client_LimitIP, client_TotalGB, client_ExpiryTime, client_Enable, client_TgID, client_SubID, client_Comment, client_Reset)
  1920. default:
  1921. return "", errors.New("unknown protocol")
  1922. }
  1923. return jsonString, nil
  1924. }
  1925. // SubmitAddClient submits the client addition request to the inbound service.
  1926. func (t *Tgbot) SubmitAddClient() (bool, error) {
  1927. inbound, err := t.inboundService.GetInbound(receiver_inbound_ID)
  1928. if err != nil {
  1929. logger.Warning("getIboundClients run failed:", err)
  1930. return false, errors.New(t.I18nBot("tgbot.answers.getInboundsFailed"))
  1931. }
  1932. jsonString, err := t.BuildJSONForProtocol(inbound.Protocol)
  1933. if err != nil {
  1934. logger.Warning("BuildJSONForProtocol run failed:", err)
  1935. return false, errors.New("failed to build JSON for protocol")
  1936. }
  1937. newInbound := &model.Inbound{
  1938. Id: receiver_inbound_ID,
  1939. Settings: jsonString,
  1940. }
  1941. return t.inboundService.AddInboundClient(newInbound)
  1942. }
  1943. // checkAdmin checks if the given Telegram ID is an admin.
  1944. func checkAdmin(tgId int64) bool {
  1945. for _, adminId := range adminIds {
  1946. if adminId == tgId {
  1947. return true
  1948. }
  1949. }
  1950. return false
  1951. }
  1952. // SendAnswer sends a response message with an inline keyboard to the specified chat.
  1953. func (t *Tgbot) SendAnswer(chatId int64, msg string, isAdmin bool) {
  1954. numericKeyboard := tu.InlineKeyboard(
  1955. tu.InlineKeyboardRow(
  1956. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.SortedTrafficUsageReport")).WithCallbackData(t.encodeQuery("get_sorted_traffic_usage_report")),
  1957. ),
  1958. tu.InlineKeyboardRow(
  1959. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.serverUsage")).WithCallbackData(t.encodeQuery("get_usage")),
  1960. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.ResetAllTraffics")).WithCallbackData(t.encodeQuery("reset_all_traffics")),
  1961. ),
  1962. tu.InlineKeyboardRow(
  1963. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.dbBackup")).WithCallbackData(t.encodeQuery("get_backup")),
  1964. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.getBanLogs")).WithCallbackData(t.encodeQuery("get_banlogs")),
  1965. ),
  1966. tu.InlineKeyboardRow(
  1967. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.getInbounds")).WithCallbackData(t.encodeQuery("inbounds")),
  1968. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.depleteSoon")).WithCallbackData(t.encodeQuery("deplete_soon")),
  1969. ),
  1970. tu.InlineKeyboardRow(
  1971. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.commands")).WithCallbackData(t.encodeQuery("commands")),
  1972. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.onlines")).WithCallbackData(t.encodeQuery("onlines")),
  1973. ),
  1974. tu.InlineKeyboardRow(
  1975. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.allClients")).WithCallbackData(t.encodeQuery("get_inbounds")),
  1976. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.addClient")).WithCallbackData(t.encodeQuery("add_client")),
  1977. ),
  1978. tu.InlineKeyboardRow(
  1979. tu.InlineKeyboardButton(t.I18nBot("pages.settings.subSettings")).WithCallbackData(t.encodeQuery("admin_client_sub_links")),
  1980. tu.InlineKeyboardButton(t.I18nBot("subscription.individualLinks")).WithCallbackData(t.encodeQuery("admin_client_individual_links")),
  1981. tu.InlineKeyboardButton(t.I18nBot("qrCode")).WithCallbackData(t.encodeQuery("admin_client_qr_links")),
  1982. ),
  1983. // TODOOOOOOOOOOOOOO: Add restart button here.
  1984. )
  1985. numericKeyboardClient := tu.InlineKeyboard(
  1986. tu.InlineKeyboardRow(
  1987. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.clientUsage")).WithCallbackData(t.encodeQuery("client_traffic")),
  1988. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.commands")).WithCallbackData(t.encodeQuery("client_commands")),
  1989. ),
  1990. tu.InlineKeyboardRow(
  1991. tu.InlineKeyboardButton(t.I18nBot("pages.settings.subSettings")).WithCallbackData(t.encodeQuery("client_sub_links")),
  1992. tu.InlineKeyboardButton(t.I18nBot("subscription.individualLinks")).WithCallbackData(t.encodeQuery("client_individual_links")),
  1993. ),
  1994. tu.InlineKeyboardRow(
  1995. tu.InlineKeyboardButton(t.I18nBot("qrCode")).WithCallbackData(t.encodeQuery("client_qr_links")),
  1996. ),
  1997. )
  1998. var ReplyMarkup telego.ReplyMarkup
  1999. if isAdmin {
  2000. ReplyMarkup = numericKeyboard
  2001. } else {
  2002. ReplyMarkup = numericKeyboardClient
  2003. }
  2004. t.SendMsgToTgbot(chatId, msg, ReplyMarkup)
  2005. }
  2006. // SendMsgToTgbot sends a message to the Telegram bot with optional reply markup.
  2007. func (t *Tgbot) SendMsgToTgbot(chatId int64, msg string, replyMarkup ...telego.ReplyMarkup) {
  2008. if !isRunning {
  2009. return
  2010. }
  2011. if msg == "" {
  2012. logger.Info("[tgbot] message is empty!")
  2013. return
  2014. }
  2015. var allMessages []string
  2016. limit := 2000
  2017. // paging message if it is big
  2018. if len(msg) > limit {
  2019. messages := strings.Split(msg, "\r\n\r\n")
  2020. lastIndex := -1
  2021. for _, message := range messages {
  2022. if (len(allMessages) == 0) || (len(allMessages[lastIndex])+len(message) > limit) {
  2023. allMessages = append(allMessages, message)
  2024. lastIndex++
  2025. } else {
  2026. allMessages[lastIndex] += "\r\n\r\n" + message
  2027. }
  2028. }
  2029. if strings.TrimSpace(allMessages[len(allMessages)-1]) == "" {
  2030. allMessages = allMessages[:len(allMessages)-1]
  2031. }
  2032. } else {
  2033. allMessages = append(allMessages, msg)
  2034. }
  2035. for n, message := range allMessages {
  2036. params := telego.SendMessageParams{
  2037. ChatID: tu.ID(chatId),
  2038. Text: message,
  2039. ParseMode: "HTML",
  2040. }
  2041. // only add replyMarkup to last message
  2042. if len(replyMarkup) > 0 && n == (len(allMessages)-1) {
  2043. params.ReplyMarkup = replyMarkup[0]
  2044. }
  2045. _, err := bot.SendMessage(context.Background(), &params)
  2046. if err != nil {
  2047. logger.Warning("Error sending telegram message :", err)
  2048. }
  2049. // Reduced delay to improve performance (only needed for rate limiting)
  2050. if n < len(allMessages)-1 { // Only delay between messages, not after the last one
  2051. time.Sleep(100 * time.Millisecond)
  2052. }
  2053. }
  2054. }
  2055. // buildSubscriptionURLs builds the HTML sub page URL and JSON subscription URL for a client email
  2056. func (t *Tgbot) buildSubscriptionURLs(email string) (string, string, error) {
  2057. // Resolve subId from client email
  2058. traffic, client, err := t.inboundService.GetClientByEmail(email)
  2059. _ = traffic
  2060. if err != nil || client == nil {
  2061. return "", "", errors.New("client not found")
  2062. }
  2063. // Gather settings to construct absolute URLs
  2064. subDomain, _ := t.settingService.GetSubDomain()
  2065. subPort, _ := t.settingService.GetSubPort()
  2066. subPath, _ := t.settingService.GetSubPath()
  2067. subJsonPath, _ := t.settingService.GetSubJsonPath()
  2068. subJsonEnable, _ := t.settingService.GetSubJsonEnable()
  2069. subKeyFile, _ := t.settingService.GetSubKeyFile()
  2070. subCertFile, _ := t.settingService.GetSubCertFile()
  2071. tls := (subKeyFile != "" && subCertFile != "")
  2072. scheme := "http"
  2073. if tls {
  2074. scheme = "https"
  2075. }
  2076. // Fallbacks
  2077. if subDomain == "" {
  2078. // try panel domain, otherwise OS hostname
  2079. if d, err := t.settingService.GetWebDomain(); err == nil && d != "" {
  2080. subDomain = d
  2081. } else if hostname != "" {
  2082. subDomain = hostname
  2083. } else {
  2084. subDomain = "localhost"
  2085. }
  2086. }
  2087. host := subDomain
  2088. if (subPort == 443 && tls) || (subPort == 80 && !tls) {
  2089. // standard ports: no port in host
  2090. } else {
  2091. host = fmt.Sprintf("%s:%d", subDomain, subPort)
  2092. }
  2093. // Ensure paths
  2094. if !strings.HasPrefix(subPath, "/") {
  2095. subPath = "/" + subPath
  2096. }
  2097. if !strings.HasSuffix(subPath, "/") {
  2098. subPath = subPath + "/"
  2099. }
  2100. if !strings.HasPrefix(subJsonPath, "/") {
  2101. subJsonPath = "/" + subJsonPath
  2102. }
  2103. if !strings.HasSuffix(subJsonPath, "/") {
  2104. subJsonPath = subJsonPath + "/"
  2105. }
  2106. subURL := fmt.Sprintf("%s://%s%s%s", scheme, host, subPath, client.SubID)
  2107. subJsonURL := fmt.Sprintf("%s://%s%s%s", scheme, host, subJsonPath, client.SubID)
  2108. if !subJsonEnable {
  2109. subJsonURL = ""
  2110. }
  2111. return subURL, subJsonURL, nil
  2112. }
  2113. // sendClientSubLinks sends the subscription links for the client to the chat.
  2114. func (t *Tgbot) sendClientSubLinks(chatId int64, email string) {
  2115. subURL, subJsonURL, err := t.buildSubscriptionURLs(email)
  2116. if err != nil {
  2117. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.errorOperation")+"\r\n"+err.Error())
  2118. return
  2119. }
  2120. msg := "Subscription URL:\r\n<code>" + subURL + "</code>"
  2121. if subJsonURL != "" {
  2122. msg += "\r\n\r\nJSON URL:\r\n<code>" + subJsonURL + "</code>"
  2123. }
  2124. inlineKeyboard := tu.InlineKeyboard(
  2125. tu.InlineKeyboardRow(
  2126. tu.InlineKeyboardButton(t.I18nBot("subscription.individualLinks")).WithCallbackData(t.encodeQuery("client_individual_links "+email)),
  2127. ),
  2128. tu.InlineKeyboardRow(
  2129. tu.InlineKeyboardButton(t.I18nBot("qrCode")).WithCallbackData(t.encodeQuery("client_qr_links "+email)),
  2130. ),
  2131. )
  2132. t.SendMsgToTgbot(chatId, msg, inlineKeyboard)
  2133. }
  2134. // sendClientIndividualLinks fetches the subscription content (individual links) and sends it to the user
  2135. func (t *Tgbot) sendClientIndividualLinks(chatId int64, email string) {
  2136. // Build the HTML sub page URL; we'll call it with header Accept to get raw content
  2137. subURL, _, err := t.buildSubscriptionURLs(email)
  2138. if err != nil {
  2139. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.errorOperation")+"\r\n"+err.Error())
  2140. return
  2141. }
  2142. // Try to fetch raw subscription links. Prefer plain text response.
  2143. req, err := http.NewRequest("GET", subURL, nil)
  2144. if err != nil {
  2145. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.errorOperation")+"\r\n"+err.Error())
  2146. return
  2147. }
  2148. // Force plain text to avoid HTML page; controller respects Accept header
  2149. req.Header.Set("Accept", "text/plain, */*;q=0.1")
  2150. // Use optimized client with connection pooling
  2151. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  2152. defer cancel()
  2153. req = req.WithContext(ctx)
  2154. resp, err := optimizedHTTPClient.Do(req)
  2155. if err != nil {
  2156. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.errorOperation")+"\r\n"+err.Error())
  2157. return
  2158. }
  2159. defer resp.Body.Close()
  2160. bodyBytes, err := io.ReadAll(resp.Body)
  2161. if err != nil {
  2162. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.errorOperation")+"\r\n"+err.Error())
  2163. return
  2164. }
  2165. // If service is configured to encode (Base64), decode it
  2166. encoded, _ := t.settingService.GetSubEncrypt()
  2167. var content string
  2168. if encoded {
  2169. decoded, err := base64.StdEncoding.DecodeString(string(bodyBytes))
  2170. if err != nil {
  2171. // fallback to raw text
  2172. content = string(bodyBytes)
  2173. } else {
  2174. content = string(decoded)
  2175. }
  2176. } else {
  2177. content = string(bodyBytes)
  2178. }
  2179. // Normalize line endings and trim
  2180. lines := strings.Split(strings.ReplaceAll(content, "\r\n", "\n"), "\n")
  2181. var cleaned []string
  2182. for _, l := range lines {
  2183. l = strings.TrimSpace(l)
  2184. if l != "" {
  2185. cleaned = append(cleaned, l)
  2186. }
  2187. }
  2188. if len(cleaned) == 0 {
  2189. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.noResult"))
  2190. return
  2191. }
  2192. // Send in chunks to respect message length; use monospace formatting
  2193. const maxPerMessage = 50
  2194. for i := 0; i < len(cleaned); i += maxPerMessage {
  2195. j := i + maxPerMessage
  2196. if j > len(cleaned) {
  2197. j = len(cleaned)
  2198. }
  2199. chunk := cleaned[i:j]
  2200. msg := t.I18nBot("subscription.individualLinks") + ":\r\n"
  2201. for _, link := range chunk {
  2202. // wrap each link in <code>
  2203. msg += "<code>" + link + "</code>\r\n"
  2204. }
  2205. t.SendMsgToTgbot(chatId, msg)
  2206. }
  2207. }
  2208. // sendClientQRLinks generates QR images for subscription URL, JSON URL, and a few individual links, then sends them
  2209. func (t *Tgbot) sendClientQRLinks(chatId int64, email string) {
  2210. subURL, subJsonURL, err := t.buildSubscriptionURLs(email)
  2211. if err != nil {
  2212. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.errorOperation")+"\r\n"+err.Error())
  2213. return
  2214. }
  2215. // Helper to create QR PNG bytes from content
  2216. createQR := func(content string, size int) ([]byte, error) {
  2217. if size <= 0 {
  2218. size = 256
  2219. }
  2220. return qrcode.Encode(content, qrcode.Medium, size)
  2221. }
  2222. // Inform user
  2223. t.SendMsgToTgbot(chatId, "QRCode"+":")
  2224. // Send sub URL QR (filename: sub.png)
  2225. if png, err := createQR(subURL, 320); err == nil {
  2226. document := tu.Document(
  2227. tu.ID(chatId),
  2228. tu.FileFromBytes(png, "sub.png"),
  2229. )
  2230. _, _ = bot.SendDocument(context.Background(), document)
  2231. } else {
  2232. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.errorOperation")+"\r\n"+err.Error())
  2233. }
  2234. // Send JSON URL QR (filename: subjson.png) when available
  2235. if subJsonURL != "" {
  2236. if png, err := createQR(subJsonURL, 320); err == nil {
  2237. document := tu.Document(
  2238. tu.ID(chatId),
  2239. tu.FileFromBytes(png, "subjson.png"),
  2240. )
  2241. _, _ = bot.SendDocument(context.Background(), document)
  2242. } else {
  2243. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.errorOperation")+"\r\n"+err.Error())
  2244. }
  2245. }
  2246. // Also generate a few individual links' QRs (first up to 5)
  2247. subPageURL := subURL
  2248. req, err := http.NewRequest("GET", subPageURL, nil)
  2249. if err == nil {
  2250. req.Header.Set("Accept", "text/plain, */*;q=0.1")
  2251. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  2252. defer cancel()
  2253. req = req.WithContext(ctx)
  2254. if resp, err := optimizedHTTPClient.Do(req); err == nil {
  2255. body, _ := io.ReadAll(resp.Body)
  2256. _ = resp.Body.Close()
  2257. encoded, _ := t.settingService.GetSubEncrypt()
  2258. var content string
  2259. if encoded {
  2260. if dec, err := base64.StdEncoding.DecodeString(string(body)); err == nil {
  2261. content = string(dec)
  2262. } else {
  2263. content = string(body)
  2264. }
  2265. } else {
  2266. content = string(body)
  2267. }
  2268. lines := strings.Split(strings.ReplaceAll(content, "\r\n", "\n"), "\n")
  2269. var cleaned []string
  2270. for _, l := range lines {
  2271. l = strings.TrimSpace(l)
  2272. if l != "" {
  2273. cleaned = append(cleaned, l)
  2274. }
  2275. }
  2276. if len(cleaned) > 0 {
  2277. max := min(len(cleaned), 5)
  2278. for i := range max {
  2279. if png, err := createQR(cleaned[i], 320); err == nil {
  2280. // Use the email as filename for individual link QR
  2281. filename := email + ".png"
  2282. document := tu.Document(
  2283. tu.ID(chatId),
  2284. tu.FileFromBytes(png, filename),
  2285. )
  2286. _, _ = bot.SendDocument(context.Background(), document)
  2287. // Reduced delay for better performance
  2288. if i < max-1 { // Only delay between documents, not after the last one
  2289. time.Sleep(50 * time.Millisecond)
  2290. }
  2291. }
  2292. }
  2293. }
  2294. }
  2295. }
  2296. }
  2297. // SendMsgToTgbotAdmins sends a message to all admin Telegram chats.
  2298. func (t *Tgbot) SendMsgToTgbotAdmins(msg string, replyMarkup ...telego.ReplyMarkup) {
  2299. if len(replyMarkup) > 0 {
  2300. for _, adminId := range adminIds {
  2301. t.SendMsgToTgbot(adminId, msg, replyMarkup[0])
  2302. }
  2303. } else {
  2304. for _, adminId := range adminIds {
  2305. t.SendMsgToTgbot(adminId, msg)
  2306. }
  2307. }
  2308. }
  2309. // SendReport sends a periodic report to admin chats.
  2310. func (t *Tgbot) SendReport() {
  2311. runTime, err := t.settingService.GetTgbotRuntime()
  2312. if err == nil && len(runTime) > 0 {
  2313. msg := ""
  2314. msg += t.I18nBot("tgbot.messages.report", "RunTime=="+runTime)
  2315. msg += t.I18nBot("tgbot.messages.datetime", "DateTime=="+time.Now().Format("2006-01-02 15:04:05"))
  2316. t.SendMsgToTgbotAdmins(msg)
  2317. }
  2318. info := t.sendServerUsage()
  2319. t.SendMsgToTgbotAdmins(info)
  2320. t.sendExhaustedToAdmins()
  2321. t.notifyExhausted()
  2322. backupEnable, err := t.settingService.GetTgBotBackup()
  2323. if err == nil && backupEnable {
  2324. t.SendBackupToAdmins()
  2325. }
  2326. }
  2327. // SendBackupToAdmins sends a database backup to admin chats.
  2328. func (t *Tgbot) SendBackupToAdmins() {
  2329. if !t.IsRunning() {
  2330. return
  2331. }
  2332. for _, adminId := range adminIds {
  2333. t.sendBackup(int64(adminId))
  2334. }
  2335. }
  2336. // sendExhaustedToAdmins sends notifications about exhausted clients to admins.
  2337. func (t *Tgbot) sendExhaustedToAdmins() {
  2338. if !t.IsRunning() {
  2339. return
  2340. }
  2341. for _, adminId := range adminIds {
  2342. t.getExhausted(int64(adminId))
  2343. }
  2344. }
  2345. // getServerUsage retrieves and formats server usage information.
  2346. func (t *Tgbot) getServerUsage(chatId int64, messageID ...int) string {
  2347. info := t.prepareServerUsageInfo()
  2348. keyboard := tu.InlineKeyboard(tu.InlineKeyboardRow(
  2349. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.refresh")).WithCallbackData(t.encodeQuery("usage_refresh"))))
  2350. if len(messageID) > 0 {
  2351. t.editMessageTgBot(chatId, messageID[0], info, keyboard)
  2352. } else {
  2353. t.SendMsgToTgbot(chatId, info, keyboard)
  2354. }
  2355. return info
  2356. }
  2357. // Send server usage without an inline keyboard
  2358. func (t *Tgbot) sendServerUsage() string {
  2359. info := t.prepareServerUsageInfo()
  2360. return info
  2361. }
  2362. // prepareServerUsageInfo prepares the server usage information string.
  2363. func (t *Tgbot) prepareServerUsageInfo() string {
  2364. // Check if we have cached data first
  2365. if cachedStats, found := t.getCachedServerStats(); found {
  2366. return cachedStats
  2367. }
  2368. info, ipv4, ipv6 := "", "", ""
  2369. // get latest status of server with caching
  2370. if cachedStatus, found := t.getCachedStatus(); found {
  2371. t.lastStatus = cachedStatus
  2372. } else {
  2373. t.lastStatus = t.serverService.GetStatus(t.lastStatus)
  2374. t.setCachedStatus(t.lastStatus)
  2375. }
  2376. onlines := p.GetOnlineClients()
  2377. info += t.I18nBot("tgbot.messages.hostname", "Hostname=="+hostname)
  2378. info += t.I18nBot("tgbot.messages.version", "Version=="+config.GetVersion())
  2379. info += t.I18nBot("tgbot.messages.xrayVersion", "XrayVersion=="+fmt.Sprint(t.lastStatus.Xray.Version))
  2380. // get ip address
  2381. netInterfaces, err := net.Interfaces()
  2382. if err != nil {
  2383. logger.Error("net.Interfaces failed, err: ", err.Error())
  2384. info += t.I18nBot("tgbot.messages.ip", "IP=="+t.I18nBot("tgbot.unknown"))
  2385. info += "\r\n"
  2386. } else {
  2387. for i := 0; i < len(netInterfaces); i++ {
  2388. if (netInterfaces[i].Flags & net.FlagUp) != 0 {
  2389. addrs, _ := netInterfaces[i].Addrs()
  2390. for _, address := range addrs {
  2391. if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
  2392. if ipnet.IP.To4() != nil {
  2393. ipv4 += ipnet.IP.String() + " "
  2394. } else if ipnet.IP.To16() != nil && !ipnet.IP.IsLinkLocalUnicast() {
  2395. ipv6 += ipnet.IP.String() + " "
  2396. }
  2397. }
  2398. }
  2399. }
  2400. }
  2401. info += t.I18nBot("tgbot.messages.ipv4", "IPv4=="+ipv4)
  2402. info += t.I18nBot("tgbot.messages.ipv6", "IPv6=="+ipv6)
  2403. }
  2404. info += t.I18nBot("tgbot.messages.serverUpTime", "UpTime=="+strconv.FormatUint(t.lastStatus.Uptime/86400, 10), "Unit=="+t.I18nBot("tgbot.days"))
  2405. 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))
  2406. info += t.I18nBot("tgbot.messages.serverMemory", "Current=="+common.FormatTraffic(int64(t.lastStatus.Mem.Current)), "Total=="+common.FormatTraffic(int64(t.lastStatus.Mem.Total)))
  2407. info += t.I18nBot("tgbot.messages.onlinesCount", "Count=="+fmt.Sprint(len(onlines)))
  2408. info += t.I18nBot("tgbot.messages.tcpCount", "Count=="+strconv.Itoa(t.lastStatus.TcpCount))
  2409. info += t.I18nBot("tgbot.messages.udpCount", "Count=="+strconv.Itoa(t.lastStatus.UdpCount))
  2410. 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)))
  2411. info += t.I18nBot("tgbot.messages.xrayStatus", "State=="+fmt.Sprint(t.lastStatus.Xray.State))
  2412. // Cache the complete server stats
  2413. t.setCachedServerStats(info)
  2414. return info
  2415. }
  2416. // UserLoginNotify sends a notification about user login attempts to admins.
  2417. func (t *Tgbot) UserLoginNotify(username string, password string, ip string, time string, status LoginStatus) {
  2418. if !t.IsRunning() {
  2419. return
  2420. }
  2421. if username == "" || ip == "" || time == "" {
  2422. logger.Warning("UserLoginNotify failed, invalid info!")
  2423. return
  2424. }
  2425. loginNotifyEnabled, err := t.settingService.GetTgBotLoginNotify()
  2426. if err != nil || !loginNotifyEnabled {
  2427. return
  2428. }
  2429. msg := ""
  2430. switch status {
  2431. case LoginSuccess:
  2432. msg += t.I18nBot("tgbot.messages.loginSuccess")
  2433. msg += t.I18nBot("tgbot.messages.hostname", "Hostname=="+hostname)
  2434. case LoginFail:
  2435. msg += t.I18nBot("tgbot.messages.loginFailed")
  2436. msg += t.I18nBot("tgbot.messages.hostname", "Hostname=="+hostname)
  2437. msg += t.I18nBot("tgbot.messages.password", "Password=="+password)
  2438. }
  2439. msg += t.I18nBot("tgbot.messages.username", "Username=="+username)
  2440. msg += t.I18nBot("tgbot.messages.ip", "IP=="+ip)
  2441. msg += t.I18nBot("tgbot.messages.time", "Time=="+time)
  2442. t.SendMsgToTgbotAdmins(msg)
  2443. }
  2444. // getInboundUsages retrieves and formats inbound usage information.
  2445. func (t *Tgbot) getInboundUsages() string {
  2446. info := ""
  2447. // get traffic
  2448. inbounds, err := t.inboundService.GetAllInbounds()
  2449. if err != nil {
  2450. logger.Warning("GetAllInbounds run failed:", err)
  2451. info += t.I18nBot("tgbot.answers.getInboundsFailed")
  2452. } else {
  2453. // NOTE:If there no any sessions here,need to notify here
  2454. // TODO:Sub-node push, automatic conversion format
  2455. for _, inbound := range inbounds {
  2456. info += t.I18nBot("tgbot.messages.inbound", "Remark=="+inbound.Remark)
  2457. info += t.I18nBot("tgbot.messages.port", "Port=="+strconv.Itoa(inbound.Port))
  2458. info += t.I18nBot("tgbot.messages.traffic", "Total=="+common.FormatTraffic((inbound.Up+inbound.Down)), "Upload=="+common.FormatTraffic(inbound.Up), "Download=="+common.FormatTraffic(inbound.Down))
  2459. if inbound.ExpiryTime == 0 {
  2460. info += t.I18nBot("tgbot.messages.expire", "Time=="+t.I18nBot("tgbot.unlimited"))
  2461. } else {
  2462. info += t.I18nBot("tgbot.messages.expire", "Time=="+time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05"))
  2463. }
  2464. info += "\r\n"
  2465. }
  2466. }
  2467. return info
  2468. }
  2469. // getInbounds creates an inline keyboard with all inbounds.
  2470. func (t *Tgbot) getInbounds() (*telego.InlineKeyboardMarkup, error) {
  2471. inbounds, err := t.inboundService.GetAllInbounds()
  2472. if err != nil {
  2473. logger.Warning("GetAllInbounds run failed:", err)
  2474. return nil, errors.New(t.I18nBot("tgbot.answers.getInboundsFailed"))
  2475. }
  2476. if len(inbounds) == 0 {
  2477. logger.Warning("No inbounds found")
  2478. return nil, errors.New(t.I18nBot("tgbot.answers.getInboundsFailed"))
  2479. }
  2480. var buttons []telego.InlineKeyboardButton
  2481. for _, inbound := range inbounds {
  2482. status := "❌"
  2483. if inbound.Enable {
  2484. status = "✅"
  2485. }
  2486. callbackData := t.encodeQuery(fmt.Sprintf("%s %d", "get_clients", inbound.Id))
  2487. buttons = append(buttons, tu.InlineKeyboardButton(fmt.Sprintf("%v - %v", inbound.Remark, status)).WithCallbackData(callbackData))
  2488. }
  2489. cols := 1
  2490. if len(buttons) >= 6 {
  2491. cols = 2
  2492. }
  2493. keyboard := tu.InlineKeyboardGrid(tu.InlineKeyboardCols(cols, buttons...))
  2494. return keyboard, nil
  2495. }
  2496. // getInboundsFor builds an inline keyboard of inbounds for a custom next action.
  2497. func (t *Tgbot) getInboundsFor(nextAction string) (*telego.InlineKeyboardMarkup, error) {
  2498. inbounds, err := t.inboundService.GetAllInbounds()
  2499. if err != nil {
  2500. logger.Warning("GetAllInbounds run failed:", err)
  2501. return nil, errors.New(t.I18nBot("tgbot.answers.getInboundsFailed"))
  2502. }
  2503. if len(inbounds) == 0 {
  2504. logger.Warning("No inbounds found")
  2505. return nil, errors.New(t.I18nBot("tgbot.answers.getInboundsFailed"))
  2506. }
  2507. var buttons []telego.InlineKeyboardButton
  2508. for _, inbound := range inbounds {
  2509. status := "❌"
  2510. if inbound.Enable {
  2511. status = "✅"
  2512. }
  2513. callbackData := t.encodeQuery(fmt.Sprintf("%s %d", nextAction, inbound.Id))
  2514. buttons = append(buttons, tu.InlineKeyboardButton(fmt.Sprintf("%v - %v", inbound.Remark, status)).WithCallbackData(callbackData))
  2515. }
  2516. cols := 1
  2517. if len(buttons) >= 6 {
  2518. cols = 2
  2519. }
  2520. keyboard := tu.InlineKeyboardGrid(tu.InlineKeyboardCols(cols, buttons...))
  2521. return keyboard, nil
  2522. }
  2523. // getInboundClientsFor lists clients of an inbound with a specific action prefix to be appended with email
  2524. func (t *Tgbot) getInboundClientsFor(inboundID int, action string) (*telego.InlineKeyboardMarkup, error) {
  2525. inbound, err := t.inboundService.GetInbound(inboundID)
  2526. if err != nil {
  2527. logger.Warning("getInboundClientsFor run failed:", err)
  2528. return nil, errors.New(t.I18nBot("tgbot.answers.getInboundsFailed"))
  2529. }
  2530. clients, err := t.inboundService.GetClients(inbound)
  2531. var buttons []telego.InlineKeyboardButton
  2532. if err != nil {
  2533. logger.Warning("GetInboundClients run failed:", err)
  2534. return nil, errors.New(t.I18nBot("tgbot.answers.getInboundsFailed"))
  2535. } else {
  2536. if len(clients) > 0 {
  2537. for _, client := range clients {
  2538. buttons = append(buttons, tu.InlineKeyboardButton(client.Email).WithCallbackData(t.encodeQuery(action+" "+client.Email)))
  2539. }
  2540. } else {
  2541. return nil, errors.New(t.I18nBot("tgbot.answers.getClientsFailed"))
  2542. }
  2543. }
  2544. cols := 0
  2545. if len(buttons) < 6 {
  2546. cols = 3
  2547. } else {
  2548. cols = 2
  2549. }
  2550. keyboard := tu.InlineKeyboardGrid(tu.InlineKeyboardCols(cols, buttons...))
  2551. return keyboard, nil
  2552. }
  2553. // getInboundsAddClient creates an inline keyboard for adding clients to inbounds.
  2554. func (t *Tgbot) getInboundsAddClient() (*telego.InlineKeyboardMarkup, error) {
  2555. inbounds, err := t.inboundService.GetAllInbounds()
  2556. if err != nil {
  2557. logger.Warning("GetAllInbounds run failed:", err)
  2558. return nil, errors.New(t.I18nBot("tgbot.answers.getInboundsFailed"))
  2559. }
  2560. if len(inbounds) == 0 {
  2561. logger.Warning("No inbounds found")
  2562. return nil, errors.New(t.I18nBot("tgbot.answers.getInboundsFailed"))
  2563. }
  2564. excludedProtocols := map[model.Protocol]bool{
  2565. model.Tunnel: true,
  2566. model.Mixed: true,
  2567. model.WireGuard: true,
  2568. model.HTTP: true,
  2569. }
  2570. var buttons []telego.InlineKeyboardButton
  2571. for _, inbound := range inbounds {
  2572. if excludedProtocols[inbound.Protocol] {
  2573. continue
  2574. }
  2575. status := "❌"
  2576. if inbound.Enable {
  2577. status = "✅"
  2578. }
  2579. callbackData := t.encodeQuery(fmt.Sprintf("%s %d", "add_client_to", inbound.Id))
  2580. buttons = append(buttons, tu.InlineKeyboardButton(fmt.Sprintf("%v - %v", inbound.Remark, status)).WithCallbackData(callbackData))
  2581. }
  2582. cols := 1
  2583. if len(buttons) >= 6 {
  2584. cols = 2
  2585. }
  2586. keyboard := tu.InlineKeyboardGrid(tu.InlineKeyboardCols(cols, buttons...))
  2587. return keyboard, nil
  2588. }
  2589. // getInboundClients creates an inline keyboard with clients of a specific inbound.
  2590. func (t *Tgbot) getInboundClients(id int) (*telego.InlineKeyboardMarkup, error) {
  2591. inbound, err := t.inboundService.GetInbound(id)
  2592. if err != nil {
  2593. logger.Warning("getIboundClients run failed:", err)
  2594. return nil, errors.New(t.I18nBot("tgbot.answers.getInboundsFailed"))
  2595. }
  2596. clients, err := t.inboundService.GetClients(inbound)
  2597. var buttons []telego.InlineKeyboardButton
  2598. if err != nil {
  2599. logger.Warning("GetInboundClients run failed:", err)
  2600. return nil, errors.New(t.I18nBot("tgbot.answers.getInboundsFailed"))
  2601. } else {
  2602. if len(clients) > 0 {
  2603. for _, client := range clients {
  2604. buttons = append(buttons, tu.InlineKeyboardButton(client.Email).WithCallbackData(t.encodeQuery("client_get_usage "+client.Email)))
  2605. }
  2606. } else {
  2607. return nil, errors.New(t.I18nBot("tgbot.answers.getClientsFailed"))
  2608. }
  2609. }
  2610. cols := 0
  2611. if len(buttons) < 6 {
  2612. cols = 3
  2613. } else {
  2614. cols = 2
  2615. }
  2616. keyboard := tu.InlineKeyboardGrid(tu.InlineKeyboardCols(cols, buttons...))
  2617. return keyboard, nil
  2618. }
  2619. // clientInfoMsg formats client information message based on traffic and flags.
  2620. func (t *Tgbot) clientInfoMsg(
  2621. traffic *xray.ClientTraffic,
  2622. printEnabled bool,
  2623. printOnline bool,
  2624. printActive bool,
  2625. printDate bool,
  2626. printTraffic bool,
  2627. printRefreshed bool,
  2628. ) string {
  2629. now := time.Now().Unix()
  2630. expiryTime := ""
  2631. flag := false
  2632. diff := traffic.ExpiryTime/1000 - now
  2633. if traffic.ExpiryTime == 0 {
  2634. expiryTime = t.I18nBot("tgbot.unlimited")
  2635. } else if diff > 172800 || !traffic.Enable {
  2636. expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
  2637. if diff > 0 {
  2638. days := diff / 86400
  2639. hours := (diff % 86400) / 3600
  2640. minutes := (diff % 3600) / 60
  2641. remainingTime := ""
  2642. if days > 0 {
  2643. remainingTime += fmt.Sprintf("%d %s ", days, t.I18nBot("tgbot.days"))
  2644. }
  2645. if hours > 0 {
  2646. remainingTime += fmt.Sprintf("%d %s ", hours, t.I18nBot("tgbot.hours"))
  2647. }
  2648. if minutes > 0 {
  2649. remainingTime += fmt.Sprintf("%d %s", minutes, t.I18nBot("tgbot.minutes"))
  2650. }
  2651. expiryTime += fmt.Sprintf(" (%s)", remainingTime)
  2652. }
  2653. } else if traffic.ExpiryTime < 0 {
  2654. expiryTime = fmt.Sprintf("%d %s", traffic.ExpiryTime/-86400000, t.I18nBot("tgbot.days"))
  2655. flag = true
  2656. } else {
  2657. expiryTime = fmt.Sprintf("%d %s", diff/3600, t.I18nBot("tgbot.hours"))
  2658. flag = true
  2659. }
  2660. total := ""
  2661. if traffic.Total == 0 {
  2662. total = t.I18nBot("tgbot.unlimited")
  2663. } else {
  2664. total = common.FormatTraffic((traffic.Total))
  2665. }
  2666. enabled := ""
  2667. isEnabled, err := t.inboundService.checkIsEnabledByEmail(traffic.Email)
  2668. if err != nil {
  2669. logger.Warning(err)
  2670. enabled = t.I18nBot("tgbot.wentWrong")
  2671. } else if isEnabled {
  2672. enabled = t.I18nBot("tgbot.messages.yes")
  2673. } else {
  2674. enabled = t.I18nBot("tgbot.messages.no")
  2675. }
  2676. active := ""
  2677. if traffic.Enable {
  2678. active = t.I18nBot("tgbot.messages.yes")
  2679. } else {
  2680. active = t.I18nBot("tgbot.messages.no")
  2681. }
  2682. status := t.I18nBot("tgbot.offline")
  2683. if p.IsRunning() {
  2684. for _, online := range p.GetOnlineClients() {
  2685. if online == traffic.Email {
  2686. status = t.I18nBot("tgbot.online")
  2687. break
  2688. }
  2689. }
  2690. }
  2691. output := ""
  2692. output += t.I18nBot("tgbot.messages.email", "Email=="+traffic.Email)
  2693. if printEnabled {
  2694. output += t.I18nBot("tgbot.messages.enabled", "Enable=="+enabled)
  2695. }
  2696. if printOnline {
  2697. output += t.I18nBot("tgbot.messages.online", "Status=="+status)
  2698. }
  2699. if printActive {
  2700. output += t.I18nBot("tgbot.messages.active", "Enable=="+active)
  2701. }
  2702. if printDate {
  2703. if flag {
  2704. output += t.I18nBot("tgbot.messages.expireIn", "Time=="+expiryTime)
  2705. } else {
  2706. output += t.I18nBot("tgbot.messages.expire", "Time=="+expiryTime)
  2707. }
  2708. }
  2709. if printTraffic {
  2710. output += t.I18nBot("tgbot.messages.upload", "Upload=="+common.FormatTraffic(traffic.Up))
  2711. output += t.I18nBot("tgbot.messages.download", "Download=="+common.FormatTraffic(traffic.Down))
  2712. output += t.I18nBot("tgbot.messages.total", "UpDown=="+common.FormatTraffic((traffic.Up+traffic.Down)), "Total=="+total)
  2713. }
  2714. if printRefreshed {
  2715. output += t.I18nBot("tgbot.messages.refreshedOn", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
  2716. }
  2717. return output
  2718. }
  2719. // getClientUsage retrieves and sends client usage information to the chat.
  2720. func (t *Tgbot) getClientUsage(chatId int64, tgUserID int64, email ...string) {
  2721. traffics, err := t.inboundService.GetClientTrafficTgBot(tgUserID)
  2722. if err != nil {
  2723. logger.Warning(err)
  2724. msg := t.I18nBot("tgbot.wentWrong")
  2725. t.SendMsgToTgbot(chatId, msg)
  2726. return
  2727. }
  2728. if len(traffics) == 0 {
  2729. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.askToAddUserId", "TgUserID=="+strconv.FormatInt(tgUserID, 10)))
  2730. return
  2731. }
  2732. output := ""
  2733. if len(traffics) > 0 {
  2734. if len(email) > 0 {
  2735. for _, traffic := range traffics {
  2736. if traffic.Email == email[0] {
  2737. output := t.clientInfoMsg(traffic, true, true, true, true, true, true)
  2738. t.SendMsgToTgbot(chatId, output)
  2739. return
  2740. }
  2741. }
  2742. msg := t.I18nBot("tgbot.noResult")
  2743. t.SendMsgToTgbot(chatId, msg)
  2744. return
  2745. } else {
  2746. for _, traffic := range traffics {
  2747. output += t.clientInfoMsg(traffic, true, true, true, true, true, false)
  2748. output += "\r\n"
  2749. }
  2750. }
  2751. }
  2752. output += t.I18nBot("tgbot.messages.refreshedOn", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
  2753. t.SendMsgToTgbot(chatId, output)
  2754. output = t.I18nBot("tgbot.commands.pleaseChoose")
  2755. t.SendAnswer(chatId, output, false)
  2756. }
  2757. // searchClientIps searches and sends client IP addresses for the given email.
  2758. func (t *Tgbot) searchClientIps(chatId int64, email string, messageID ...int) {
  2759. ips, err := t.inboundService.GetInboundClientIps(email)
  2760. if err != nil || len(ips) == 0 {
  2761. ips = t.I18nBot("tgbot.noIpRecord")
  2762. }
  2763. output := ""
  2764. output += t.I18nBot("tgbot.messages.email", "Email=="+email)
  2765. output += t.I18nBot("tgbot.messages.ips", "IPs=="+ips)
  2766. output += t.I18nBot("tgbot.messages.refreshedOn", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
  2767. inlineKeyboard := tu.InlineKeyboard(
  2768. tu.InlineKeyboardRow(
  2769. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.refresh")).WithCallbackData(t.encodeQuery("ips_refresh "+email)),
  2770. ),
  2771. tu.InlineKeyboardRow(
  2772. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.clearIPs")).WithCallbackData(t.encodeQuery("clear_ips "+email)),
  2773. ),
  2774. )
  2775. if len(messageID) > 0 {
  2776. t.editMessageTgBot(chatId, messageID[0], output, inlineKeyboard)
  2777. } else {
  2778. t.SendMsgToTgbot(chatId, output, inlineKeyboard)
  2779. }
  2780. }
  2781. // clientTelegramUserInfo retrieves and sends Telegram user info for the client.
  2782. func (t *Tgbot) clientTelegramUserInfo(chatId int64, email string, messageID ...int) {
  2783. traffic, client, err := t.inboundService.GetClientByEmail(email)
  2784. if err != nil {
  2785. logger.Warning(err)
  2786. msg := t.I18nBot("tgbot.wentWrong")
  2787. t.SendMsgToTgbot(chatId, msg)
  2788. return
  2789. }
  2790. if client == nil {
  2791. msg := t.I18nBot("tgbot.noResult")
  2792. t.SendMsgToTgbot(chatId, msg)
  2793. return
  2794. }
  2795. tgId := "None"
  2796. if client.TgID != 0 {
  2797. tgId = strconv.FormatInt(client.TgID, 10)
  2798. }
  2799. output := ""
  2800. output += t.I18nBot("tgbot.messages.email", "Email=="+email)
  2801. output += t.I18nBot("tgbot.messages.TGUser", "TelegramID=="+tgId)
  2802. output += t.I18nBot("tgbot.messages.refreshedOn", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
  2803. inlineKeyboard := tu.InlineKeyboard(
  2804. tu.InlineKeyboardRow(
  2805. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.refresh")).WithCallbackData(t.encodeQuery("tgid_refresh "+email)),
  2806. ),
  2807. tu.InlineKeyboardRow(
  2808. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.removeTGUser")).WithCallbackData(t.encodeQuery("tgid_remove "+email)),
  2809. ),
  2810. )
  2811. if len(messageID) > 0 {
  2812. t.editMessageTgBot(chatId, messageID[0], output, inlineKeyboard)
  2813. } else {
  2814. t.SendMsgToTgbot(chatId, output, inlineKeyboard)
  2815. requestUser := telego.KeyboardButtonRequestUsers{
  2816. RequestID: int32(traffic.Id),
  2817. UserIsBot: new(bool),
  2818. }
  2819. keyboard := tu.Keyboard(
  2820. tu.KeyboardRow(
  2821. tu.KeyboardButton(t.I18nBot("tgbot.buttons.selectTGUser")).WithRequestUsers(&requestUser),
  2822. ),
  2823. tu.KeyboardRow(
  2824. tu.KeyboardButton(t.I18nBot("tgbot.buttons.closeKeyboard")),
  2825. ),
  2826. ).WithIsPersistent().WithResizeKeyboard()
  2827. t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.buttons.selectOneTGUser"), keyboard)
  2828. }
  2829. }
  2830. // searchClient searches for a client by email and sends the information.
  2831. func (t *Tgbot) searchClient(chatId int64, email string, messageID ...int) {
  2832. traffic, err := t.inboundService.GetClientTrafficByEmail(email)
  2833. if err != nil {
  2834. logger.Warning(err)
  2835. msg := t.I18nBot("tgbot.wentWrong")
  2836. t.SendMsgToTgbot(chatId, msg)
  2837. return
  2838. }
  2839. if traffic == nil {
  2840. msg := t.I18nBot("tgbot.noResult")
  2841. t.SendMsgToTgbot(chatId, msg)
  2842. return
  2843. }
  2844. output := t.clientInfoMsg(traffic, true, true, true, true, true, true)
  2845. inlineKeyboard := tu.InlineKeyboard(
  2846. tu.InlineKeyboardRow(
  2847. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.refresh")).WithCallbackData(t.encodeQuery("client_refresh "+email)),
  2848. ),
  2849. tu.InlineKeyboardRow(
  2850. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.resetTraffic")).WithCallbackData(t.encodeQuery("reset_traffic "+email)),
  2851. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.limitTraffic")).WithCallbackData(t.encodeQuery("limit_traffic "+email)),
  2852. ),
  2853. tu.InlineKeyboardRow(
  2854. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.resetExpire")).WithCallbackData(t.encodeQuery("reset_exp "+email)),
  2855. ),
  2856. tu.InlineKeyboardRow(
  2857. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.ipLog")).WithCallbackData(t.encodeQuery("ip_log "+email)),
  2858. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.ipLimit")).WithCallbackData(t.encodeQuery("ip_limit "+email)),
  2859. ),
  2860. tu.InlineKeyboardRow(
  2861. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.setTGUser")).WithCallbackData(t.encodeQuery("tg_user "+email)),
  2862. ),
  2863. tu.InlineKeyboardRow(
  2864. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.toggle")).WithCallbackData(t.encodeQuery("toggle_enable "+email)),
  2865. ),
  2866. )
  2867. if len(messageID) > 0 {
  2868. t.editMessageTgBot(chatId, messageID[0], output, inlineKeyboard)
  2869. } else {
  2870. t.SendMsgToTgbot(chatId, output, inlineKeyboard)
  2871. }
  2872. }
  2873. // addClient handles the process of adding a new client to an inbound.
  2874. func (t *Tgbot) addClient(chatId int64, msg string, messageID ...int) {
  2875. inbound, err := t.inboundService.GetInbound(receiver_inbound_ID)
  2876. if err != nil {
  2877. t.SendMsgToTgbot(chatId, err.Error())
  2878. return
  2879. }
  2880. protocol := inbound.Protocol
  2881. switch protocol {
  2882. case model.VMESS, model.VLESS:
  2883. inlineKeyboard := tu.InlineKeyboard(
  2884. tu.InlineKeyboardRow(
  2885. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.change_email")).WithCallbackData("add_client_ch_default_email"),
  2886. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.change_id")).WithCallbackData("add_client_ch_default_id"),
  2887. ),
  2888. tu.InlineKeyboardRow(
  2889. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.limitTraffic")).WithCallbackData("add_client_ch_default_traffic"),
  2890. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.resetExpire")).WithCallbackData("add_client_ch_default_exp"),
  2891. ),
  2892. tu.InlineKeyboardRow(
  2893. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.change_comment")).WithCallbackData("add_client_ch_default_comment"),
  2894. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.ipLimit")).WithCallbackData("add_client_ch_default_ip_limit"),
  2895. ),
  2896. tu.InlineKeyboardRow(
  2897. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.submitDisable")).WithCallbackData("add_client_submit_disable"),
  2898. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.submitEnable")).WithCallbackData("add_client_submit_enable"),
  2899. ),
  2900. tu.InlineKeyboardRow(
  2901. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData("add_client_cancel"),
  2902. ),
  2903. )
  2904. if len(messageID) > 0 {
  2905. t.editMessageTgBot(chatId, messageID[0], msg, inlineKeyboard)
  2906. } else {
  2907. t.SendMsgToTgbot(chatId, msg, inlineKeyboard)
  2908. }
  2909. case model.Trojan:
  2910. inlineKeyboard := tu.InlineKeyboard(
  2911. tu.InlineKeyboardRow(
  2912. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.change_email")).WithCallbackData("add_client_ch_default_email"),
  2913. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.change_password")).WithCallbackData("add_client_ch_default_pass_tr"),
  2914. ),
  2915. tu.InlineKeyboardRow(
  2916. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.limitTraffic")).WithCallbackData("add_client_ch_default_traffic"),
  2917. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.resetExpire")).WithCallbackData("add_client_ch_default_exp"),
  2918. ),
  2919. tu.InlineKeyboardRow(
  2920. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.change_comment")).WithCallbackData("add_client_ch_default_comment"),
  2921. tu.InlineKeyboardButton("ip limit").WithCallbackData("add_client_ch_default_ip_limit"),
  2922. ),
  2923. tu.InlineKeyboardRow(
  2924. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.submitDisable")).WithCallbackData("add_client_submit_disable"),
  2925. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.submitEnable")).WithCallbackData("add_client_submit_enable"),
  2926. ),
  2927. tu.InlineKeyboardRow(
  2928. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData("add_client_cancel"),
  2929. ),
  2930. )
  2931. if len(messageID) > 0 {
  2932. t.editMessageTgBot(chatId, messageID[0], msg, inlineKeyboard)
  2933. } else {
  2934. t.SendMsgToTgbot(chatId, msg, inlineKeyboard)
  2935. }
  2936. case model.Shadowsocks:
  2937. inlineKeyboard := tu.InlineKeyboard(
  2938. tu.InlineKeyboardRow(
  2939. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.change_email")).WithCallbackData("add_client_ch_default_email"),
  2940. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.change_password")).WithCallbackData("add_client_ch_default_pass_sh"),
  2941. ),
  2942. tu.InlineKeyboardRow(
  2943. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.limitTraffic")).WithCallbackData("add_client_ch_default_traffic"),
  2944. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.resetExpire")).WithCallbackData("add_client_ch_default_exp"),
  2945. ),
  2946. tu.InlineKeyboardRow(
  2947. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.change_comment")).WithCallbackData("add_client_ch_default_comment"),
  2948. tu.InlineKeyboardButton("ip limit").WithCallbackData("add_client_ch_default_ip_limit"),
  2949. ),
  2950. tu.InlineKeyboardRow(
  2951. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.submitDisable")).WithCallbackData("add_client_submit_disable"),
  2952. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.submitEnable")).WithCallbackData("add_client_submit_enable"),
  2953. ),
  2954. tu.InlineKeyboardRow(
  2955. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData("add_client_cancel"),
  2956. ),
  2957. )
  2958. if len(messageID) > 0 {
  2959. t.editMessageTgBot(chatId, messageID[0], msg, inlineKeyboard)
  2960. } else {
  2961. t.SendMsgToTgbot(chatId, msg, inlineKeyboard)
  2962. }
  2963. }
  2964. }
  2965. // searchInbound searches for inbounds by remark and sends the results.
  2966. func (t *Tgbot) searchInbound(chatId int64, remark string) {
  2967. inbounds, err := t.inboundService.SearchInbounds(remark)
  2968. if err != nil {
  2969. logger.Warning(err)
  2970. msg := t.I18nBot("tgbot.wentWrong")
  2971. t.SendMsgToTgbot(chatId, msg)
  2972. return
  2973. }
  2974. if len(inbounds) == 0 {
  2975. msg := t.I18nBot("tgbot.noInbounds")
  2976. t.SendMsgToTgbot(chatId, msg)
  2977. return
  2978. }
  2979. for _, inbound := range inbounds {
  2980. info := ""
  2981. info += t.I18nBot("tgbot.messages.inbound", "Remark=="+inbound.Remark)
  2982. info += t.I18nBot("tgbot.messages.port", "Port=="+strconv.Itoa(inbound.Port))
  2983. info += t.I18nBot("tgbot.messages.traffic", "Total=="+common.FormatTraffic((inbound.Up+inbound.Down)), "Upload=="+common.FormatTraffic(inbound.Up), "Download=="+common.FormatTraffic(inbound.Down))
  2984. if inbound.ExpiryTime == 0 {
  2985. info += t.I18nBot("tgbot.messages.expire", "Time=="+t.I18nBot("tgbot.unlimited"))
  2986. } else {
  2987. info += t.I18nBot("tgbot.messages.expire", "Time=="+time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05"))
  2988. }
  2989. t.SendMsgToTgbot(chatId, info)
  2990. if len(inbound.ClientStats) > 0 {
  2991. output := ""
  2992. for _, traffic := range inbound.ClientStats {
  2993. output += t.clientInfoMsg(&traffic, true, true, true, true, true, true)
  2994. }
  2995. t.SendMsgToTgbot(chatId, output)
  2996. }
  2997. }
  2998. }
  2999. // getExhausted retrieves and sends information about exhausted clients.
  3000. func (t *Tgbot) getExhausted(chatId int64) {
  3001. trDiff := int64(0)
  3002. exDiff := int64(0)
  3003. now := time.Now().Unix() * 1000
  3004. var exhaustedInbounds []model.Inbound
  3005. var exhaustedClients []xray.ClientTraffic
  3006. var disabledInbounds []model.Inbound
  3007. var disabledClients []xray.ClientTraffic
  3008. TrafficThreshold, err := t.settingService.GetTrafficDiff()
  3009. if err == nil && TrafficThreshold > 0 {
  3010. trDiff = int64(TrafficThreshold) * 1073741824
  3011. }
  3012. ExpireThreshold, err := t.settingService.GetExpireDiff()
  3013. if err == nil && ExpireThreshold > 0 {
  3014. exDiff = int64(ExpireThreshold) * 86400000
  3015. }
  3016. inbounds, err := t.inboundService.GetAllInbounds()
  3017. if err != nil {
  3018. logger.Warning("Unable to load Inbounds", err)
  3019. }
  3020. for _, inbound := range inbounds {
  3021. if inbound.Enable {
  3022. if (inbound.ExpiryTime > 0 && (inbound.ExpiryTime-now < exDiff)) ||
  3023. (inbound.Total > 0 && (inbound.Total-(inbound.Up+inbound.Down) < trDiff)) {
  3024. exhaustedInbounds = append(exhaustedInbounds, *inbound)
  3025. }
  3026. if len(inbound.ClientStats) > 0 {
  3027. for _, client := range inbound.ClientStats {
  3028. if client.Enable {
  3029. if (client.ExpiryTime > 0 && (client.ExpiryTime-now < exDiff)) ||
  3030. (client.Total > 0 && (client.Total-(client.Up+client.Down) < trDiff)) {
  3031. exhaustedClients = append(exhaustedClients, client)
  3032. }
  3033. } else {
  3034. disabledClients = append(disabledClients, client)
  3035. }
  3036. }
  3037. }
  3038. } else {
  3039. disabledInbounds = append(disabledInbounds, *inbound)
  3040. }
  3041. }
  3042. // Inbounds
  3043. output := ""
  3044. output += t.I18nBot("tgbot.messages.exhaustedCount", "Type=="+t.I18nBot("tgbot.inbounds"))
  3045. output += t.I18nBot("tgbot.messages.disabled", "Disabled=="+strconv.Itoa(len(disabledInbounds)))
  3046. output += t.I18nBot("tgbot.messages.depleteSoon", "Deplete=="+strconv.Itoa(len(exhaustedInbounds)))
  3047. if len(exhaustedInbounds) > 0 {
  3048. output += t.I18nBot("tgbot.messages.depleteSoon", "Deplete=="+t.I18nBot("tgbot.inbounds"))
  3049. for _, inbound := range exhaustedInbounds {
  3050. output += t.I18nBot("tgbot.messages.inbound", "Remark=="+inbound.Remark)
  3051. output += t.I18nBot("tgbot.messages.port", "Port=="+strconv.Itoa(inbound.Port))
  3052. output += t.I18nBot("tgbot.messages.traffic", "Total=="+common.FormatTraffic((inbound.Up+inbound.Down)), "Upload=="+common.FormatTraffic(inbound.Up), "Download=="+common.FormatTraffic(inbound.Down))
  3053. if inbound.ExpiryTime == 0 {
  3054. output += t.I18nBot("tgbot.messages.expire", "Time=="+t.I18nBot("tgbot.unlimited"))
  3055. } else {
  3056. output += t.I18nBot("tgbot.messages.expire", "Time=="+time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05"))
  3057. }
  3058. output += "\r\n"
  3059. }
  3060. }
  3061. // Clients
  3062. exhaustedCC := len(exhaustedClients)
  3063. output += t.I18nBot("tgbot.messages.exhaustedCount", "Type=="+t.I18nBot("tgbot.clients"))
  3064. output += t.I18nBot("tgbot.messages.disabled", "Disabled=="+strconv.Itoa(len(disabledClients)))
  3065. output += t.I18nBot("tgbot.messages.depleteSoon", "Deplete=="+strconv.Itoa(exhaustedCC))
  3066. if exhaustedCC > 0 {
  3067. output += t.I18nBot("tgbot.messages.depleteSoon", "Deplete=="+t.I18nBot("tgbot.clients"))
  3068. var buttons []telego.InlineKeyboardButton
  3069. for _, traffic := range exhaustedClients {
  3070. output += t.clientInfoMsg(&traffic, true, false, false, true, true, false)
  3071. output += "\r\n"
  3072. buttons = append(buttons, tu.InlineKeyboardButton(traffic.Email).WithCallbackData(t.encodeQuery("client_get_usage "+traffic.Email)))
  3073. }
  3074. cols := 0
  3075. if exhaustedCC < 11 {
  3076. cols = 1
  3077. } else {
  3078. cols = 2
  3079. }
  3080. output += t.I18nBot("tgbot.messages.refreshedOn", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
  3081. keyboard := tu.InlineKeyboardGrid(tu.InlineKeyboardCols(cols, buttons...))
  3082. t.SendMsgToTgbot(chatId, output, keyboard)
  3083. } else {
  3084. output += t.I18nBot("tgbot.messages.refreshedOn", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
  3085. t.SendMsgToTgbot(chatId, output)
  3086. }
  3087. }
  3088. // notifyExhausted sends notifications for exhausted clients.
  3089. func (t *Tgbot) notifyExhausted() {
  3090. trDiff := int64(0)
  3091. exDiff := int64(0)
  3092. now := time.Now().Unix() * 1000
  3093. TrafficThreshold, err := t.settingService.GetTrafficDiff()
  3094. if err == nil && TrafficThreshold > 0 {
  3095. trDiff = int64(TrafficThreshold) * 1073741824
  3096. }
  3097. ExpireThreshold, err := t.settingService.GetExpireDiff()
  3098. if err == nil && ExpireThreshold > 0 {
  3099. exDiff = int64(ExpireThreshold) * 86400000
  3100. }
  3101. inbounds, err := t.inboundService.GetAllInbounds()
  3102. if err != nil {
  3103. logger.Warning("Unable to load Inbounds", err)
  3104. }
  3105. var chatIDsDone []int64
  3106. for _, inbound := range inbounds {
  3107. if inbound.Enable {
  3108. if len(inbound.ClientStats) > 0 {
  3109. clients, err := t.inboundService.GetClients(inbound)
  3110. if err == nil {
  3111. for _, client := range clients {
  3112. if client.TgID != 0 {
  3113. chatID := client.TgID
  3114. if !int64Contains(chatIDsDone, chatID) && !checkAdmin(chatID) {
  3115. var disabledClients []xray.ClientTraffic
  3116. var exhaustedClients []xray.ClientTraffic
  3117. traffics, err := t.inboundService.GetClientTrafficTgBot(client.TgID)
  3118. if err == nil && len(traffics) > 0 {
  3119. output := t.I18nBot("tgbot.messages.exhaustedCount", "Type=="+t.I18nBot("tgbot.clients"))
  3120. for _, traffic := range traffics {
  3121. if traffic.Enable {
  3122. if (traffic.ExpiryTime > 0 && (traffic.ExpiryTime-now < exDiff)) ||
  3123. (traffic.Total > 0 && (traffic.Total-(traffic.Up+traffic.Down) < trDiff)) {
  3124. exhaustedClients = append(exhaustedClients, *traffic)
  3125. }
  3126. } else {
  3127. disabledClients = append(disabledClients, *traffic)
  3128. }
  3129. }
  3130. if len(exhaustedClients) > 0 {
  3131. output += t.I18nBot("tgbot.messages.disabled", "Disabled=="+strconv.Itoa(len(disabledClients)))
  3132. if len(disabledClients) > 0 {
  3133. output += t.I18nBot("tgbot.clients") + ":\r\n"
  3134. for _, traffic := range disabledClients {
  3135. output += " " + traffic.Email
  3136. }
  3137. output += "\r\n"
  3138. }
  3139. output += "\r\n"
  3140. output += t.I18nBot("tgbot.messages.depleteSoon", "Deplete=="+strconv.Itoa(len(exhaustedClients)))
  3141. for _, traffic := range exhaustedClients {
  3142. output += t.clientInfoMsg(&traffic, true, false, false, true, true, false)
  3143. output += "\r\n"
  3144. }
  3145. t.SendMsgToTgbot(chatID, output)
  3146. }
  3147. chatIDsDone = append(chatIDsDone, chatID)
  3148. }
  3149. }
  3150. }
  3151. }
  3152. }
  3153. }
  3154. }
  3155. }
  3156. }
  3157. // int64Contains checks if an int64 slice contains a specific item.
  3158. func int64Contains(slice []int64, item int64) bool {
  3159. for _, s := range slice {
  3160. if s == item {
  3161. return true
  3162. }
  3163. }
  3164. return false
  3165. }
  3166. // onlineClients retrieves and sends information about online clients.
  3167. func (t *Tgbot) onlineClients(chatId int64, messageID ...int) {
  3168. if !p.IsRunning() {
  3169. return
  3170. }
  3171. onlines := p.GetOnlineClients()
  3172. onlinesCount := len(onlines)
  3173. output := t.I18nBot("tgbot.messages.onlinesCount", "Count=="+fmt.Sprint(onlinesCount))
  3174. keyboard := tu.InlineKeyboard(tu.InlineKeyboardRow(
  3175. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.refresh")).WithCallbackData(t.encodeQuery("onlines_refresh"))))
  3176. if onlinesCount > 0 {
  3177. var buttons []telego.InlineKeyboardButton
  3178. for _, online := range onlines {
  3179. buttons = append(buttons, tu.InlineKeyboardButton(online).WithCallbackData(t.encodeQuery("client_get_usage "+online)))
  3180. }
  3181. cols := 0
  3182. if onlinesCount < 21 {
  3183. cols = 2
  3184. } else if onlinesCount < 61 {
  3185. cols = 3
  3186. } else {
  3187. cols = 4
  3188. }
  3189. keyboard.InlineKeyboard = append(keyboard.InlineKeyboard, tu.InlineKeyboardCols(cols, buttons...)...)
  3190. }
  3191. if len(messageID) > 0 {
  3192. t.editMessageTgBot(chatId, messageID[0], output, keyboard)
  3193. } else {
  3194. t.SendMsgToTgbot(chatId, output, keyboard)
  3195. }
  3196. }
  3197. // sendBackup sends a backup of the database and configuration files.
  3198. func (t *Tgbot) sendBackup(chatId int64) {
  3199. output := t.I18nBot("tgbot.messages.backupTime", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
  3200. t.SendMsgToTgbot(chatId, output)
  3201. // Update by manually trigger a checkpoint operation
  3202. err := database.Checkpoint()
  3203. if err != nil {
  3204. logger.Error("Error in trigger a checkpoint operation: ", err)
  3205. }
  3206. file, err := os.Open(config.GetDBPath())
  3207. if err == nil {
  3208. document := tu.Document(
  3209. tu.ID(chatId),
  3210. tu.File(file),
  3211. )
  3212. _, err = bot.SendDocument(context.Background(), document)
  3213. if err != nil {
  3214. logger.Error("Error in uploading backup: ", err)
  3215. }
  3216. } else {
  3217. logger.Error("Error in opening db file for backup: ", err)
  3218. }
  3219. file, err = os.Open(xray.GetConfigPath())
  3220. if err == nil {
  3221. document := tu.Document(
  3222. tu.ID(chatId),
  3223. tu.File(file),
  3224. )
  3225. _, err = bot.SendDocument(context.Background(), document)
  3226. if err != nil {
  3227. logger.Error("Error in uploading config.json: ", err)
  3228. }
  3229. } else {
  3230. logger.Error("Error in opening config.json file for backup: ", err)
  3231. }
  3232. }
  3233. // sendBanLogs sends the ban logs to the specified chat.
  3234. func (t *Tgbot) sendBanLogs(chatId int64, dt bool) {
  3235. if dt {
  3236. output := t.I18nBot("tgbot.messages.datetime", "DateTime=="+time.Now().Format("2006-01-02 15:04:05"))
  3237. t.SendMsgToTgbot(chatId, output)
  3238. }
  3239. file, err := os.Open(xray.GetIPLimitBannedPrevLogPath())
  3240. if err == nil {
  3241. // Check if the file is non-empty before attempting to upload
  3242. fileInfo, _ := file.Stat()
  3243. if fileInfo.Size() > 0 {
  3244. document := tu.Document(
  3245. tu.ID(chatId),
  3246. tu.File(file),
  3247. )
  3248. _, err = bot.SendDocument(context.Background(), document)
  3249. if err != nil {
  3250. logger.Error("Error in uploading IPLimitBannedPrevLog: ", err)
  3251. }
  3252. } else {
  3253. logger.Warning("IPLimitBannedPrevLog file is empty, not uploading.")
  3254. }
  3255. file.Close()
  3256. } else {
  3257. logger.Error("Error in opening IPLimitBannedPrevLog file for backup: ", err)
  3258. }
  3259. file, err = os.Open(xray.GetIPLimitBannedLogPath())
  3260. if err == nil {
  3261. // Check if the file is non-empty before attempting to upload
  3262. fileInfo, _ := file.Stat()
  3263. if fileInfo.Size() > 0 {
  3264. document := tu.Document(
  3265. tu.ID(chatId),
  3266. tu.File(file),
  3267. )
  3268. _, err = bot.SendDocument(context.Background(), document)
  3269. if err != nil {
  3270. logger.Error("Error in uploading IPLimitBannedLog: ", err)
  3271. }
  3272. } else {
  3273. logger.Warning("IPLimitBannedLog file is empty, not uploading.")
  3274. }
  3275. file.Close()
  3276. } else {
  3277. logger.Error("Error in opening IPLimitBannedLog file for backup: ", err)
  3278. }
  3279. }
  3280. // sendCallbackAnswerTgBot answers a callback query with a message.
  3281. func (t *Tgbot) sendCallbackAnswerTgBot(id string, message string) {
  3282. params := telego.AnswerCallbackQueryParams{
  3283. CallbackQueryID: id,
  3284. Text: message,
  3285. }
  3286. if err := bot.AnswerCallbackQuery(context.Background(), &params); err != nil {
  3287. logger.Warning(err)
  3288. }
  3289. }
  3290. // editMessageCallbackTgBot edits the reply markup of a message.
  3291. func (t *Tgbot) editMessageCallbackTgBot(chatId int64, messageID int, inlineKeyboard *telego.InlineKeyboardMarkup) {
  3292. params := telego.EditMessageReplyMarkupParams{
  3293. ChatID: tu.ID(chatId),
  3294. MessageID: messageID,
  3295. ReplyMarkup: inlineKeyboard,
  3296. }
  3297. if _, err := bot.EditMessageReplyMarkup(context.Background(), &params); err != nil {
  3298. logger.Warning(err)
  3299. }
  3300. }
  3301. // editMessageTgBot edits the text and reply markup of a message.
  3302. func (t *Tgbot) editMessageTgBot(chatId int64, messageID int, text string, inlineKeyboard ...*telego.InlineKeyboardMarkup) {
  3303. params := telego.EditMessageTextParams{
  3304. ChatID: tu.ID(chatId),
  3305. MessageID: messageID,
  3306. Text: text,
  3307. ParseMode: "HTML",
  3308. }
  3309. if len(inlineKeyboard) > 0 {
  3310. params.ReplyMarkup = inlineKeyboard[0]
  3311. }
  3312. if _, err := bot.EditMessageText(context.Background(), &params); err != nil {
  3313. logger.Warning(err)
  3314. }
  3315. }
  3316. // SendMsgToTgbotDeleteAfter sends a message and deletes it after a specified delay.
  3317. func (t *Tgbot) SendMsgToTgbotDeleteAfter(chatId int64, msg string, delayInSeconds int, replyMarkup ...telego.ReplyMarkup) {
  3318. // Determine if replyMarkup was passed; otherwise, set it to nil
  3319. var replyMarkupParam telego.ReplyMarkup
  3320. if len(replyMarkup) > 0 {
  3321. replyMarkupParam = replyMarkup[0] // Use the first element
  3322. }
  3323. // Send the message
  3324. sentMsg, err := bot.SendMessage(context.Background(), &telego.SendMessageParams{
  3325. ChatID: tu.ID(chatId),
  3326. Text: msg,
  3327. ReplyMarkup: replyMarkupParam, // Use the correct replyMarkup value
  3328. })
  3329. if err != nil {
  3330. logger.Warning("Failed to send message:", err)
  3331. return
  3332. }
  3333. // Delete the sent message after the specified number of seconds
  3334. go func() {
  3335. time.Sleep(time.Duration(delayInSeconds) * time.Second) // Wait for the specified delay
  3336. t.deleteMessageTgBot(chatId, sentMsg.MessageID) // Delete the message
  3337. delete(userStates, chatId)
  3338. }()
  3339. }
  3340. // deleteMessageTgBot deletes a message from the chat.
  3341. func (t *Tgbot) deleteMessageTgBot(chatId int64, messageID int) {
  3342. params := telego.DeleteMessageParams{
  3343. ChatID: tu.ID(chatId),
  3344. MessageID: messageID,
  3345. }
  3346. if err := bot.DeleteMessage(context.Background(), &params); err != nil {
  3347. logger.Warning("Failed to delete message:", err)
  3348. } else {
  3349. logger.Info("Message deleted successfully")
  3350. }
  3351. }
  3352. // isSingleWord checks if the text contains only a single word.
  3353. func (t *Tgbot) isSingleWord(text string) bool {
  3354. text = strings.TrimSpace(text)
  3355. re := regexp.MustCompile(`\s+`)
  3356. return re.MatchString(text)
  3357. }