tgbot.go 113 KB

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