tgbot.go 112 KB

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