tgbot.go 137 KB

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