tgbot.go 112 KB

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