tgbot.go 138 KB

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