tgbot.go 130 KB

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