tgbot.go 140 KB

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