Skip to content

Commit

Permalink
feat(tgbot): Add the option to change the telegram API server (#2584)
Browse files Browse the repository at this point in the history
  • Loading branch information
MadrinX authored Oct 17, 2024
1 parent a23f390 commit f1f8132
Show file tree
Hide file tree
Showing 16 changed files with 73 additions and 19 deletions.
1 change: 1 addition & 0 deletions web/assets/js/model/setting.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ class AllSetting {
this.tgBotEnable = false;
this.tgBotToken = "";
this.tgBotProxy = "";
this.tgBotAPIServer = "";
this.tgBotChatId = "";
this.tgRunTime = "@daily";
this.tgBotBackup = false;
Expand Down
1 change: 1 addition & 0 deletions web/entity/entity.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ type AllSetting struct {
TgBotEnable bool `json:"tgBotEnable" form:"tgBotEnable"`
TgBotToken string `json:"tgBotToken" form:"tgBotToken"`
TgBotProxy string `json:"tgBotProxy" form:"tgBotProxy"`
TgBotAPIServer string `json:"tgBotAPIServer" form:"tgBotAPIServer"`
TgBotChatId string `json:"tgBotChatId" form:"tgBotChatId"`
TgRunTime string `json:"tgRunTime" form:"tgRunTime"`
TgBotBackup bool `json:"tgBotBackup" form:"tgBotBackup"`
Expand Down
1 change: 1 addition & 0 deletions web/html/xui/settings.html
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,7 @@
<setting-list-item type="switch" title='{{ i18n "pages.settings.tgNotifyLogin" }}' desc='{{ i18n "pages.settings.tgNotifyLoginDesc" }}' v-model="allSetting.tgBotLoginNotify"></setting-list-item>
<setting-list-item type="number" title='{{ i18n "pages.settings.tgNotifyCpu" }}' desc='{{ i18n "pages.settings.tgNotifyCpuDesc" }}' v-model="allSetting.tgCpu" :min="0" :max="100"></setting-list-item>
<setting-list-item type="text" title='{{ i18n "pages.settings.telegramProxy"}}' desc='{{ i18n "pages.settings.telegramProxyDesc"}}' v-model="allSetting.tgBotProxy" placeholder="socks5://user:pass@host:port"></setting-list-item>
<setting-list-item type="text" title='{{ i18n "pages.settings.telegramAPIServer"}}' desc='{{ i18n "pages.settings.telegramAPIServerDesc"}}' v-model="allSetting.tgBotAPIServer" placeholder="https://api.example.com"></setting-list-item>
<a-list-item>
<a-row style="padding: 20px">
<a-col :lg="24" :xl="12">
Expand Down
9 changes: 9 additions & 0 deletions web/service/setting.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ var defaultValueMap = map[string]string{
"tgBotEnable": "false",
"tgBotToken": "",
"tgBotProxy": "",
"tgBotAPIServer": "",
"tgBotChatId": "",
"tgRunTime": "@daily",
"tgBotBackup": "false",
Expand Down Expand Up @@ -262,6 +263,14 @@ func (s *SettingService) SetTgBotProxy(token string) error {
return s.setString("tgBotProxy", token)
}

func (s *SettingService) GetTgBotAPIServer() (string, error) {
return s.getString("tgBotAPIServer")
}

func (s *SettingService) SetTgBotAPIServer(token string) error {
return s.setString("tgBotAPIServer", token)
}

func (s *SettingService) GetTgBotChatId() (string, error) {
return s.getString("tgBotChatId")
}
Expand Down
42 changes: 31 additions & 11 deletions web/service/tgbot.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,14 @@ func (t *Tgbot) Start(i18nFS embed.FS) error {
logger.Warning("Failed to get Telegram bot proxy URL:", err)
}

// Get Telegram bot API server URL
tgBotAPIServer, err := t.settingService.GetTgBotAPIServer()
if err != nil {
logger.Warning("Failed to get Telegram bot API server URL:", err)
}

// Create new Telegram bot instance
bot, err = t.NewBot(tgBotToken, tgBotProxy)
bot, err = t.NewBot(tgBotToken, tgBotProxy, tgBotAPIServer)
if err != nil {
logger.Error("Failed to initialize Telegram bot API:", err)
return err
Expand All @@ -125,26 +131,40 @@ func (t *Tgbot) Start(i18nFS embed.FS) error {
return nil
}

func (t *Tgbot) NewBot(token string, proxyUrl string) (*telego.Bot, error) {
if proxyUrl == "" {
// No proxy URL provided, use default instance
func (t *Tgbot) NewBot(token string, proxyUrl string, apiServerUrl string) (*telego.Bot, error) {
if proxyUrl == "" && apiServerUrl == "" {
return telego.NewBot(token)
}

if !strings.HasPrefix(proxyUrl, "socks5://") {
logger.Warning("Invalid socks5 URL, starting with default")
if proxyUrl != "" {
if !strings.HasPrefix(proxyUrl, "socks5://") {
logger.Warning("Invalid socks5 URL, using default")
return telego.NewBot(token)
}

_, err := url.Parse(proxyUrl)
if err != nil {
logger.Warningf("Can't parse proxy URL, using default instance for tgbot: %v", err)
return telego.NewBot(token)
}

return telego.NewBot(token, telego.WithFastHTTPClient(&fasthttp.Client{
Dial: fasthttpproxy.FasthttpSocksDialer(proxyUrl),
}))
}

if !strings.HasPrefix(apiServerUrl, "http") {
logger.Warning("Invalid http(s) URL, using default")
return telego.NewBot(token)
}

_, err := url.Parse(proxyUrl)
_, err := url.Parse(apiServerUrl)
if err != nil {
logger.Warning("Can't parse proxy URL, using default instance for tgbot:", err)
logger.Warningf("Can't parse API server URL, using default instance for tgbot: %v", err)
return telego.NewBot(token)
}

return telego.NewBot(token, telego.WithFastHTTPClient(&fasthttp.Client{
Dial: fasthttpproxy.FasthttpSocksDialer(proxyUrl),
}))
return telego.NewBot(token, telego.WithAPIServer(apiServerUrl))
}

func (t *Tgbot) IsRunning() bool {
Expand Down
2 changes: 2 additions & 0 deletions web/translation/translate.en_US.toml
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,8 @@
"telegramTokenDesc" = "The Telegram bot token obtained from '@BotFather'."
"telegramProxy" = "SOCKS Proxy"
"telegramProxyDesc" = "Enables SOCKS5 proxy for connecting to Telegram. (adjust settings as per guide)"
"telegramAPIServer" = "Telegram API Server"
"telegramAPIServerDesc" = "The Telegram API server to use. Leave blank to use the default server."
"telegramChatId" = "Admin Chat ID"
"telegramChatIdDesc" = "The Telegram Admin Chat ID(s). (comma-separated)(get it here @userinfobot) or (use '/id' command in the bot)"
"telegramNotifyTime" = "Notification Time"
Expand Down
4 changes: 3 additions & 1 deletion web/translation/translate.es_ES.toml
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,8 @@
"telegramTokenDesc" = "Debe obtener el token del administrador de bots de Telegram @botfather."
"telegramProxy" = "Socks5 Proxy"
"telegramProxyDesc" = "Si necesita el proxy Socks5 para conectarse a Telegram. Ajuste su configuración según la guía."
"telegramAPIServer" = "API Server de Telegram"
"telegramAPIServerDesc" = "El servidor API de Telegram a utilizar. Déjelo en blanco para utilizar el servidor predeterminado."
"telegramChatId" = "IDs de Chat de Telegram para Administradores"
"telegramChatIdDesc" = "IDs de Chat múltiples separados por comas. Use @userinfobot o use el comando '/id' en el bot para obtener sus IDs de Chat."
"telegramNotifyTime" = "Hora de Notificación del Bot de Telegram"
Expand Down Expand Up @@ -592,4 +594,4 @@
"disableSuccess" = "✅ {{ .Email }} : Deshabilitado exitosamente."
"askToAddUserId" = "¡No se encuentra su configuración!\r\nPor favor, pídale a su administrador que use su ChatID de usuario de Telegram en su(s) configuración(es).\r\n\r\nSu ChatID de usuario: <code>{{ .TgUserID }}</code>"
"chooseClient" = "Elige un Cliente para Inbound {{ .Inbound }}"
"chooseInbound" = "Elige un Inbound"
"chooseInbound" = "Elige un Inbound"
4 changes: 3 additions & 1 deletion web/translation/translate.fa_IR.toml
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,8 @@
"telegramTokenDesc" = "دریافت کنید @botfather توکن را می‌توانید از"
"telegramProxy" = "SOCKS پراکسی"
"telegramProxyDesc" = "را برای اتصال به تلگرام فعال می کند SOCKS5 پراکسی"
"telegramAPIServer" = "سرور API تلگرام"
"telegramAPIServerDesc" = "API سرور تلگرام برای اتصال را تغییر میدهد. برای استفاده از سرور پیش فرض خالی بگذارید"
"telegramChatId" = "آی‌دی چت مدیر"
"telegramChatIdDesc" = "دریافت ‌کنید ('/id'یا (دستور (@userinfobot) آی‌دی(های) چت تلگرام مدیر، از"
"telegramNotifyTime" = "زمان نوتیفیکیشن"
Expand Down Expand Up @@ -592,4 +594,4 @@
"disableSuccess" = "✅ {{ .Email }} : با موفقیت غیرفعال شد."
"askToAddUserId" = "پیکربندی شما یافت نشد!\r\nلطفاً از مدیر خود بخواهید که شناسه کاربر تلگرام خود را در پیکربندی (های) خود استفاده کند.\r\n\r\nشناسه کاربری شما: <code>{{ .TgUserID }}</code>"
"chooseClient" = "یک مشتری برای ورودی {{ .Inbound }} انتخاب کنید"
"chooseInbound" = "یک ورودی انتخاب کنید"
"chooseInbound" = "یک ورودی انتخاب کنید"
4 changes: 3 additions & 1 deletion web/translation/translate.id_ID.toml
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,8 @@
"telegramTokenDesc" = "Token bot Telegram yang diperoleh dari '@BotFather'."
"telegramProxy" = "Proxy SOCKS"
"telegramProxyDesc" = "Mengaktifkan proxy SOCKS5 untuk terhubung ke Telegram. (sesuaikan pengaturan sesuai panduan)"
"telegramAPIServer" = "Telegram API Server"
"telegramAPIServerDesc" = "Server API Telegram yang akan digunakan. Biarkan kosong untuk menggunakan server default."
"telegramChatId" = "ID Obrolan Admin"
"telegramChatIdDesc" = "ID Obrolan Admin Telegram. (dipisahkan koma)(dapatkan di sini @userinfobot) atau (gunakan perintah '/id' di bot)"
"telegramNotifyTime" = "Waktu Notifikasi"
Expand Down Expand Up @@ -592,4 +594,4 @@
"disableSuccess" = "✅ {{ .Email }}: Dinonaktifkan dengan berhasil."
"askToAddUserId" = "Konfigurasi Anda tidak ditemukan!\r\nSilakan minta admin Anda untuk menggunakan ChatID Telegram Anda dalam konfigurasi Anda.\r\n\r\nChatID Pengguna Anda: <code>{{ .TgUserID }}</code>"
"chooseClient" = "Pilih Klien untuk Inbound {{ .Inbound }}"
"chooseInbound" = "Pilih Inbound"
"chooseInbound" = "Pilih Inbound"
2 changes: 2 additions & 0 deletions web/translation/translate.pt_BR.toml
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,8 @@
"telegramTokenDesc" = "O token do bot do Telegram obtido de '@BotFather'."
"telegramProxy" = "Proxy SOCKS"
"telegramProxyDesc" = "Ativa o proxy SOCKS5 para conectar ao Telegram. (ajuste as configurações conforme o guia)"
"telegramAPIServer" = "API Server do Telegram"
"telegramAPIServerDesc" = "O servidor API do Telegram a ser usado. Deixe em branco para usar o servidor padrão."
"telegramChatId" = "ID de Chat do Administrador"
"telegramChatIdDesc" = "O(s) ID(s) de Chat do Administrador no Telegram. (separado por vírgulas)(obtenha aqui @userinfobot) ou (use o comando '/id' no bot)"
"telegramNotifyTime" = "Hora da Notificação"
Expand Down
2 changes: 2 additions & 0 deletions web/translation/translate.ru_RU.toml
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,8 @@
"telegramTokenDesc" = "Необходимо получить токен у менеджера ботов Telegram @botfather"
"telegramProxy" = "Прокси Socks5"
"telegramProxyDesc" = "Если для подключения к Telegram вам нужен прокси Socks5. Настройте его параметры согласно руководству."
"telegramAPIServer" = "API-сервер Telegram"
"telegramAPIServerDesc" = "Используемый API-сервер Telegram. Оставьте пустым, чтобы использовать сервер по умолчанию."
"telegramChatId" = "Идентификатор Telegram администратора бота"
"telegramChatIdDesc" = "Один или несколько идентификаторов администратора бота. Чтобы получить идентификатор, используйте @userinfobot или команду '/id' в боте."
"telegramNotifyTime" = "Частота уведомлений бота Telegram"
Expand Down
4 changes: 3 additions & 1 deletion web/translation/translate.tr_TR.toml
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,8 @@
"telegramTokenDesc" = "'@BotFather'dan alınan Telegram bot token."
"telegramProxy" = "SOCKS Proxy"
"telegramProxyDesc" = "Telegram'a bağlanmak için SOCKS5 proxy'sini etkinleştirir. (ayarları kılavuzda belirtilen şekilde ayarlayın)"
"telegramAPIServer" = "Telegram API Server"
"telegramAPIServerDesc" = "Kullanılacak Telegram API sunucusu. Varsayılan sunucuyu kullanmak için boş bırakın."
"telegramChatId" = "Yönetici Sohbet Kimliği"
"telegramChatIdDesc" = "Telegram Yönetici Sohbet Kimliği(leri). (virgülle ayrılmış)(buradan alın @userinfobot) veya (botta '/id' komutunu kullanın)"
"telegramNotifyTime" = "Bildirim Zamanı"
Expand Down Expand Up @@ -592,4 +594,4 @@
"disableSuccess" = "✅ {{ .Email }}: Başarıyla devre dışı bırakıldı."
"askToAddUserId" = "Yapılandırmanız bulunamadı!\r\nLütfen yöneticinizden yapılandırmalarınıza Telegram ChatID'nizi eklemesini isteyin.\r\n\r\nKullanıcı ChatID'niz: <code>{{ .TgUserID }}</code>"
"chooseClient" = "Gelen {{ .Inbound }} için bir Müşteri Seçin"
"chooseInbound" = "Bir Gelen Seçin"
"chooseInbound" = "Bir Gelen Seçin"
4 changes: 3 additions & 1 deletion web/translation/translate.uk_UA.toml
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,8 @@
"telegramTokenDesc" = "Токен бота Telegram, отриманий від '@BotFather'."
"telegramProxy" = "SOCKS Проксі"
"telegramProxyDesc" = "Вмикає проксі-сервер SOCKS5 для підключення до Telegram. (відкоригуйте параметри відповідно до посібника)"
"telegramAPIServer" = "Сервер Telegram API"
"telegramAPIServerDesc" = "Сервер Telegram API для використання. Залиште поле порожнім, щоб використовувати сервер за умовчанням."
"telegramChatId" = "Ідентифікатор чату адміністратора"
"telegramChatIdDesc" = "Ідентифікатори чату адміністратора Telegram. (розділені комами) (отримайте тут @userinfobot) або (використовуйте команду '/id' у боті)"
"telegramNotifyTime" = "Час сповіщення"
Expand Down Expand Up @@ -592,4 +594,4 @@
"disableSuccess" = "✅ {{ .Email }}: Успішно вимкнено."
"askToAddUserId" = "Вашу конфігурацію не знайдено!\r\nБудь ласка, попросіть свого адміністратора використовувати ваш ідентифікатор Telegram у вашій конфігурації.\r\n\r\nВаш ідентифікатор користувача: <code>{{ .TgUserID }}</code>"
"chooseClient" = "Виберіть клієнта для Вхідного {{ .Inbound }}"
"chooseInbound" = "Виберіть Вхідний"
"chooseInbound" = "Виберіть Вхідний"
4 changes: 3 additions & 1 deletion web/translation/translate.vi_VN.toml
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,8 @@
"telegramTokenDesc" = "Bạn phải nhận token từ quản lý bot Telegram @botfather"
"telegramProxy" = "Socks5 Proxy"
"telegramProxyDesc" = "Nếu bạn cần socks5 proxy để kết nối với Telegram. Điều chỉnh cài đặt của nó theo hướng dẫn."
"telegramAPIServer" = "Telegram API Server"
"telegramAPIServerDesc" = "Máy chủ API Telegram để sử dụng. Để trống để sử dụng máy chủ mặc định."
"telegramChatId" = "Chat ID Telegram của quản trị viên"
"telegramChatIdDesc" = "Nhiều Chat ID phân tách bằng dấu phẩy. Sử dụng @userinfobot hoặc sử dụng lệnh '/id' trong bot để lấy Chat ID của bạn."
"telegramNotifyTime" = "Thời gian thông báo của bot Telegram"
Expand Down Expand Up @@ -592,4 +594,4 @@
"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: <code>{{ .TgUserID }}</code>"
"chooseClient" = "Chọn một Khách hàng cho Inbound {{ .Inbound }}"
"chooseInbound" = "Chọn một Inbound"
"chooseInbound" = "Chọn một Inbound"
4 changes: 3 additions & 1 deletion web/translation/translate.zh_CN.toml
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,8 @@
"telegramTokenDesc" = "从 '@BotFather' 获取的 Telegram 机器人令牌"
"telegramProxy" = "SOCKS5 Proxy"
"telegramProxyDesc" = "启用 SOCKS5 代理连接到 Telegram(根据指南调整设置)"
"telegramAPIServer" = "Telegram API Server"
"telegramAPIServerDesc" = "要使用的 Telegram API 服务器。留空以使用默认服务器。"
"telegramChatId" = "管理员聊天 ID"
"telegramChatIdDesc" = "Telegram 管理员聊天 ID (多个以逗号分隔)(可通过 @userinfobot 获取,或在机器人中使用 '/id' 命令获取)"
"telegramNotifyTime" = "通知时间"
Expand Down Expand Up @@ -592,4 +594,4 @@
"disableSuccess" = "✅ {{ .Email }}:已成功禁用。"
"askToAddUserId" = "未找到您的配置!\r\n请向管理员询问,在您的配置中使用您的 Telegram 用户 ChatID。\r\n\r\n您的用户 ChatID:<code>{{ .TgUserID }}</code>"
"chooseClient" = "为入站 {{ .Inbound }} 选择一个客户"
"chooseInbound" = "选择一个入站"
"chooseInbound" = "选择一个入站"
4 changes: 3 additions & 1 deletion web/translation/translate.zh_TW.toml
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,8 @@
"telegramTokenDesc" = "從 '@BotFather' 獲取的 Telegram 機器人令牌"
"telegramProxy" = "SOCKS5 Proxy"
"telegramProxyDesc" = "啟用 SOCKS5 代理連線到 Telegram(根據指南調整設定)"
"telegramAPIServer" = "Telegram API Server"
"telegramAPIServerDesc" = "要使用的 Telegram API 伺服器。留空以使用預設伺服器。"
"telegramChatId" = "管理員聊天 ID"
"telegramChatIdDesc" = "Telegram 管理員聊天 ID (多個以逗號分隔)(可通過 @userinfobot 獲取,或在機器人中使用 '/id' 命令獲取)"
"telegramNotifyTime" = "通知時間"
Expand Down Expand Up @@ -592,4 +594,4 @@
"disableSuccess" = "✅ {{ .Email }}:已成功禁用。"
"askToAddUserId" = "未找到您的配置!\r\n請向管理員詢問,在您的配置中使用您的 Telegram 使用者 ChatID。\r\n\r\n您的使用者 ChatID:<code>{{ .TgUserID }}</code>"
"chooseClient" = "為入站 {{ .Inbound }} 選擇一個客戶"
"chooseInbound" = "選擇一個入站"
"chooseInbound" = "選擇一個入站"

1 comment on commit f1f8132

@badmast
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks.

Please sign in to comment.