1
0

tgbot.go 101 KB

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