From 7be85c7503c7717e6976e60b5c3f7d61af34ecdd Mon Sep 17 00:00:00 2001 From: somebodywashere <68244480+somebodywashere@users.noreply.github.com> Date: Mon, 25 Dec 2023 22:00:08 +0300 Subject: [PATCH] [tgbot] Removed usernames support for Notifications to work --- web/service/inbound.go | 8 +- web/service/tgbot.go | 123 +++++-------------------- web/translation/translate.en_US.toml | 5 +- web/translation/translate.es_ES.toml | 5 +- web/translation/translate.fa_IR.toml | 5 +- web/translation/translate.ru_RU.toml | 5 +- web/translation/translate.vi_VN.toml | 5 +- web/translation/translate.zh_Hans.toml | 5 +- 8 files changed, 36 insertions(+), 125 deletions(-) diff --git a/web/service/inbound.go b/web/service/inbound.go index 6124bd0b..30619791 100644 --- a/web/service/inbound.go +++ b/web/service/inbound.go @@ -1649,12 +1649,10 @@ func (s *InboundService) DelDepletedClients(id int) (err error) { return nil } -func (s *InboundService) GetClientTrafficTgBot(tguname string) ([]*xray.ClientTraffic, error) { - tguname = strings.Trim(tguname, "@") - tguname2 := "@" + tguname +func (s *InboundService) GetClientTrafficTgBot(tgId string) ([]*xray.ClientTraffic, error) { db := database.GetDB() var inbounds []*model.Inbound - err := db.Model(model.Inbound{}).Where("settings like ?", fmt.Sprintf(`%%"tgId": "%s"%%`, tguname)).Or("settings like ?", fmt.Sprintf(`%%"tgId": "%s"%%`, tguname2)).Find(&inbounds).Error + err := db.Model(model.Inbound{}).Where("settings like ?", fmt.Sprintf(`%%"tgId": "%s"%%`, tgId)).Find(&inbounds).Error if err != nil && err != gorm.ErrRecordNotFound { return nil, err } @@ -1665,7 +1663,7 @@ func (s *InboundService) GetClientTrafficTgBot(tguname string) ([]*xray.ClientTr logger.Error("Unable to get clients from inbound") } for _, client := range clients { - if client.TgID == tguname || client.TgID == tguname2 { + if client.TgID == tgId { emails = append(emails, client.Email) } } diff --git a/web/service/tgbot.go b/web/service/tgbot.go index 90aaf05c..29276ff6 100644 --- a/web/service/tgbot.go +++ b/web/service/tgbot.go @@ -219,7 +219,7 @@ func (t *Tgbot) answerCommand(message *telego.Message, chatId int64, isAdmin boo if isAdmin { t.searchClient(chatId, commandArgs[0]) } else { - t.getClientUsage(chatId, message.From.Username, strconv.FormatInt(message.From.ID, 10), commandArgs[0]) + t.getClientUsage(chatId, strconv.FormatInt(message.From.ID, 10), commandArgs[0]) } } else { msg += t.I18nBot("tgbot.commands.usage") @@ -732,7 +732,7 @@ func (t *Tgbot) asnwerCallback(callbackQuery *telego.CallbackQuery, isAdmin bool t.sendBanLogs(chatId, true) case "client_traffic": t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.clientUsage")) - t.getClientUsage(chatId, callbackQuery.From.Username, strconv.FormatInt(callbackQuery.From.ID, 10)) + t.getClientUsage(chatId, strconv.FormatInt(callbackQuery.From.ID, 10)) case "client_commands": t.sendCallbackAnswerTgBot(callbackQuery.ID, t.I18nBot("tgbot.buttons.commands")) t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.commands.helpClientCommands")) @@ -837,52 +837,6 @@ func (t *Tgbot) SendMsgToTgbot(chatId int64, msg string, replyMarkup ...telego.R } } -func (t *Tgbot) SendMsgToTgUsername(chatId string, msg string, replyMarkup ...telego.ReplyMarkup) { - if !isRunning { - return - } - - if msg == "" { - logger.Info("[tgbot] message is empty!") - return - } - - var allMessages []string - limit := 2000 - - // paging message if it is big - if len(msg) > limit { - messages := strings.Split(msg, "\r\n \r\n") - lastIndex := -1 - - 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 { - params := telego.SendMessageParams{ - ChatID: tu.Username(chatId), - Text: message, - ParseMode: "HTML", - } - if len(replyMarkup) > 0 { - params.ReplyMarkup = replyMarkup[0] - } - _, err := bot.SendMessage(¶ms) - if err != nil { - logger.Warning("Error sending telegram message :", err) - } - time.Sleep(500 * time.Millisecond) - } -} - func (t *Tgbot) SendMsgToTgbotAdmins(msg string, replyMarkup ...telego.ReplyMarkup) { if len(replyMarkup) > 0 { for _, adminId := range adminIds { @@ -1119,7 +1073,7 @@ func (t *Tgbot) clientInfoMsg(traffic *xray.ClientTraffic, printEnabled bool, pr return output } -func (t *Tgbot) getClientUsage(chatId int64, tgUserName string, tgUserID string, email ...string) { +func (t *Tgbot) getClientUsage(chatId int64, tgUserID string, email ...string) { traffics, err := t.inboundService.GetClientTrafficTgBot(tgUserID) if err != nil { logger.Warning(err) @@ -1127,25 +1081,16 @@ func (t *Tgbot) getClientUsage(chatId int64, tgUserName string, tgUserID string, t.SendMsgToTgbot(chatId, msg) return } - traffics2, err := t.inboundService.GetClientTrafficTgBot(tgUserName) - if err != nil { - logger.Warning(err) - msg := t.I18nBot("tgbot.wentWrong") - t.SendMsgToTgbot(chatId, msg) + + if len(traffics) == 0 { + t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.askToAddUserId", "TgUserID=="+tgUserID)) return } - if len(traffics) == 0 && len(traffics2) == 0 { - if len(tgUserName) == 0 { - t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.askToAddUserId", "TgUserID=="+tgUserID)) - } else { - t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.askToAddUserName", "TgUserName=="+tgUserName, "TgUserID=="+tgUserID)) - } - return - } + output := "" - if len(email) > 0 { - if len(traffics) > 0 { + if len(traffics) > 0 { + if len(email) > 0 { for _, traffic := range traffics { if traffic.Email == email[0] { output := t.clientInfoMsg(traffic, true, true, true, true, true, true) @@ -1153,35 +1098,15 @@ func (t *Tgbot) getClientUsage(chatId int64, tgUserName string, tgUserID string, return } } - } - if len(traffics2) > 0 { - for _, traffic := range traffics2 { - if traffic.Email == email[0] { - output := t.clientInfoMsg(traffic, true, true, true, true, true, true) - t.SendMsgToTgbot(chatId, output) - return - } + msg := t.I18nBot("tgbot.noResult") + t.SendMsgToTgbot(chatId, msg) + return + } else { + for _, traffic := range traffics { + output += t.clientInfoMsg(traffic, true, true, true, true, true, false) + output += "\r\n" } } - msg := t.I18nBot("tgbot.noResult") - t.SendMsgToTgbot(chatId, msg) - return - } - - output := "" - - if len(traffics) > 0 { - for _, traffic := range traffics { - output += t.clientInfoMsg(traffic, true, true, true, true, true, false) - output += "\r\n" - } - } - - if len(traffics2) > 0 { - for _, traffic := range traffics2 { - output += t.clientInfoMsg(traffic, true, true, true, true, true, false) - output += "\r\n" - } } output += t.I18nBot("tgbot.messages.refreshedOn", "Time=="+time.Now().Format("2006-01-02 15:04:05")) @@ -1476,13 +1401,12 @@ func (t *Tgbot) notifyExhausted() { var chatIDsDone []string for _, client := range clients { if client.TgID != "" { - //convert tgID to chatID (also convert if it's username) chatID, err := strconv.ParseInt(client.TgID, 10, 64) - chatUsername := "" if err != nil { - chatUsername = "@"+strings.Trim(client.TgID, "@") + logger.Warning("TgID is not a number: ", client.TgID) + continue } - if !slices.Contains(chatIDsDone, strings.Trim(client.TgID, "@")) { + if !slices.Contains(chatIDsDone, client.TgID) && !checkAdmin(chatID) { traffics, err := t.inboundService.GetClientTrafficTgBot(client.TgID) if err == nil { output := t.I18nBot("tgbot.messages.exhaustedCount", "Type=="+t.I18nBot("tgbot.clients")) @@ -1510,15 +1434,10 @@ func (t *Tgbot) notifyExhausted() { output += t.clientInfoMsg(&traffic, true, false, false, true, true, false) output += "\r\n" } - if chatUsername == "" { - t.SendMsgToTgbot(chatID, output) - } else { - t.SendMsgToTgUsername(chatUsername, output) - } - + t.SendMsgToTgbot(chatID, output) } } - chatIDsDone = append(chatIDsDone, strings.Trim(client.TgID, "@")) + chatIDsDone = append(chatIDsDone, client.TgID) } } } diff --git a/web/translation/translate.en_US.toml b/web/translation/translate.en_US.toml index 82b56d7c..416e540e 100644 --- a/web/translation/translate.en_US.toml +++ b/web/translation/translate.en_US.toml @@ -173,7 +173,7 @@ "setDefaultCert" = "Set Cert from Panel" "xtlsDesc" = "Xray core needs to be 1.7.5" "realityDesc" = "Xray core needs to be 1.8.0 or higher." -"telegramDesc" = "Use Telegram ID with or without @ or chat ID (you can get it here @userinfobot or use '/id' command in bot)" +"telegramDesc" = "Only use Chat ID (you can get it here @userinfobot or use '/id' command in bot)" "subscriptionDesc" = "you can find your sub link on Details, also you can use the same name for several configurations" "info" = "Info" "same" = "Same" @@ -557,5 +557,4 @@ "removedTGUserSuccess" = "✅ {{ .Email }} : Telegram User removed successfully." "enableSuccess" = "✅ {{ .Email }} : Enabled successfully." "disableSuccess" = "✅ {{ .Email }} : Disabled successfully." -"askToAddUserId" = "Your configuration is not found!\r\nPlease ask your Admin to use your telegram user id in your configuration(s).\r\n\r\nYour user id: {{ .TgUserID }}" -"askToAddUserName" = "Your configuration is not found!\r\nPlease ask your Admin to use your telegram username or user id in your configuration(s).\r\n\r\nYour username: @{{ .TgUserName }}\r\n\r\nYour user id: {{ .TgUserID }}" +"askToAddUserId" = "Your configuration is not found!\r\nPlease ask your Admin to use your telegram user id in your configuration(s).\r\n\r\nYour user id: {{ .TgUserID }}" diff --git a/web/translation/translate.es_ES.toml b/web/translation/translate.es_ES.toml index 029e7be0..63da5dbf 100644 --- a/web/translation/translate.es_ES.toml +++ b/web/translation/translate.es_ES.toml @@ -173,7 +173,7 @@ "setDefaultCert" = "Establecer certificado desde el panel" "xtlsDesc" = "La versión del núcleo de Xray debe ser 1.7.5" "realityDesc" = "La versión del núcleo de Xray debe ser 1.8.0 o superior." -"telegramDesc" = "Utiliza el ID de Telegram con o sin @ o los IDs de chat (puedes obtenerlo aquí @userinfobot o usando el comando '/id' en el bot)." +"telegramDesc" = "Utiliza únicamente IDs de chat (puedes obtenerlo aquí @userinfobot o usando el comando '/id' en el bot)." "subscriptionDesc" = "Puedes encontrar tu enlace de suscripción en Detalles, también puedes usar el mismo nombre para varias configuraciones." "info" = "Info" "same" = "misma" @@ -557,5 +557,4 @@ "removedTGUserSuccess" = "✅ {{ .Email }} : Usuario de Telegram eliminado exitosamente." "enableSuccess" = "✅ {{ .Email }} : Habilitado exitosamente." "disableSuccess" = "✅ {{ .Email }} : Deshabilitado exitosamente." -"askToAddUserId" = "¡No se encuentra su configuración!\r\nPor favor, pídale a su administrador que use su ID de usuario de Telegram en su(s) configuración(es).\r\n\r\nSu ID de usuario: {{ .TgUserID }}" -"askToAddUserName" = "¡No se encuentra su configuración!\r\nPor favor, pídale a su administrador que use su nombre de usuario o ID de usuario de Telegram en su(s) configuración(es).\r\n\r\nSu nombre de usuario: @{{ .TgUserName }}\r\n\r\nSu ID de usuario: {{ .TgUserID }}" +"askToAddUserId" = "¡No se encuentra su configuración!\r\nPor favor, pídale a su administrador que use su ID de usuario de Telegram en su(s) configuración(es).\r\n\r\nSu ID de usuario: {{ .TgUserID }}" diff --git a/web/translation/translate.fa_IR.toml b/web/translation/translate.fa_IR.toml index 168eaa99..b405761c 100644 --- a/web/translation/translate.fa_IR.toml +++ b/web/translation/translate.fa_IR.toml @@ -173,7 +173,7 @@ "setDefaultCert" = "استفاده از گواهی پنل" "xtlsDesc" = "هسته Xray باید 1.7.5 باشد" "realityDesc" = "هسته Xray باید 1.8.0 و بالاتر باشد" -"telegramDesc" = "از آیدی تلگرام با یا بدون @ یا آیدی چت استفاده کنید (می توانید آن را از اینجا دریافت کنید @userinfobot یا در ربات دستور '/id' را وارد کنید)" +"telegramDesc" = "فقط از شناسه چت استفاده کنید (می توانید آن را از اینجا دریافت کنید @userinfobot یا در ربات دستور '/id' را وارد کنید)" "subscriptionDesc" = "می توانید ساب لینک خود را در جزئیات پیدا کنید، همچنین می توانید از همین نام برای چندین کانفیگ استفاده کنید" "info" = "اطلاعات" "same" = "همسان" @@ -557,5 +557,4 @@ "removedTGUserSuccess" = "✅ {{ .Email }} : کاربر تلگرام با موفقیت حذف شد." "enableSuccess" = "✅ {{ .Email }} : با موفقیت فعال شد." "disableSuccess" = "✅ {{ .Email }} : با موفقیت غیرفعال شد." -"askToAddUserId" = "پیکربندی شما یافت نشد!\r\nلطفاً از مدیر خود بخواهید که شناسه کاربر تلگرام خود را در پیکربندی (های) خود استفاده کند.\r\n\r\nشناسه کاربری شما: {{ .TgUserID }}" -"askToAddUserName" = "پیکربندی شما یافت نشد!\r\nلطفاً از مدیر خود بخواهید که نام کاربری یا شناسه کاربر تلگرام خود را در پیکربندی (های) خود استفاده کند.\r\n\r\nنام کاربری شما: @{{ .TgUserName }}\r\n\r\nشناسه کاربری شما: {{ .TgUserID }}" +"askToAddUserId" = "پیکربندی شما یافت نشد!\r\nلطفاً از مدیر خود بخواهید که شناسه کاربر تلگرام خود را در پیکربندی (های) خود استفاده کند.\r\n\r\nشناسه کاربری شما: {{ .TgUserID }}" diff --git a/web/translation/translate.ru_RU.toml b/web/translation/translate.ru_RU.toml index b7d9a387..c2949667 100644 --- a/web/translation/translate.ru_RU.toml +++ b/web/translation/translate.ru_RU.toml @@ -173,7 +173,7 @@ "setDefaultCert" = "Установить сертификат с панели" "xtlsDesc" = "Версия Xray должна быть не ниже 1.7.5" "realityDesc" = "Версия Xray должна быть не ниже 1.8.0" -"telegramDesc" = "Используйте имя пользователя Telegram с или без @ или ID чата (можно получить его здесь @userinfobot или использовать команду '/id' в боте)" +"telegramDesc" = "Используйте только ID чата (можно получить его здесь @userinfobot или использовать команду '/id' в боте)" "subscriptionDesc" = "Вы можете найти свою ссылку подписки в разделе 'Подробнее', также вы можете использовать одно и то же имя для нескольких конфигураций" "info" = "Информация" "same" = "Тот же" @@ -557,5 +557,4 @@ "removedTGUserSuccess" = "✅ {{ .Email }}: Пользователь Telegram успешно удален." "enableSuccess" = "✅ {{ .Email }}: Включено успешно." "disableSuccess" = "✅ {{ .Email }}: Отключено успешно." -"askToAddUserId" = "Ваша конфигурация не найдена!\r\nПожалуйста, попросите администратора использовать ваш идентификатор пользователя Telegram в ваших конфигурациях.\r\n\r\nВаш идентификатор пользователя: {{ .TgUserID }}" -"askToAddUserName" = "Ваша конфигурация не найдена!\r\nПожалуйста, попросите администратора использовать ваше имя пользователя или идентификатор пользователя Telegram в ваших конфигурациях.\r\n\r\nВаше имя пользователя: @{{ .TgUserName }}\r\n\r\nВаш идентификатор пользователя: {{ .TgUserID }}" +"askToAddUserId" = "Ваша конфигурация не найдена!\r\nПожалуйста, попросите администратора использовать ваш идентификатор пользователя Telegram в ваших конфигурациях.\r\n\r\nВаш идентификатор пользователя: {{ .TgUserID }}" diff --git a/web/translation/translate.vi_VN.toml b/web/translation/translate.vi_VN.toml index ad95f084..d16c46ed 100644 --- a/web/translation/translate.vi_VN.toml +++ b/web/translation/translate.vi_VN.toml @@ -173,7 +173,7 @@ "setDefaultCert" = "Đặt chứng chỉ từ bảng điều khiển" "xtlsDesc" = "Xray core cần phiên bản 1.7.5" "realityDesc" = "Xray core cần phiên bản 1.8.0 hoặc cao hơn." -"telegramDesc" = "Sử dụng ID Telegram có hoặc không có @ hoặc chat IDs (bạn có thể nhận được nó ở đây @userinfobot hoặc sử dụng lệnh '/id' trong bot)" +"telegramDesc" = "Chỉ sử dụng ID trò chuyện (bạn có thể nhận được nó ở đây @userinfobot hoặc sử dụng lệnh '/id' trong bot)" "subscriptionDesc" = "Bạn có thể tìm liên kết đăng ký của mình trong Chi tiết, cũng như bạn có thể sử dụng cùng tên cho nhiều cấu hình khác nhau" "info" = "Thông tin" "same" = "Giống nhau" @@ -557,5 +557,4 @@ "removedTGUserSuccess" = "✅ {{ .Email }} : Người Dùng Telegram Đã Được Xóa Thành Công." "enableSuccess" = "✅ {{ .Email }} : Đã Bật Thành Công." "disableSuccess" = "✅ {{ .Email }} : Đã Tắt Thành Công." -"askToAddUserId" = "Cấu hình của bạn không được tìm thấy!\r\nVui lòng yêu cầu Quản trị viên sử dụng ID người dùng telegram của bạn trong cấu hình của bạn.\r\n\r\nID người dùng của bạn: {{ .TgUserID }}" -"askToAddUserName" = "Cấu hình của bạn không được tìm thấy!\r\nVui lòng yêu cầu Quản trị viên sử dụng tên người dùng hoặc ID người dùng telegram của bạn trong cấu hình của bạn.\r\n\r\nTên người dùng của bạn: @{{ .TgUserName }}\r\n\r\nID người dùng của bạn: {{ .TgUserID }}" +"askToAddUserId" = "Cấu hình của bạn không được tìm thấy!\r\nVui lòng yêu cầu Quản trị viên sử dụng ID người dùng telegram của bạn trong cấu hình của bạn.\r\n\r\nID người dùng của bạn: {{ .TgUserID }}" diff --git a/web/translation/translate.zh_Hans.toml b/web/translation/translate.zh_Hans.toml index deaf9da7..8093255a 100644 --- a/web/translation/translate.zh_Hans.toml +++ b/web/translation/translate.zh_Hans.toml @@ -173,7 +173,7 @@ "setDefaultCert" = "从面板设置证书" "xtlsDesc" = "Xray核心需要1.7.5" "realityDesc" = "Xray核心需要1.8.0及以上版本" -"telegramDesc" = "使用 Telegram ID(带或不带 @) 符号或聊天 ID(可以在 @userinfobot 处获取,或在机器人中使用'/id'命令)" +"telegramDesc" = "仅使用聊天 ID(可以在 @userinfobot 处获取,或在机器人中使用'/id'命令)" "subscriptionDesc" = "您可以在详细信息上找到您的子链接,也可以对多个配置使用相同的名称" "info" = "信息" "same" = "相同" @@ -557,5 +557,4 @@ "removedTGUserSuccess" = "✅ {{ .Email }}:Telegram 用户已成功移除。" "enableSuccess" = "✅ {{ .Email }}:已成功启用。" "disableSuccess" = "✅ {{ .Email }}:已成功禁用。" -"askToAddUserId" = "未找到您的配置!\r\n请向管理员询问,在您的配置中使用您的 Telegram 用户ID。\r\n\r\n您的用户ID:{{ .TgUserID }}" -"askToAddUserName" = "未找到您的配置!\r\n请向管理员询问,在您的配置中使用您的 Telegram 用户名或用户ID。\r\n\r\n您的用户名:@{{ .TgUserName }}\r\n\r\n您的用户ID:{{ .TgUserID }}" +"askToAddUserId" = "未找到您的配置!\r\n请向管理员询问,在您的配置中使用您的 Telegram 用户ID。\r\n\r\n您的用户ID:{{ .TgUserID }}"