3x-ui/web/service/tgbot.go

1129 lines
40 KiB
Go
Raw Normal View History

2023-03-17 19:07:49 +03:00
package service
import (
2023-05-20 18:38:01 +03:00
"embed"
2023-03-17 19:07:49 +03:00
"fmt"
"net"
"os"
"strconv"
"strings"
"time"
"x-ui/config"
"x-ui/database/model"
"x-ui/logger"
"x-ui/util/common"
"x-ui/web/global"
2023-05-20 18:38:01 +03:00
"x-ui/web/locale"
2023-03-17 19:07:49 +03:00
"x-ui/xray"
2023-05-14 18:20:01 +03:00
"github.com/mymmrac/telego"
th "github.com/mymmrac/telego/telegohandler"
tu "github.com/mymmrac/telego/telegoutil"
2023-03-17 19:07:49 +03:00
)
2023-05-14 18:20:01 +03:00
var bot *telego.Bot
var botHandler *th.BotHandler
2023-03-17 19:07:49 +03:00
var adminIds []int64
var isRunning bool
2023-05-21 02:00:26 +03:00
var hostname string
2023-05-21 04:03:01 +03:00
var hashStorage *global.HashStorage
2023-03-17 19:07:49 +03:00
type LoginStatus byte
const (
LoginSuccess LoginStatus = 1
LoginFail LoginStatus = 0
)
type Tgbot struct {
inboundService InboundService
settingService SettingService
serverService ServerService
2023-05-05 02:17:26 +03:00
xrayService XrayService
2023-03-17 19:07:49 +03:00
lastStatus *Status
}
func (t *Tgbot) NewTgbot() *Tgbot {
return new(Tgbot)
}
2023-05-21 02:00:26 +03:00
func (t *Tgbot) I18nBot(name string, params ...string) string {
2023-05-20 18:38:01 +03:00
return locale.I18n(locale.Bot, name, params...)
}
func (t *Tgbot) GetHashStorage() *global.HashStorage {
2023-05-21 04:03:01 +03:00
return hashStorage
}
2023-05-20 18:38:01 +03:00
func (t *Tgbot) Start(i18nFS embed.FS) error {
err := locale.InitLocalizer(i18nFS, &t.settingService)
if err != nil {
return err
}
2023-05-20 20:16:42 +03:00
// init hash storage => store callback queries
// NOTE: it only save the query if its length is more than 64 chars.
2023-05-21 04:03:01 +03:00
hashStorage = global.NewHashStorage(20*time.Minute, false)
2023-05-21 02:00:26 +03:00
t.SetHostname()
2023-03-17 19:07:49 +03:00
tgBottoken, err := t.settingService.GetTgBotToken()
if err != nil || tgBottoken == "" {
logger.Warning("Get TgBotToken failed:", err)
return err
}
tgBotid, err := t.settingService.GetTgBotChatId()
if err != nil {
logger.Warning("Get GetTgBotChatId failed:", err)
return err
}
for _, adminId := range strings.Split(tgBotid, ",") {
id, err := strconv.Atoi(adminId)
if err != nil {
logger.Warning("Failed to get IDs from GetTgBotChatId:", err)
return err
}
adminIds = append(adminIds, int64(id))
}
2023-05-14 18:20:01 +03:00
bot, err = telego.NewBot(tgBottoken)
2023-03-17 19:07:49 +03:00
if err != nil {
fmt.Println("Get tgbot's api error:", err)
return err
}
// listen for TG bot income messages
if !isRunning {
logger.Info("Starting Telegram receiver ...")
go t.OnReceive()
isRunning = true
}
return nil
}
2023-05-20 18:09:01 +03:00
func (t *Tgbot) IsRunning() bool {
2023-03-17 19:07:49 +03:00
return isRunning
}
2023-05-21 02:00:26 +03:00
func (t *Tgbot) SetHostname() {
host, err := os.Hostname()
if err != nil {
logger.Error("get hostname error:", err)
hostname = ""
return
}
hostname = host
}
2023-03-17 19:07:49 +03:00
func (t *Tgbot) Stop() {
2023-05-14 18:20:01 +03:00
botHandler.Stop()
bot.StopLongPolling()
2023-03-17 19:07:49 +03:00
logger.Info("Stop Telegram receiver ...")
isRunning = false
adminIds = nil
}
func (t *Tgbot) OnReceive() {
2023-05-14 18:20:01 +03:00
params := telego.GetUpdatesParams{
Timeout: 10,
2023-03-17 19:07:49 +03:00
}
2023-05-14 18:20:01 +03:00
updates, _ := bot.UpdatesViaLongPolling(&params)
botHandler, _ = th.NewBotHandler(bot, updates)
2023-05-20 18:09:01 +03:00
botHandler.HandleMessage(func(_ *telego.Bot, message telego.Message) {
2023-05-21 02:00:26 +03:00
t.SendMsgToTgbot(message.Chat.ID, t.I18nBot("tgbot.keyboardClosed"), tu.ReplyKeyboardRemove())
}, th.TextEqual(t.I18nBot("tgbot.buttons.closeKeyboard")))
2023-05-20 18:09:01 +03:00
botHandler.HandleMessage(func(_ *telego.Bot, message telego.Message) {
2023-05-14 18:20:01 +03:00
t.answerCommand(&message, message.Chat.ID, checkAdmin(message.From.ID))
}, th.AnyCommand())
2023-05-20 18:09:01 +03:00
botHandler.HandleCallbackQuery(func(_ *telego.Bot, query telego.CallbackQuery) {
2023-05-14 18:20:01 +03:00
t.asnwerCallback(&query, checkAdmin(query.From.ID))
}, th.AnyCallbackQueryWithMessage())
2023-05-20 18:09:01 +03:00
botHandler.HandleMessage(func(_ *telego.Bot, message telego.Message) {
if message.UserShared != nil {
if checkAdmin(message.From.ID) {
err := t.inboundService.SetClientTelegramUserID(message.UserShared.RequestID, strconv.FormatInt(message.UserShared.UserID, 10))
2023-05-21 02:00:26 +03:00
output := ""
if err != nil {
2023-05-21 02:00:26 +03:00
output += t.I18nBot("tgbot.messages.selectUserFailed")
} else {
2023-05-21 02:00:26 +03:00
output += t.I18nBot("tgbot.messages.userSaved")
}
t.SendMsgToTgbot(message.Chat.ID, output, tu.ReplyKeyboardRemove())
} else {
2023-05-21 02:00:26 +03:00
t.SendMsgToTgbot(message.Chat.ID, t.I18nBot("tgbot.noResult"), tu.ReplyKeyboardRemove())
}
}
}, th.AnyMessage())
2023-05-14 18:20:01 +03:00
botHandler.Start()
2023-03-17 19:07:49 +03:00
}
2023-05-14 18:20:01 +03:00
func (t *Tgbot) answerCommand(message *telego.Message, chatId int64, isAdmin bool) {
2023-03-17 19:07:49 +03:00
msg := ""
2023-05-14 18:20:01 +03:00
command, commandArgs := tu.ParseCommand(message.Text)
2023-03-17 19:07:49 +03:00
// Extract the command from the Message.
2023-05-14 18:20:01 +03:00
switch command {
2023-03-17 19:07:49 +03:00
case "help":
2023-05-21 02:00:26 +03:00
msg += t.I18nBot("tgbot.commands.help")
msg += t.I18nBot("tgbot.commands.pleaseChoose")
2023-03-17 19:07:49 +03:00
case "start":
2023-05-21 02:00:26 +03:00
msg += t.I18nBot("tgbot.commands.start", "Firstname=="+message.From.FirstName)
2023-03-17 19:07:49 +03:00
if isAdmin {
2023-05-21 02:00:26 +03:00
msg += t.I18nBot("tgbot.commands.welcome", "Hostname=="+hostname)
2023-03-17 19:07:49 +03:00
}
2023-05-21 02:00:26 +03:00
msg += "\n\n" + t.I18nBot("tgbot.commands.pleaseChoose")
2023-03-17 19:07:49 +03:00
case "status":
2023-05-21 02:00:26 +03:00
msg += t.I18nBot("tgbot.commands.status")
2023-03-17 19:07:49 +03:00
case "usage":
2023-05-14 18:20:01 +03:00
if len(commandArgs) > 0 {
2023-03-24 16:10:56 +03:00
if isAdmin {
2023-05-14 18:20:01 +03:00
t.searchClient(chatId, commandArgs[0])
2023-03-24 16:10:56 +03:00
} else {
2023-05-14 18:20:01 +03:00
t.searchForClient(chatId, commandArgs[0])
2023-03-24 16:10:56 +03:00
}
2023-03-17 19:07:49 +03:00
} else {
2023-05-21 02:00:26 +03:00
msg += t.I18nBot("tgbot.commands.usage")
2023-03-17 19:07:49 +03:00
}
case "inbound":
2023-05-14 18:20:01 +03:00
if isAdmin && len(commandArgs) > 0 {
t.searchInbound(chatId, commandArgs[0])
} else {
2023-05-21 02:00:26 +03:00
msg += t.I18nBot("tgbot.commands.unknown")
}
2023-03-17 19:07:49 +03:00
default:
2023-05-21 02:00:26 +03:00
msg += t.I18nBot("tgbot.commands.unknown")
2023-03-17 19:07:49 +03:00
}
t.SendAnswer(chatId, msg, isAdmin)
}
2023-05-14 18:20:01 +03:00
func (t *Tgbot) asnwerCallback(callbackQuery *telego.CallbackQuery, isAdmin bool) {
chatId := callbackQuery.Message.Chat.ID
2023-05-05 00:46:43 +03:00
if isAdmin {
2023-05-20 20:16:42 +03:00
// get query from hash storage
2023-05-21 04:03:01 +03:00
decodedQuery, err := hashStorage.GetValue(callbackQuery.Data)
2023-05-20 20:16:42 +03:00
if err != nil {
2023-05-21 04:03:01 +03:00
t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.noQuery"))
2023-05-20 20:16:42 +03:00
return
}
dataArray := strings.Split(decodedQuery, " ")
2023-05-05 00:46:43 +03:00
if len(dataArray) >= 2 && len(dataArray[1]) > 0 {
email := dataArray[1]
switch dataArray[0] {
case "client_refresh":
2023-05-21 02:00:26 +03:00
t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.clientRefreshSuccess", "Email=="+email))
2023-05-14 18:20:01 +03:00
t.searchClient(chatId, email, callbackQuery.Message.MessageID)
case "client_cancel":
2023-05-21 02:00:26 +03:00
t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.canceled", "Email=="+email))
2023-05-14 18:20:01 +03:00
t.searchClient(chatId, email, callbackQuery.Message.MessageID)
case "ips_refresh":
2023-05-21 02:00:26 +03:00
t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.IpRefreshSuccess", "Email=="+email))
2023-05-14 18:20:01 +03:00
t.searchClientIps(chatId, email, callbackQuery.Message.MessageID)
case "ips_cancel":
2023-05-21 02:00:26 +03:00
t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.canceled", "Email=="+email))
2023-05-14 18:20:01 +03:00
t.searchClientIps(chatId, email, callbackQuery.Message.MessageID)
case "tgid_refresh":
2023-05-21 02:00:26 +03:00
t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.TGIdRefreshSuccess", "Email=="+email))
t.clientTelegramUserInfo(chatId, email, callbackQuery.Message.MessageID)
case "tgid_cancel":
2023-05-21 02:00:26 +03:00
t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.canceled", "Email=="+email))
t.clientTelegramUserInfo(chatId, email, callbackQuery.Message.MessageID)
2023-05-05 00:46:43 +03:00
case "reset_traffic":
2023-05-14 18:20:01 +03:00
inlineKeyboard := tu.InlineKeyboard(
tu.InlineKeyboardRow(
2023-05-21 04:03:01 +03:00
tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancelReset")).WithCallbackData(hashStorage.AddHash("client_cancel "+email)),
2023-05-05 00:46:43 +03:00
),
2023-05-14 18:20:01 +03:00
tu.InlineKeyboardRow(
2023-05-21 04:03:01 +03:00
tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmResetTraffic")).WithCallbackData(hashStorage.AddHash("reset_traffic_c "+email)),
2023-05-05 00:46:43 +03:00
),
)
2023-05-14 18:20:01 +03:00
t.editMessageCallbackTgBot(chatId, callbackQuery.Message.MessageID, inlineKeyboard)
2023-05-05 15:32:16 +03:00
case "reset_traffic_c":
2023-05-05 04:04:39 +03:00
err := t.inboundService.ResetClientTrafficByEmail(email)
if err == nil {
2023-05-05 02:17:26 +03:00
t.xrayService.SetToNeedRestart()
2023-05-21 02:00:26 +03:00
t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.resetTrafficSuccess", "Email=="+email))
2023-05-14 18:20:01 +03:00
t.searchClient(chatId, email, callbackQuery.Message.MessageID)
2023-05-05 02:17:26 +03:00
} else {
2023-05-21 02:00:26 +03:00
t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
2023-05-05 02:17:26 +03:00
}
2023-05-05 15:32:16 +03:00
case "reset_exp":
2023-05-21 02:00:26 +03:00
inlineKeyboard := tu.InlineKeyboard(
2023-05-14 18:20:01 +03:00
tu.InlineKeyboardRow(
2023-05-21 04:03:01 +03:00
tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancelReset")).WithCallbackData(hashStorage.AddHash("client_cancel "+email)),
2023-05-05 00:46:43 +03:00
),
2023-05-14 18:20:01 +03:00
tu.InlineKeyboardRow(
2023-05-21 04:03:01 +03:00
tu.InlineKeyboardButton(t.I18nBot("tgbot.unlimited")).WithCallbackData(hashStorage.AddHash("reset_exp_c "+email+" 0")),
),
2023-05-14 18:20:01 +03:00
tu.InlineKeyboardRow(
2023-05-21 04:03:01 +03:00
tu.InlineKeyboardButton("1 "+t.I18nBot("tgbot.month")).WithCallbackData(hashStorage.AddHash("reset_exp_c "+email+" 30")),
tu.InlineKeyboardButton("2 "+t.I18nBot("tgbot.months")).WithCallbackData(hashStorage.AddHash("reset_exp_c "+email+" 60")),
2023-05-05 00:46:43 +03:00
),
2023-05-14 18:20:01 +03:00
tu.InlineKeyboardRow(
2023-05-21 04:03:01 +03:00
tu.InlineKeyboardButton("3 "+t.I18nBot("tgbot.months")).WithCallbackData(hashStorage.AddHash("reset_exp_c "+email+" 90")),
tu.InlineKeyboardButton("6 "+t.I18nBot("tgbot.months")).WithCallbackData(hashStorage.AddHash("reset_exp_c "+email+" 180")),
2023-05-05 00:46:43 +03:00
),
2023-05-14 18:20:01 +03:00
tu.InlineKeyboardRow(
2023-05-21 04:03:01 +03:00
tu.InlineKeyboardButton("9 "+t.I18nBot("tgbot.months")).WithCallbackData(hashStorage.AddHash("reset_exp_c "+email+" 270")),
tu.InlineKeyboardButton("12 "+t.I18nBot("tgbot.months")).WithCallbackData(hashStorage.AddHash("reset_exp_c "+email+" 360")),
2023-05-05 00:46:43 +03:00
),
2023-05-14 18:20:01 +03:00
tu.InlineKeyboardRow(
2023-05-21 04:03:01 +03:00
tu.InlineKeyboardButton("10 "+t.I18nBot("tgbot.days")).WithCallbackData(hashStorage.AddHash("reset_exp_c "+email+" 10")),
tu.InlineKeyboardButton("20 "+t.I18nBot("tgbot.days")).WithCallbackData(hashStorage.AddHash("reset_exp_c "+email+" 20")),
2023-05-05 00:46:43 +03:00
),
)
2023-05-14 18:20:01 +03:00
t.editMessageCallbackTgBot(chatId, callbackQuery.Message.MessageID, inlineKeyboard)
2023-05-05 15:32:16 +03:00
case "reset_exp_c":
2023-05-05 04:04:39 +03:00
if len(dataArray) == 3 {
days, err := strconv.Atoi(dataArray[2])
if err == nil {
var date int64 = 0
if days > 0 {
date = int64(-(days * 24 * 60 * 60000))
}
2023-05-05 04:04:39 +03:00
err := t.inboundService.ResetClientExpiryTimeByEmail(email, date)
if err == nil {
2023-05-05 02:17:26 +03:00
t.xrayService.SetToNeedRestart()
2023-05-21 02:00:26 +03:00
t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.expireResetSuccess", "Email=="+email))
2023-05-14 18:20:01 +03:00
t.searchClient(chatId, email, callbackQuery.Message.MessageID)
2023-05-05 04:04:39 +03:00
return
2023-05-05 02:17:26 +03:00
}
2023-05-05 00:46:43 +03:00
}
}
2023-05-21 02:00:26 +03:00
t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
2023-05-14 18:20:01 +03:00
t.searchClient(chatId, email, callbackQuery.Message.MessageID)
case "ip_limit":
2023-05-14 18:20:01 +03:00
inlineKeyboard := tu.InlineKeyboard(
tu.InlineKeyboardRow(
2023-05-21 04:03:01 +03:00
tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancelIpLimit")).WithCallbackData(hashStorage.AddHash("client_cancel "+email)),
),
2023-05-14 18:20:01 +03:00
tu.InlineKeyboardRow(
2023-05-21 04:03:01 +03:00
tu.InlineKeyboardButton(t.I18nBot("tgbot.unlimited")).WithCallbackData(hashStorage.AddHash("ip_limit_c "+email+" 0")),
),
2023-05-14 18:20:01 +03:00
tu.InlineKeyboardRow(
2023-05-21 04:03:01 +03:00
tu.InlineKeyboardButton("1").WithCallbackData(hashStorage.AddHash("ip_limit_c "+email+" 1")),
tu.InlineKeyboardButton("2").WithCallbackData(hashStorage.AddHash("ip_limit_c "+email+" 2")),
),
2023-05-14 18:20:01 +03:00
tu.InlineKeyboardRow(
2023-05-21 04:03:01 +03:00
tu.InlineKeyboardButton("3").WithCallbackData(hashStorage.AddHash("ip_limit_c "+email+" 3")),
tu.InlineKeyboardButton("4").WithCallbackData(hashStorage.AddHash("ip_limit_c "+email+" 4")),
),
2023-05-14 18:20:01 +03:00
tu.InlineKeyboardRow(
2023-05-21 04:03:01 +03:00
tu.InlineKeyboardButton("5").WithCallbackData(hashStorage.AddHash("ip_limit_c "+email+" 5")),
tu.InlineKeyboardButton("6").WithCallbackData(hashStorage.AddHash("ip_limit_c "+email+" 6")),
tu.InlineKeyboardButton("7").WithCallbackData(hashStorage.AddHash("ip_limit_c "+email+" 7")),
),
2023-05-14 18:20:01 +03:00
tu.InlineKeyboardRow(
2023-05-21 04:03:01 +03:00
tu.InlineKeyboardButton("8").WithCallbackData(hashStorage.AddHash("ip_limit_c "+email+" 8")),
tu.InlineKeyboardButton("9").WithCallbackData(hashStorage.AddHash("ip_limit_c "+email+" 9")),
tu.InlineKeyboardButton("10").WithCallbackData(hashStorage.AddHash("ip_limit_c "+email+" 10")),
),
)
2023-05-14 18:20:01 +03:00
t.editMessageCallbackTgBot(chatId, callbackQuery.Message.MessageID, inlineKeyboard)
case "ip_limit_c":
if len(dataArray) == 3 {
count, err := strconv.Atoi(dataArray[2])
if err == nil {
err := t.inboundService.ResetClientIpLimitByEmail(email, count)
if err == nil {
t.xrayService.SetToNeedRestart()
2023-05-21 02:00:26 +03:00
t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.resetIpSuccess", "Email=="+email, "Count=="+strconv.Itoa(count)))
2023-05-14 18:20:01 +03:00
t.searchClient(chatId, email, callbackQuery.Message.MessageID)
return
}
}
}
2023-05-21 02:00:26 +03:00
t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
2023-05-14 18:20:01 +03:00
t.searchClient(chatId, email, callbackQuery.Message.MessageID)
case "clear_ips":
2023-05-14 18:20:01 +03:00
inlineKeyboard := tu.InlineKeyboard(
tu.InlineKeyboardRow(
2023-05-21 04:03:01 +03:00
tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(hashStorage.AddHash("ips_cancel "+email)),
),
2023-05-14 18:20:01 +03:00
tu.InlineKeyboardRow(
2023-05-21 04:03:01 +03:00
tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmClearIps")).WithCallbackData(hashStorage.AddHash("clear_ips_c "+email)),
),
)
2023-05-14 18:20:01 +03:00
t.editMessageCallbackTgBot(chatId, callbackQuery.Message.MessageID, inlineKeyboard)
case "clear_ips_c":
err := t.inboundService.ClearClientIps(email)
if err == nil {
2023-05-21 02:00:26 +03:00
t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.clearIpSuccess", "Email=="+email))
2023-05-14 18:20:01 +03:00
t.searchClientIps(chatId, email, callbackQuery.Message.MessageID)
} else {
2023-05-21 02:00:26 +03:00
t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
}
case "ip_log":
2023-05-21 02:00:26 +03:00
t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.getIpLog", "Email=="+email))
2023-05-14 18:20:01 +03:00
t.searchClientIps(chatId, email)
case "tg_user":
2023-05-21 02:00:26 +03:00
t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.getUserInfo", "Email=="+email))
t.clientTelegramUserInfo(chatId, email)
case "tgid_remove":
inlineKeyboard := tu.InlineKeyboard(
tu.InlineKeyboardRow(
2023-05-21 04:03:01 +03:00
tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(hashStorage.AddHash("tgid_cancel "+email)),
),
tu.InlineKeyboardRow(
2023-05-21 04:03:01 +03:00
tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.confirmRemoveTGUser")).WithCallbackData(hashStorage.AddHash("tgid_remove_c "+email)),
),
)
t.editMessageCallbackTgBot(chatId, callbackQuery.Message.MessageID, inlineKeyboard)
case "tgid_remove_c":
traffic, err := t.inboundService.GetClientTrafficByEmail(email)
if err != nil || traffic == nil {
2023-05-21 02:00:26 +03:00
t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
return
}
err = t.inboundService.SetClientTelegramUserID(traffic.Id, "")
if err == nil {
2023-05-21 02:00:26 +03:00
t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.removedTGUserSuccess", "Email=="+email))
t.clientTelegramUserInfo(chatId, email, callbackQuery.Message.MessageID)
} else {
2023-05-21 02:00:26 +03:00
t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
}
case "toggle_enable":
2023-05-05 19:20:40 +03:00
enabled, err := t.inboundService.ToggleClientEnableByEmail(email)
if err == nil {
t.xrayService.SetToNeedRestart()
2023-05-05 19:20:40 +03:00
if enabled {
2023-05-21 02:00:26 +03:00
t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.enableSuccess", "Email=="+email))
} else {
2023-05-21 02:00:26 +03:00
t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.disableSuccess", "Email=="+email))
}
2023-05-14 18:20:01 +03:00
t.searchClient(chatId, email, callbackQuery.Message.MessageID)
} else {
2023-05-21 02:00:26 +03:00
t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.answers.errorOperation"))
}
2023-05-05 00:46:43 +03:00
}
return
}
}
2023-03-17 19:07:49 +03:00
// Respond to the callback query, telling Telegram to show the user
// a message with the data received.
2023-05-14 18:20:01 +03:00
t.sendCallbackAnswerTgBot(callbackQuery.ID, callbackQuery.Data)
2023-03-17 19:07:49 +03:00
switch callbackQuery.Data {
case "get_usage":
2023-05-14 18:20:01 +03:00
t.SendMsgToTgbot(chatId, t.getServerUsage())
2023-03-17 19:07:49 +03:00
case "inbounds":
2023-05-14 18:20:01 +03:00
t.SendMsgToTgbot(chatId, t.getInboundUsages())
case "deplete_soon":
2023-05-14 18:20:01 +03:00
t.SendMsgToTgbot(chatId, t.getExhausted())
2023-03-17 19:07:49 +03:00
case "get_backup":
2023-05-14 18:20:01 +03:00
t.sendBackup(chatId)
2023-03-17 19:07:49 +03:00
case "client_traffic":
2023-05-14 18:20:01 +03:00
t.getClientUsage(chatId, callbackQuery.From.Username, strconv.FormatInt(callbackQuery.From.ID, 10))
2023-03-17 19:07:49 +03:00
case "client_commands":
2023-05-21 02:00:26 +03:00
t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.commands.helpClientCommands"))
2023-03-17 19:07:49 +03:00
case "commands":
2023-05-21 02:00:26 +03:00
t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.commands.helpAdminCommands"))
2023-03-17 19:07:49 +03:00
}
}
func checkAdmin(tgId int64) bool {
for _, adminId := range adminIds {
if adminId == tgId {
return true
}
}
return false
}
func (t *Tgbot) SendAnswer(chatId int64, msg string, isAdmin bool) {
2023-05-14 18:20:01 +03:00
numericKeyboard := tu.InlineKeyboard(
tu.InlineKeyboardRow(
2023-05-21 04:03:01 +03:00
tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.serverUsage")).WithCallbackData(hashStorage.AddHash("get_usage")),
tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.dbBackup")).WithCallbackData(hashStorage.AddHash("get_backup")),
2023-03-17 19:07:49 +03:00
),
2023-05-14 18:20:01 +03:00
tu.InlineKeyboardRow(
2023-05-21 04:03:01 +03:00
tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.getInbounds")).WithCallbackData(hashStorage.AddHash("inbounds")),
tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.depleteSoon")).WithCallbackData(hashStorage.AddHash("deplete_soon")),
2023-03-17 19:07:49 +03:00
),
2023-05-14 18:20:01 +03:00
tu.InlineKeyboardRow(
2023-05-21 04:03:01 +03:00
tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.commands")).WithCallbackData(hashStorage.AddHash("commands")),
2023-03-17 19:07:49 +03:00
),
)
2023-05-14 18:20:01 +03:00
numericKeyboardClient := tu.InlineKeyboard(
tu.InlineKeyboardRow(
2023-05-21 04:03:01 +03:00
tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.clientUsage")).WithCallbackData(hashStorage.AddHash("client_traffic")),
tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.commands")).WithCallbackData(hashStorage.AddHash("client_commands")),
2023-03-17 19:07:49 +03:00
),
)
2023-05-21 02:00:26 +03:00
2023-05-20 18:09:01 +03:00
var ReplyMarkup telego.ReplyMarkup
2023-03-17 19:07:49 +03:00
if isAdmin {
2023-05-20 18:09:01 +03:00
ReplyMarkup = numericKeyboard
2023-03-17 19:07:49 +03:00
} else {
2023-05-20 18:09:01 +03:00
ReplyMarkup = numericKeyboardClient
2023-03-17 19:07:49 +03:00
}
2023-05-20 18:09:01 +03:00
t.SendMsgToTgbot(chatId, msg, ReplyMarkup)
2023-03-17 19:07:49 +03:00
}
func (t *Tgbot) SendMsgToTgbot(chatId int64, msg string, replyMarkup ...telego.ReplyMarkup) {
if !isRunning {
return
}
2023-05-20 18:09:01 +03:00
if msg == "" {
logger.Info("[tgbot] message is empty!")
return
}
2023-03-17 19:07:49 +03:00
var allMessages []string
limit := 2000
2023-05-20 18:09:01 +03:00
2023-03-17 19:07:49 +03:00
// paging message if it is big
if len(msg) > limit {
messages := strings.Split(msg, "\r\n \r\n")
lastIndex := -1
2023-05-20 18:09:01 +03:00
2023-03-17 19:07:49 +03:00
for _, message := range messages {
if (len(allMessages) == 0) || (len(allMessages[lastIndex])+len(message) > limit) {
allMessages = append(allMessages, message)
lastIndex++
} else {
allMessages[lastIndex] += "\r\n \r\n" + message
}
}
} else {
allMessages = append(allMessages, msg)
}
for _, message := range allMessages {
2023-05-14 18:20:01 +03:00
params := telego.SendMessageParams{
ChatID: tu.ID(chatId),
Text: message,
ParseMode: "HTML",
}
if len(replyMarkup) > 0 {
params.ReplyMarkup = replyMarkup[0]
2023-05-05 00:46:43 +03:00
}
2023-05-14 18:20:01 +03:00
_, err := bot.SendMessage(&params)
2023-03-17 19:07:49 +03:00
if err != nil {
logger.Warning("Error sending telegram message :", err)
}
time.Sleep(500 * time.Millisecond)
}
}
func (t *Tgbot) SendMsgToTgbotAdmins(msg string) {
for _, adminId := range adminIds {
t.SendMsgToTgbot(adminId, msg)
}
}
func (t *Tgbot) SendReport() {
runTime, err := t.settingService.GetTgbotRuntime()
if err == nil && len(runTime) > 0 {
2023-05-21 02:00:26 +03:00
msg := ""
msg += t.I18nBot("tgbot.messages.report", "RunTime=="+runTime)
msg += t.I18nBot("tgbot.messages.datetime", "DateTime=="+time.Now().Format("2006-01-02 15:04:05"))
t.SendMsgToTgbotAdmins(msg)
2023-03-17 19:07:49 +03:00
}
2023-05-21 02:00:26 +03:00
2023-03-17 19:07:49 +03:00
info := t.getServerUsage()
t.SendMsgToTgbotAdmins(info)
2023-05-21 02:00:26 +03:00
2023-03-17 19:07:49 +03:00
exhausted := t.getExhausted()
t.SendMsgToTgbotAdmins(exhausted)
2023-05-21 02:00:26 +03:00
2023-03-17 19:07:49 +03:00
backupEnable, err := t.settingService.GetTgBotBackup()
if err == nil && backupEnable {
2023-05-21 02:00:26 +03:00
t.SendBackupToAdmins()
2023-03-17 19:07:49 +03:00
}
}
2023-05-21 02:00:26 +03:00
func (t *Tgbot) SendBackupToAdmins() {
if !t.IsRunning() {
return
}
2023-05-19 00:01:05 +03:00
for _, adminId := range adminIds {
t.sendBackup(int64(adminId))
}
}
2023-03-17 19:07:49 +03:00
func (t *Tgbot) getServerUsage() string {
2023-05-21 02:00:26 +03:00
info, ipv4, ipv6 := "", "", ""
info += t.I18nBot("tgbot.messages.hostname", "Hostname=="+hostname)
info += t.I18nBot("tgbot.messages.version", "Version=="+config.GetVersion())
// get ip address
2023-03-17 19:07:49 +03:00
netInterfaces, err := net.Interfaces()
if err != nil {
2023-05-21 02:00:26 +03:00
logger.Error("net.Interfaces failed, err: ", err.Error())
info += t.I18nBot("tgbot.messages.ip", "IP=="+t.I18nBot("tgbot.unknown"))
info += " \r\n"
2023-03-17 19:07:49 +03:00
} else {
for i := 0; i < len(netInterfaces); i++ {
if (netInterfaces[i].Flags & net.FlagUp) != 0 {
addrs, _ := netInterfaces[i].Addrs()
for _, address := range addrs {
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
2023-05-21 02:00:26 +03:00
ipv4 += ipnet.IP.String() + " "
2023-03-17 19:07:49 +03:00
} else if ipnet.IP.To16() != nil && !ipnet.IP.IsLinkLocalUnicast() {
ipv6 += ipnet.IP.String() + " "
}
}
}
}
}
2023-05-21 02:00:26 +03:00
info += t.I18nBot("tgbot.messages.ipv4", "IPv4=="+ipv4)
info += t.I18nBot("tgbot.messages.ipv6", "IPv6=="+ipv6)
2023-03-17 19:07:49 +03:00
}
// get latest status of server
t.lastStatus = t.serverService.GetStatus(t.lastStatus)
2023-05-21 02:00:26 +03:00
info += t.I18nBot("tgbot.messages.serverUpTime", "UpTime=="+strconv.FormatUint(t.lastStatus.Uptime/86400, 10), "Unit=="+t.I18nBot("tgbot.days"))
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))
info += t.I18nBot("tgbot.messages.serverMemory", "Current=="+common.FormatTraffic(int64(t.lastStatus.Mem.Current)), "Total=="+common.FormatTraffic(int64(t.lastStatus.Mem.Total)))
info += t.I18nBot("tgbot.messages.tcpCount", "Count=="+strconv.Itoa(t.lastStatus.TcpCount))
info += t.I18nBot("tgbot.messages.udpCount", "Count=="+strconv.Itoa(t.lastStatus.UdpCount))
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)))
info += t.I18nBot("tgbot.messages.xrayStatus", "State=="+fmt.Sprint(t.lastStatus.Xray.State))
2023-03-17 19:07:49 +03:00
return info
}
func (t *Tgbot) UserLoginNotify(username string, ip string, time string, status LoginStatus) {
2023-05-20 18:09:01 +03:00
if !t.IsRunning() {
return
}
2023-03-17 19:07:49 +03:00
if username == "" || ip == "" || time == "" {
2023-05-20 18:09:01 +03:00
logger.Warning("UserLoginNotify failed, invalid info!")
2023-03-17 19:07:49 +03:00
return
}
2023-05-20 18:09:01 +03:00
msg := ""
2023-03-17 19:07:49 +03:00
if status == LoginSuccess {
2023-05-21 02:00:26 +03:00
msg += t.I18nBot("tgbot.messages.loginSuccess")
2023-03-17 19:07:49 +03:00
} else if status == LoginFail {
2023-05-21 02:00:26 +03:00
msg += t.I18nBot("tgbot.messages.loginFailed")
2023-03-17 19:07:49 +03:00
}
2023-05-20 18:09:01 +03:00
2023-05-21 02:00:26 +03:00
msg += t.I18nBot("tgbot.messages.hostname", "Hostname=="+hostname)
msg += t.I18nBot("tgbot.messages.username", "Username=="+username)
msg += t.I18nBot("tgbot.messages.ip", "IP=="+ip)
msg += t.I18nBot("tgbot.messages.time", "Time=="+time)
2023-03-17 19:07:49 +03:00
t.SendMsgToTgbotAdmins(msg)
}
func (t *Tgbot) getInboundUsages() string {
info := ""
// get traffic
inbouds, err := t.inboundService.GetAllInbounds()
if err != nil {
logger.Warning("GetAllInbounds run failed:", err)
2023-05-21 02:00:26 +03:00
info += t.I18nBot("tgbot.answers.getInboundsFailed")
2023-03-17 19:07:49 +03:00
} else {
// NOTE:If there no any sessions here,need to notify here
// TODO:Sub-node push, automatic conversion format
for _, inbound := range inbouds {
2023-05-21 02:00:26 +03:00
info += t.I18nBot("tgbot.messages.inbound", "Remark=="+inbound.Remark)
info += t.I18nBot("tgbot.messages.port", "Port=="+strconv.Itoa(inbound.Port))
info += t.I18nBot("tgbot.messages.traffic", "Total=="+common.FormatTraffic((inbound.Up+inbound.Down)), "Upload=="+common.FormatTraffic(inbound.Up), "Download=="+common.FormatTraffic(inbound.Down))
2023-03-17 19:07:49 +03:00
if inbound.ExpiryTime == 0 {
2023-05-21 02:00:26 +03:00
info += t.I18nBot("tgbot.messages.expire", "DateTime=="+t.I18nBot("tgbot.unlimited"))
2023-03-17 19:07:49 +03:00
} else {
2023-05-21 02:00:26 +03:00
info += t.I18nBot("tgbot.messages.expire", "DateTime=="+time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05"))
2023-03-17 19:07:49 +03:00
}
}
}
return info
}
func (t *Tgbot) getClientUsage(chatId int64, tgUserName string, tgUserID string) {
2023-05-06 02:06:46 +03:00
traffics, err := t.inboundService.GetClientTrafficTgBot(tgUserID)
if err != nil {
logger.Warning(err)
2023-05-21 02:00:26 +03:00
msg := t.I18nBot("tgbot.wentWrong")
t.SendMsgToTgbot(chatId, msg)
return
}
2023-05-21 02:00:26 +03:00
2023-05-06 02:06:46 +03:00
if len(traffics) == 0 {
if len(tgUserName) == 0 {
2023-05-21 02:00:26 +03:00
msg := t.I18nBot("tgbot.answers.askToAddUserId", "TgUserID=="+tgUserID)
2023-05-06 02:06:46 +03:00
t.SendMsgToTgbot(chatId, msg)
return
}
traffics, err = t.inboundService.GetClientTrafficTgBot(tgUserName)
}
2023-03-17 19:07:49 +03:00
if err != nil {
logger.Warning(err)
2023-05-21 02:00:26 +03:00
msg := t.I18nBot("tgbot.wentWrong")
2023-03-17 19:07:49 +03:00
t.SendMsgToTgbot(chatId, msg)
return
}
if len(traffics) == 0 {
2023-05-21 02:00:26 +03:00
msg := t.I18nBot("tgbot.answers.askToAddUserName", "TgUserName=="+tgUserName, "TgUserID=="+tgUserID)
2023-03-17 19:07:49 +03:00
t.SendMsgToTgbot(chatId, msg)
return
2023-03-17 19:07:49 +03:00
}
2023-05-21 02:00:26 +03:00
2023-03-17 19:07:49 +03:00
for _, traffic := range traffics {
expiryTime := ""
if traffic.ExpiryTime == 0 {
2023-05-21 02:00:26 +03:00
expiryTime = t.I18nBot("tgbot.unlimited")
} else if traffic.ExpiryTime < 0 {
2023-05-21 02:00:26 +03:00
expiryTime = fmt.Sprintf("%d %s", traffic.ExpiryTime/-86400000, t.I18nBot("tgbot.days"))
2023-03-17 19:07:49 +03:00
} else {
expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
}
2023-05-21 02:00:26 +03:00
2023-03-17 19:07:49 +03:00
total := ""
if traffic.Total == 0 {
2023-05-21 02:00:26 +03:00
total = t.I18nBot("tgbot.unlimited")
2023-03-17 19:07:49 +03:00
} else {
total = common.FormatTraffic((traffic.Total))
}
2023-05-21 02:00:26 +03:00
output := ""
output += t.I18nBot("tgbot.messages.refreshedOn", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
2023-05-21 02:00:26 +03:00
output += t.I18nBot("tgbot.messages.active", "Enable=="+strconv.FormatBool(traffic.Enable))
output += t.I18nBot("tgbot.messages.email", "Email=="+traffic.Email)
output += t.I18nBot("tgbot.messages.upload", "Upload=="+common.FormatTraffic(traffic.Up))
output += t.I18nBot("tgbot.messages.download", "Download=="+common.FormatTraffic(traffic.Down))
output += t.I18nBot("tgbot.messages.total", "UpDown=="+common.FormatTraffic((traffic.Up+traffic.Down)), "Total=="+total)
output += t.I18nBot("tgbot.messages.expireIn", "Time=="+expiryTime)
2023-03-17 19:07:49 +03:00
t.SendMsgToTgbot(chatId, output)
}
2023-05-21 02:00:26 +03:00
t.SendAnswer(chatId, t.I18nBot("tgbot.commands.pleaseChoose"), false)
2023-03-17 19:07:49 +03:00
}
func (t *Tgbot) searchClientIps(chatId int64, email string, messageID ...int) {
ips, err := t.inboundService.GetInboundClientIps(email)
if err != nil || len(ips) == 0 {
2023-05-21 02:00:26 +03:00
ips = t.I18nBot("tgbot.noIpRecord")
}
2023-05-21 02:00:26 +03:00
output := ""
output += t.I18nBot("tgbot.messages.email", "Email=="+email)
output += t.I18nBot("tgbot.messages.ips", "IPs=="+ips)
2023-05-14 18:20:01 +03:00
inlineKeyboard := tu.InlineKeyboard(
tu.InlineKeyboardRow(
2023-05-21 04:03:01 +03:00
tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.refresh")).WithCallbackData(hashStorage.AddHash("ips_refresh "+email)),
),
2023-05-14 18:20:01 +03:00
tu.InlineKeyboardRow(
2023-05-21 04:03:01 +03:00
tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.clearIPs")).WithCallbackData(hashStorage.AddHash("clear_ips "+email)),
),
)
2023-05-21 02:00:26 +03:00
if len(messageID) > 0 {
t.editMessageTgBot(chatId, messageID[0], output, inlineKeyboard)
} else {
t.SendMsgToTgbot(chatId, output, inlineKeyboard)
}
}
func (t *Tgbot) clientTelegramUserInfo(chatId int64, email string, messageID ...int) {
traffic, client, err := t.inboundService.GetClientByEmail(email)
if err != nil {
logger.Warning(err)
2023-05-21 02:00:26 +03:00
msg := t.I18nBot("tgbot.wentWrong")
t.SendMsgToTgbot(chatId, msg)
return
}
if client == nil {
2023-05-21 02:00:26 +03:00
msg := t.I18nBot("tgbot.noResult")
t.SendMsgToTgbot(chatId, msg)
return
}
2023-05-20 18:09:01 +03:00
tgId := "None"
if len(client.TgID) > 0 {
2023-05-20 18:09:01 +03:00
tgId = client.TgID
}
2023-05-20 18:09:01 +03:00
2023-05-21 02:00:26 +03:00
output := ""
output += t.I18nBot("tgbot.messages.email", "Email=="+email)
output += t.I18nBot("tgbot.messages.TGUser", "TelegramID=="+tgId)
inlineKeyboard := tu.InlineKeyboard(
tu.InlineKeyboardRow(
2023-05-21 04:03:01 +03:00
tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.refresh")).WithCallbackData(hashStorage.AddHash("tgid_refresh "+email)),
),
tu.InlineKeyboardRow(
2023-05-21 04:03:01 +03:00
tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.removeTGUser")).WithCallbackData(hashStorage.AddHash("tgid_remove "+email)),
),
)
2023-05-20 18:09:01 +03:00
if len(messageID) > 0 {
t.editMessageTgBot(chatId, messageID[0], output, inlineKeyboard)
} else {
t.SendMsgToTgbot(chatId, output, inlineKeyboard)
requestUser := telego.KeyboardButtonRequestUser{
RequestID: int32(traffic.Id),
UserIsBot: false,
}
keyboard := tu.Keyboard(
tu.KeyboardRow(
2023-05-21 02:00:26 +03:00
tu.KeyboardButton(t.I18nBot("tgbot.buttons.selectTGUser")).WithRequestUser(&requestUser),
),
tu.KeyboardRow(
2023-05-21 02:00:26 +03:00
tu.KeyboardButton(t.I18nBot("tgbot.buttons.closeKeyboard")),
),
2023-05-14 22:25:01 +03:00
).WithIsPersistent().WithResizeKeyboard()
2023-05-21 02:00:26 +03:00
t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.buttons.selectOneTGUser"), keyboard)
}
}
2023-05-05 00:46:43 +03:00
func (t *Tgbot) searchClient(chatId int64, email string, messageID ...int) {
traffic, err := t.inboundService.GetClientTrafficByEmail(email)
2023-03-17 19:07:49 +03:00
if err != nil {
logger.Warning(err)
2023-05-21 02:00:26 +03:00
msg := t.I18nBot("tgbot.wentWrong")
2023-03-17 19:07:49 +03:00
t.SendMsgToTgbot(chatId, msg)
return
}
if traffic == nil {
2023-05-21 02:00:26 +03:00
msg := t.I18nBot("tgbot.noResult")
2023-03-17 19:07:49 +03:00
t.SendMsgToTgbot(chatId, msg)
return
}
2023-05-20 18:09:01 +03:00
expiryTime := ""
if traffic.ExpiryTime == 0 {
2023-05-21 02:00:26 +03:00
expiryTime = t.I18nBot("tgbot.unlimited")
} else if traffic.ExpiryTime < 0 {
2023-05-21 02:00:26 +03:00
expiryTime = fmt.Sprintf("%d %s", traffic.ExpiryTime/-86400000, t.I18nBot("tgbot.days"))
} else {
expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
}
2023-05-20 18:09:01 +03:00
total := ""
if traffic.Total == 0 {
2023-05-21 02:00:26 +03:00
total = t.I18nBot("tgbot.unlimited")
} else {
total = common.FormatTraffic((traffic.Total))
2023-03-17 19:07:49 +03:00
}
2023-05-20 18:09:01 +03:00
2023-05-21 02:00:26 +03:00
output := ""
output += t.I18nBot("tgbot.messages.refreshedOn", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
2023-05-21 02:00:26 +03:00
output += t.I18nBot("tgbot.messages.active", "Enable=="+strconv.FormatBool(traffic.Enable))
output += t.I18nBot("tgbot.messages.email", "Email=="+traffic.Email)
output += t.I18nBot("tgbot.messages.upload", "Upload=="+common.FormatTraffic(traffic.Up))
output += t.I18nBot("tgbot.messages.download", "Download=="+common.FormatTraffic(traffic.Down))
output += t.I18nBot("tgbot.messages.total", "UpDown=="+common.FormatTraffic((traffic.Up+traffic.Down)), "Total=="+total)
output += t.I18nBot("tgbot.messages.expireIn", "Time=="+expiryTime)
2023-05-20 18:09:01 +03:00
2023-05-14 18:20:01 +03:00
inlineKeyboard := tu.InlineKeyboard(
tu.InlineKeyboardRow(
2023-05-21 04:03:01 +03:00
tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.refresh")).WithCallbackData(hashStorage.AddHash("client_refresh "+email)),
),
2023-05-14 18:20:01 +03:00
tu.InlineKeyboardRow(
2023-05-21 04:03:01 +03:00
tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.resetTraffic")).WithCallbackData(hashStorage.AddHash("reset_traffic "+email)),
2023-05-05 00:46:43 +03:00
),
2023-05-14 18:20:01 +03:00
tu.InlineKeyboardRow(
2023-05-21 04:03:01 +03:00
tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.resetExpire")).WithCallbackData(hashStorage.AddHash("reset_exp "+email)),
2023-05-05 00:46:43 +03:00
),
2023-05-14 18:20:01 +03:00
tu.InlineKeyboardRow(
2023-05-21 04:03:01 +03:00
tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.ipLog")).WithCallbackData(hashStorage.AddHash("ip_log "+email)),
tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.ipLimit")).WithCallbackData(hashStorage.AddHash("ip_limit "+email)),
),
tu.InlineKeyboardRow(
2023-05-21 04:03:01 +03:00
tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.setTGUser")).WithCallbackData(hashStorage.AddHash("tg_user "+email)),
),
2023-05-14 18:20:01 +03:00
tu.InlineKeyboardRow(
2023-05-21 04:03:01 +03:00
tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.toggle")).WithCallbackData(hashStorage.AddHash("toggle_enable "+email)),
),
2023-05-05 00:46:43 +03:00
)
2023-05-20 18:09:01 +03:00
2023-05-05 00:46:43 +03:00
if len(messageID) > 0 {
t.editMessageTgBot(chatId, messageID[0], output, inlineKeyboard)
} else {
t.SendMsgToTgbot(chatId, output, inlineKeyboard)
}
2023-03-17 19:07:49 +03:00
}
func (t *Tgbot) searchInbound(chatId int64, remark string) {
inbouds, err := t.inboundService.SearchInbounds(remark)
if err != nil {
logger.Warning(err)
2023-05-21 02:00:26 +03:00
msg := t.I18nBot("tgbot.wentWrong")
t.SendMsgToTgbot(chatId, msg)
return
}
2023-05-20 18:09:01 +03:00
if len(inbouds) == 0 {
2023-05-21 02:00:26 +03:00
msg := t.I18nBot("tgbot.noInbounds")
2023-05-20 18:09:01 +03:00
t.SendMsgToTgbot(chatId, msg)
return
}
for _, inbound := range inbouds {
info := ""
2023-05-21 02:00:26 +03:00
info += t.I18nBot("tgbot.messages.inbound", "Remark=="+inbound.Remark)
info += t.I18nBot("tgbot.messages.port", "Port=="+strconv.Itoa(inbound.Port))
info += t.I18nBot("tgbot.messages.traffic", "Total=="+common.FormatTraffic((inbound.Up+inbound.Down)), "Upload=="+common.FormatTraffic(inbound.Up), "Download=="+common.FormatTraffic(inbound.Down))
if inbound.ExpiryTime == 0 {
2023-05-21 02:00:26 +03:00
info += t.I18nBot("tgbot.messages.expire", "DateTime=="+t.I18nBot("tgbot.unlimited"))
} else {
2023-05-21 02:00:26 +03:00
info += t.I18nBot("tgbot.messages.expire", "DateTime=="+time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05"))
}
t.SendMsgToTgbot(chatId, info)
2023-05-20 18:09:01 +03:00
for _, traffic := range inbound.ClientStats {
expiryTime := ""
if traffic.ExpiryTime == 0 {
2023-05-21 02:00:26 +03:00
expiryTime = t.I18nBot("tgbot.unlimited")
} else if traffic.ExpiryTime < 0 {
2023-05-21 02:00:26 +03:00
expiryTime = fmt.Sprintf("%d %s", traffic.ExpiryTime/-86400000, t.I18nBot("tgbot.days"))
} else {
expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
}
2023-05-20 18:09:01 +03:00
total := ""
if traffic.Total == 0 {
2023-05-21 02:00:26 +03:00
total = t.I18nBot("tgbot.unlimited")
} else {
total = common.FormatTraffic((traffic.Total))
}
2023-05-21 02:00:26 +03:00
output := ""
output += t.I18nBot("tgbot.messages.refreshedOn", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
2023-05-21 02:00:26 +03:00
output += t.I18nBot("tgbot.messages.active", "Enable=="+strconv.FormatBool(traffic.Enable))
output += t.I18nBot("tgbot.messages.email", "Email=="+traffic.Email)
output += t.I18nBot("tgbot.messages.upload", "Upload=="+common.FormatTraffic(traffic.Up))
output += t.I18nBot("tgbot.messages.download", "Download=="+common.FormatTraffic(traffic.Down))
output += t.I18nBot("tgbot.messages.total", "UpDown=="+common.FormatTraffic((traffic.Up+traffic.Down)), "Total=="+total)
output += t.I18nBot("tgbot.messages.expireIn", "Time=="+expiryTime)
t.SendMsgToTgbot(chatId, output)
}
}
}
2023-03-17 19:07:49 +03:00
func (t *Tgbot) searchForClient(chatId int64, query string) {
traffic, err := t.inboundService.SearchClientTraffic(query)
if err != nil {
logger.Warning(err)
2023-05-21 02:00:26 +03:00
msg := t.I18nBot("tgbot.wentWrong")
2023-03-17 19:07:49 +03:00
t.SendMsgToTgbot(chatId, msg)
return
}
if traffic == nil {
2023-05-21 02:00:26 +03:00
msg := t.I18nBot("tgbot.noResult")
2023-03-17 19:07:49 +03:00
t.SendMsgToTgbot(chatId, msg)
return
}
2023-05-20 18:09:01 +03:00
2023-03-17 19:07:49 +03:00
expiryTime := ""
if traffic.ExpiryTime == 0 {
2023-05-21 02:00:26 +03:00
expiryTime = t.I18nBot("tgbot.unlimited")
} else if traffic.ExpiryTime < 0 {
2023-05-21 02:00:26 +03:00
expiryTime = fmt.Sprintf("%d %s", traffic.ExpiryTime/-86400000, t.I18nBot("tgbot.days"))
2023-03-17 19:07:49 +03:00
} else {
expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
}
2023-05-20 18:09:01 +03:00
2023-03-17 19:07:49 +03:00
total := ""
if traffic.Total == 0 {
2023-05-21 02:00:26 +03:00
total = t.I18nBot("tgbot.unlimited")
2023-03-17 19:07:49 +03:00
} else {
total = common.FormatTraffic((traffic.Total))
}
2023-05-20 18:09:01 +03:00
2023-05-21 02:00:26 +03:00
output := ""
output += t.I18nBot("tgbot.messages.refreshedOn", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
2023-05-21 02:00:26 +03:00
output += t.I18nBot("tgbot.messages.active", "Enable=="+strconv.FormatBool(traffic.Enable))
output += t.I18nBot("tgbot.messages.email", "Email=="+traffic.Email)
output += t.I18nBot("tgbot.messages.upload", "Upload=="+common.FormatTraffic(traffic.Up))
output += t.I18nBot("tgbot.messages.download", "Download=="+common.FormatTraffic(traffic.Down))
output += t.I18nBot("tgbot.messages.total", "UpDown=="+common.FormatTraffic((traffic.Up+traffic.Down)), "Total=="+total)
output += t.I18nBot("tgbot.messages.expireIn", "Time=="+expiryTime)
2023-03-17 19:07:49 +03:00
t.SendMsgToTgbot(chatId, output)
}
func (t *Tgbot) getExhausted() string {
trDiff := int64(0)
exDiff := int64(0)
now := time.Now().Unix() * 1000
var exhaustedInbounds []model.Inbound
var exhaustedClients []xray.ClientTraffic
var disabledInbounds []model.Inbound
var disabledClients []xray.ClientTraffic
2023-05-20 18:09:01 +03:00
TrafficThreshold, err := t.settingService.GetTrafficDiff()
2023-03-17 19:07:49 +03:00
if err == nil && TrafficThreshold > 0 {
trDiff = int64(TrafficThreshold) * 1073741824
}
ExpireThreshold, err := t.settingService.GetExpireDiff()
2023-03-17 19:07:49 +03:00
if err == nil && ExpireThreshold > 0 {
exDiff = int64(ExpireThreshold) * 86400000
2023-03-17 19:07:49 +03:00
}
inbounds, err := t.inboundService.GetAllInbounds()
if err != nil {
logger.Warning("Unable to load Inbounds", err)
}
2023-05-20 18:09:01 +03:00
2023-03-17 19:07:49 +03:00
for _, inbound := range inbounds {
if inbound.Enable {
2023-03-24 16:20:10 +03:00
if (inbound.ExpiryTime > 0 && (inbound.ExpiryTime-now < exDiff)) ||
2023-04-10 00:25:47 +03:00
(inbound.Total > 0 && (inbound.Total-(inbound.Up+inbound.Down) < trDiff)) {
2023-03-17 19:07:49 +03:00
exhaustedInbounds = append(exhaustedInbounds, *inbound)
}
if len(inbound.ClientStats) > 0 {
for _, client := range inbound.ClientStats {
if client.Enable {
2023-03-24 16:20:10 +03:00
if (client.ExpiryTime > 0 && (client.ExpiryTime-now < exDiff)) ||
2023-04-10 00:25:47 +03:00
(client.Total > 0 && (client.Total-(client.Up+client.Down) < trDiff)) {
2023-03-17 19:07:49 +03:00
exhaustedClients = append(exhaustedClients, client)
}
} else {
disabledClients = append(disabledClients, client)
}
}
}
} else {
disabledInbounds = append(disabledInbounds, *inbound)
}
}
2023-05-20 18:09:01 +03:00
2023-05-21 02:00:26 +03:00
// Inbounds
output := ""
output += t.I18nBot("tgbot.messages.exhaustedCount", "Type=="+t.I18nBot("tgbot.inbounds"))
output += t.I18nBot("tgbot.messages.disabled", "Disabled=="+strconv.Itoa(len(disabledInbounds)))
output += t.I18nBot("tgbot.messages.depleteSoon", "Deplete=="+strconv.Itoa(len(exhaustedInbounds)))
output += "\r\n \r\n"
2023-03-24 16:20:10 +03:00
if len(exhaustedInbounds) > 0 {
2023-05-21 02:00:26 +03:00
output += t.I18nBot("tgbot.messages.exhaustedMsg", "Type=="+t.I18nBot("tgbot.inbounds"))
2023-03-17 19:07:49 +03:00
for _, inbound := range exhaustedInbounds {
2023-05-21 02:00:26 +03:00
output += t.I18nBot("tgbot.messages.inbound", "Remark=="+inbound.Remark)
output += t.I18nBot("tgbot.messages.port", "Port=="+strconv.Itoa(inbound.Port))
output += t.I18nBot("tgbot.messages.traffic", "Total=="+common.FormatTraffic((inbound.Up+inbound.Down)), "Upload=="+common.FormatTraffic(inbound.Up), "Download=="+common.FormatTraffic(inbound.Down))
2023-03-17 19:07:49 +03:00
if inbound.ExpiryTime == 0 {
2023-05-21 02:00:26 +03:00
output += t.I18nBot("tgbot.messages.expire", "DateTime=="+t.I18nBot("tgbot.unlimited"))
2023-03-17 19:07:49 +03:00
} else {
2023-05-21 02:00:26 +03:00
output += t.I18nBot("tgbot.messages.expire", "DateTime=="+time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05"))
2023-03-17 19:07:49 +03:00
}
2023-05-21 02:00:26 +03:00
output += "\r\n \r\n"
2023-03-17 19:07:49 +03:00
}
}
2023-05-20 18:09:01 +03:00
2023-05-21 02:00:26 +03:00
// Clients
output += t.I18nBot("tgbot.messages.exhaustedCount", "Type=="+t.I18nBot("tgbot.clients"))
output += t.I18nBot("tgbot.messages.disabled", "Disabled=="+strconv.Itoa(len(disabledClients)))
output += t.I18nBot("tgbot.messages.depleteSoon", "Deplete=="+strconv.Itoa(len(exhaustedClients)))
output += "\r\n \r\n"
2023-03-24 16:20:10 +03:00
if len(exhaustedClients) > 0 {
2023-05-21 02:00:26 +03:00
output += t.I18nBot("tgbot.messages.exhaustedMsg", "Type=="+t.I18nBot("tgbot.clients"))
2023-03-17 19:07:49 +03:00
for _, traffic := range exhaustedClients {
expiryTime := ""
if traffic.ExpiryTime == 0 {
2023-05-21 02:00:26 +03:00
expiryTime = t.I18nBot("tgbot.unlimited")
} else if traffic.ExpiryTime < 0 {
2023-05-21 02:00:26 +03:00
expiryTime += fmt.Sprintf("%d %s", traffic.ExpiryTime/-86400000, t.I18nBot("tgbot.days"))
2023-03-17 19:07:49 +03:00
} else {
expiryTime = time.Unix((traffic.ExpiryTime / 1000), 0).Format("2006-01-02 15:04:05")
}
2023-05-21 02:00:26 +03:00
2023-03-17 19:07:49 +03:00
total := ""
if traffic.Total == 0 {
2023-05-21 02:00:26 +03:00
total = t.I18nBot("tgbot.unlimited")
2023-03-17 19:07:49 +03:00
} else {
total = common.FormatTraffic((traffic.Total))
}
2023-05-21 02:00:26 +03:00
output += t.I18nBot("tgbot.messages.refreshedOn", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
2023-05-21 02:00:26 +03:00
output += t.I18nBot("tgbot.messages.active", "Enable=="+strconv.FormatBool(traffic.Enable))
output += t.I18nBot("tgbot.messages.email", "Email=="+traffic.Email)
output += t.I18nBot("tgbot.messages.upload", "Upload=="+common.FormatTraffic(traffic.Up))
output += t.I18nBot("tgbot.messages.download", "Download=="+common.FormatTraffic(traffic.Down))
output += t.I18nBot("tgbot.messages.total", "UpDown=="+common.FormatTraffic((traffic.Up+traffic.Down)), "Total=="+total)
output += t.I18nBot("tgbot.messages.expireIn", "Time=="+expiryTime)
output += "\r\n \r\n"
2023-03-17 19:07:49 +03:00
}
}
return output
}
func (t *Tgbot) sendBackup(chatId int64) {
2023-05-21 06:11:59 +03:00
output := t.I18nBot("tgbot.messages.backupTime", "Time=="+time.Now().Format("2006-01-02 15:04:05"))
t.SendMsgToTgbot(chatId, output)
2023-05-14 18:20:01 +03:00
file, err := os.Open(config.GetDBPath())
if err != nil {
logger.Warning("Error in opening db file for backup: ", err)
}
document := tu.Document(
tu.ID(chatId),
tu.File(file),
)
_, err = bot.SendDocument(document)
2023-03-17 19:07:49 +03:00
if err != nil {
logger.Warning("Error in uploading backup: ", err)
}
2023-05-21 06:11:59 +03:00
2023-05-14 18:20:01 +03:00
file, err = os.Open(xray.GetConfigPath())
if err != nil {
logger.Warning("Error in opening config.json file for backup: ", err)
}
document = tu.Document(
tu.ID(chatId),
tu.File(file),
)
_, err = bot.SendDocument(document)
if err != nil {
logger.Warning("Error in uploading config.json: ", err)
}
2023-03-17 19:07:49 +03:00
}
2023-05-05 00:46:43 +03:00
func (t *Tgbot) sendCallbackAnswerTgBot(id string, message string) {
2023-05-14 18:20:01 +03:00
params := telego.AnswerCallbackQueryParams{
CallbackQueryID: id,
Text: message,
}
if err := bot.AnswerCallbackQuery(&params); err != nil {
2023-05-05 00:46:43 +03:00
logger.Warning(err)
}
}
2023-05-14 18:20:01 +03:00
func (t *Tgbot) editMessageCallbackTgBot(chatId int64, messageID int, inlineKeyboard *telego.InlineKeyboardMarkup) {
params := telego.EditMessageReplyMarkupParams{
ChatID: tu.ID(chatId),
MessageID: messageID,
ReplyMarkup: inlineKeyboard,
}
if _, err := bot.EditMessageReplyMarkup(&params); err != nil {
2023-05-05 00:46:43 +03:00
logger.Warning(err)
}
}
2023-05-14 18:20:01 +03:00
func (t *Tgbot) editMessageTgBot(chatId int64, messageID int, text string, inlineKeyboard ...*telego.InlineKeyboardMarkup) {
params := telego.EditMessageTextParams{
ChatID: tu.ID(chatId),
MessageID: messageID,
Text: text,
ParseMode: "HTML",
}
2023-05-05 00:46:43 +03:00
if len(inlineKeyboard) > 0 {
2023-05-14 18:20:01 +03:00
params.ReplyMarkup = inlineKeyboard[0]
2023-05-05 00:46:43 +03:00
}
2023-05-14 18:20:01 +03:00
if _, err := bot.EditMessageText(&params); err != nil {
2023-05-05 00:46:43 +03:00
logger.Warning(err)
}
}