1
0

tgbot.go 124 KB

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