tgbot.go 139 KB

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