tgbot.go 130 KB

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