tgbot.go 134 KB

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