tgbot.go 111 KB

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