tgbot.go 139 KB

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