1
0

tgbot.go 139 KB

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