tgbot.go 140 KB

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