1
0

tgbot.go 138 KB

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