tgbot.go 129 KB

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