tgbot.go 137 KB

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