diff --git a/nanobot/channels/contracts.py b/nanobot/channels/contracts.py index 75bb4a0db..0b9319a56 100644 --- a/nanobot/channels/contracts.py +++ b/nanobot/channels/contracts.py @@ -2,6 +2,7 @@ from __future__ import annotations +import json from collections.abc import Iterable from copy import deepcopy from dataclasses import dataclass @@ -11,7 +12,7 @@ from typing import TYPE_CHECKING, Any, Callable, Literal, TypeGuard, cast if TYPE_CHECKING: from nanobot.channels.plugin import ChannelPlugin -FieldKind = Literal["string", "secret", "list", "bool", "int", "enum"] +FieldKind = Literal["string", "secret", "list", "bool", "int", "float", "json", "enum"] RouteFieldType = str | tuple[str, set[str]] @@ -162,6 +163,7 @@ class ChannelSetupSpec: required: tuple[SetupRequirement, ...] = () official_url: str | None = None validator: SetupValidator | None = None + verifies_connection: bool = False @property def secrets(self) -> frozenset[str]: @@ -211,9 +213,20 @@ class ChannelSetupSpec: fields.append(public_field) payload: dict[str, Any] = { "fields": fields, + "requirements": [ + { + "alternatives": [ + [f"channels.{channel_name}.{name}" for name in alternative] + for alternative in requirement.alternatives + ] + } + for requirement in self.required + ], } if self.official_url: payload["official_url"] = self.official_url + if self.verifies_connection: + payload["verifies_connection"] = True return payload @@ -572,6 +585,8 @@ def stringify_channel_value(value: Any) -> str: return "true" if value else "false" if isinstance(value, list): return ", ".join(str(item) for item in cast(list[Any], value)) + if isinstance(value, dict): + return json.dumps(value, ensure_ascii=False, indent=2) return str(value) diff --git a/nanobot/channels/dingtalk/manifest.py b/nanobot/channels/dingtalk/manifest.py index 767d5497d..21faf504d 100644 --- a/nanobot/channels/dingtalk/manifest.py +++ b/nanobot/channels/dingtalk/manifest.py @@ -9,6 +9,10 @@ SETUP_SPEC = ChannelSetupSpec( "clientId": field(), "clientSecret": field("secret"), "allowFrom": field("list"), + "allowRemoteMediaRedirects": field("bool", default=False), + "remoteMediaRedirectAllowedHosts": field("list"), + "groupUserIsolation": field("bool", default=False), + "disablePrivateChat": field("bool", default=False), }, required=required_fields("clientId", "clientSecret"), official_url="https://open.dingtalk.com/", diff --git a/nanobot/channels/dingtalk/webui/index.ts b/nanobot/channels/dingtalk/webui/index.ts index ab352ee94..26a02e23d 100644 --- a/nanobot/channels/dingtalk/webui/index.ts +++ b/nanobot/channels/dingtalk/webui/index.ts @@ -3,18 +3,17 @@ import { chatAppGuideUrl } from "@/components/settings/channels/catalog"; export default { presentation: { + logoUrl: "https://img.alicdn.com/imgextra/i3/O1CN01WMvMRG1ks3Ixc9x1v_!!6000000004738-55-tps-32-32.svg", displayName: "DingTalk", initials: "DT", color: "#1677FF", - logoUrl: - "https://img.alicdn.com/imgextra/i3/O1CN01WMvMRG1ks3Ixc9x1v_!!6000000004738-55-tps-32-32.svg", setup: { mode: "credentials", docsUrl: chatAppGuideUrl("dingtalk"), fields: [ - { key: "channels.dingtalk.clientId" }, - { key: "channels.dingtalk.clientSecret" }, - { key: "channels.dingtalk.allowFrom" }, + { key: "channels.dingtalk.clientId", section: "credentials" }, + { key: "channels.dingtalk.clientSecret", section: "credentials" }, + { key: "channels.dingtalk.allowFrom", section: "access" }, ], }, }, diff --git a/nanobot/channels/dingtalk/webui/locales/en.json b/nanobot/channels/dingtalk/webui/locales/en.json index 9dcfd66da..82405ab39 100644 --- a/nanobot/channels/dingtalk/webui/locales/en.json +++ b/nanobot/channels/dingtalk/webui/locales/en.json @@ -1,30 +1,43 @@ { - "description": "Use nanobot from DingTalk groups.", - "requirements": "DingTalk app credentials and gateway", "setup": { "docsLabel": "Open DingTalk setup", "officialLabel": "Open DingTalk console", - "tryIt": "Send a test message from the DingTalk group where the app is installed.", - "summary": "DingTalk needs app credentials from Stream mode.", - "steps": [ - "Create or choose a DingTalk app with Stream mode enabled.", - "Add Client ID and Client Secret.", - "Save and enable DingTalk, then send a test message." - ], "fields": { "clientId": { "label": "Client ID", - "placeholder": "DingTalk client ID", - "help": "Copy it from DingTalk app credentials." + "placeholder": "DingTalk client ID" }, "clientSecret": { "label": "Client Secret", - "placeholder": "••••••", - "help": "Copy it from the same DingTalk app credentials page." + "placeholder": "••••••" }, "allowFrom": { "label": "Allowed users", "placeholder": "User IDs, comma separated" + }, + "allowRemoteMediaRedirects": { + "label": "Allow media redirects", + "choices": { + "true": "On", + "false": "Off" + } + }, + "remoteMediaRedirectAllowedHosts": { + "label": "Media redirect hosts" + }, + "groupUserIsolation": { + "label": "Separate group sessions", + "choices": { + "true": "On", + "false": "Off" + } + }, + "disablePrivateChat": { + "label": "Disable direct messages", + "choices": { + "true": "On", + "false": "Off" + } } } } diff --git a/nanobot/channels/dingtalk/webui/locales/es.json b/nanobot/channels/dingtalk/webui/locales/es.json index 7d411699c..edcc0eb85 100644 --- a/nanobot/channels/dingtalk/webui/locales/es.json +++ b/nanobot/channels/dingtalk/webui/locales/es.json @@ -1,30 +1,43 @@ { - "description": "Usa nanobot desde grupos de DingTalk.", - "requirements": "Credenciales de la app de DingTalk y pasarela", "setup": { "docsLabel": "Abrir guía de DingTalk", "officialLabel": "Abrir consola de DingTalk", - "tryIt": "Envía un mensaje de prueba desde el grupo de DingTalk donde está instalada la app.", - "summary": "DingTalk necesita credenciales de una app en modo Stream.", - "steps": [ - "Crea o elige una app de DingTalk con el modo Stream activado.", - "Añade el Client ID y el Client Secret.", - "Guarda y activa DingTalk; después envía un mensaje de prueba." - ], "fields": { "clientId": { "label": "Client ID", - "placeholder": "Client ID de DingTalk", - "help": "Cópialo de las credenciales de la app de DingTalk." + "placeholder": "Client ID de DingTalk" }, "clientSecret": { "label": "Client Secret", - "placeholder": "••••••", - "help": "Cópialo de la misma página de credenciales." + "placeholder": "••••••" }, "allowFrom": { "label": "Usuarios permitidos", "placeholder": "ID de usuario separados por comas" + }, + "allowRemoteMediaRedirects": { + "label": "Permitir redirecciones de medios", + "choices": { + "true": "encendido", + "false": "Apagado" + } + }, + "remoteMediaRedirectAllowedHosts": { + "label": "Hosts de redireccionamiento de medios" + }, + "groupUserIsolation": { + "label": "Sesiones grupales separadas", + "choices": { + "true": "encendido", + "false": "Apagado" + } + }, + "disablePrivateChat": { + "label": "Desactivar mensajes directos", + "choices": { + "true": "encendido", + "false": "Apagado" + } } } } diff --git a/nanobot/channels/dingtalk/webui/locales/fr.json b/nanobot/channels/dingtalk/webui/locales/fr.json index d0eb8fa51..ec5b162d2 100644 --- a/nanobot/channels/dingtalk/webui/locales/fr.json +++ b/nanobot/channels/dingtalk/webui/locales/fr.json @@ -1,30 +1,43 @@ { - "description": "Utilisez nanobot depuis les groupes DingTalk.", - "requirements": "Identifiants d’application DingTalk et passerelle", "setup": { "docsLabel": "Ouvrir le guide DingTalk", "officialLabel": "Ouvrir la console DingTalk", - "tryIt": "Envoyez un message test dans le groupe DingTalk où l’application est installée.", - "summary": "DingTalk nécessite les identifiants d’une application en mode Stream.", - "steps": [ - "Créez ou choisissez une application DingTalk avec le mode Stream activé.", - "Ajoutez le Client ID et le Client Secret.", - "Enregistrez et activez DingTalk, puis envoyez un message test." - ], "fields": { "clientId": { "label": "Client ID", - "placeholder": "Client ID DingTalk", - "help": "Copiez-le depuis les identifiants de l’application DingTalk." + "placeholder": "Client ID DingTalk" }, "clientSecret": { "label": "Client Secret", - "placeholder": "••••••", - "help": "Copiez-le depuis la même page d’identifiants DingTalk." + "placeholder": "••••••" }, "allowFrom": { "label": "Utilisateurs autorisés", "placeholder": "ID utilisateur séparés par des virgules" + }, + "allowRemoteMediaRedirects": { + "label": "Autoriser les redirections multimédias", + "choices": { + "true": "Sur", + "false": "Désactivé" + } + }, + "remoteMediaRedirectAllowedHosts": { + "label": "Hôtes de redirection multimédia" + }, + "groupUserIsolation": { + "label": "Séances de groupe séparées", + "choices": { + "true": "Sur", + "false": "Désactivé" + } + }, + "disablePrivateChat": { + "label": "Désactiver les messages directs", + "choices": { + "true": "Sur", + "false": "Désactivé" + } } } } diff --git a/nanobot/channels/dingtalk/webui/locales/id.json b/nanobot/channels/dingtalk/webui/locales/id.json index c4728d003..38bb612e2 100644 --- a/nanobot/channels/dingtalk/webui/locales/id.json +++ b/nanobot/channels/dingtalk/webui/locales/id.json @@ -1,30 +1,43 @@ { - "description": "Gunakan nanobot dari grup DingTalk.", - "requirements": "Kredensial aplikasi DingTalk dan gateway", "setup": { "docsLabel": "Buka panduan DingTalk", "officialLabel": "Buka konsol DingTalk", - "tryIt": "Kirim pesan uji dari grup DingTalk tempat aplikasi dipasang.", - "summary": "DingTalk memerlukan kredensial aplikasi dari mode Stream.", - "steps": [ - "Buat atau pilih aplikasi DingTalk dengan mode Stream aktif.", - "Tambahkan Client ID dan Client Secret.", - "Simpan dan aktifkan DingTalk, lalu kirim pesan uji." - ], "fields": { "clientId": { "label": "Client ID", - "placeholder": "Client ID DingTalk", - "help": "Salin dari kredensial aplikasi DingTalk." + "placeholder": "Client ID DingTalk" }, "clientSecret": { "label": "Client Secret", - "placeholder": "••••••", - "help": "Salin dari halaman kredensial yang sama." + "placeholder": "••••••" }, "allowFrom": { "label": "Pengguna yang diizinkan", "placeholder": "ID pengguna, dipisahkan koma" + }, + "allowRemoteMediaRedirects": { + "label": "Izinkan pengalihan media", + "choices": { + "true": "Aktif", + "false": "Mati" + } + }, + "remoteMediaRedirectAllowedHosts": { + "label": "Host pengalihan media" + }, + "groupUserIsolation": { + "label": "Sesi kelompok terpisah", + "choices": { + "true": "Aktif", + "false": "Mati" + } + }, + "disablePrivateChat": { + "label": "Nonaktifkan pesan langsung", + "choices": { + "true": "Aktif", + "false": "Mati" + } } } } diff --git a/nanobot/channels/dingtalk/webui/locales/ja.json b/nanobot/channels/dingtalk/webui/locales/ja.json index 3ffbd5d1c..8bf27f0d0 100644 --- a/nanobot/channels/dingtalk/webui/locales/ja.json +++ b/nanobot/channels/dingtalk/webui/locales/ja.json @@ -1,30 +1,43 @@ { - "description": "DingTalk グループから nanobot を利用します。", - "requirements": "DingTalk アプリの認証情報とゲートウェイ", "setup": { "docsLabel": "DingTalk 設定ガイドを開く", "officialLabel": "DingTalk コンソールを開く", - "tryIt": "アプリをインストールした DingTalk グループからテストメッセージを送信します。", - "summary": "DingTalk には Stream モードのアプリ認証情報が必要です。", - "steps": [ - "Stream モードを有効にした DingTalk アプリを作成または選択します。", - "Client ID と Client Secret を追加します。", - "保存して DingTalk を有効にし、テストメッセージを送信します。" - ], "fields": { "clientId": { "label": "Client ID", - "placeholder": "DingTalk Client ID", - "help": "DingTalk アプリの認証情報からコピーします。" + "placeholder": "DingTalk Client ID" }, "clientSecret": { "label": "Client Secret", - "placeholder": "••••••", - "help": "同じ認証情報ページからコピーします。" + "placeholder": "••••••" }, "allowFrom": { "label": "許可するユーザー", "placeholder": "ユーザー ID(カンマ区切り)" + }, + "allowRemoteMediaRedirects": { + "label": "メディアのリダイレクトを許可する", + "choices": { + "true": "オン", + "false": "オフ" + } + }, + "remoteMediaRedirectAllowedHosts": { + "label": "メディアリダイレクトホスト" + }, + "groupUserIsolation": { + "label": "個別のグループセッション", + "choices": { + "true": "オン", + "false": "オフ" + } + }, + "disablePrivateChat": { + "label": "ダイレクトメッセージを無効にする", + "choices": { + "true": "オン", + "false": "オフ" + } } } } diff --git a/nanobot/channels/dingtalk/webui/locales/ko.json b/nanobot/channels/dingtalk/webui/locales/ko.json index ccc7eb5a5..e754728d6 100644 --- a/nanobot/channels/dingtalk/webui/locales/ko.json +++ b/nanobot/channels/dingtalk/webui/locales/ko.json @@ -1,30 +1,43 @@ { - "description": "DingTalk 그룹에서 nanobot을 사용합니다.", - "requirements": "DingTalk 앱 인증 정보 및 게이트웨이", "setup": { "docsLabel": "DingTalk 설정 가이드 열기", "officialLabel": "DingTalk 콘솔 열기", - "tryIt": "앱이 설치된 DingTalk 그룹에서 테스트 메시지를 보내세요.", - "summary": "DingTalk에는 Stream 모드 앱 인증 정보이 필요합니다.", - "steps": [ - "Stream 모드가 활성화된 DingTalk 앱을 만들거나 선택하세요.", - "Client ID와 Client Secret을 추가하세요.", - "저장하고 DingTalk을 활성화한 다음 테스트 메시지를 보내세요." - ], "fields": { "clientId": { "label": "Client ID", - "placeholder": "DingTalk Client ID", - "help": "DingTalk 앱 인증 정보에서 복사하세요." + "placeholder": "DingTalk Client ID" }, "clientSecret": { "label": "Client Secret", - "placeholder": "••••••", - "help": "같은 인증 정보 페이지에서 복사하세요." + "placeholder": "••••••" }, "allowFrom": { "label": "허용된 사용자", "placeholder": "사용자 ID, 쉼표로 구분" + }, + "allowRemoteMediaRedirects": { + "label": "미디어 리디렉션 허용", + "choices": { + "true": "켜기", + "false": "끄기" + } + }, + "remoteMediaRedirectAllowedHosts": { + "label": "미디어 리디렉션 호스트" + }, + "groupUserIsolation": { + "label": "별도의 그룹 세션", + "choices": { + "true": "켜기", + "false": "끄기" + } + }, + "disablePrivateChat": { + "label": "다이렉트 메시지 비활성화", + "choices": { + "true": "켜기", + "false": "끄기" + } } } } diff --git a/nanobot/channels/dingtalk/webui/locales/pt-BR.json b/nanobot/channels/dingtalk/webui/locales/pt-BR.json index 9dbca3735..545ee3eaf 100644 --- a/nanobot/channels/dingtalk/webui/locales/pt-BR.json +++ b/nanobot/channels/dingtalk/webui/locales/pt-BR.json @@ -1,30 +1,43 @@ { - "description": "Use o nanobot em grupos do DingTalk.", - "requirements": "Credenciais do app DingTalk e gateway", "setup": { "docsLabel": "Abrir guia do DingTalk", "officialLabel": "Abrir console do DingTalk", - "tryIt": "Envie uma mensagem de teste no grupo do DingTalk onde o app está instalado.", - "summary": "O DingTalk precisa das credenciais de um app no modo Stream.", - "steps": [ - "Crie ou escolha um app do DingTalk com o modo Stream ativado.", - "Adicione o Client ID e o Client Secret.", - "Salve e ative o DingTalk; depois, envie uma mensagem de teste." - ], "fields": { "clientId": { "label": "Client ID", - "placeholder": "Client ID do DingTalk", - "help": "Copie das credenciais do app DingTalk." + "placeholder": "Client ID do DingTalk" }, "clientSecret": { "label": "Client Secret", - "placeholder": "••••••", - "help": "Copie da mesma página de credenciais." + "placeholder": "••••••" }, "allowFrom": { "label": "Usuários permitidos", "placeholder": "IDs de usuário separados por vírgulas" + }, + "allowRemoteMediaRedirects": { + "label": "Permitir redirecionamentos de mídia", + "choices": { + "true": "Ligado", + "false": "Desligado" + } + }, + "remoteMediaRedirectAllowedHosts": { + "label": "Hosts de redirecionamento de mídia" + }, + "groupUserIsolation": { + "label": "Sessões de grupo separadas", + "choices": { + "true": "Ligado", + "false": "Desligado" + } + }, + "disablePrivateChat": { + "label": "Desativar mensagens diretas", + "choices": { + "true": "Ligado", + "false": "Desligado" + } } } } diff --git a/nanobot/channels/dingtalk/webui/locales/vi.json b/nanobot/channels/dingtalk/webui/locales/vi.json index d0616d0a7..b71da5533 100644 --- a/nanobot/channels/dingtalk/webui/locales/vi.json +++ b/nanobot/channels/dingtalk/webui/locales/vi.json @@ -1,30 +1,43 @@ { - "description": "Sử dụng nanobot trong các nhóm DingTalk.", - "requirements": "Thông tin xác thực ứng dụng DingTalk và gateway", "setup": { "docsLabel": "Mở hướng dẫn DingTalk", "officialLabel": "Mở bảng điều khiển DingTalk", - "tryIt": "Gửi tin nhắn thử từ nhóm DingTalk đã cài ứng dụng.", - "summary": "DingTalk cần thông tin xác thực ứng dụng ở chế độ Stream.", - "steps": [ - "Tạo hoặc chọn ứng dụng DingTalk đã bật chế độ Stream.", - "Thêm Client ID và Client Secret.", - "Lưu và bật DingTalk, sau đó gửi tin nhắn thử." - ], "fields": { "clientId": { "label": "Client ID", - "placeholder": "Client ID DingTalk", - "help": "Sao chép từ thông tin xác thực ứng dụng DingTalk." + "placeholder": "Client ID DingTalk" }, "clientSecret": { "label": "Client Secret", - "placeholder": "••••••", - "help": "Sao chép từ cùng trang thông tin xác thực." + "placeholder": "••••••" }, "allowFrom": { "label": "Người dùng được phép", "placeholder": "ID người dùng, phân tách bằng dấu phẩy" + }, + "allowRemoteMediaRedirects": { + "label": "Cho phép chuyển hướng phương tiện", + "choices": { + "true": "Bật", + "false": "Tắt" + } + }, + "remoteMediaRedirectAllowedHosts": { + "label": "Máy chủ chuyển hướng phương tiện" + }, + "groupUserIsolation": { + "label": "Các buổi nhóm riêng biệt", + "choices": { + "true": "Bật", + "false": "Tắt" + } + }, + "disablePrivateChat": { + "label": "Tắt tin nhắn trực tiếp", + "choices": { + "true": "Bật", + "false": "Tắt" + } } } } diff --git a/nanobot/channels/dingtalk/webui/locales/zh-CN.json b/nanobot/channels/dingtalk/webui/locales/zh-CN.json index b80ad7b86..04c0cfcbf 100644 --- a/nanobot/channels/dingtalk/webui/locales/zh-CN.json +++ b/nanobot/channels/dingtalk/webui/locales/zh-CN.json @@ -1,31 +1,44 @@ { "displayName": "钉钉", - "description": "在钉钉群中使用 nanobot。", - "requirements": "钉钉应用凭据和网关", "setup": { "docsLabel": "打开钉钉配置指南", "officialLabel": "打开钉钉开发者后台", - "tryIt": "在已安装应用的钉钉群中发送一条测试消息。", - "summary": "钉钉需要 Stream 模式的应用凭据。", - "steps": [ - "创建或选择一个已启用 Stream 模式的钉钉应用。", - "填写 Client ID 和 Client Secret。", - "保存并启用钉钉,然后发送一条测试消息。" - ], "fields": { "clientId": { "label": "Client ID", - "placeholder": "钉钉 Client ID", - "help": "从钉钉应用凭据页面复制。" + "placeholder": "钉钉 Client ID" }, "clientSecret": { "label": "Client Secret", - "placeholder": "••••••", - "help": "从同一个钉钉应用凭据页面复制。" + "placeholder": "••••••" }, "allowFrom": { "label": "允许的用户", "placeholder": "用户 ID,用逗号分隔" + }, + "allowRemoteMediaRedirects": { + "label": "允许媒体重定向", + "choices": { + "true": "开启", + "false": "关闭" + } + }, + "remoteMediaRedirectAllowedHosts": { + "label": "允许重定向的媒体主机" + }, + "groupUserIsolation": { + "label": "按群成员隔离会话", + "choices": { + "true": "开启", + "false": "关闭" + } + }, + "disablePrivateChat": { + "label": "禁用私聊", + "choices": { + "true": "开启", + "false": "关闭" + } } } } diff --git a/nanobot/channels/dingtalk/webui/locales/zh-TW.json b/nanobot/channels/dingtalk/webui/locales/zh-TW.json index 2ce8a1c6e..df60ca07d 100644 --- a/nanobot/channels/dingtalk/webui/locales/zh-TW.json +++ b/nanobot/channels/dingtalk/webui/locales/zh-TW.json @@ -1,31 +1,44 @@ { "displayName": "釘釘", - "description": "在釘釘群組中使用 nanobot。", - "requirements": "釘釘應用程式憑證和閘道", "setup": { "docsLabel": "開啟釘釘設定指南", "officialLabel": "開啟釘釘開發者後台", - "tryIt": "在已安裝應用程式的釘釘群組中傳送一則測試訊息。", - "summary": "釘釘需要 Stream 模式的應用程式憑證。", - "steps": [ - "建立或選擇一個已啟用 Stream 模式的釘釘應用程式。", - "填入 Client ID 和 Client Secret。", - "儲存並啟用釘釘,然後傳送一則測試訊息。" - ], "fields": { "clientId": { "label": "Client ID", - "placeholder": "釘釘 Client ID", - "help": "從釘釘應用程式憑證頁面複製。" + "placeholder": "釘釘 Client ID" }, "clientSecret": { "label": "Client Secret", - "placeholder": "••••••", - "help": "從同一個釘釘應用程式憑證頁面複製。" + "placeholder": "••••••" }, "allowFrom": { "label": "允許的使用者", "placeholder": "使用者 ID,以逗號分隔" + }, + "allowRemoteMediaRedirects": { + "label": "允許媒體重定向", + "choices": { + "true": "開啟", + "false": "關閉" + } + }, + "remoteMediaRedirectAllowedHosts": { + "label": "允許重定向的媒體主機" + }, + "groupUserIsolation": { + "label": "按群組成員隔離會話", + "choices": { + "true": "開啟", + "false": "關閉" + } + }, + "disablePrivateChat": { + "label": "停用私聊", + "choices": { + "true": "開啟", + "false": "關閉" + } } } } diff --git a/nanobot/channels/discord/manifest.py b/nanobot/channels/discord/manifest.py index 8c6a1ab3e..f398ffe10 100644 --- a/nanobot/channels/discord/manifest.py +++ b/nanobot/channels/discord/manifest.py @@ -8,13 +8,22 @@ from nanobot.channels.plugin import ChannelPlugin SETUP_SPEC = ChannelSetupSpec( fields={ "token": field("secret"), + "proxy": field(), + "proxyUsername": field(), + "proxyPassword": field("secret"), "allowFrom": field("list", snapshot=False), "allowChannels": field("list"), "groupPolicy": field("enum", choices=DIRECT_GROUP_POLICIES, default="mention"), + "intents": field("int", default=37377), + "readReceiptEmoji": field(default="👀"), + "workingEmoji": field(default="🔧"), + "workingEmojiDelay": field("float", default=2.0), + "streaming": field("bool", default=True), }, required=(required("token"),), official_url="https://discord.com/developers/applications", validator=validate, + verifies_connection=True, ) PLUGIN = ChannelPlugin( diff --git a/nanobot/channels/discord/runtime.py b/nanobot/channels/discord/runtime.py index 38dcce695..71083d62f 100644 --- a/nanobot/channels/discord/runtime.py +++ b/nanobot/channels/discord/runtime.py @@ -464,10 +464,13 @@ class DiscordChannel(BaseChannel): "proxy_password must be set; ignoring partial credentials", ) + proxy = self.config.proxy + if proxy and "://" not in proxy: + proxy = f"http://{proxy}" self._client = DiscordBotClient( self, intents=intents, - proxy=self.config.proxy, + proxy=proxy, proxy_auth=proxy_auth, ) except Exception: diff --git a/nanobot/channels/discord/validation.py b/nanobot/channels/discord/validation.py index 6b24e8936..6fb1025ee 100644 --- a/nanobot/channels/discord/validation.py +++ b/nanobot/channels/discord/validation.py @@ -18,11 +18,13 @@ from nanobot.channels.validation import ( def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dict[str, Any]: checks, missing = required_checks("discord", values) token = string_value(values.get("token")) + proxy = string_value(values.get("proxy")) if token: try: data = http_get( "https://discord.com/api/v10/users/@me", headers={"Authorization": f"Bot {token}"}, + proxy=proxy or None, ) bot_id = str(data.get("id") or "") checks.append(check("bot_token", "Bot token", "pass", "Discord accepted the bot token.")) diff --git a/nanobot/channels/discord/webui/index.ts b/nanobot/channels/discord/webui/index.ts index b6e58715e..f59324dee 100644 --- a/nanobot/channels/discord/webui/index.ts +++ b/nanobot/channels/discord/webui/index.ts @@ -3,17 +3,21 @@ import { chatAppGuideUrl } from "@/components/settings/channels/catalog"; export default { presentation: { + logoUrl: "https://discord.com/favicon.ico", displayName: "Discord", initials: "DC", color: "#5865F2", - logoUrl: "https://discord.com/favicon.ico", setup: { mode: "credentials", docsUrl: chatAppGuideUrl("discord"), fields: [ - { key: "channels.discord.token" }, - { key: "channels.discord.allowChannels" }, - { key: "channels.discord.groupPolicy" }, + { key: "channels.discord.token", section: "credentials" }, + { key: "channels.discord.proxy", section: "connection" }, + { key: "channels.discord.proxyUsername", section: "connection" }, + { key: "channels.discord.proxyPassword", section: "connection" }, + { key: "channels.discord.allowFrom", section: "access" }, + { key: "channels.discord.allowChannels", section: "access" }, + { key: "channels.discord.groupPolicy", section: "behavior" }, ], }, }, diff --git a/nanobot/channels/discord/webui/locales/en.json b/nanobot/channels/discord/webui/locales/en.json index e3ab140a1..a72a33564 100644 --- a/nanobot/channels/discord/webui/locales/en.json +++ b/nanobot/channels/discord/webui/locales/en.json @@ -1,26 +1,15 @@ { - "description": "Use nanobot from Discord servers and DMs.", - "requirements": "Discord bot token, permissions, gateway", "setup": { "docsLabel": "Open Discord setup", "officialLabel": "Open Discord portal", - "tryIt": "Mention the bot in a server or send it a direct message.", - "summary": "Connecting Discord requires a bot token and the appropriate server permissions.", - "steps": [ - "Create a bot in Discord Developer Portal and copy its token.", - "Invite the bot to your server with message read/send and slash command permissions.", - "Save and enable Discord, then mention the bot or send a direct message." - ], "fields": { "token": { "label": "Bot token", - "placeholder": "Discord bot token", - "help": "Create it from the Bot page in Discord Developer Portal." + "placeholder": "Discord bot token" }, "allowChannels": { "label": "Allowed channels", - "placeholder": "Channel IDs, comma separated", - "help": "Leave empty to allow any channel the bot can read." + "placeholder": "Channel IDs, comma separated" }, "groupPolicy": { "label": "Group behavior", @@ -33,6 +22,34 @@ "allowFrom": { "label": "Allowed users", "placeholder": "User IDs, comma separated" + }, + "proxy": { + "label": "Network proxy" + }, + "proxyUsername": { + "label": "Proxy username" + }, + "proxyPassword": { + "label": "Proxy password" + }, + "intents": { + "label": "Gateway intents" + }, + "readReceiptEmoji": { + "label": "Read emoji" + }, + "workingEmoji": { + "label": "Working emoji" + }, + "workingEmojiDelay": { + "label": "Working emoji delay" + }, + "streaming": { + "label": "Streaming", + "choices": { + "true": "On", + "false": "Off" + } } } } diff --git a/nanobot/channels/discord/webui/locales/es.json b/nanobot/channels/discord/webui/locales/es.json index c22ee5ae3..d59e479de 100644 --- a/nanobot/channels/discord/webui/locales/es.json +++ b/nanobot/channels/discord/webui/locales/es.json @@ -1,26 +1,15 @@ { - "description": "Usa nanobot en servidores y mensajes directos de Discord.", - "requirements": "Token del bot de Discord, permisos y pasarela", "setup": { "docsLabel": "Abrir guía de Discord", "officialLabel": "Abrir portal de Discord", - "tryIt": "Menciona al bot en un servidor o envíale un mensaje directo.", - "summary": "Para conectar Discord necesitas un token de bot y los permisos adecuados en el servidor.", - "steps": [ - "Crea un bot en Discord Developer Portal y copia su token.", - "Invítalo al servidor con permisos para leer/enviar mensajes y usar comandos slash.", - "Guarda y activa Discord; después menciona al bot o envíale un mensaje directo." - ], "fields": { "token": { "label": "Token del bot", - "placeholder": "Token del bot de Discord", - "help": "Créalo desde la página Bot de Discord Developer Portal." + "placeholder": "Token del bot de Discord" }, "allowChannels": { "label": "Canales permitidos", - "placeholder": "ID de canal separados por comas", - "help": "Déjalo vacío para permitir cualquier canal que el bot pueda leer." + "placeholder": "ID de canal separados por comas" }, "groupPolicy": { "label": "Comportamiento en grupos", @@ -33,6 +22,34 @@ "allowFrom": { "label": "Usuarios permitidos", "placeholder": "ID de usuario separados por comas" + }, + "proxy": { + "label": "proxy de red" + }, + "proxyUsername": { + "label": "Nombre de usuario proxy" + }, + "proxyPassword": { + "label": "Contraseña de proxy" + }, + "intents": { + "label": "Intentos de puerta de enlace" + }, + "readReceiptEmoji": { + "label": "Leer emojis" + }, + "workingEmoji": { + "label": "Emoji de trabajo" + }, + "workingEmojiDelay": { + "label": "Retraso de emoji de trabajo" + }, + "streaming": { + "label": "Transmisión", + "choices": { + "true": "encendido", + "false": "Apagado" + } } } } diff --git a/nanobot/channels/discord/webui/locales/fr.json b/nanobot/channels/discord/webui/locales/fr.json index b0462580a..0cc69e573 100644 --- a/nanobot/channels/discord/webui/locales/fr.json +++ b/nanobot/channels/discord/webui/locales/fr.json @@ -1,26 +1,15 @@ { - "description": "Utilisez nanobot sur les serveurs Discord et en messages privés.", - "requirements": "Jeton du bot Discord, permissions et passerelle", "setup": { "docsLabel": "Ouvrir le guide Discord", "officialLabel": "Ouvrir le portail Discord", - "tryIt": "Mentionnez le bot sur un serveur ou envoyez-lui un message privé.", - "summary": "La connexion à Discord nécessite un jeton de bot et les permissions appropriées sur le serveur.", - "steps": [ - "Créez un bot dans le portail développeur Discord et copiez son jeton.", - "Invitez-le sur votre serveur avec les permissions de lecture, d’envoi et de commandes slash.", - "Enregistrez et activez Discord, puis mentionnez le bot ou envoyez-lui un message privé." - ], "fields": { "token": { "label": "Jeton du bot", - "placeholder": "Jeton du bot Discord", - "help": "Créez-le depuis la page Bot du portail développeur Discord." + "placeholder": "Jeton du bot Discord" }, "allowChannels": { "label": "Salons autorisés", - "placeholder": "ID de salon séparés par des virgules", - "help": "Laissez vide pour autoriser tous les salons lisibles par le bot." + "placeholder": "ID de salon séparés par des virgules" }, "groupPolicy": { "label": "Comportement en groupe", @@ -33,6 +22,34 @@ "allowFrom": { "label": "Utilisateurs autorisés", "placeholder": "ID utilisateur séparés par des virgules" + }, + "proxy": { + "label": "Mandataire réseau" + }, + "proxyUsername": { + "label": "Nom d'utilisateur du proxy" + }, + "proxyPassword": { + "label": "Mot de passe proxy" + }, + "intents": { + "label": "Intentions de passerelle" + }, + "readReceiptEmoji": { + "label": "Lire les emoji" + }, + "workingEmoji": { + "label": "Emoji fonctionnel" + }, + "workingEmojiDelay": { + "label": "Retard d'emoji fonctionnel" + }, + "streaming": { + "label": "Diffusion en continu", + "choices": { + "true": "Sur", + "false": "Désactivé" + } } } } diff --git a/nanobot/channels/discord/webui/locales/id.json b/nanobot/channels/discord/webui/locales/id.json index 91c194526..a251732a5 100644 --- a/nanobot/channels/discord/webui/locales/id.json +++ b/nanobot/channels/discord/webui/locales/id.json @@ -1,26 +1,15 @@ { - "description": "Gunakan nanobot dari server dan DM Discord.", - "requirements": "Token bot Discord, izin, dan gateway", "setup": { "docsLabel": "Buka panduan Discord", "officialLabel": "Buka portal Discord", - "tryIt": "Sebut bot di server atau kirim pesan langsung.", - "summary": "Untuk menghubungkan Discord, Anda memerlukan token bot dan izin yang sesuai di server.", - "steps": [ - "Buat bot di Discord Developer Portal dan salin tokennya.", - "Undang bot ke server dengan izin baca/kirim pesan dan perintah slash.", - "Simpan dan aktifkan Discord, lalu sebut bot atau kirim DM." - ], "fields": { "token": { "label": "Token bot", - "placeholder": "Token bot Discord", - "help": "Buat dari halaman Bot di Discord Developer Portal." + "placeholder": "Token bot Discord" }, "allowChannels": { "label": "Kanal yang diizinkan", - "placeholder": "ID kanal, dipisahkan koma", - "help": "Kosongkan untuk mengizinkan semua kanal yang dapat dibaca bot." + "placeholder": "ID kanal, dipisahkan koma" }, "groupPolicy": { "label": "Perilaku grup", @@ -33,6 +22,34 @@ "allowFrom": { "label": "Pengguna yang diizinkan", "placeholder": "ID pengguna, dipisahkan koma" + }, + "proxy": { + "label": "Proksi jaringan" + }, + "proxyUsername": { + "label": "Nama pengguna proksi" + }, + "proxyPassword": { + "label": "Kata sandi proksi" + }, + "intents": { + "label": "Maksud gerbang" + }, + "readReceiptEmoji": { + "label": "Baca emoji" + }, + "workingEmoji": { + "label": "Emoji yang berfungsi" + }, + "workingEmojiDelay": { + "label": "Penundaan emoji yang berfungsi" + }, + "streaming": { + "label": "Streaming", + "choices": { + "true": "Aktif", + "false": "Mati" + } } } } diff --git a/nanobot/channels/discord/webui/locales/ja.json b/nanobot/channels/discord/webui/locales/ja.json index 75a550bcb..5d7b7e903 100644 --- a/nanobot/channels/discord/webui/locales/ja.json +++ b/nanobot/channels/discord/webui/locales/ja.json @@ -1,26 +1,15 @@ { - "description": "Discord サーバーと DM から nanobot を利用します。", - "requirements": "Discord ボットトークン、権限、ゲートウェイ", "setup": { "docsLabel": "Discord 設定ガイドを開く", "officialLabel": "Discord ポータルを開く", - "tryIt": "サーバーでボットをメンションするか、DM を送信します。", - "summary": "Discord への接続には、ボットトークンとサーバー上の適切な権限が必要です。", - "steps": [ - "Discord Developer Portal でボットを作成し、トークンをコピーします。", - "メッセージの読み書きとスラッシュコマンド権限を付けてサーバーに招待します。", - "保存して Discord を有効にし、メンションまたは DM を送信します。" - ], "fields": { "token": { "label": "ボットトークン", - "placeholder": "Discord ボットトークン", - "help": "Discord Developer Portal の Bot ページで作成します。" + "placeholder": "Discord ボットトークン" }, "allowChannels": { "label": "許可するチャンネル", - "placeholder": "チャンネル ID(カンマ区切り)", - "help": "空欄の場合、ボットが読めるすべてのチャンネルを許可します。" + "placeholder": "チャンネル ID(カンマ区切り)" }, "groupPolicy": { "label": "グループでの動作", @@ -33,6 +22,34 @@ "allowFrom": { "label": "許可するユーザー", "placeholder": "ユーザー ID(カンマ区切り)" + }, + "proxy": { + "label": "ネットワークプロキシ" + }, + "proxyUsername": { + "label": "プロキシのユーザー名" + }, + "proxyPassword": { + "label": "プロキシパスワード" + }, + "intents": { + "label": "ゲートウェイの意図" + }, + "readReceiptEmoji": { + "label": "絵文字を読む" + }, + "workingEmoji": { + "label": "働く絵文字" + }, + "workingEmojiDelay": { + "label": "絵文字の動作遅延" + }, + "streaming": { + "label": "ストリーミング", + "choices": { + "true": "オン", + "false": "オフ" + } } } } diff --git a/nanobot/channels/discord/webui/locales/ko.json b/nanobot/channels/discord/webui/locales/ko.json index c27ba75ad..19084d271 100644 --- a/nanobot/channels/discord/webui/locales/ko.json +++ b/nanobot/channels/discord/webui/locales/ko.json @@ -1,26 +1,15 @@ { - "description": "Discord 서버와 DM에서 nanobot을 사용합니다.", - "requirements": "Discord 봇 토큰, 권한 및 게이트웨이", "setup": { "docsLabel": "Discord 설정 가이드 열기", "officialLabel": "Discord 포털 열기", - "tryIt": "서버에서 봇을 멘션하거나 DM을 보내세요.", - "summary": "Discord에 연결하려면 봇 토큰과 서버 내 접근 권한이 필요합니다.", - "steps": [ - "Discord Developer Portal에서 봇을 만들고 토큰을 복사하세요.", - "메시지 읽기/보내기 및 슬래시 명령 권한으로 서버에 초대하세요.", - "저장하고 Discord를 활성화한 다음 봇을 멘션하거나 DM을 보내세요." - ], "fields": { "token": { "label": "봇 토큰", - "placeholder": "Discord 봇 토큰", - "help": "Discord Developer Portal의 Bot 페이지에서 생성하세요." + "placeholder": "Discord 봇 토큰" }, "allowChannels": { "label": "허용된 채널", - "placeholder": "채널 ID, 쉼표로 구분", - "help": "비워 두면 봇이 읽을 수 있는 모든 채널을 허용합니다." + "placeholder": "채널 ID, 쉼표로 구분" }, "groupPolicy": { "label": "그룹 동작", @@ -33,6 +22,34 @@ "allowFrom": { "label": "허용된 사용자", "placeholder": "사용자 ID, 쉼표로 구분" + }, + "proxy": { + "label": "네트워크 프록시" + }, + "proxyUsername": { + "label": "프록시 사용자 이름" + }, + "proxyPassword": { + "label": "프록시 비밀번호" + }, + "intents": { + "label": "게이트웨이 인텐트" + }, + "readReceiptEmoji": { + "label": "이모티콘 읽기" + }, + "workingEmoji": { + "label": "일하는 이모티콘" + }, + "workingEmojiDelay": { + "label": "작동하는 이모티콘 지연" + }, + "streaming": { + "label": "스트리밍", + "choices": { + "true": "켜기", + "false": "끄기" + } } } } diff --git a/nanobot/channels/discord/webui/locales/pt-BR.json b/nanobot/channels/discord/webui/locales/pt-BR.json index 970f646a9..00f815f97 100644 --- a/nanobot/channels/discord/webui/locales/pt-BR.json +++ b/nanobot/channels/discord/webui/locales/pt-BR.json @@ -1,26 +1,15 @@ { - "description": "Use o nanobot em servidores e DMs do Discord.", - "requirements": "Token do bot Discord, permissões e gateway", "setup": { "docsLabel": "Abrir guia do Discord", "officialLabel": "Abrir portal do Discord", - "tryIt": "Mencione o bot em um servidor ou envie uma mensagem direta.", - "summary": "Para conectar o Discord, você precisa de um token de bot e das permissões adequadas no servidor.", - "steps": [ - "Crie um bot no Discord Developer Portal e copie o token.", - "Convide-o para o servidor com permissões de leitura/envio e comandos slash.", - "Salve e ative o Discord; depois, mencione o bot ou envie uma DM." - ], "fields": { "token": { "label": "Token do bot", - "placeholder": "Token do bot Discord", - "help": "Crie-o na página Bot do Discord Developer Portal." + "placeholder": "Token do bot Discord" }, "allowChannels": { "label": "Canais permitidos", - "placeholder": "IDs de canal separados por vírgulas", - "help": "Deixe vazio para permitir qualquer canal que o bot consiga ler." + "placeholder": "IDs de canal separados por vírgulas" }, "groupPolicy": { "label": "Comportamento em grupos", @@ -33,6 +22,34 @@ "allowFrom": { "label": "Usuários permitidos", "placeholder": "IDs de usuário separados por vírgulas" + }, + "proxy": { + "label": "Proxy de rede" + }, + "proxyUsername": { + "label": "Nome de usuário proxy" + }, + "proxyPassword": { + "label": "Senha proxy" + }, + "intents": { + "label": "Intenções de gateway" + }, + "readReceiptEmoji": { + "label": "Ler emoticons" + }, + "workingEmoji": { + "label": "Emoji de trabalho" + }, + "workingEmojiDelay": { + "label": "Atraso de emoji funcionando" + }, + "streaming": { + "label": "Transmissão", + "choices": { + "true": "Ligado", + "false": "Desligado" + } } } } diff --git a/nanobot/channels/discord/webui/locales/vi.json b/nanobot/channels/discord/webui/locales/vi.json index 2f830d06f..99b5a89a1 100644 --- a/nanobot/channels/discord/webui/locales/vi.json +++ b/nanobot/channels/discord/webui/locales/vi.json @@ -1,26 +1,15 @@ { - "description": "Sử dụng nanobot trong máy chủ và tin nhắn riêng Discord.", - "requirements": "Token bot Discord, quyền và gateway", "setup": { "docsLabel": "Mở hướng dẫn Discord", "officialLabel": "Mở cổng nhà phát triển Discord", - "tryIt": "Nhắc bot trong máy chủ hoặc gửi tin nhắn riêng.", - "summary": "Để kết nối Discord, bạn cần token bot và các quyền phù hợp trên máy chủ.", - "steps": [ - "Tạo bot trong Discord Developer Portal và sao chép token.", - "Mời bot vào máy chủ với quyền đọc/gửi tin nhắn và lệnh slash.", - "Lưu và bật Discord, sau đó nhắc bot hoặc gửi tin nhắn riêng." - ], "fields": { "token": { "label": "Token bot", - "placeholder": "Token bot Discord", - "help": "Tạo từ trang Bot trong Discord Developer Portal." + "placeholder": "Token bot Discord" }, "allowChannels": { "label": "Kênh được phép", - "placeholder": "ID kênh, phân tách bằng dấu phẩy", - "help": "Để trống để cho phép mọi kênh bot có thể đọc." + "placeholder": "ID kênh, phân tách bằng dấu phẩy" }, "groupPolicy": { "label": "Hành vi trong nhóm", @@ -33,6 +22,34 @@ "allowFrom": { "label": "Người dùng được phép", "placeholder": "ID người dùng, phân tách bằng dấu phẩy" + }, + "proxy": { + "label": "Proxy mạng" + }, + "proxyUsername": { + "label": "Tên người dùng proxy" + }, + "proxyPassword": { + "label": "Mật khẩu proxy" + }, + "intents": { + "label": "Ý định của cổng" + }, + "readReceiptEmoji": { + "label": "Đọc biểu tượng cảm xúc" + }, + "workingEmoji": { + "label": "Biểu tượng cảm xúc đang hoạt động" + }, + "workingEmojiDelay": { + "label": "Độ trễ biểu tượng cảm xúc đang hoạt động" + }, + "streaming": { + "label": "Truyền phát", + "choices": { + "true": "Bật", + "false": "Tắt" + } } } } diff --git a/nanobot/channels/discord/webui/locales/zh-CN.json b/nanobot/channels/discord/webui/locales/zh-CN.json index ae614d08f..9f78658bd 100644 --- a/nanobot/channels/discord/webui/locales/zh-CN.json +++ b/nanobot/channels/discord/webui/locales/zh-CN.json @@ -1,26 +1,15 @@ { - "description": "在 Discord 服务器和私信中使用 nanobot。", - "requirements": "Discord 机器人令牌、权限和网关", "setup": { "docsLabel": "打开 Discord 配置指南", "officialLabel": "打开 Discord 开发者后台", - "tryIt": "在服务器中提及机器人,或向它发送私信。", - "summary": "连接 Discord 需要机器人令牌,以及机器人在服务器中的相应权限。", - "steps": [ - "在 Discord Developer Portal 中创建机器人并复制令牌。", - "将机器人邀请到服务器,并授予读取/发送消息及斜杠命令权限。", - "保存并启用 Discord,然后提及机器人或发送私信。" - ], "fields": { "token": { "label": "机器人令牌", - "placeholder": "Discord 机器人令牌", - "help": "从 Discord Developer Portal 的 Bot 页面创建。" + "placeholder": "Discord 机器人令牌" }, "allowChannels": { "label": "允许的频道", - "placeholder": "频道 ID,用逗号分隔", - "help": "留空则允许机器人可读取的所有频道。" + "placeholder": "频道 ID,用逗号分隔" }, "groupPolicy": { "label": "群组行为", @@ -33,6 +22,34 @@ "allowFrom": { "label": "允许的用户", "placeholder": "用户 ID,用逗号分隔" + }, + "proxy": { + "label": "网络代理" + }, + "proxyUsername": { + "label": "代理用户名" + }, + "proxyPassword": { + "label": "代理密码" + }, + "intents": { + "label": "Gateway Intents" + }, + "readReceiptEmoji": { + "label": "已读表情" + }, + "workingEmoji": { + "label": "处理中表情" + }, + "workingEmojiDelay": { + "label": "处理中表情延迟" + }, + "streaming": { + "label": "流式输出", + "choices": { + "true": "开启", + "false": "关闭" + } } } } diff --git a/nanobot/channels/discord/webui/locales/zh-TW.json b/nanobot/channels/discord/webui/locales/zh-TW.json index 9d173bd67..215fa4402 100644 --- a/nanobot/channels/discord/webui/locales/zh-TW.json +++ b/nanobot/channels/discord/webui/locales/zh-TW.json @@ -1,26 +1,15 @@ { - "description": "在 Discord 伺服器和私訊中使用 nanobot。", - "requirements": "Discord 機器人權杖、權限和閘道", "setup": { "docsLabel": "開啟 Discord 設定指南", "officialLabel": "開啟 Discord 開發者後台", - "tryIt": "在伺服器中提及機器人,或向它傳送私訊。", - "summary": "連接 Discord 需要機器人權杖,以及機器人在伺服器中的適當權限。", - "steps": [ - "在 Discord Developer Portal 中建立機器人並複製權杖。", - "將機器人邀請到伺服器,並授予讀取/傳送訊息及斜線指令權限。", - "儲存並啟用 Discord,然後提及機器人或傳送私訊。" - ], "fields": { "token": { "label": "機器人權杖", - "placeholder": "Discord 機器人權杖", - "help": "從 Discord Developer Portal 的 Bot 頁面建立。" + "placeholder": "Discord 機器人權杖" }, "allowChannels": { "label": "允許的頻道", - "placeholder": "頻道 ID,以逗號分隔", - "help": "留空則允許機器人可讀取的所有頻道。" + "placeholder": "頻道 ID,以逗號分隔" }, "groupPolicy": { "label": "群組行為", @@ -33,6 +22,34 @@ "allowFrom": { "label": "允許的使用者", "placeholder": "使用者 ID,以逗號分隔" + }, + "proxy": { + "label": "網路代理" + }, + "proxyUsername": { + "label": "代理用戶名" + }, + "proxyPassword": { + "label": "代理密碼" + }, + "intents": { + "label": "Gateway Intents" + }, + "readReceiptEmoji": { + "label": "已讀表情" + }, + "workingEmoji": { + "label": "處理中表情" + }, + "workingEmojiDelay": { + "label": "處理中表情延遲" + }, + "streaming": { + "label": "串流輸出", + "choices": { + "true": "開啟", + "false": "關閉" + } } } } diff --git a/nanobot/channels/email/manifest.py b/nanobot/channels/email/manifest.py index ba046d714..e8a1fa6a0 100644 --- a/nanobot/channels/email/manifest.py +++ b/nanobot/channels/email/manifest.py @@ -21,6 +21,21 @@ SETUP_SPEC = ChannelSetupSpec( "allowFrom": field("list"), "verifyDkim": field("bool", default=True), "verifySpf": field("bool", default=True), + "imapMailbox": field(default="INBOX"), + "imapUseSsl": field("bool", default=True), + "smtpUseTls": field("bool", default=True), + "smtpUseSsl": field("bool", default=False), + "autoReplyEnabled": field("bool", default=True), + "markSeen": field("bool", default=True), + "postAction": field("enum", choices={"delete", "move"}), + "postActionMoveMailbox": field(), + "postActionExpunge": field("bool", default=False), + "postActionIgnoreSkipped": field("bool", default=True), + "maxBodyChars": field("int", default=12000), + "subjectPrefix": field(default="Re: "), + "allowedAttachmentTypes": field("list"), + "maxAttachmentSize": field("int", default=2_000_000), + "maxAttachmentsPerEmail": field("int", default=5), }, required=required_fields( "consentGranted", @@ -33,6 +48,7 @@ SETUP_SPEC = ChannelSetupSpec( ), official_url="https://support.google.com/accounts/answer/185833", validator=validate, + verifies_connection=True, ) PLUGIN = ChannelPlugin( diff --git a/nanobot/channels/email/tests/test_validation.py b/nanobot/channels/email/tests/test_validation.py index 01e3da8be..0de376f54 100644 --- a/nanobot/channels/email/tests/test_validation.py +++ b/nanobot/channels/email/tests/test_validation.py @@ -1,13 +1,20 @@ from __future__ import annotations +import imaplib + import pytest from nanobot.channels.email import validation as email_validation +from nanobot.channels.email.manifest import SETUP_SPEC from nanobot.channels.validation import validate_channel_config from nanobot.config.loader import save_config from nanobot.config.schema import Config +def test_email_exposes_connection_checks_to_setup_clients() -> None: + assert SETUP_SPEC.verifies_connection is True + + def test_validate_email_presets_are_checked_without_saving( tmp_path, monkeypatch: pytest.MonkeyPatch, @@ -17,6 +24,17 @@ def test_validate_email_presets_are_checked_without_saving( original_config = config_path.read_bytes() monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path) monkeypatch.setattr(email_validation, "probe_tcp", lambda *_args, **_kwargs: None) + login_calls: list[tuple[str, tuple[object, ...], dict[str, object]]] = [] + monkeypatch.setattr( + email_validation, + "_imap_login", + lambda *args, **kwargs: login_calls.append(("imap", args, kwargs)), + ) + monkeypatch.setattr( + email_validation, + "_smtp_login", + lambda *args, **kwargs: login_calls.append(("smtp", args, kwargs)), + ) result = validate_channel_config( "email", @@ -33,9 +51,64 @@ def test_validate_email_presets_are_checked_without_saving( assert result["status"] == "connected" assert result["can_enable"] is True + assert [check["id"] for check in result["checks"]][-2:] == [ + "smtp_reachability", + "smtp_account", + ] + assert login_calls == [ + ( + "imap", + ("imap.gmail.com", 993, "bot@example.com", "imap-secret"), + {"mailbox": "INBOX", "use_ssl": True}, + ), + ( + "smtp", + ("smtp.gmail.com", 587, "bot@example.com", "smtp-secret"), + {"use_ssl": False, "use_tls": True}, + ), + ] assert config_path.read_bytes() == original_config +def test_validate_email_rejects_invalid_account_credentials( + tmp_path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + config_path = tmp_path / "config.json" + save_config(Config(), config_path) + monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path) + monkeypatch.setattr(email_validation, "probe_tcp", lambda *_args, **_kwargs: None) + + def reject_imap_login(*_args, **_kwargs) -> None: + raise imaplib.IMAP4.error("AUTH failed") + + monkeypatch.setattr(email_validation, "_imap_login", reject_imap_login) + monkeypatch.setattr(email_validation, "_smtp_login", lambda *_args, **_kwargs: None) + + result = validate_channel_config( + "email", + { + "channels.email.consentGranted": "true", + "channels.email.imapHost": "imap.example.com", + "channels.email.imapUsername": "bot@example.com", + "channels.email.imapPassword": "wrong-secret", + "channels.email.smtpHost": "smtp.example.com", + "channels.email.smtpUsername": "bot@example.com", + "channels.email.smtpPassword": "smtp-secret", + }, + ) + + assert result["status"] == "invalid" + assert result["can_enable"] is False + assert { + check["id"]: (check["status"], check.get("message")) + for check in result["checks"] + }["imap_account"] == ( + "fail", + "IMAP rejected the username or password.", + ) + + def test_validate_email_blocks_private_targets_when_local_access_is_disabled( tmp_path, monkeypatch: pytest.MonkeyPatch, diff --git a/nanobot/channels/email/validation.py b/nanobot/channels/email/validation.py index ebcd410f0..ccedcd4b5 100644 --- a/nanobot/channels/email/validation.py +++ b/nanobot/channels/email/validation.py @@ -1,5 +1,9 @@ """Email setup validation owned by the channel package.""" +import imaplib +import smtplib +import ssl +from contextlib import suppress from typing import Any from nanobot.channels.contracts import ChannelValidationContext @@ -13,6 +17,84 @@ from nanobot.channels.validation import ( truthy, ) +_TIMEOUT_SECONDS = 4.0 + + +class _MailboxSelectionError(Exception): + pass + + +def _resolved_string(values: dict[str, Any], field: str) -> str: + from nanobot.config.loader import resolve_env_refs + + return string_value(resolve_env_refs(string_value(values.get(field)))) + + +def _bool_value(values: dict[str, Any], field: str, *, default: bool) -> bool: + value = values.get(field) + return default if value in (None, "") else truthy(value) + + +def _imap_login( + host: str, + port: int, + username: str, + password: str, + *, + mailbox: str, + use_ssl: bool, +) -> None: + client: Any = ( + imaplib.IMAP4_SSL(host, port, timeout=_TIMEOUT_SECONDS) + if use_ssl + else imaplib.IMAP4(host, port, timeout=_TIMEOUT_SECONDS) + ) + try: + client.login(username, password) + try: + status, _ = client.select(mailbox, readonly=True) + except imaplib.IMAP4.error as exc: + raise _MailboxSelectionError from exc + if status != "OK": + raise _MailboxSelectionError + finally: + with suppress(Exception): + client.logout() + + +def _smtp_login( + host: str, + port: int, + username: str, + password: str, + *, + use_ssl: bool, + use_tls: bool, +) -> None: + client = ( + smtplib.SMTP_SSL(host, port, timeout=_TIMEOUT_SECONDS) + if use_ssl + else smtplib.SMTP(host, port, timeout=_TIMEOUT_SECONDS) + ) + with client: + if use_tls and not use_ssl: + client.starttls(context=ssl.create_default_context()) + client.login(username, password) + + +def _connection_error_message(prefix: str, exc: Exception) -> tuple[str, str]: + if isinstance(exc, _MailboxSelectionError): + return "fail", "IMAP connected, but the selected mailbox could not be opened." + if isinstance(exc, (imaplib.IMAP4.error, smtplib.SMTPAuthenticationError)): + return "fail", f"{prefix} rejected the username or password." + if isinstance(exc, (ssl.SSLError, smtplib.SMTPNotSupportedError)): + return "fail", f"{prefix} security settings are not accepted by the server." + if isinstance(exc, smtplib.SMTPResponseException): + return "fail", f"{prefix} rejected the connection settings." + if isinstance(exc, (TimeoutError, OSError)): + return "warn", f"Could not reach {prefix} now. Try again later." + return "warn", f"Could not verify {prefix} now. Try again later." + def validate( values: dict[str, Any], @@ -32,15 +114,33 @@ def validate( ) for prefix, default_port in (("imap", 993), ("smtp", 587)): - host = string_value(values.get(f"{prefix}Host")) - port = int_value(values.get(f"{prefix}Port")) or default_port + label = prefix.upper() + host = _resolved_string(values, f"{prefix}Host") + username = _resolved_string(values, f"{prefix}Username") + password = _resolved_string(values, f"{prefix}Password") + unresolved = any( + string_value(values.get(field)) and not _resolved_string(values, field) + for field in (f"{prefix}Host", f"{prefix}Username", f"{prefix}Password") + ) + if unresolved: + checks.append( + check( + f"{prefix}_environment", + f"{label} account", + "fail", + f"Set every environment variable referenced by the {label} settings.", + ) + ) + continue + raw_port = values.get(f"{prefix}Port") + port = default_port if raw_port in (None, "") else int_value(raw_port) if not host: continue - if port <= 0 or port > 65535: + if port is None or port <= 0 or port > 65535: checks.append( check( f"{prefix}_port", - f"{prefix.upper()} port", + f"{label} port", "fail", "Port must be between 1 and 65535.", ) @@ -49,7 +149,7 @@ def validate( checks.append( check( f"{prefix}_settings", - f"{prefix.upper()} settings", + f"{label} settings", "pass", f"{host}:{port} is set.", ) @@ -63,7 +163,7 @@ def validate( checks.append( check( f"{prefix}_reachability", - f"{prefix.upper()} reachability", + f"{label} reachability", "pass", "The server accepted a TCP connection.", ) @@ -72,17 +172,51 @@ def validate( checks.append( check( f"{prefix}_reachability", - f"{prefix.upper()} reachability", + f"{label} reachability", "warn", f"Could not verify network reachability now: {exc}", ) ) + continue + + if not username or not password: + continue + try: + if prefix == "imap": + _imap_login( + host, + port, + username, + password, + mailbox=_resolved_string(values, "imapMailbox") or "INBOX", + use_ssl=_bool_value(values, "imapUseSsl", default=True), + ) + else: + _smtp_login( + host, + port, + username, + password, + use_ssl=_bool_value(values, "smtpUseSsl", default=False), + use_tls=_bool_value(values, "smtpUseTls", default=True), + ) + checks.append( + check( + f"{prefix}_account", + f"{label} account", + "pass", + f"{label} accepted the account credentials.", + ) + ) + except Exception as exc: + status, message = _connection_error_message(label, exc) + checks.append(check(f"{prefix}_account", f"{label} account", status, message)) identity = { - "account": string_value( - values.get("fromAddress") - or values.get("imapUsername") - or values.get("smtpUsername") + "account": ( + _resolved_string(values, "fromAddress") + or _resolved_string(values, "imapUsername") + or _resolved_string(values, "smtpUsername") ) } return status_from_checks("email", checks, missing, identity=identity) diff --git a/nanobot/channels/email/webui/index.ts b/nanobot/channels/email/webui/index.ts index cea01cdaa..e069edda6 100644 --- a/nanobot/channels/email/webui/index.ts +++ b/nanobot/channels/email/webui/index.ts @@ -32,34 +32,33 @@ const EMAIL_PROVIDER_PRESETS: ChannelProviderPresetDefinition[] = [ "channels.email.smtpPort": "587", }, }, - { id: "custom", values: {} }, ]; export default { presentation: { + logoUrl: "https://gmail.com/favicon.ico", displayName: "Email", initials: "EM", color: "#64748B", - logoUrl: "https://gmail.com/favicon.ico", setup: { mode: "credentials", docsUrl: chatAppGuideUrl("email"), presets: EMAIL_PROVIDER_PRESETS, fields: [ - { key: "channels.email.consentGranted" }, - { key: "channels.email.imapHost" }, - { key: "channels.email.imapUsername" }, - { key: "channels.email.imapPassword" }, - { key: "channels.email.smtpHost" }, - { key: "channels.email.smtpUsername" }, - { key: "channels.email.smtpPassword" }, - { key: "channels.email.imapPort" }, - { key: "channels.email.smtpPort" }, - { key: "channels.email.fromAddress" }, - { key: "channels.email.pollIntervalSeconds" }, - { key: "channels.email.allowFrom" }, - { key: "channels.email.verifyDkim" }, - { key: "channels.email.verifySpf" }, + { key: "channels.email.consentGranted", section: "account" }, + { key: "channels.email.imapHost", section: "receiving" }, + { key: "channels.email.imapUsername", section: "receiving" }, + { key: "channels.email.imapPassword", section: "receiving" }, + { key: "channels.email.imapPort", section: "receiving" }, + { key: "channels.email.smtpHost", section: "sending" }, + { key: "channels.email.smtpUsername", section: "sending" }, + { key: "channels.email.smtpPassword", section: "sending" }, + { key: "channels.email.smtpPort", section: "sending" }, + { key: "channels.email.fromAddress", section: "sending" }, + { key: "channels.email.pollIntervalSeconds", section: "behavior" }, + { key: "channels.email.allowFrom", section: "access" }, + { key: "channels.email.verifyDkim", section: "security" }, + { key: "channels.email.verifySpf", section: "security" }, ], }, }, diff --git a/nanobot/channels/email/webui/locales/en.json b/nanobot/channels/email/webui/locales/en.json index 2391edd6c..d3bf43894 100644 --- a/nanobot/channels/email/webui/locales/en.json +++ b/nanobot/channels/email/webui/locales/en.json @@ -1,26 +1,20 @@ { - "description": "Let nanobot receive and answer email messages.", - "requirements": "IMAP inbox, SMTP sender, app password, explicit consent", "setup": { "docsLabel": "Open Email setup", "officialLabel": "Open app password guide", - "tryIt": "Send a test email to the connected mailbox.", - "summary": "Email reads messages over IMAP and replies over SMTP. Use a dedicated mailbox and grant consent before enabling it.", - "steps": [ - "Create a dedicated mailbox and, when required, an app password.", - "Choose a provider preset or enter the IMAP and SMTP settings manually.", - "Grant consent, save and enable Email, then send a test message to the mailbox." - ], + "presetLabel": "Quick fill", + "sections": { + "receiving": "Receiving mail", + "sending": "Sending mail" + }, "presets": { "gmail": "Gmail", "outlook": "Outlook", - "icloud": "iCloud", - "custom": "Custom" + "icloud": "iCloud" }, "fields": { "consentGranted": { "label": "Allow nanobot to read and send email", - "help": "Turn on to give nanobot access to this mailbox. Make sure this is the dedicated mailbox you want the bot to use.", "choices": { "true": "Granted", "false": "Not granted" @@ -36,8 +30,7 @@ }, "imapPassword": { "label": "IMAP password", - "placeholder": "App password", - "help": "Use an app password when your mail provider requires one." + "placeholder": "App password" }, "smtpHost": { "label": "SMTP host", @@ -49,8 +42,7 @@ }, "smtpPassword": { "label": "SMTP password", - "placeholder": "App password", - "help": "Usually the same app password used for IMAP." + "placeholder": "App password" }, "imapPort": { "label": "IMAP port", @@ -70,8 +62,7 @@ }, "allowFrom": { "label": "Allowed senders", - "placeholder": "Email addresses, comma separated", - "help": "Leave empty to require pairing before a sender can use email." + "placeholder": "Email addresses, comma separated" }, "verifyDkim": { "label": "Verify DKIM", @@ -86,6 +77,83 @@ "true": "On", "false": "Off" } + }, + "imapMailbox": { + "label": "IMAP mailbox" + }, + "imapUseSsl": { + "label": "IMAP SSL", + "choices": { + "true": "On", + "false": "Off" + } + }, + "smtpUseTls": { + "label": "SMTP TLS", + "choices": { + "true": "On", + "false": "Off" + } + }, + "smtpUseSsl": { + "label": "SMTP SSL", + "choices": { + "true": "On", + "false": "Off" + } + }, + "autoReplyEnabled": { + "label": "Automatic replies", + "choices": { + "true": "On", + "false": "Off" + } + }, + "markSeen": { + "label": "Mark as read", + "choices": { + "true": "On", + "false": "Off" + } + }, + "postAction": { + "label": "After processing", + "choices": { + "delete": "Delete", + "move": "Move" + } + }, + "postActionMoveMailbox": { + "label": "Move to mailbox" + }, + "postActionExpunge": { + "label": "Permanently apply action", + "choices": { + "true": "On", + "false": "Off" + } + }, + "postActionIgnoreSkipped": { + "label": "Ignore skipped messages", + "choices": { + "true": "On", + "false": "Off" + } + }, + "maxBodyChars": { + "label": "Maximum body length" + }, + "subjectPrefix": { + "label": "Reply subject prefix" + }, + "allowedAttachmentTypes": { + "label": "Allowed attachment types" + }, + "maxAttachmentSize": { + "label": "Maximum attachment size" + }, + "maxAttachmentsPerEmail": { + "label": "Maximum attachments" } } } diff --git a/nanobot/channels/email/webui/locales/es.json b/nanobot/channels/email/webui/locales/es.json index 692679c2e..ca4df63fd 100644 --- a/nanobot/channels/email/webui/locales/es.json +++ b/nanobot/channels/email/webui/locales/es.json @@ -1,27 +1,21 @@ { "displayName": "Correo electrónico", - "description": "Permite que nanobot reciba y responda correos.", - "requirements": "Bandeja IMAP, envío SMTP, contraseña de app y consentimiento explícito", "setup": { "docsLabel": "Abrir guía de Email", "officialLabel": "Abrir guía de contraseñas de app", - "tryIt": "Envía un correo de prueba al buzón conectado.", - "summary": "Email lee mensajes por IMAP y responde por SMTP. Usa un buzón dedicado y da tu consentimiento antes de activarlo.", - "steps": [ - "Crea un buzón dedicado y, si hace falta, una contraseña de app.", - "Elige un proveedor o introduce manualmente IMAP y SMTP.", - "Da tu consentimiento, guarda y activa Email; después envía un mensaje de prueba." - ], + "presetLabel": "Relleno rápido", + "sections": { + "receiving": "Recepción de correo", + "sending": "Envío de correo" + }, "presets": { "gmail": "Gmail", "outlook": "Outlook", - "icloud": "iCloud", - "custom": "Personalizado" + "icloud": "iCloud" }, "fields": { "consentGranted": { "label": "Permitir que nanobot lea y envíe correos", - "help": "Activa esta opción para permitir el acceso al buzón. Comprueba que sea el buzón dedicado al bot.", "choices": { "true": "Concedido", "false": "No concedido" @@ -37,8 +31,7 @@ }, "imapPassword": { "label": "Contraseña IMAP", - "placeholder": "Contraseña de app", - "help": "Usa una contraseña de app si el proveedor la exige." + "placeholder": "Contraseña de app" }, "smtpHost": { "label": "Host SMTP", @@ -50,8 +43,7 @@ }, "smtpPassword": { "label": "Contraseña SMTP", - "placeholder": "Contraseña de app", - "help": "Normalmente es la misma que para IMAP." + "placeholder": "Contraseña de app" }, "imapPort": { "label": "Puerto IMAP", @@ -71,8 +63,7 @@ }, "allowFrom": { "label": "Remitentes permitidos", - "placeholder": "Correos separados por comas", - "help": "Déjalo vacío para exigir vinculación previa." + "placeholder": "Correos separados por comas" }, "verifyDkim": { "label": "Verificar DKIM", @@ -87,6 +78,83 @@ "true": "Activado", "false": "Desactivado" } + }, + "imapMailbox": { + "label": "buzón IMAP" + }, + "imapUseSsl": { + "label": "SSL IMAP", + "choices": { + "true": "encendido", + "false": "Apagado" + } + }, + "smtpUseTls": { + "label": "TLS SMTP", + "choices": { + "true": "encendido", + "false": "Apagado" + } + }, + "smtpUseSsl": { + "label": "SSL SMTP", + "choices": { + "true": "encendido", + "false": "Apagado" + } + }, + "autoReplyEnabled": { + "label": "Respuestas automáticas", + "choices": { + "true": "encendido", + "false": "Apagado" + } + }, + "markSeen": { + "label": "Marcar como leído", + "choices": { + "true": "encendido", + "false": "Apagado" + } + }, + "postAction": { + "label": "Después del procesamiento", + "choices": { + "delete": "Eliminar", + "move": "Mover" + } + }, + "postActionMoveMailbox": { + "label": "Mover al buzón" + }, + "postActionExpunge": { + "label": "Aplicar permanentemente la acción", + "choices": { + "true": "encendido", + "false": "Apagado" + } + }, + "postActionIgnoreSkipped": { + "label": "Ignorar mensajes omitidos", + "choices": { + "true": "encendido", + "false": "Apagado" + } + }, + "maxBodyChars": { + "label": "Longitud máxima del cuerpo" + }, + "subjectPrefix": { + "label": "Prefijo del asunto de respuesta" + }, + "allowedAttachmentTypes": { + "label": "Tipos de archivos adjuntos permitidos" + }, + "maxAttachmentSize": { + "label": "Tamaño máximo de archivo adjunto" + }, + "maxAttachmentsPerEmail": { + "label": "Archivos adjuntos máximos" } } } diff --git a/nanobot/channels/email/webui/locales/fr.json b/nanobot/channels/email/webui/locales/fr.json index 078a76693..1b62dab3b 100644 --- a/nanobot/channels/email/webui/locales/fr.json +++ b/nanobot/channels/email/webui/locales/fr.json @@ -1,27 +1,21 @@ { "displayName": "E-mail", - "description": "Permettez à nanobot de recevoir des e-mails et d’y répondre.", - "requirements": "Boîte IMAP, envoi SMTP, mot de passe d’application et consentement explicite", "setup": { "docsLabel": "Ouvrir le guide Email", "officialLabel": "Ouvrir le guide des mots de passe d’application", - "tryIt": "Envoyez un e-mail test à la boîte connectée.", - "summary": "nanobot lit les messages via IMAP et répond via SMTP. Utilisez une boîte dédiée et autorisez l’accès avant d’activer le canal.", - "steps": [ - "Créez une boîte dédiée et, si nécessaire, un mot de passe d’application.", - "Choisissez un fournisseur ou saisissez les paramètres IMAP et SMTP.", - "Accordez le consentement, enregistrez et activez Email, puis envoyez un message test." - ], + "presetLabel": "Remplissage rapide", + "sections": { + "receiving": "Réception des e-mails", + "sending": "Envoi des e-mails" + }, "presets": { "gmail": "Gmail", "outlook": "Outlook", - "icloud": "iCloud", - "custom": "Personnalisé" + "icloud": "iCloud" }, "fields": { "consentGranted": { "label": "Autoriser nanobot à lire et envoyer des e-mails", - "help": "Activez cette option pour autoriser l’accès à cette boîte. Vérifiez qu’il s’agit bien de la boîte dédiée au bot.", "choices": { "true": "Accordé", "false": "Non accordé" @@ -37,8 +31,7 @@ }, "imapPassword": { "label": "Mot de passe IMAP", - "placeholder": "Mot de passe d’application", - "help": "Utilisez un mot de passe d’application si le fournisseur l’exige." + "placeholder": "Mot de passe d’application" }, "smtpHost": { "label": "Hôte SMTP", @@ -50,8 +43,7 @@ }, "smtpPassword": { "label": "Mot de passe SMTP", - "placeholder": "Mot de passe d’application", - "help": "Généralement identique à celui d’IMAP." + "placeholder": "Mot de passe d’application" }, "imapPort": { "label": "Port IMAP", @@ -71,8 +63,7 @@ }, "allowFrom": { "label": "Expéditeurs autorisés", - "placeholder": "Adresses séparées par des virgules", - "help": "Laissez vide pour que les expéditeurs doivent d’abord s’associer au bot." + "placeholder": "Adresses séparées par des virgules" }, "verifyDkim": { "label": "Vérifier DKIM", @@ -87,6 +78,83 @@ "true": "Activé", "false": "Désactivé" } + }, + "imapMailbox": { + "label": "Boîte aux lettres IMAP" + }, + "imapUseSsl": { + "label": "SSL IMAP", + "choices": { + "true": "Sur", + "false": "Désactivé" + } + }, + "smtpUseTls": { + "label": "SMTP-TLS", + "choices": { + "true": "Sur", + "false": "Désactivé" + } + }, + "smtpUseSsl": { + "label": "SMTP-SSL", + "choices": { + "true": "Sur", + "false": "Désactivé" + } + }, + "autoReplyEnabled": { + "label": "Réponses automatiques", + "choices": { + "true": "Sur", + "false": "Désactivé" + } + }, + "markSeen": { + "label": "Marquer comme lu", + "choices": { + "true": "Sur", + "false": "Désactivé" + } + }, + "postAction": { + "label": "Après traitement", + "choices": { + "delete": "Supprimer", + "move": "Déplacer" + } + }, + "postActionMoveMailbox": { + "label": "Déplacer vers la boîte aux lettres" + }, + "postActionExpunge": { + "label": "Appliquer l'action de manière permanente", + "choices": { + "true": "Sur", + "false": "Désactivé" + } + }, + "postActionIgnoreSkipped": { + "label": "Ignorer les messages ignorés", + "choices": { + "true": "Sur", + "false": "Désactivé" + } + }, + "maxBodyChars": { + "label": "Longueur maximale du corps" + }, + "subjectPrefix": { + "label": "Préfixe du sujet de la réponse" + }, + "allowedAttachmentTypes": { + "label": "Types de pièces jointes autorisés" + }, + "maxAttachmentSize": { + "label": "Taille maximale des pièces jointes" + }, + "maxAttachmentsPerEmail": { + "label": "Nombre maximal de pièces jointes" } } } diff --git a/nanobot/channels/email/webui/locales/id.json b/nanobot/channels/email/webui/locales/id.json index a99b59b5f..da98c16d6 100644 --- a/nanobot/channels/email/webui/locales/id.json +++ b/nanobot/channels/email/webui/locales/id.json @@ -1,27 +1,21 @@ { "displayName": "Email", - "description": "Izinkan nanobot menerima dan membalas email.", - "requirements": "Kotak masuk IMAP, pengirim SMTP, kata sandi aplikasi, dan persetujuan eksplisit", "setup": { "docsLabel": "Buka panduan Email", "officialLabel": "Buka panduan kata sandi aplikasi", - "tryIt": "Kirim email uji ke kotak surat yang terhubung.", - "summary": "Email membaca pesan melalui IMAP dan membalas melalui SMTP. Gunakan kotak surat khusus dan berikan persetujuan sebelum mengaktifkan.", - "steps": [ - "Buat kotak surat khusus dan kata sandi aplikasi bila diperlukan.", - "Pilih prasetel penyedia atau masukkan pengaturan IMAP dan SMTP secara manual.", - "Berikan persetujuan, simpan dan aktifkan Email, lalu kirim pesan uji." - ], + "presetLabel": "Isi cepat", + "sections": { + "receiving": "Penerimaan email", + "sending": "Pengiriman email" + }, "presets": { "gmail": "Gmail", "outlook": "Outlook", - "icloud": "iCloud", - "custom": "Kustom" + "icloud": "iCloud" }, "fields": { "consentGranted": { "label": "Izinkan nanobot membaca dan mengirim email", - "help": "Aktifkan untuk memberi nanobot akses ke kotak surat ini. Pastikan kotak surat tersebut memang dikhususkan untuk bot.", "choices": { "true": "Diberikan", "false": "Belum diberikan" @@ -37,8 +31,7 @@ }, "imapPassword": { "label": "Kata sandi IMAP", - "placeholder": "Kata sandi aplikasi", - "help": "Gunakan kata sandi aplikasi jika diwajibkan penyedia." + "placeholder": "Kata sandi aplikasi" }, "smtpHost": { "label": "Host SMTP", @@ -50,8 +43,7 @@ }, "smtpPassword": { "label": "Kata sandi SMTP", - "placeholder": "Kata sandi aplikasi", - "help": "Biasanya sama dengan kata sandi aplikasi IMAP." + "placeholder": "Kata sandi aplikasi" }, "imapPort": { "label": "Port IMAP", @@ -71,8 +63,7 @@ }, "allowFrom": { "label": "Pengirim yang diizinkan", - "placeholder": "Alamat email, dipisahkan koma", - "help": "Kosongkan untuk mewajibkan pairing terlebih dahulu." + "placeholder": "Alamat email, dipisahkan koma" }, "verifyDkim": { "label": "Verifikasi DKIM", @@ -87,6 +78,83 @@ "true": "Aktif", "false": "Nonaktif" } + }, + "imapMailbox": { + "label": "kotak surat IMAP" + }, + "imapUseSsl": { + "label": "SSL IMAP", + "choices": { + "true": "Aktif", + "false": "Mati" + } + }, + "smtpUseTls": { + "label": "TLS SMTP", + "choices": { + "true": "Aktif", + "false": "Mati" + } + }, + "smtpUseSsl": { + "label": "SSL SMTP", + "choices": { + "true": "Aktif", + "false": "Mati" + } + }, + "autoReplyEnabled": { + "label": "Balasan otomatis", + "choices": { + "true": "Aktif", + "false": "Mati" + } + }, + "markSeen": { + "label": "Tandai sebagai telah dibaca", + "choices": { + "true": "Aktif", + "false": "Mati" + } + }, + "postAction": { + "label": "Setelah diproses", + "choices": { + "delete": "Hapus", + "move": "Pindah" + } + }, + "postActionMoveMailbox": { + "label": "Pindah ke kotak surat" + }, + "postActionExpunge": { + "label": "Terapkan tindakan secara permanen", + "choices": { + "true": "Aktif", + "false": "Mati" + } + }, + "postActionIgnoreSkipped": { + "label": "Abaikan pesan yang dilewati", + "choices": { + "true": "Aktif", + "false": "Mati" + } + }, + "maxBodyChars": { + "label": "Panjang tubuh maksimal" + }, + "subjectPrefix": { + "label": "Awalan subjek balasan" + }, + "allowedAttachmentTypes": { + "label": "Jenis lampiran yang diizinkan" + }, + "maxAttachmentSize": { + "label": "Ukuran lampiran maksimum" + }, + "maxAttachmentsPerEmail": { + "label": "Lampiran maksimum" } } } diff --git a/nanobot/channels/email/webui/locales/ja.json b/nanobot/channels/email/webui/locales/ja.json index 4469c13b7..16f786b68 100644 --- a/nanobot/channels/email/webui/locales/ja.json +++ b/nanobot/channels/email/webui/locales/ja.json @@ -1,27 +1,21 @@ { "displayName": "メール", - "description": "nanobot でメールを受信し、返信します。", - "requirements": "IMAP 受信箱、SMTP 送信、アプリパスワード、明示的な同意", "setup": { "docsLabel": "メール設定ガイドを開く", "officialLabel": "アプリパスワードガイドを開く", - "tryIt": "接続したメールボックスにテストメールを送信します。", - "summary": "メールは IMAP で受信し SMTP で返信します。専用メールボックスを使い、有効化前に同意してください。", - "steps": [ - "専用メールボックスを作成し、必要ならアプリパスワードを発行します。", - "プロバイダープリセットを選ぶか、IMAP と SMTP を手動入力します。", - "同意して保存し、メールを有効にしてテストメールを送信します。" - ], + "presetLabel": "クイック入力", + "sections": { + "receiving": "メール受信", + "sending": "メール送信" + }, "presets": { "gmail": "Gmail", "outlook": "Outlook", - "icloud": "iCloud", - "custom": "カスタム" + "icloud": "iCloud" }, "fields": { "consentGranted": { "label": "nanobot にメールの読み取りと送信を許可", - "help": "オンにすると nanobot がこのメールボックスにアクセスできます。ボット用の専用メールボックスであることを確認してください。", "choices": { "true": "同意済み", "false": "未同意" @@ -37,8 +31,7 @@ }, "imapPassword": { "label": "IMAP パスワード", - "placeholder": "アプリパスワード", - "help": "プロバイダーが求める場合はアプリパスワードを使います。" + "placeholder": "アプリパスワード" }, "smtpHost": { "label": "SMTP ホスト", @@ -50,8 +43,7 @@ }, "smtpPassword": { "label": "SMTP パスワード", - "placeholder": "アプリパスワード", - "help": "通常は IMAP と同じアプリパスワードです。" + "placeholder": "アプリパスワード" }, "imapPort": { "label": "IMAP ポート", @@ -71,8 +63,7 @@ }, "allowFrom": { "label": "許可する送信者", - "placeholder": "メールアドレス(カンマ区切り)", - "help": "空欄の場合、送信者は先にペアリングが必要です。" + "placeholder": "メールアドレス(カンマ区切り)" }, "verifyDkim": { "label": "DKIM を検証", @@ -87,6 +78,83 @@ "true": "オン", "false": "オフ" } + }, + "imapMailbox": { + "label": "IMAPメールボックス" + }, + "imapUseSsl": { + "label": "IMAP SSL", + "choices": { + "true": "オン", + "false": "オフ" + } + }, + "smtpUseTls": { + "label": "SMTP TLS", + "choices": { + "true": "オン", + "false": "オフ" + } + }, + "smtpUseSsl": { + "label": "SMTP SSL", + "choices": { + "true": "オン", + "false": "オフ" + } + }, + "autoReplyEnabled": { + "label": "自動応答", + "choices": { + "true": "オン", + "false": "オフ" + } + }, + "markSeen": { + "label": "既読としてマークする", + "choices": { + "true": "オン", + "false": "オフ" + } + }, + "postAction": { + "label": "加工後", + "choices": { + "delete": "削除", + "move": "移動" + } + }, + "postActionMoveMailbox": { + "label": "メールボックスに移動" + }, + "postActionExpunge": { + "label": "アクションを永続的に適用する", + "choices": { + "true": "オン", + "false": "オフ" + } + }, + "postActionIgnoreSkipped": { + "label": "スキップされたメッセージを無視する", + "choices": { + "true": "オン", + "false": "オフ" + } + }, + "maxBodyChars": { + "label": "最大体長" + }, + "subjectPrefix": { + "label": "返信件名の接頭辞" + }, + "allowedAttachmentTypes": { + "label": "許可される添付ファイルの種類" + }, + "maxAttachmentSize": { + "label": "添付ファイルの最大サイズ" + }, + "maxAttachmentsPerEmail": { + "label": "最大添付ファイル数" } } } diff --git a/nanobot/channels/email/webui/locales/ko.json b/nanobot/channels/email/webui/locales/ko.json index ab9e2049c..a768e67bb 100644 --- a/nanobot/channels/email/webui/locales/ko.json +++ b/nanobot/channels/email/webui/locales/ko.json @@ -1,27 +1,21 @@ { "displayName": "이메일", - "description": "nanobot이 이메일을 받고 답장하도록 합니다.", - "requirements": "IMAP 받은편지함, SMTP 발신, 앱 비밀번호 및 명시적 동의", "setup": { "docsLabel": "이메일 설정 가이드 열기", "officialLabel": "앱 비밀번호 가이드 열기", - "tryIt": "연결된 사서함으로 테스트 이메일을 보내세요.", - "summary": "이메일은 IMAP으로 읽고 SMTP로 답장합니다. 전용 사서함을 사용하고 활성화 전에 동의하세요.", - "steps": [ - "전용 사서함을 만들고 필요하면 앱 비밀번호를 생성하세요.", - "제공업체 프리셋을 선택하거나 IMAP 및 SMTP 설정을 직접 입력하세요.", - "동의하고 저장한 뒤 이메일을 활성화하고 테스트 메시지를 보내세요." - ], + "presetLabel": "빠른 입력", + "sections": { + "receiving": "메일 수신", + "sending": "메일 발신" + }, "presets": { "gmail": "Gmail", "outlook": "Outlook", - "icloud": "iCloud", - "custom": "사용자 지정" + "icloud": "iCloud" }, "fields": { "consentGranted": { "label": "nanobot의 이메일 읽기 및 보내기 허용", - "help": "켜면 nanobot이 이 사서함에 접근할 수 있습니다. 봇 전용 사서함이 맞는지 확인하세요.", "choices": { "true": "동의함", "false": "동의하지 않음" @@ -37,8 +31,7 @@ }, "imapPassword": { "label": "IMAP 비밀번호", - "placeholder": "앱 비밀번호", - "help": "메일 제공업체가 요구하면 앱 비밀번호를 사용하세요." + "placeholder": "앱 비밀번호" }, "smtpHost": { "label": "SMTP 호스트", @@ -50,8 +43,7 @@ }, "smtpPassword": { "label": "SMTP 비밀번호", - "placeholder": "앱 비밀번호", - "help": "보통 IMAP과 같은 앱 비밀번호를 사용합니다." + "placeholder": "앱 비밀번호" }, "imapPort": { "label": "IMAP 포트", @@ -71,8 +63,7 @@ }, "allowFrom": { "label": "허용된 발신자", - "placeholder": "이메일 주소, 쉼표로 구분", - "help": "비워 두면 발신자가 먼저 페어링해야 합니다." + "placeholder": "이메일 주소, 쉼표로 구분" }, "verifyDkim": { "label": "DKIM 확인", @@ -87,6 +78,83 @@ "true": "켜짐", "false": "꺼짐" } + }, + "imapMailbox": { + "label": "IMAP 사서함" + }, + "imapUseSsl": { + "label": "IMAP SSL", + "choices": { + "true": "켜기", + "false": "끄기" + } + }, + "smtpUseTls": { + "label": "SMTP TLS", + "choices": { + "true": "켜기", + "false": "끄기" + } + }, + "smtpUseSsl": { + "label": "SMTP SSL", + "choices": { + "true": "켜기", + "false": "끄기" + } + }, + "autoReplyEnabled": { + "label": "자동 답장", + "choices": { + "true": "켜기", + "false": "끄기" + } + }, + "markSeen": { + "label": "읽음으로 표시", + "choices": { + "true": "켜기", + "false": "끄기" + } + }, + "postAction": { + "label": "처리 후", + "choices": { + "delete": "삭제", + "move": "이동" + } + }, + "postActionMoveMailbox": { + "label": "사서함으로 이동" + }, + "postActionExpunge": { + "label": "영구적으로 작업 적용", + "choices": { + "true": "켜기", + "false": "끄기" + } + }, + "postActionIgnoreSkipped": { + "label": "건너뛴 메시지 무시", + "choices": { + "true": "켜기", + "false": "끄기" + } + }, + "maxBodyChars": { + "label": "최대 몸체 길이" + }, + "subjectPrefix": { + "label": "답장 제목 접두어" + }, + "allowedAttachmentTypes": { + "label": "허용되는 첨부 파일 유형" + }, + "maxAttachmentSize": { + "label": "최대 첨부 파일 크기" + }, + "maxAttachmentsPerEmail": { + "label": "최대 첨부 파일" } } } diff --git a/nanobot/channels/email/webui/locales/pt-BR.json b/nanobot/channels/email/webui/locales/pt-BR.json index 57fd4faef..4e4d865bd 100644 --- a/nanobot/channels/email/webui/locales/pt-BR.json +++ b/nanobot/channels/email/webui/locales/pt-BR.json @@ -1,27 +1,21 @@ { "displayName": "E-mail", - "description": "Permita que o nanobot receba e responda e-mails.", - "requirements": "Caixa IMAP, envio SMTP, senha de app e consentimento explícito", "setup": { "docsLabel": "Abrir guia de e-mail", "officialLabel": "Abrir guia de senhas de app", - "tryIt": "Envie um e-mail de teste para a caixa conectada.", - "summary": "O nanobot lê e-mails por IMAP e responde por SMTP. Use uma caixa dedicada e autorize o acesso antes de ativar o canal.", - "steps": [ - "Crie uma caixa dedicada e, quando necessário, uma senha de app.", - "Escolha um provedor ou informe IMAP e SMTP manualmente.", - "Autorize o acesso, salve e ative o canal de e-mail. Depois, envie uma mensagem de teste." - ], + "presetLabel": "Preenchimento rápido", + "sections": { + "receiving": "Recebimento de e-mail", + "sending": "Envio de e-mail" + }, "presets": { "gmail": "Gmail", "outlook": "Outlook", - "icloud": "iCloud", - "custom": "Personalizado" + "icloud": "iCloud" }, "fields": { "consentGranted": { "label": "Permitir que o nanobot leia e envie e-mails", - "help": "Ative para permitir o acesso a esta caixa de e-mail. Confirme que ela é dedicada ao bot.", "choices": { "true": "Concedido", "false": "Não concedido" @@ -37,8 +31,7 @@ }, "imapPassword": { "label": "Senha IMAP", - "placeholder": "Senha de app", - "help": "Use uma senha de app quando o provedor exigir." + "placeholder": "Senha de app" }, "smtpHost": { "label": "Host SMTP", @@ -50,8 +43,7 @@ }, "smtpPassword": { "label": "Senha SMTP", - "placeholder": "Senha de app", - "help": "Normalmente é a mesma senha usada no IMAP." + "placeholder": "Senha de app" }, "imapPort": { "label": "Porta IMAP", @@ -71,8 +63,7 @@ }, "allowFrom": { "label": "Remetentes permitidos", - "placeholder": "E-mails separados por vírgulas", - "help": "Deixe vazio para exigir pareamento prévio." + "placeholder": "E-mails separados por vírgulas" }, "verifyDkim": { "label": "Verificar DKIM", @@ -87,6 +78,83 @@ "true": "Ativado", "false": "Desativado" } + }, + "imapMailbox": { + "label": "Caixa de correio IMAP" + }, + "imapUseSsl": { + "label": "SSL IMAP", + "choices": { + "true": "Ligado", + "false": "Desligado" + } + }, + "smtpUseTls": { + "label": "TLS SMTP", + "choices": { + "true": "Ligado", + "false": "Desligado" + } + }, + "smtpUseSsl": { + "label": "SSL SMTP", + "choices": { + "true": "Ligado", + "false": "Desligado" + } + }, + "autoReplyEnabled": { + "label": "Respostas automáticas", + "choices": { + "true": "Ligado", + "false": "Desligado" + } + }, + "markSeen": { + "label": "Marcar como lido", + "choices": { + "true": "Ligado", + "false": "Desligado" + } + }, + "postAction": { + "label": "Após o processamento", + "choices": { + "delete": "Excluir", + "move": "Mover" + } + }, + "postActionMoveMailbox": { + "label": "Mover para caixa de correio" + }, + "postActionExpunge": { + "label": "Aplicar ação permanentemente", + "choices": { + "true": "Ligado", + "false": "Desligado" + } + }, + "postActionIgnoreSkipped": { + "label": "Ignorar mensagens ignoradas", + "choices": { + "true": "Ligado", + "false": "Desligado" + } + }, + "maxBodyChars": { + "label": "Comprimento máximo do corpo" + }, + "subjectPrefix": { + "label": "Prefixo do assunto da resposta" + }, + "allowedAttachmentTypes": { + "label": "Tipos de anexos permitidos" + }, + "maxAttachmentSize": { + "label": "Tamanho máximo do anexo" + }, + "maxAttachmentsPerEmail": { + "label": "Máximo de anexos" } } } diff --git a/nanobot/channels/email/webui/locales/vi.json b/nanobot/channels/email/webui/locales/vi.json index 24ce00fce..c476a3cde 100644 --- a/nanobot/channels/email/webui/locales/vi.json +++ b/nanobot/channels/email/webui/locales/vi.json @@ -1,27 +1,21 @@ { "displayName": "Email", - "description": "Cho phép nanobot nhận và trả lời email.", - "requirements": "Hộp thư IMAP, gửi SMTP, mật khẩu ứng dụng và sự đồng ý rõ ràng", "setup": { "docsLabel": "Mở hướng dẫn Email", "officialLabel": "Mở hướng dẫn mật khẩu ứng dụng", - "tryIt": "Gửi email thử đến hộp thư đã kết nối.", - "summary": "Email đọc thư qua IMAP và trả lời qua SMTP. Dùng hộp thư riêng và cấp quyền trước khi bật.", - "steps": [ - "Tạo hộp thư riêng và mật khẩu ứng dụng nếu cần.", - "Chọn nhà cung cấp hoặc nhập thủ công cài đặt IMAP và SMTP.", - "Cấp quyền, lưu và bật Email, sau đó gửi tin nhắn thử." - ], + "presetLabel": "Điền nhanh", + "sections": { + "receiving": "Nhận thư", + "sending": "Gửi thư" + }, "presets": { "gmail": "Gmail", "outlook": "Outlook", - "icloud": "iCloud", - "custom": "Tùy chỉnh" + "icloud": "iCloud" }, "fields": { "consentGranted": { "label": "Cho phép nanobot đọc và gửi email", - "help": "Bật để cho phép nanobot truy cập hộp thư này. Hãy kiểm tra đây là hộp thư dành riêng cho bot.", "choices": { "true": "Đã đồng ý", "false": "Chưa đồng ý" @@ -37,8 +31,7 @@ }, "imapPassword": { "label": "Mật khẩu IMAP", - "placeholder": "Mật khẩu ứng dụng", - "help": "Dùng mật khẩu ứng dụng khi nhà cung cấp yêu cầu." + "placeholder": "Mật khẩu ứng dụng" }, "smtpHost": { "label": "Máy chủ SMTP", @@ -50,8 +43,7 @@ }, "smtpPassword": { "label": "Mật khẩu SMTP", - "placeholder": "Mật khẩu ứng dụng", - "help": "Thường giống mật khẩu ứng dụng dùng cho IMAP." + "placeholder": "Mật khẩu ứng dụng" }, "imapPort": { "label": "Cổng IMAP", @@ -71,8 +63,7 @@ }, "allowFrom": { "label": "Người gửi được phép", - "placeholder": "Địa chỉ email, phân tách bằng dấu phẩy", - "help": "Để trống để yêu cầu ghép nối trước." + "placeholder": "Địa chỉ email, phân tách bằng dấu phẩy" }, "verifyDkim": { "label": "Xác minh DKIM", @@ -87,6 +78,83 @@ "true": "Bật", "false": "Tắt" } + }, + "imapMailbox": { + "label": "Hộp thư IMAP" + }, + "imapUseSsl": { + "label": "SSL IMAP", + "choices": { + "true": "Bật", + "false": "Tắt" + } + }, + "smtpUseTls": { + "label": "TLS SMTP", + "choices": { + "true": "Bật", + "false": "Tắt" + } + }, + "smtpUseSsl": { + "label": "SSL SMTP", + "choices": { + "true": "Bật", + "false": "Tắt" + } + }, + "autoReplyEnabled": { + "label": "Trả lời tự động", + "choices": { + "true": "Bật", + "false": "Tắt" + } + }, + "markSeen": { + "label": "Đánh dấu là đã đọc", + "choices": { + "true": "Bật", + "false": "Tắt" + } + }, + "postAction": { + "label": "Sau khi xử lý", + "choices": { + "delete": "Xóa", + "move": "Di chuyển" + } + }, + "postActionMoveMailbox": { + "label": "Di chuyển tới hộp thư" + }, + "postActionExpunge": { + "label": "Áp dụng hành động vĩnh viễn", + "choices": { + "true": "Bật", + "false": "Tắt" + } + }, + "postActionIgnoreSkipped": { + "label": "Bỏ qua tin nhắn bị bỏ qua", + "choices": { + "true": "Bật", + "false": "Tắt" + } + }, + "maxBodyChars": { + "label": "Chiều dài cơ thể tối đa" + }, + "subjectPrefix": { + "label": "Trả lời tiền tố chủ đề" + }, + "allowedAttachmentTypes": { + "label": "Các loại tệp đính kèm được phép" + }, + "maxAttachmentSize": { + "label": "Kích thước tệp đính kèm tối đa" + }, + "maxAttachmentsPerEmail": { + "label": "Tệp đính kèm tối đa" } } } diff --git a/nanobot/channels/email/webui/locales/zh-CN.json b/nanobot/channels/email/webui/locales/zh-CN.json index 961422b47..b664ad8f8 100644 --- a/nanobot/channels/email/webui/locales/zh-CN.json +++ b/nanobot/channels/email/webui/locales/zh-CN.json @@ -1,26 +1,20 @@ { - "description": "让 nanobot 接收并回复电子邮件。", - "requirements": "IMAP 收件箱、SMTP 发件服务、应用专用密码和明确授权", "setup": { "docsLabel": "打开邮件配置指南", "officialLabel": "打开应用专用密码指南", - "tryIt": "向已连接的邮箱发送一封测试邮件。", - "summary": "邮件渠道通过 IMAP 读取邮件并通过 SMTP 回复。请使用专用邮箱,并在启用前明确授权。", - "steps": [ - "创建专用邮箱,并在服务商要求时创建应用专用密码。", - "选择服务商预设,或手动填写 IMAP 和 SMTP 设置。", - "授予授权,保存并启用邮件渠道,然后向邮箱发送一封测试邮件。" - ], + "presetLabel": "快速填充", + "sections": { + "receiving": "接收邮件", + "sending": "发送邮件" + }, "presets": { "gmail": "Gmail", "outlook": "Outlook", - "icloud": "iCloud", - "custom": "自定义" + "icloud": "iCloud" }, "fields": { "consentGranted": { "label": "允许 nanobot 读取和发送邮件", - "help": "开启即表示同意 nanobot 访问此邮箱。请确认这是你要连接的机器人专用邮箱。", "choices": { "true": "已授权", "false": "未授权" @@ -36,8 +30,7 @@ }, "imapPassword": { "label": "IMAP 密码", - "placeholder": "应用专用密码", - "help": "如果邮件服务商要求,请使用应用专用密码。" + "placeholder": "应用专用密码" }, "smtpHost": { "label": "SMTP 主机", @@ -49,8 +42,7 @@ }, "smtpPassword": { "label": "SMTP 密码", - "placeholder": "应用专用密码", - "help": "通常与 IMAP 使用同一个应用专用密码。" + "placeholder": "应用专用密码" }, "imapPort": { "label": "IMAP 端口", @@ -70,8 +62,7 @@ }, "allowFrom": { "label": "允许的发件人", - "placeholder": "邮箱地址,用逗号分隔", - "help": "留空则要求发件人先完成配对。" + "placeholder": "邮箱地址,用逗号分隔" }, "verifyDkim": { "label": "验证 DKIM", @@ -86,6 +77,83 @@ "true": "开启", "false": "关闭" } + }, + "imapMailbox": { + "label": "IMAP 邮箱" + }, + "imapUseSsl": { + "label": "IMAP SSL", + "choices": { + "true": "开启", + "false": "关闭" + } + }, + "smtpUseTls": { + "label": "SMTP TLS", + "choices": { + "true": "开启", + "false": "关闭" + } + }, + "smtpUseSsl": { + "label": "SMTP SSL", + "choices": { + "true": "开启", + "false": "关闭" + } + }, + "autoReplyEnabled": { + "label": "自动回复", + "choices": { + "true": "开启", + "false": "关闭" + } + }, + "markSeen": { + "label": "标为已读", + "choices": { + "true": "开启", + "false": "关闭" + } + }, + "postAction": { + "label": "处理后", + "choices": { + "delete": "删除", + "move": "移动" + } + }, + "postActionMoveMailbox": { + "label": "移至邮箱" + }, + "postActionExpunge": { + "label": "永久执行操作", + "choices": { + "true": "开启", + "false": "关闭" + } + }, + "postActionIgnoreSkipped": { + "label": "忽略未处理邮件", + "choices": { + "true": "开启", + "false": "关闭" + } + }, + "maxBodyChars": { + "label": "正文长度上限" + }, + "subjectPrefix": { + "label": "回复主题前缀" + }, + "allowedAttachmentTypes": { + "label": "允许的附件类型" + }, + "maxAttachmentSize": { + "label": "附件大小上限" + }, + "maxAttachmentsPerEmail": { + "label": "附件数量上限" } } }, diff --git a/nanobot/channels/email/webui/locales/zh-TW.json b/nanobot/channels/email/webui/locales/zh-TW.json index fbce0a910..27d5b4166 100644 --- a/nanobot/channels/email/webui/locales/zh-TW.json +++ b/nanobot/channels/email/webui/locales/zh-TW.json @@ -1,27 +1,21 @@ { "displayName": "電子郵件", - "description": "讓 nanobot 接收並回覆電子郵件。", - "requirements": "IMAP 收件匣、SMTP 寄件服務、應用程式密碼和明確授權", "setup": { "docsLabel": "開啟郵件設定指南", "officialLabel": "開啟應用程式密碼指南", - "tryIt": "向已連接的信箱傳送一封測試郵件。", - "summary": "郵件管道透過 IMAP 讀取郵件並透過 SMTP 回覆。請使用專用信箱,並在啟用前明確授權。", - "steps": [ - "建立專用信箱,並在服務商要求時建立應用程式密碼。", - "選擇服務商預設,或手動填入 IMAP 和 SMTP 設定。", - "授予權限,儲存並啟用郵件管道,然後向信箱傳送一封測試郵件。" - ], + "presetLabel": "快速填入", + "sections": { + "receiving": "接收郵件", + "sending": "傳送郵件" + }, "presets": { "gmail": "Gmail", "outlook": "Outlook", - "icloud": "iCloud", - "custom": "自訂" + "icloud": "iCloud" }, "fields": { "consentGranted": { "label": "允許 nanobot 讀取及傳送電子郵件", - "help": "開啟即表示同意 nanobot 存取此信箱。請確認這是要提供給機器人使用的專用信箱。", "choices": { "true": "已授權", "false": "未授權" @@ -37,8 +31,7 @@ }, "imapPassword": { "label": "IMAP 密碼", - "placeholder": "應用程式密碼", - "help": "若郵件服務商要求,請使用應用程式密碼。" + "placeholder": "應用程式密碼" }, "smtpHost": { "label": "SMTP 主機", @@ -50,8 +43,7 @@ }, "smtpPassword": { "label": "SMTP 密碼", - "placeholder": "應用程式密碼", - "help": "通常與 IMAP 使用同一個應用程式密碼。" + "placeholder": "應用程式密碼" }, "imapPort": { "label": "IMAP 連接埠", @@ -71,8 +63,7 @@ }, "allowFrom": { "label": "允許的寄件者", - "placeholder": "電子郵件地址,以逗號分隔", - "help": "留空則要求寄件者先完成配對。" + "placeholder": "電子郵件地址,以逗號分隔" }, "verifyDkim": { "label": "驗證 DKIM", @@ -87,6 +78,83 @@ "true": "開啟", "false": "關閉" } + }, + "imapMailbox": { + "label": "IMAP 信箱" + }, + "imapUseSsl": { + "label": "IMAP SSL", + "choices": { + "true": "開啟", + "false": "關閉" + } + }, + "smtpUseTls": { + "label": "SMTP TLS", + "choices": { + "true": "開啟", + "false": "關閉" + } + }, + "smtpUseSsl": { + "label": "SMTP SSL", + "choices": { + "true": "開啟", + "false": "關閉" + } + }, + "autoReplyEnabled": { + "label": "自動回覆", + "choices": { + "true": "開啟", + "false": "關閉" + } + }, + "markSeen": { + "label": "標為已讀", + "choices": { + "true": "開啟", + "false": "關閉" + } + }, + "postAction": { + "label": "處理後", + "choices": { + "delete": "刪除", + "move": "移動" + } + }, + "postActionMoveMailbox": { + "label": "移至信箱" + }, + "postActionExpunge": { + "label": "永久執行操作", + "choices": { + "true": "開啟", + "false": "關閉" + } + }, + "postActionIgnoreSkipped": { + "label": "忽略未處理郵件", + "choices": { + "true": "開啟", + "false": "關閉" + } + }, + "maxBodyChars": { + "label": "正文長度上限" + }, + "subjectPrefix": { + "label": "回覆主題前綴" + }, + "allowedAttachmentTypes": { + "label": "允許的附件類型" + }, + "maxAttachmentSize": { + "label": "附件大小上限" + }, + "maxAttachmentsPerEmail": { + "label": "附件數量上限" } } } diff --git a/nanobot/channels/feishu/manifest.py b/nanobot/channels/feishu/manifest.py index ee6c00f4a..2b248f7a1 100644 --- a/nanobot/channels/feishu/manifest.py +++ b/nanobot/channels/feishu/manifest.py @@ -24,6 +24,16 @@ SETUP_SPEC = ChannelSetupSpec( ), "allowFrom": field("list", snapshot=False), "topicIsolation": field("bool", default=True, snapshot=False), + "name": field(default="nanobot", snapshot=False), + "encryptKey": field("secret", snapshot=False), + "verificationToken": field("secret", snapshot=False), + "reactEmoji": field(default="THUMBSUP", snapshot=False), + "doneEmoji": field(snapshot=False), + "toolHintPrefix": field(default="🔧", snapshot=False), + "replyToMessage": field("bool", default=False, snapshot=False), + "streaming": field("bool", default=True, snapshot=False), + "instanceId": field(writable=False, snapshot=False), + "identityKey": field(writable=False, snapshot=False), }, required=required_fields("appId", "appSecret"), official_url="https://open.feishu.cn/app", diff --git a/nanobot/channels/feishu/webui/FeishuAssistantsPanel.tsx b/nanobot/channels/feishu/webui/FeishuAssistantsPanel.tsx index f9536903a..012638544 100644 --- a/nanobot/channels/feishu/webui/FeishuAssistantsPanel.tsx +++ b/nanobot/channels/feishu/webui/FeishuAssistantsPanel.tsx @@ -1,29 +1,20 @@ -import { useState } from "react"; -import { Loader2, RotateCcw } from "lucide-react"; import { useTranslation } from "react-i18next"; import { channelTranslator, - type ChannelTranslator, } from "@/channel-plugins/i18n"; import type { ChannelPluginPanelProps } from "@/channel-plugins/types"; import { ChannelInstancesPanel } from "@/components/settings/channels/ChannelInstancesPanel"; -import { Button } from "@/components/ui/button"; -import { enableNanobotFeature } from "@/lib/api"; import type { NanobotChannelInstanceInfo, NanobotFeatureInfo, - NanobotFeaturesPayload, } from "@/lib/types"; -import { useClient } from "@/providers/ClientProvider"; - import { FeishuConnectFlow } from "./FeishuConnectFlow"; export function FeishuAssistantsPanel({ token, feature, showBrandLogos, - chatAppsDocsUrl, onFeaturesUpdate, }: ChannelPluginPanelProps) { const { t } = useTranslation(); @@ -36,122 +27,30 @@ export function FeishuAssistantsPanel({ feishuAssistantCountLabel(count, tx), toggleAriaLabel: (instance) => tx("custom.toggleAssistant", "{{name}} assistant", { name: instanceDisplayName(instance), }), configuredLabel: tx("custom.configured", "Connected"), needsSetupLabel: tx("custom.needsSetup", "Needs authorization"), - renderInstanceSummary: (instance) => ( - maskFeishuAppId(instance.config_values?.["channels.feishu.appId"]) - || tx("custom.noAppId", "No App ID") - ), - renderInstanceAction: (instance) => ( - null, + renderInstanceAction: (instance) => instance.configured ? null : ( + ), - footer: ( -
-
- {tx("custom.createAnother", "Create another assistant")} -
-

- {tx( - "custom.createHint", - "Create a separate Feishu bot for another team, space, or workflow.", - )} -

- -
- ), }} /> ); } -function FeishuInstanceAction({ - token, - instance, - onFeaturesUpdate, -}: { - token: string; - instance: NanobotChannelInstanceInfo; - onFeaturesUpdate: (payload: NanobotFeaturesPayload) => void; -}) { - const { client } = useClient(); - const { t } = useTranslation(); - const tx = channelTranslator(t, "feishu"); - const [busy, setBusy] = useState(false); - const [error, setError] = useState(null); - - if (!instance.configured) { - return ( - - ); - } - - const reconnect = async () => { - setBusy(true); - setError(null); - try { - onFeaturesUpdate( - await enableNanobotFeature(client, "feishu", { instanceId: instance.id }), - ); - } catch (err) { - setError((err as Error).message); - } finally { - setBusy(false); - } - }; - - return ( - <> -
- -
- {error ? ( -
- {error} -
- ) : null} - - ); -} - function defaultFeishuInstance(feature: NanobotFeatureInfo): NanobotChannelInstanceInfo { return { id: "default", @@ -163,21 +62,6 @@ function defaultFeishuInstance(feature: NanobotFeatureInfo): NanobotChannelInsta }; } -function feishuAssistantCountLabel( - count: number, - tx: ChannelTranslator, -): string { - if (count === 0) return tx("custom.countNone", "No assistant connected"); - if (count === 1) return tx("custom.countOne", "1 assistant connected"); - return tx("custom.countMany", "{{count}} assistants connected", { count }); -} - function instanceDisplayName(instance: NanobotChannelInstanceInfo): string { return instance.display_name?.trim() || instance.name.trim() || instance.id; } - -function maskFeishuAppId(appId: string | undefined): string { - if (!appId) return ""; - if (appId.length <= 10) return appId; - return `${appId.slice(0, 7)}...${appId.slice(-4)}`; -} diff --git a/nanobot/channels/feishu/webui/FeishuConnectFlow.tsx b/nanobot/channels/feishu/webui/FeishuConnectFlow.tsx index 7142ebe54..471a57bc0 100644 --- a/nanobot/channels/feishu/webui/FeishuConnectFlow.tsx +++ b/nanobot/channels/feishu/webui/FeishuConnectFlow.tsx @@ -25,7 +25,7 @@ export function FeishuConnectFlow({ None: + def __init__(self, homeserver, user, store_path, config, proxy=None) -> None: self.homeserver = homeserver self.user = user self.store_path = store_path self.config = config + self.proxy = proxy self.user_id: str | None = None self.access_token: str | None = None self.device_id: str | None = None @@ -326,11 +327,15 @@ async def test_start_skips_load_store_when_device_id_missing( "nanobot.channels.matrix.runtime.asyncio.create_task", _fake_create_task ) - channel = MatrixChannel(_make_config(device_id="", e2ee_enabled=True), MessageBus()) + channel = MatrixChannel( + _make_config(device_id="", e2ee_enabled=True, proxy="127.0.0.1:7890"), + MessageBus(), + ) await channel.start() assert len(clients) == 1 assert clients[0].config.encryption_enabled is True + assert clients[0].proxy == "http://127.0.0.1:7890" assert clients[0].load_store_called is False assert len(clients[0].callbacks) == 3 assert clients[0].to_device_callbacks == [] diff --git a/nanobot/channels/matrix/tests/test_validation.py b/nanobot/channels/matrix/tests/test_validation.py index 6cd621a7c..36d02a499 100644 --- a/nanobot/channels/matrix/tests/test_validation.py +++ b/nanobot/channels/matrix/tests/test_validation.py @@ -10,7 +10,7 @@ from nanobot.config.schema import Config @pytest.mark.parametrize( ("credentials", "expected_status", "expected_missing"), [ - ({}, "needs_setup", "password_or_accessToken"), + ({}, "needs_setup", "password"), ({"channels.matrix.accessToken": "token"}, "needs_setup", "deviceId"), ({"channels.matrix.password": "secret"}, "configured", None), ( @@ -49,3 +49,35 @@ def test_validate_matrix_requires_a_complete_login_method( assert result["missing_fields"] == [] else: assert expected_missing in result["missing_fields"] + + +def test_validate_matrix_can_replace_a_saved_password_with_a_token( + tmp_path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + config_path = tmp_path / "config.json" + save_config( + Config.model_validate({ + "channels": { + "matrix": { + "homeserver": "https://matrix.example", + "userId": "@nanobot:matrix.example", + "password": "saved-password", + }, + }, + }), + config_path, + ) + monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path) + + result = validate_channel_config( + "matrix", + { + "channels.matrix.password": None, + "channels.matrix.accessToken": "replacement-token", + "channels.matrix.deviceId": "DEVICE", + }, + ) + + assert result["status"] == "configured" + assert result["missing_fields"] == [] diff --git a/nanobot/channels/matrix/validation.py b/nanobot/channels/matrix/validation.py index 19b9a8c82..cfe443661 100644 --- a/nanobot/channels/matrix/validation.py +++ b/nanobot/channels/matrix/validation.py @@ -25,7 +25,7 @@ def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dict ) else: if not password and not access_token: - missing.append("password_or_accessToken") + missing.append("password") message = "Add a password, or an access token with its device ID." else: missing.append("deviceId") diff --git a/nanobot/channels/matrix/webui/index.ts b/nanobot/channels/matrix/webui/index.ts index 1d9a00487..8a45162a3 100644 --- a/nanobot/channels/matrix/webui/index.ts +++ b/nanobot/channels/matrix/webui/index.ts @@ -3,20 +3,20 @@ import { chatAppGuideUrl } from "@/components/settings/channels/catalog"; export default { presentation: { + logoUrl: "https://matrix.org/favicon.ico", displayName: "Matrix", initials: "MX", color: "#0DBD8B", - logoUrl: "https://matrix.org/favicon.ico", setup: { mode: "credentials", docsUrl: chatAppGuideUrl("matrix"), fields: [ - { key: "channels.matrix.homeserver" }, - { key: "channels.matrix.userId" }, - { key: "channels.matrix.password" }, - { key: "channels.matrix.accessToken" }, - { key: "channels.matrix.deviceId" }, - { key: "channels.matrix.groupPolicy" }, + { key: "channels.matrix.homeserver", section: "connection" }, + { key: "channels.matrix.userId", section: "account" }, + { key: "channels.matrix.password", section: "credentials" }, + { key: "channels.matrix.accessToken", section: "credentials" }, + { key: "channels.matrix.deviceId", section: "credentials" }, + { key: "channels.matrix.groupPolicy", section: "behavior" }, ], }, }, diff --git a/nanobot/channels/matrix/webui/locales/en.json b/nanobot/channels/matrix/webui/locales/en.json index 6c0de5fd9..9d3f97646 100644 --- a/nanobot/channels/matrix/webui/locales/en.json +++ b/nanobot/channels/matrix/webui/locales/en.json @@ -1,16 +1,7 @@ { - "description": "Use nanobot from Matrix rooms.", - "requirements": "Homeserver, account token, room access", "setup": { "docsLabel": "Open Matrix setup", "officialLabel": "Open Matrix clients", - "tryIt": "Invite the Matrix account into a room and send a test message.", - "summary": "Enter your Matrix homeserver and sign in with a password or access token.", - "steps": [ - "Create or choose a Matrix account for nanobot.", - "Enter the homeserver, user ID, and either password or access-token credentials.", - "Save and enable Matrix, invite the account to a room, and send a test message." - ], "fields": { "homeserver": { "label": "Homeserver", @@ -22,18 +13,15 @@ }, "password": { "label": "Password", - "placeholder": "••••••", - "help": "Use either password login or access token login." + "placeholder": "••••••" }, "accessToken": { "label": "Access token", - "placeholder": "Enter an access token", - "help": "Preferred when your Matrix client exposes an access token." + "placeholder": "Enter an access token" }, "deviceId": { "label": "Device ID", - "placeholder": "Required with an access token", - "help": "Copy the device ID associated with the access token. Password login does not need it." + "placeholder": "Required with an access token" }, "groupPolicy": { "label": "Group behavior", @@ -42,6 +30,53 @@ "open": "All messages", "allowlist": "Allowlist" } + }, + "allowFrom": { + "label": "Allowed users" + }, + "e2eeEnabled": { + "label": "End-to-end encryption", + "choices": { + "true": "On", + "false": "Off" + } + }, + "sasVerification": { + "label": "SAS verification", + "choices": { + "true": "On", + "false": "Off" + } + }, + "syncStopGraceSeconds": { + "label": "Sync stop grace period" + }, + "maxMediaBytes": { + "label": "Maximum media size" + }, + "maxConcurrentMediaDownloads": { + "label": "Concurrent media downloads" + }, + "groupAllowFrom": { + "label": "Allowed groups" + }, + "allowRoomMentions": { + "label": "Allow room mentions", + "choices": { + "true": "On", + "false": "Off" + } + }, + "streaming": { + "label": "Streaming", + "choices": { + "true": "On", + "false": "Off" + } + }, + "proxy": { + "label": "Network proxy", + "placeholder": "http://127.0.0.1:7890" } } } diff --git a/nanobot/channels/matrix/webui/locales/es.json b/nanobot/channels/matrix/webui/locales/es.json index 3e5b405ca..f7c08b3b0 100644 --- a/nanobot/channels/matrix/webui/locales/es.json +++ b/nanobot/channels/matrix/webui/locales/es.json @@ -1,16 +1,7 @@ { - "description": "Usa nanobot desde salas de Matrix.", - "requirements": "Servidor de la cuenta, credenciales de acceso y permisos para las salas", "setup": { "docsLabel": "Abrir guía de Matrix", "officialLabel": "Abrir lista de clientes Matrix", - "tryIt": "Invita la cuenta de Matrix a una sala y envía un mensaje de prueba.", - "summary": "Introduce el servidor de tu cuenta de Matrix e inicia sesión con una contraseña o un token de acceso.", - "steps": [ - "Crea o elige una cuenta de Matrix para nanobot.", - "Introduce el servidor de tu cuenta, el ID de usuario y la contraseña o el token de acceso.", - "Guarda y activa Matrix, invita la cuenta a una sala y envía un mensaje de prueba." - ], "fields": { "homeserver": { "label": "Servidor de la cuenta", @@ -22,18 +13,15 @@ }, "password": { "label": "Contraseña", - "placeholder": "••••••", - "help": "Usa contraseña o token de acceso." + "placeholder": "••••••" }, "accessToken": { "label": "Token de acceso", - "placeholder": "Introduce un token de acceso", - "help": "Preferible si tu cliente Matrix muestra un token de acceso." + "placeholder": "Introduce un token de acceso" }, "deviceId": { "label": "ID del dispositivo", - "placeholder": "Obligatorio con token", - "help": "Copia el ID asociado al token. No se necesita con contraseña." + "placeholder": "Obligatorio con token" }, "groupPolicy": { "label": "Comportamiento en grupos", @@ -42,6 +30,53 @@ "open": "Todos los mensajes", "allowlist": "Lista de permitidos" } + }, + "allowFrom": { + "label": "Usuarios permitidos" + }, + "e2eeEnabled": { + "label": "Cifrado de extremo a extremo", + "choices": { + "true": "encendido", + "false": "Apagado" + } + }, + "sasVerification": { + "label": "verificación SAS", + "choices": { + "true": "encendido", + "false": "Apagado" + } + }, + "syncStopGraceSeconds": { + "label": "Período de gracia para detener la sincronización" + }, + "maxMediaBytes": { + "label": "Tamaño máximo de medios" + }, + "maxConcurrentMediaDownloads": { + "label": "Descargas multimedia simultáneas" + }, + "groupAllowFrom": { + "label": "Grupos permitidos" + }, + "allowRoomMentions": { + "label": "Permitir menciones de sala", + "choices": { + "true": "encendido", + "false": "Apagado" + } + }, + "streaming": { + "label": "Transmisión", + "choices": { + "true": "encendido", + "false": "Apagado" + } + }, + "proxy": { + "label": "Proxy de red", + "placeholder": "http://127.0.0.1:7890" } } } diff --git a/nanobot/channels/matrix/webui/locales/fr.json b/nanobot/channels/matrix/webui/locales/fr.json index 319ad92c4..9e7843ac0 100644 --- a/nanobot/channels/matrix/webui/locales/fr.json +++ b/nanobot/channels/matrix/webui/locales/fr.json @@ -1,16 +1,7 @@ { - "description": "Utilisez nanobot depuis les salons Matrix.", - "requirements": "Serveur d’accueil, jeton de compte et accès aux salons", "setup": { "docsLabel": "Ouvrir le guide Matrix", "officialLabel": "Ouvrir la liste des clients Matrix", - "tryIt": "Invitez le compte Matrix dans un salon et envoyez un message test.", - "summary": "Saisissez le serveur de votre compte Matrix et connectez-vous avec un mot de passe ou un jeton d’accès.", - "steps": [ - "Créez ou choisissez un compte Matrix pour nanobot.", - "Saisissez le serveur, l’ID utilisateur et le mot de passe ou le jeton d’accès.", - "Enregistrez et activez Matrix, invitez le compte dans un salon et envoyez un message test." - ], "fields": { "homeserver": { "label": "Serveur d’accueil", @@ -22,18 +13,15 @@ }, "password": { "label": "Mot de passe", - "placeholder": "••••••", - "help": "Utilisez le mot de passe ou le jeton d’accès." + "placeholder": "••••••" }, "accessToken": { "label": "Jeton d’accès", - "placeholder": "Saisir un jeton d’accès", - "help": "À privilégier si votre client Matrix expose un jeton d’accès." + "placeholder": "Saisir un jeton d’accès" }, "deviceId": { "label": "ID de l’appareil", - "placeholder": "Requis avec un jeton d’accès", - "help": "Copiez l’ID d’appareil associé au jeton. Il n’est pas nécessaire avec un mot de passe." + "placeholder": "Requis avec un jeton d’accès" }, "groupPolicy": { "label": "Comportement en groupe", @@ -42,6 +30,53 @@ "open": "Tous les messages", "allowlist": "Liste d’autorisation" } + }, + "allowFrom": { + "label": "Utilisateurs autorisés" + }, + "e2eeEnabled": { + "label": "Chiffrement de bout en bout", + "choices": { + "true": "Sur", + "false": "Désactivé" + } + }, + "sasVerification": { + "label": "Vérification SAS", + "choices": { + "true": "Sur", + "false": "Désactivé" + } + }, + "syncStopGraceSeconds": { + "label": "Délai de grâce pour l'arrêt de la synchronisation" + }, + "maxMediaBytes": { + "label": "Taille maximale du support" + }, + "maxConcurrentMediaDownloads": { + "label": "Téléchargements multimédias simultanés" + }, + "groupAllowFrom": { + "label": "Groupes autorisés" + }, + "allowRoomMentions": { + "label": "Autoriser les mentions de salles", + "choices": { + "true": "Sur", + "false": "Désactivé" + } + }, + "streaming": { + "label": "Diffusion en continu", + "choices": { + "true": "Sur", + "false": "Désactivé" + } + }, + "proxy": { + "label": "Proxy réseau", + "placeholder": "http://127.0.0.1:7890" } } } diff --git a/nanobot/channels/matrix/webui/locales/id.json b/nanobot/channels/matrix/webui/locales/id.json index 28edefe1c..1753c9b2e 100644 --- a/nanobot/channels/matrix/webui/locales/id.json +++ b/nanobot/channels/matrix/webui/locales/id.json @@ -1,16 +1,7 @@ { - "description": "Gunakan nanobot dari ruang Matrix.", - "requirements": "Server akun, kredensial, dan akses ruang", "setup": { "docsLabel": "Buka panduan Matrix", "officialLabel": "Buka daftar klien Matrix", - "tryIt": "Undang akun Matrix ke ruang dan kirim pesan uji.", - "summary": "Masukkan server akun Matrix, lalu masuk dengan kata sandi atau token akses.", - "steps": [ - "Buat atau pilih akun Matrix untuk nanobot.", - "Masukkan server akun, ID pengguna, serta kata sandi atau token akses.", - "Simpan dan aktifkan Matrix, undang akun ke ruang, lalu kirim pesan uji." - ], "fields": { "homeserver": { "label": "Server akun", @@ -22,18 +13,15 @@ }, "password": { "label": "Kata sandi", - "placeholder": "••••••", - "help": "Gunakan kata sandi atau token akses." + "placeholder": "••••••" }, "accessToken": { "label": "Token akses", - "placeholder": "Masukkan token akses", - "help": "Disarankan jika klien Matrix menyediakan token akses." + "placeholder": "Masukkan token akses" }, "deviceId": { "label": "ID perangkat", - "placeholder": "Wajib dengan token akses", - "help": "Salin ID perangkat yang terkait token. Login kata sandi tidak memerlukannya." + "placeholder": "Wajib dengan token akses" }, "groupPolicy": { "label": "Perilaku grup", @@ -42,6 +30,53 @@ "open": "Semua pesan", "allowlist": "Daftar izin" } + }, + "allowFrom": { + "label": "Pengguna yang diizinkan" + }, + "e2eeEnabled": { + "label": "Enkripsi ujung ke ujung", + "choices": { + "true": "Aktif", + "false": "Mati" + } + }, + "sasVerification": { + "label": "verifikasi SAS", + "choices": { + "true": "Aktif", + "false": "Mati" + } + }, + "syncStopGraceSeconds": { + "label": "Sinkronisasi menghentikan masa tenggang" + }, + "maxMediaBytes": { + "label": "Ukuran media maksimum" + }, + "maxConcurrentMediaDownloads": { + "label": "Pengunduhan media secara bersamaan" + }, + "groupAllowFrom": { + "label": "Grup yang diizinkan" + }, + "allowRoomMentions": { + "label": "Izinkan penyebutan ruangan", + "choices": { + "true": "Aktif", + "false": "Mati" + } + }, + "streaming": { + "label": "Streaming", + "choices": { + "true": "Aktif", + "false": "Mati" + } + }, + "proxy": { + "label": "Proxy jaringan", + "placeholder": "http://127.0.0.1:7890" } } } diff --git a/nanobot/channels/matrix/webui/locales/ja.json b/nanobot/channels/matrix/webui/locales/ja.json index 9c0769d43..cc587fef2 100644 --- a/nanobot/channels/matrix/webui/locales/ja.json +++ b/nanobot/channels/matrix/webui/locales/ja.json @@ -1,16 +1,7 @@ { - "description": "Matrix ルームから nanobot を利用します。", - "requirements": "ホームサーバー、アカウントトークン、ルームへのアクセス", "setup": { "docsLabel": "Matrix 設定ガイドを開く", "officialLabel": "Matrix クライアント一覧を開く", - "tryIt": "Matrix アカウントをルームに招待し、テストメッセージを送信します。", - "summary": "Matrix アカウントのホームサーバーを入力し、パスワードまたはアクセストークンでログインします。", - "steps": [ - "nanobot 用の Matrix アカウントを作成または選択します。", - "ホームサーバー、ユーザー ID、パスワードまたはアクセストークンを入力します。", - "保存して Matrix を有効にし、アカウントをルームに招待してテストメッセージを送信します。" - ], "fields": { "homeserver": { "label": "ホームサーバー", @@ -22,18 +13,15 @@ }, "password": { "label": "パスワード", - "placeholder": "••••••", - "help": "パスワードまたはアクセストークンのどちらかを使います。" + "placeholder": "••••••" }, "accessToken": { "label": "アクセストークン", - "placeholder": "アクセストークンを入力", - "help": "Matrix クライアントでアクセストークンを取得できる場合に推奨します。" + "placeholder": "アクセストークンを入力" }, "deviceId": { "label": "デバイス ID", - "placeholder": "アクセストークン使用時に必須", - "help": "トークンに関連付けられたデバイス ID をコピーします。パスワードログインでは不要です。" + "placeholder": "アクセストークン使用時に必須" }, "groupPolicy": { "label": "グループでの動作", @@ -42,6 +30,53 @@ "open": "すべてのメッセージ", "allowlist": "許可リスト" } + }, + "allowFrom": { + "label": "許可されたユーザー" + }, + "e2eeEnabled": { + "label": "エンドツーエンドの暗号化", + "choices": { + "true": "オン", + "false": "オフ" + } + }, + "sasVerification": { + "label": "SAS 検証", + "choices": { + "true": "オン", + "false": "オフ" + } + }, + "syncStopGraceSeconds": { + "label": "同期停止猶予期間" + }, + "maxMediaBytes": { + "label": "最大メディアサイズ" + }, + "maxConcurrentMediaDownloads": { + "label": "メディアの同時ダウンロード" + }, + "groupAllowFrom": { + "label": "許可されたグループ" + }, + "allowRoomMentions": { + "label": "部屋のメンションを許可する", + "choices": { + "true": "オン", + "false": "オフ" + } + }, + "streaming": { + "label": "ストリーミング", + "choices": { + "true": "オン", + "false": "オフ" + } + }, + "proxy": { + "label": "ネットワークプロキシ", + "placeholder": "http://127.0.0.1:7890" } } } diff --git a/nanobot/channels/matrix/webui/locales/ko.json b/nanobot/channels/matrix/webui/locales/ko.json index 99b4692b7..391c32324 100644 --- a/nanobot/channels/matrix/webui/locales/ko.json +++ b/nanobot/channels/matrix/webui/locales/ko.json @@ -1,16 +1,7 @@ { - "description": "Matrix 룸에서 nanobot을 사용합니다.", - "requirements": "홈서버, 계정 토큰 및 룸 접근 권한", "setup": { "docsLabel": "Matrix 설정 가이드 열기", "officialLabel": "Matrix 클라이언트 목록 열기", - "tryIt": "Matrix 계정을 룸에 초대하고 테스트 메시지를 보내세요.", - "summary": "Matrix 계정의 홈서버를 입력하고 비밀번호 또는 액세스 토큰으로 로그인하세요.", - "steps": [ - "nanobot용 Matrix 계정을 만들거나 선택하세요.", - "홈서버, 사용자 ID, 비밀번호 또는 액세스 토큰을 입력하세요.", - "저장하고 Matrix를 활성화한 다음 계정을 룸에 초대하고 테스트 메시지를 보내세요." - ], "fields": { "homeserver": { "label": "홈서버", @@ -22,18 +13,15 @@ }, "password": { "label": "비밀번호", - "placeholder": "••••••", - "help": "비밀번호 또는 액세스 토큰 중 하나를 사용하세요." + "placeholder": "••••••" }, "accessToken": { "label": "액세스 토큰", - "placeholder": "액세스 토큰 입력", - "help": "Matrix 클라이언트에서 토큰을 확인할 수 있다면 권장합니다." + "placeholder": "액세스 토큰 입력" }, "deviceId": { "label": "장치 ID", - "placeholder": "액세스 토큰 사용 시 필수", - "help": "토큰과 연결된 장치 ID를 복사하세요. 비밀번호 로그인에는 필요하지 않습니다." + "placeholder": "액세스 토큰 사용 시 필수" }, "groupPolicy": { "label": "그룹 동작", @@ -42,6 +30,53 @@ "open": "모든 메시지", "allowlist": "허용 목록" } + }, + "allowFrom": { + "label": "허용된 사용자" + }, + "e2eeEnabled": { + "label": "엔드투엔드 암호화", + "choices": { + "true": "켜기", + "false": "끄기" + } + }, + "sasVerification": { + "label": "SAS 검증", + "choices": { + "true": "켜기", + "false": "끄기" + } + }, + "syncStopGraceSeconds": { + "label": "동기화 중지 유예 기간" + }, + "maxMediaBytes": { + "label": "최대 미디어 크기" + }, + "maxConcurrentMediaDownloads": { + "label": "동시 미디어 다운로드" + }, + "groupAllowFrom": { + "label": "허용된 그룹" + }, + "allowRoomMentions": { + "label": "회의실 언급 허용", + "choices": { + "true": "켜기", + "false": "끄기" + } + }, + "streaming": { + "label": "스트리밍", + "choices": { + "true": "켜기", + "false": "끄기" + } + }, + "proxy": { + "label": "네트워크 프록시", + "placeholder": "http://127.0.0.1:7890" } } } diff --git a/nanobot/channels/matrix/webui/locales/pt-BR.json b/nanobot/channels/matrix/webui/locales/pt-BR.json index 20c8f8d5a..759b49b2a 100644 --- a/nanobot/channels/matrix/webui/locales/pt-BR.json +++ b/nanobot/channels/matrix/webui/locales/pt-BR.json @@ -1,16 +1,7 @@ { - "description": "Use o nanobot em salas do Matrix.", - "requirements": "Servidor da conta, credenciais e acesso às salas", "setup": { "docsLabel": "Abrir guia do Matrix", "officialLabel": "Abrir lista de clientes Matrix", - "tryIt": "Convide a conta Matrix para uma sala e envie uma mensagem de teste.", - "summary": "Informe o servidor da sua conta Matrix e entre com uma senha ou um token de acesso.", - "steps": [ - "Crie ou escolha uma conta Matrix para o nanobot.", - "Informe o servidor da conta, o ID de usuário e a senha ou o token de acesso.", - "Salve e ative o Matrix, convide a conta para uma sala e envie uma mensagem de teste." - ], "fields": { "homeserver": { "label": "Servidor da conta", @@ -22,18 +13,15 @@ }, "password": { "label": "Senha", - "placeholder": "••••••", - "help": "Use senha ou token de acesso." + "placeholder": "••••••" }, "accessToken": { "label": "Token de acesso", - "placeholder": "Informe um token de acesso", - "help": "Preferível quando o cliente Matrix fornece um token." + "placeholder": "Informe um token de acesso" }, "deviceId": { "label": "ID do dispositivo", - "placeholder": "Obrigatório com token", - "help": "Copie o ID associado ao token. O login por senha não precisa dele." + "placeholder": "Obrigatório com token" }, "groupPolicy": { "label": "Comportamento em grupos", @@ -42,6 +30,53 @@ "open": "Todas as mensagens", "allowlist": "Lista de permissão" } + }, + "allowFrom": { + "label": "Usuários permitidos" + }, + "e2eeEnabled": { + "label": "Criptografia ponta a ponta", + "choices": { + "true": "Ligado", + "false": "Desligado" + } + }, + "sasVerification": { + "label": "Verificação SAS", + "choices": { + "true": "Ligado", + "false": "Desligado" + } + }, + "syncStopGraceSeconds": { + "label": "Período de carência para interrupção da sincronização" + }, + "maxMediaBytes": { + "label": "Tamanho máximo da mídia" + }, + "maxConcurrentMediaDownloads": { + "label": "Downloads simultâneos de mídia" + }, + "groupAllowFrom": { + "label": "Grupos permitidos" + }, + "allowRoomMentions": { + "label": "Permitir menções à sala", + "choices": { + "true": "Ligado", + "false": "Desligado" + } + }, + "streaming": { + "label": "Transmissão", + "choices": { + "true": "Ligado", + "false": "Desligado" + } + }, + "proxy": { + "label": "Proxy de rede", + "placeholder": "http://127.0.0.1:7890" } } } diff --git a/nanobot/channels/matrix/webui/locales/vi.json b/nanobot/channels/matrix/webui/locales/vi.json index a09dd040f..a34bae5d1 100644 --- a/nanobot/channels/matrix/webui/locales/vi.json +++ b/nanobot/channels/matrix/webui/locales/vi.json @@ -1,16 +1,7 @@ { - "description": "Sử dụng nanobot từ các phòng Matrix.", - "requirements": "Máy chủ tài khoản, thông tin đăng nhập và quyền truy cập phòng", "setup": { "docsLabel": "Mở hướng dẫn Matrix", "officialLabel": "Mở danh sách ứng dụng Matrix", - "tryIt": "Mời tài khoản Matrix vào phòng và gửi tin nhắn thử.", - "summary": "Nhập máy chủ của tài khoản Matrix rồi đăng nhập bằng mật khẩu hoặc token truy cập.", - "steps": [ - "Tạo hoặc chọn tài khoản Matrix cho nanobot.", - "Nhập máy chủ tài khoản, ID người dùng và mật khẩu hoặc token truy cập.", - "Lưu và bật Matrix, mời tài khoản vào phòng rồi gửi tin nhắn thử." - ], "fields": { "homeserver": { "label": "Máy chủ tài khoản", @@ -22,18 +13,15 @@ }, "password": { "label": "Mật khẩu", - "placeholder": "••••••", - "help": "Dùng mật khẩu hoặc token truy cập." + "placeholder": "••••••" }, "accessToken": { "label": "Token truy cập", - "placeholder": "Nhập token truy cập", - "help": "Nên dùng khi ứng dụng Matrix cung cấp token truy cập." + "placeholder": "Nhập token truy cập" }, "deviceId": { "label": "ID thiết bị", - "placeholder": "Bắt buộc khi dùng token", - "help": "Sao chép ID thiết bị gắn với token. Đăng nhập mật khẩu không cần." + "placeholder": "Bắt buộc khi dùng token" }, "groupPolicy": { "label": "Hành vi trong nhóm", @@ -42,6 +30,53 @@ "open": "Mọi tin nhắn", "allowlist": "Danh sách cho phép" } + }, + "allowFrom": { + "label": "Người dùng được phép" + }, + "e2eeEnabled": { + "label": "Mã hóa đầu cuối", + "choices": { + "true": "Bật", + "false": "Tắt" + } + }, + "sasVerification": { + "label": "Xác minh SAS", + "choices": { + "true": "Bật", + "false": "Tắt" + } + }, + "syncStopGraceSeconds": { + "label": "Thời gian gia hạn dừng đồng bộ hóa" + }, + "maxMediaBytes": { + "label": "Kích thước phương tiện tối đa" + }, + "maxConcurrentMediaDownloads": { + "label": "Tải xuống phương tiện đồng thời" + }, + "groupAllowFrom": { + "label": "Nhóm được phép" + }, + "allowRoomMentions": { + "label": "Cho phép đề cập đến phòng", + "choices": { + "true": "Bật", + "false": "Tắt" + } + }, + "streaming": { + "label": "Truyền phát", + "choices": { + "true": "Bật", + "false": "Tắt" + } + }, + "proxy": { + "label": "Proxy mạng", + "placeholder": "http://127.0.0.1:7890" } } } diff --git a/nanobot/channels/matrix/webui/locales/zh-CN.json b/nanobot/channels/matrix/webui/locales/zh-CN.json index 1c43b9e68..b34e7a768 100644 --- a/nanobot/channels/matrix/webui/locales/zh-CN.json +++ b/nanobot/channels/matrix/webui/locales/zh-CN.json @@ -1,16 +1,7 @@ { - "description": "在 Matrix 房间中使用 nanobot。", - "requirements": "主服务器、账户令牌和房间访问权限", "setup": { "docsLabel": "打开 Matrix 配置指南", "officialLabel": "打开 Matrix 客户端列表", - "tryIt": "将 Matrix 账户邀请进房间并发送一条测试消息。", - "summary": "填写 Matrix 账户所在的服务器,并使用密码或访问令牌登录。", - "steps": [ - "为 nanobot 创建或选择一个 Matrix 账户。", - "填写主服务器、用户 ID,以及密码或访问令牌凭据。", - "保存并启用 Matrix,将账户邀请进房间,然后发送一条测试消息。" - ], "fields": { "homeserver": { "label": "账户服务器", @@ -22,18 +13,15 @@ }, "password": { "label": "密码", - "placeholder": "••••••", - "help": "密码登录和访问令牌登录任选其一。" + "placeholder": "••••••" }, "accessToken": { "label": "访问令牌", - "placeholder": "输入访问令牌", - "help": "如果 Matrix 客户端可以显示访问令牌,建议使用该方式。" + "placeholder": "输入访问令牌" }, "deviceId": { "label": "设备 ID", - "placeholder": "使用访问令牌时必填", - "help": "复制与访问令牌关联的设备 ID;密码登录不需要。" + "placeholder": "使用访问令牌时必填" }, "groupPolicy": { "label": "群组行为", @@ -42,6 +30,53 @@ "open": "所有消息", "allowlist": "白名单" } + }, + "allowFrom": { + "label": "允许的用户" + }, + "e2eeEnabled": { + "label": "端到端加密", + "choices": { + "true": "开启", + "false": "关闭" + } + }, + "sasVerification": { + "label": "SAS 验证", + "choices": { + "true": "开启", + "false": "关闭" + } + }, + "syncStopGraceSeconds": { + "label": "同步停止等待时间" + }, + "maxMediaBytes": { + "label": "媒体大小上限" + }, + "maxConcurrentMediaDownloads": { + "label": "并发媒体下载数" + }, + "groupAllowFrom": { + "label": "允许的群组" + }, + "allowRoomMentions": { + "label": "响应房间提及", + "choices": { + "true": "开启", + "false": "关闭" + } + }, + "streaming": { + "label": "流式输出", + "choices": { + "true": "开启", + "false": "关闭" + } + }, + "proxy": { + "label": "网络代理", + "placeholder": "http://127.0.0.1:7890" } } } diff --git a/nanobot/channels/matrix/webui/locales/zh-TW.json b/nanobot/channels/matrix/webui/locales/zh-TW.json index fb61c19d2..5c5b1c545 100644 --- a/nanobot/channels/matrix/webui/locales/zh-TW.json +++ b/nanobot/channels/matrix/webui/locales/zh-TW.json @@ -1,16 +1,7 @@ { - "description": "在 Matrix 房間中使用 nanobot。", - "requirements": "主伺服器、帳戶權杖和房間存取權限", "setup": { "docsLabel": "開啟 Matrix 設定指南", "officialLabel": "開啟 Matrix 用戶端列表", - "tryIt": "將 Matrix 帳戶邀請進房間並傳送一則測試訊息。", - "summary": "填入 Matrix 帳戶所在的伺服器,並使用密碼或存取權杖登入。", - "steps": [ - "為 nanobot 建立或選擇一個 Matrix 帳戶。", - "填入主伺服器、使用者 ID,以及密碼或存取權杖憑證。", - "儲存並啟用 Matrix,將帳戶邀請進房間,然後傳送一則測試訊息。" - ], "fields": { "homeserver": { "label": "帳戶伺服器", @@ -22,18 +13,15 @@ }, "password": { "label": "密碼", - "placeholder": "••••••", - "help": "密碼登入和存取權杖登入任選其一。" + "placeholder": "••••••" }, "accessToken": { "label": "存取權杖", - "placeholder": "輸入存取權杖", - "help": "若 Matrix 用戶端可顯示存取權杖,建議使用此方式。" + "placeholder": "輸入存取權杖" }, "deviceId": { "label": "裝置 ID", - "placeholder": "使用存取權杖時必填", - "help": "複製與存取權杖關聯的裝置 ID;密碼登入不需要。" + "placeholder": "使用存取權杖時必填" }, "groupPolicy": { "label": "群組行為", @@ -42,6 +30,53 @@ "open": "所有訊息", "allowlist": "允許清單" } + }, + "allowFrom": { + "label": "允許的用戶" + }, + "e2eeEnabled": { + "label": "端對端加密", + "choices": { + "true": "開啟", + "false": "關閉" + } + }, + "sasVerification": { + "label": "SAS 驗證", + "choices": { + "true": "開啟", + "false": "關閉" + } + }, + "syncStopGraceSeconds": { + "label": "同步停止等待時間" + }, + "maxMediaBytes": { + "label": "媒體大小上限" + }, + "maxConcurrentMediaDownloads": { + "label": "並發媒體下載數" + }, + "groupAllowFrom": { + "label": "允許的群組" + }, + "allowRoomMentions": { + "label": "響應房間提及", + "choices": { + "true": "開啟", + "false": "關閉" + } + }, + "streaming": { + "label": "串流輸出", + "choices": { + "true": "開啟", + "false": "關閉" + } + }, + "proxy": { + "label": "網路代理", + "placeholder": "http://127.0.0.1:7890" } } } diff --git a/nanobot/channels/mattermost/manifest.py b/nanobot/channels/mattermost/manifest.py index 4061a3513..61c162215 100644 --- a/nanobot/channels/mattermost/manifest.py +++ b/nanobot/channels/mattermost/manifest.py @@ -12,6 +12,21 @@ SETUP_SPEC = ChannelSetupSpec( "groupPolicy": field("enum", choices=GROUP_POLICIES, default="mention"), "groupPolicyInThread": field("enum", choices=GROUP_POLICIES, default="mention"), "allowFrom": field("list"), + "allowFromMatchMode": field( + "enum", choices={"id", "username", "email"}, default="id" + ), + "groupAllowFrom": field("list"), + "replyInThread": field("bool", default=True), + "includeThreadContext": field("bool", default=True), + "threadContextLimit": field("int", default=20), + "streaming": field("bool", default=True), + "reactEmoji": field(default="eyes"), + "doneEmoji": field(default="white_check_mark"), + "sendProgress": field("bool", default=True), + "sendToolHints": field("bool", default=True), + "dm.enabled": field("bool", default=True), + "dm.policy": field("enum", choices={"open", "allowlist"}, default="open"), + "dm.allowFrom": field("list"), }, required=required_fields("serverUrl", "token"), official_url="https://developers.mattermost.com/integrate/reference/bot-accounts/", diff --git a/nanobot/channels/mattermost/webui/index.ts b/nanobot/channels/mattermost/webui/index.ts index a6206cde0..d18eb84b5 100644 --- a/nanobot/channels/mattermost/webui/index.ts +++ b/nanobot/channels/mattermost/webui/index.ts @@ -3,19 +3,20 @@ import { chatAppGuideUrl } from "@/components/settings/channels/catalog"; export default { presentation: { + logoUrl: "https://mattermost.com/favicon.ico", displayName: "Mattermost", initials: "MM", color: "#1C58D9", - logoUrl: "https://mattermost.com/favicon.ico", setup: { mode: "credentials", docsUrl: chatAppGuideUrl("mattermost"), fields: [ - { key: "channels.mattermost.serverUrl" }, - { key: "channels.mattermost.token" }, - { key: "channels.mattermost.teamId" }, - { key: "channels.mattermost.groupPolicy" }, - { key: "channels.mattermost.groupPolicyInThread" }, + { key: "channels.mattermost.serverUrl", section: "connection" }, + { key: "channels.mattermost.teamId", section: "account" }, + { key: "channels.mattermost.token", section: "credentials" }, + { key: "channels.mattermost.allowFrom", section: "access" }, + { key: "channels.mattermost.groupPolicy", section: "behavior" }, + { key: "channels.mattermost.groupPolicyInThread", section: "behavior" }, ], }, }, diff --git a/nanobot/channels/mattermost/webui/locales/en.json b/nanobot/channels/mattermost/webui/locales/en.json index 5c2945211..c8e7ec50d 100644 --- a/nanobot/channels/mattermost/webui/locales/en.json +++ b/nanobot/channels/mattermost/webui/locales/en.json @@ -1,26 +1,15 @@ { - "description": "Use nanobot from Mattermost channels and DMs.", - "requirements": "Mattermost server URL, bot token, channel access", "setup": { "docsLabel": "Open Mattermost setup", "officialLabel": "Open Mattermost bot guide", - "tryIt": "Mention the bot in a Mattermost channel or send it a direct message.", - "summary": "Mattermost connects through a bot account on your server and listens for channel and direct messages.", - "steps": [ - "Create a Mattermost bot account and copy its access token.", - "Enter the server URL and grant the bot access to the target team and channels.", - "Save and enable Mattermost, then mention the bot or send a direct message." - ], "fields": { "serverUrl": { "label": "Server URL", - "placeholder": "https://mattermost.example.com", - "help": "Use the base URL of your Mattermost workspace." + "placeholder": "https://mattermost.example.com" }, "token": { "label": "Bot token", - "placeholder": "Mattermost bot token", - "help": "Create this from a Mattermost bot account." + "placeholder": "Mattermost bot token" }, "teamId": { "label": "Team ID", @@ -45,6 +34,78 @@ "allowFrom": { "label": "Allowed users", "placeholder": "User IDs, comma separated" + }, + "allowFromMatchMode": { + "label": "User matching", + "choices": { + "email": "Email", + "id": "User ID", + "username": "Username" + } + }, + "groupAllowFrom": { + "label": "Allowed channels" + }, + "replyInThread": { + "label": "Reply in thread", + "choices": { + "true": "On", + "false": "Off" + } + }, + "includeThreadContext": { + "label": "Include thread context", + "choices": { + "true": "On", + "false": "Off" + } + }, + "threadContextLimit": { + "label": "Thread context limit" + }, + "streaming": { + "label": "Streaming", + "choices": { + "true": "On", + "false": "Off" + } + }, + "reactEmoji": { + "label": "Read emoji" + }, + "doneEmoji": { + "label": "Done emoji" + }, + "sendProgress": { + "label": "Send progress", + "choices": { + "true": "On", + "false": "Off" + } + }, + "sendToolHints": { + "label": "Send tool hints", + "choices": { + "true": "On", + "false": "Off" + } + }, + "dm_enabled": { + "label": "Enable direct messages", + "choices": { + "true": "On", + "false": "Off" + } + }, + "dm_policy": { + "label": "Direct message access", + "choices": { + "allowlist": "Allowlist", + "open": "Open" + } + }, + "dm_allowFrom": { + "label": "Allowed direct-message users" } } } diff --git a/nanobot/channels/mattermost/webui/locales/es.json b/nanobot/channels/mattermost/webui/locales/es.json index 6d4456614..bfaed53fe 100644 --- a/nanobot/channels/mattermost/webui/locales/es.json +++ b/nanobot/channels/mattermost/webui/locales/es.json @@ -1,26 +1,15 @@ { - "description": "Usa nanobot en canales y mensajes directos de Mattermost.", - "requirements": "URL del servidor Mattermost, token del bot y acceso a canales", "setup": { "docsLabel": "Abrir guía de Mattermost", "officialLabel": "Abrir guía de bots de Mattermost", - "tryIt": "Menciona al bot en un canal de Mattermost o envíale un mensaje directo.", - "summary": "Mattermost se conecta mediante una cuenta bot en tu servidor y escucha canales y mensajes directos.", - "steps": [ - "Crea una cuenta bot de Mattermost y copia su token de acceso.", - "Introduce la URL del servidor y permite acceso al equipo y canales de destino.", - "Guarda y activa Mattermost; después menciona al bot o envíale un mensaje directo." - ], "fields": { "serverUrl": { "label": "URL del servidor", - "placeholder": "https://mattermost.example.com", - "help": "Usa la URL base de tu espacio Mattermost." + "placeholder": "https://mattermost.example.com" }, "token": { "label": "Token del bot", - "placeholder": "Token del bot Mattermost", - "help": "Créalo desde una cuenta bot de Mattermost." + "placeholder": "Token del bot Mattermost" }, "teamId": { "label": "ID del equipo", @@ -45,6 +34,78 @@ "allowFrom": { "label": "Usuarios permitidos", "placeholder": "ID de usuario separados por comas" + }, + "allowFromMatchMode": { + "label": "Coincidencia de usuarios", + "choices": { + "email": "Correo electrónico", + "id": "ID de usuario", + "username": "Nombre de usuario" + } + }, + "groupAllowFrom": { + "label": "Canales permitidos" + }, + "replyInThread": { + "label": "Responder en el hilo", + "choices": { + "true": "encendido", + "false": "Apagado" + } + }, + "includeThreadContext": { + "label": "Incluir contexto de hilo", + "choices": { + "true": "encendido", + "false": "Apagado" + } + }, + "threadContextLimit": { + "label": "Límite de contexto del hilo" + }, + "streaming": { + "label": "Transmisión", + "choices": { + "true": "encendido", + "false": "Apagado" + } + }, + "reactEmoji": { + "label": "Leer emojis" + }, + "doneEmoji": { + "label": "emoji hecho" + }, + "sendProgress": { + "label": "Enviar progreso", + "choices": { + "true": "encendido", + "false": "Apagado" + } + }, + "sendToolHints": { + "label": "Enviar sugerencias de herramientas", + "choices": { + "true": "encendido", + "false": "Apagado" + } + }, + "dm_enabled": { + "label": "Habilitar mensajes directos", + "choices": { + "true": "encendido", + "false": "Apagado" + } + }, + "dm_policy": { + "label": "Acceso a mensajes directos", + "choices": { + "allowlist": "Lista de permitidos", + "open": "Abierto" + } + }, + "dm_allowFrom": { + "label": "Usuarios permitidos de mensajes directos" } } } diff --git a/nanobot/channels/mattermost/webui/locales/fr.json b/nanobot/channels/mattermost/webui/locales/fr.json index c0063b2b2..70fe37ee1 100644 --- a/nanobot/channels/mattermost/webui/locales/fr.json +++ b/nanobot/channels/mattermost/webui/locales/fr.json @@ -1,26 +1,15 @@ { - "description": "Utilisez nanobot dans les canaux et messages privés Mattermost.", - "requirements": "URL du serveur Mattermost, jeton du bot et accès aux canaux", "setup": { "docsLabel": "Ouvrir le guide Mattermost", "officialLabel": "Ouvrir le guide des bots Mattermost", - "tryIt": "Mentionnez le bot dans un canal Mattermost ou envoyez-lui un message privé.", - "summary": "Mattermost se connecte via un compte bot sur votre serveur et écoute les canaux et messages privés.", - "steps": [ - "Créez un compte bot Mattermost et copiez son jeton d’accès.", - "Saisissez l’URL du serveur et accordez l’accès à l’équipe et aux canaux cibles.", - "Enregistrez et activez Mattermost, puis mentionnez le bot ou envoyez-lui un message privé." - ], "fields": { "serverUrl": { "label": "URL du serveur", - "placeholder": "https://mattermost.example.com", - "help": "Utilisez l’URL de base de votre espace Mattermost." + "placeholder": "https://mattermost.example.com" }, "token": { "label": "Jeton du bot", - "placeholder": "Jeton du bot Mattermost", - "help": "Créez-le depuis un compte bot Mattermost." + "placeholder": "Jeton du bot Mattermost" }, "teamId": { "label": "ID de l’équipe", @@ -45,6 +34,78 @@ "allowFrom": { "label": "Utilisateurs autorisés", "placeholder": "ID utilisateur séparés par des virgules" + }, + "allowFromMatchMode": { + "label": "Correspondance des utilisateurs", + "choices": { + "email": "Courriel", + "id": "Identifiant utilisateur", + "username": "Nom d'utilisateur" + } + }, + "groupAllowFrom": { + "label": "Chaînes autorisées" + }, + "replyInThread": { + "label": "Répondre dans le fil de discussion", + "choices": { + "true": "Sur", + "false": "Désactivé" + } + }, + "includeThreadContext": { + "label": "Inclure le contexte du fil de discussion", + "choices": { + "true": "Sur", + "false": "Désactivé" + } + }, + "threadContextLimit": { + "label": "Limite du contexte du fil de discussion" + }, + "streaming": { + "label": "Diffusion en continu", + "choices": { + "true": "Sur", + "false": "Désactivé" + } + }, + "reactEmoji": { + "label": "Lire les emoji" + }, + "doneEmoji": { + "label": "Terminé emoji" + }, + "sendProgress": { + "label": "Envoyer la progression", + "choices": { + "true": "Sur", + "false": "Désactivé" + } + }, + "sendToolHints": { + "label": "Envoyer des conseils sur les outils", + "choices": { + "true": "Sur", + "false": "Désactivé" + } + }, + "dm_enabled": { + "label": "Activer les messages directs", + "choices": { + "true": "Sur", + "false": "Désactivé" + } + }, + "dm_policy": { + "label": "Accès aux messages directs", + "choices": { + "allowlist": "Liste verte", + "open": "Ouvert" + } + }, + "dm_allowFrom": { + "label": "Utilisateurs de messagerie directe autorisés" } } } diff --git a/nanobot/channels/mattermost/webui/locales/id.json b/nanobot/channels/mattermost/webui/locales/id.json index d57870eeb..c0966f2f2 100644 --- a/nanobot/channels/mattermost/webui/locales/id.json +++ b/nanobot/channels/mattermost/webui/locales/id.json @@ -1,26 +1,15 @@ { - "description": "Gunakan nanobot dari kanal dan DM Mattermost.", - "requirements": "URL server Mattermost, token bot, dan akses kanal", "setup": { "docsLabel": "Buka panduan Mattermost", "officialLabel": "Buka panduan bot Mattermost", - "tryIt": "Sebut bot di kanal Mattermost atau kirim pesan langsung.", - "summary": "Mattermost terhubung melalui akun bot di server dan menerima pesan kanal serta pesan langsung.", - "steps": [ - "Buat akun bot Mattermost dan salin token aksesnya.", - "Masukkan URL server dan berikan akses ke tim serta kanal tujuan.", - "Simpan dan aktifkan Mattermost, lalu sebut bot atau kirim DM." - ], "fields": { "serverUrl": { "label": "URL server", - "placeholder": "https://mattermost.example.com", - "help": "Gunakan URL dasar ruang kerja Mattermost." + "placeholder": "https://mattermost.example.com" }, "token": { "label": "Token bot", - "placeholder": "Token bot Mattermost", - "help": "Buat dari akun bot Mattermost." + "placeholder": "Token bot Mattermost" }, "teamId": { "label": "ID tim", @@ -45,6 +34,78 @@ "allowFrom": { "label": "Pengguna yang diizinkan", "placeholder": "ID pengguna, dipisahkan koma" + }, + "allowFromMatchMode": { + "label": "Pencocokan pengguna", + "choices": { + "email": "Surel", + "id": "ID Pengguna", + "username": "Nama pengguna" + } + }, + "groupAllowFrom": { + "label": "Saluran yang diizinkan" + }, + "replyInThread": { + "label": "Balas di thread", + "choices": { + "true": "Aktif", + "false": "Mati" + } + }, + "includeThreadContext": { + "label": "Sertakan konteks thread", + "choices": { + "true": "Aktif", + "false": "Mati" + } + }, + "threadContextLimit": { + "label": "Batas konteks thread" + }, + "streaming": { + "label": "Streaming", + "choices": { + "true": "Aktif", + "false": "Mati" + } + }, + "reactEmoji": { + "label": "Baca emoji" + }, + "doneEmoji": { + "label": "Selesai emoji" + }, + "sendProgress": { + "label": "Kirim kemajuan", + "choices": { + "true": "Aktif", + "false": "Mati" + } + }, + "sendToolHints": { + "label": "Kirim petunjuk alat", + "choices": { + "true": "Aktif", + "false": "Mati" + } + }, + "dm_enabled": { + "label": "Aktifkan pesan langsung", + "choices": { + "true": "Aktif", + "false": "Mati" + } + }, + "dm_policy": { + "label": "Akses pesan langsung", + "choices": { + "allowlist": "Daftar yang diizinkan", + "open": "Buka" + } + }, + "dm_allowFrom": { + "label": "Mengizinkan pengguna pesan langsung" } } } diff --git a/nanobot/channels/mattermost/webui/locales/ja.json b/nanobot/channels/mattermost/webui/locales/ja.json index 33b42d25f..34ef2cffb 100644 --- a/nanobot/channels/mattermost/webui/locales/ja.json +++ b/nanobot/channels/mattermost/webui/locales/ja.json @@ -1,26 +1,15 @@ { - "description": "Mattermost のチャンネルと DM から nanobot を利用します。", - "requirements": "Mattermost サーバー URL、ボットトークン、チャンネルアクセス", "setup": { "docsLabel": "Mattermost 設定ガイドを開く", "officialLabel": "Mattermost ボットガイドを開く", - "tryIt": "Mattermost チャンネルでボットをメンションするか、DM を送信します。", - "summary": "Mattermost はサーバー上のボットアカウントで接続し、チャンネルと DM を受信します。", - "steps": [ - "Mattermost ボットアカウントを作成し、アクセストークンをコピーします。", - "サーバー URL を入力し、対象チームとチャンネルへのアクセスを許可します。", - "保存して Mattermost を有効にし、メンションまたは DM を送信します。" - ], "fields": { "serverUrl": { "label": "サーバー URL", - "placeholder": "https://mattermost.example.com", - "help": "Mattermost ワークスペースのベース URL を使います。" + "placeholder": "https://mattermost.example.com" }, "token": { "label": "ボットトークン", - "placeholder": "Mattermost ボットトークン", - "help": "Mattermost ボットアカウントから作成します。" + "placeholder": "Mattermost ボットトークン" }, "teamId": { "label": "チーム ID", @@ -45,6 +34,78 @@ "allowFrom": { "label": "許可するユーザー", "placeholder": "ユーザー ID(カンマ区切り)" + }, + "allowFromMatchMode": { + "label": "ユーザーマッチング", + "choices": { + "email": "電子メール", + "id": "ユーザーID", + "username": "ユーザー名" + } + }, + "groupAllowFrom": { + "label": "許可されたチャネル" + }, + "replyInThread": { + "label": "スレッド内で返信する", + "choices": { + "true": "オン", + "false": "オフ" + } + }, + "includeThreadContext": { + "label": "スレッドコンテキストを含める", + "choices": { + "true": "オン", + "false": "オフ" + } + }, + "threadContextLimit": { + "label": "スレッドコンテキストの制限" + }, + "streaming": { + "label": "ストリーミング", + "choices": { + "true": "オン", + "false": "オフ" + } + }, + "reactEmoji": { + "label": "絵文字を読む" + }, + "doneEmoji": { + "label": "完了絵文字" + }, + "sendProgress": { + "label": "進捗状況の送信", + "choices": { + "true": "オン", + "false": "オフ" + } + }, + "sendToolHints": { + "label": "ツールヒントを送信する", + "choices": { + "true": "オン", + "false": "オフ" + } + }, + "dm_enabled": { + "label": "ダイレクトメッセージを有効にする", + "choices": { + "true": "オン", + "false": "オフ" + } + }, + "dm_policy": { + "label": "ダイレクトメッセージへのアクセス", + "choices": { + "allowlist": "ホワイトリスト", + "open": "開く" + } + }, + "dm_allowFrom": { + "label": "許可されたダイレクトメッセージユーザー" } } } diff --git a/nanobot/channels/mattermost/webui/locales/ko.json b/nanobot/channels/mattermost/webui/locales/ko.json index 28257647e..4f8e3682e 100644 --- a/nanobot/channels/mattermost/webui/locales/ko.json +++ b/nanobot/channels/mattermost/webui/locales/ko.json @@ -1,26 +1,15 @@ { - "description": "Mattermost 채널과 DM에서 nanobot을 사용합니다.", - "requirements": "Mattermost 서버 URL, 봇 토큰 및 채널 접근 권한", "setup": { "docsLabel": "Mattermost 설정 가이드 열기", "officialLabel": "Mattermost 봇 가이드 열기", - "tryIt": "Mattermost 채널에서 봇을 멘션하거나 DM을 보내세요.", - "summary": "Mattermost는 서버의 봇 계정으로 연결해 채널과 DM을 수신합니다.", - "steps": [ - "Mattermost 봇 계정을 만들고 액세스 토큰을 복사하세요.", - "서버 URL을 입력하고 대상 팀과 채널 접근 권한을 부여하세요.", - "저장하고 Mattermost를 활성화한 다음 봇을 멘션하거나 DM을 보내세요." - ], "fields": { "serverUrl": { "label": "서버 URL", - "placeholder": "https://mattermost.example.com", - "help": "Mattermost 작업 공간 기본 URL을 사용하세요." + "placeholder": "https://mattermost.example.com" }, "token": { "label": "봇 토큰", - "placeholder": "Mattermost 봇 토큰", - "help": "Mattermost 봇 계정에서 생성하세요." + "placeholder": "Mattermost 봇 토큰" }, "teamId": { "label": "팀 ID", @@ -45,6 +34,78 @@ "allowFrom": { "label": "허용된 사용자", "placeholder": "사용자 ID, 쉼표로 구분" + }, + "allowFromMatchMode": { + "label": "사용자 매칭", + "choices": { + "email": "이메일", + "id": "사용자 ID", + "username": "사용자 이름" + } + }, + "groupAllowFrom": { + "label": "허용된 채널" + }, + "replyInThread": { + "label": "스레드로 답장하기", + "choices": { + "true": "켜기", + "false": "끄기" + } + }, + "includeThreadContext": { + "label": "스레드 컨텍스트 포함", + "choices": { + "true": "켜기", + "false": "끄기" + } + }, + "threadContextLimit": { + "label": "스레드 컨텍스트 제한" + }, + "streaming": { + "label": "스트리밍", + "choices": { + "true": "켜기", + "false": "끄기" + } + }, + "reactEmoji": { + "label": "이모티콘 읽기" + }, + "doneEmoji": { + "label": "이모티콘 완료" + }, + "sendProgress": { + "label": "진행 상황 보내기", + "choices": { + "true": "켜기", + "false": "끄기" + } + }, + "sendToolHints": { + "label": "도구 힌트 보내기", + "choices": { + "true": "켜기", + "false": "끄기" + } + }, + "dm_enabled": { + "label": "다이렉트 메시지 활성화", + "choices": { + "true": "켜기", + "false": "끄기" + } + }, + "dm_policy": { + "label": "다이렉트 메시지 액세스", + "choices": { + "allowlist": "허용 목록", + "open": "열기" + } + }, + "dm_allowFrom": { + "label": "허용된 직접 메시지 사용자" } } } diff --git a/nanobot/channels/mattermost/webui/locales/pt-BR.json b/nanobot/channels/mattermost/webui/locales/pt-BR.json index e8794f2f0..eacddaa85 100644 --- a/nanobot/channels/mattermost/webui/locales/pt-BR.json +++ b/nanobot/channels/mattermost/webui/locales/pt-BR.json @@ -1,26 +1,15 @@ { - "description": "Use o nanobot em canais e DMs do Mattermost.", - "requirements": "URL do servidor Mattermost, token do bot e acesso aos canais", "setup": { "docsLabel": "Abrir guia do Mattermost", "officialLabel": "Abrir guia de bots do Mattermost", - "tryIt": "Mencione o bot em um canal Mattermost ou envie uma mensagem direta.", - "summary": "O nanobot se conecta ao servidor Mattermost com uma conta de bot para receber mensagens de canais e mensagens diretas.", - "steps": [ - "Crie uma conta de bot Mattermost e copie o token de acesso.", - "Informe a URL do servidor e conceda acesso à equipe e aos canais desejados.", - "Salve e ative o Mattermost; depois, mencione o bot ou envie uma DM." - ], "fields": { "serverUrl": { "label": "URL do servidor", - "placeholder": "https://mattermost.example.com", - "help": "Use a URL base do seu espaço de trabalho Mattermost." + "placeholder": "https://mattermost.example.com" }, "token": { "label": "Token do bot", - "placeholder": "Token do bot Mattermost", - "help": "Crie-o em uma conta de bot Mattermost." + "placeholder": "Token do bot Mattermost" }, "teamId": { "label": "ID da equipe", @@ -45,6 +34,78 @@ "allowFrom": { "label": "Usuários permitidos", "placeholder": "IDs de usuário separados por vírgulas" + }, + "allowFromMatchMode": { + "label": "Correspondência de usuário", + "choices": { + "email": "E-mail", + "id": "ID do usuário", + "username": "Nome de usuário" + } + }, + "groupAllowFrom": { + "label": "Canais permitidos" + }, + "replyInThread": { + "label": "Responder no tópico", + "choices": { + "true": "Ligado", + "false": "Desligado" + } + }, + "includeThreadContext": { + "label": "Incluir contexto do thread", + "choices": { + "true": "Ligado", + "false": "Desligado" + } + }, + "threadContextLimit": { + "label": "Limite de contexto do thread" + }, + "streaming": { + "label": "Transmissão", + "choices": { + "true": "Ligado", + "false": "Desligado" + } + }, + "reactEmoji": { + "label": "Ler emoticons" + }, + "doneEmoji": { + "label": "Emoji pronto" + }, + "sendProgress": { + "label": "Enviar progresso", + "choices": { + "true": "Ligado", + "false": "Desligado" + } + }, + "sendToolHints": { + "label": "Envie dicas de ferramentas", + "choices": { + "true": "Ligado", + "false": "Desligado" + } + }, + "dm_enabled": { + "label": "Habilitar mensagens diretas", + "choices": { + "true": "Ligado", + "false": "Desligado" + } + }, + "dm_policy": { + "label": "Acesso direto a mensagens", + "choices": { + "allowlist": "Lista de permissões", + "open": "Abrir" + } + }, + "dm_allowFrom": { + "label": "Usuários de mensagens diretas permitidos" } } } diff --git a/nanobot/channels/mattermost/webui/locales/vi.json b/nanobot/channels/mattermost/webui/locales/vi.json index c68e3b2bb..7071e9ae4 100644 --- a/nanobot/channels/mattermost/webui/locales/vi.json +++ b/nanobot/channels/mattermost/webui/locales/vi.json @@ -1,26 +1,15 @@ { - "description": "Sử dụng nanobot trong kênh và tin nhắn riêng Mattermost.", - "requirements": "URL máy chủ Mattermost, token bot và quyền truy cập kênh", "setup": { "docsLabel": "Mở hướng dẫn Mattermost", "officialLabel": "Mở hướng dẫn bot Mattermost", - "tryIt": "Nhắc bot trong kênh Mattermost hoặc gửi tin nhắn riêng.", - "summary": "Mattermost kết nối qua tài khoản bot trên máy chủ và nhận tin nhắn kênh cùng tin nhắn riêng.", - "steps": [ - "Tạo tài khoản bot Mattermost và sao chép token truy cập.", - "Nhập URL máy chủ và cấp quyền vào nhóm cùng các kênh đích.", - "Lưu và bật Mattermost, sau đó nhắc bot hoặc gửi tin nhắn riêng." - ], "fields": { "serverUrl": { "label": "URL máy chủ", - "placeholder": "https://mattermost.example.com", - "help": "Dùng URL gốc của không gian Mattermost." + "placeholder": "https://mattermost.example.com" }, "token": { "label": "Token bot", - "placeholder": "Token bot Mattermost", - "help": "Tạo từ tài khoản bot Mattermost." + "placeholder": "Token bot Mattermost" }, "teamId": { "label": "ID nhóm", @@ -45,6 +34,78 @@ "allowFrom": { "label": "Người dùng được phép", "placeholder": "ID người dùng, phân tách bằng dấu phẩy" + }, + "allowFromMatchMode": { + "label": "So khớp người dùng", + "choices": { + "email": "Email", + "id": "ID người dùng", + "username": "Tên người dùng" + } + }, + "groupAllowFrom": { + "label": "Các kênh được phép" + }, + "replyInThread": { + "label": "Trả lời trong chủ đề", + "choices": { + "true": "Bật", + "false": "Tắt" + } + }, + "includeThreadContext": { + "label": "Bao gồm bối cảnh chủ đề", + "choices": { + "true": "Bật", + "false": "Tắt" + } + }, + "threadContextLimit": { + "label": "Giới hạn bối cảnh của chủ đề" + }, + "streaming": { + "label": "Truyền phát", + "choices": { + "true": "Bật", + "false": "Tắt" + } + }, + "reactEmoji": { + "label": "Đọc biểu tượng cảm xúc" + }, + "doneEmoji": { + "label": "biểu tượng cảm xúc xong" + }, + "sendProgress": { + "label": "Gửi tiến trình", + "choices": { + "true": "Bật", + "false": "Tắt" + } + }, + "sendToolHints": { + "label": "Gửi gợi ý công cụ", + "choices": { + "true": "Bật", + "false": "Tắt" + } + }, + "dm_enabled": { + "label": "Bật tin nhắn trực tiếp", + "choices": { + "true": "Bật", + "false": "Tắt" + } + }, + "dm_policy": { + "label": "Truy cập tin nhắn trực tiếp", + "choices": { + "allowlist": "Danh sách cho phép", + "open": "Mở" + } + }, + "dm_allowFrom": { + "label": "Cho phép người dùng nhắn tin trực tiếp" } } } diff --git a/nanobot/channels/mattermost/webui/locales/zh-CN.json b/nanobot/channels/mattermost/webui/locales/zh-CN.json index 521a5c06d..072d98965 100644 --- a/nanobot/channels/mattermost/webui/locales/zh-CN.json +++ b/nanobot/channels/mattermost/webui/locales/zh-CN.json @@ -1,26 +1,15 @@ { - "description": "在 Mattermost 频道和私信中使用 nanobot。", - "requirements": "Mattermost 服务器地址、机器人令牌和频道权限", "setup": { "docsLabel": "打开 Mattermost 配置指南", "officialLabel": "打开 Mattermost 机器人指南", - "tryIt": "在 Mattermost 频道中提及机器人,或向它发送私信。", - "summary": "Mattermost 通过服务器中的机器人账户连接,并监听频道和私信。", - "steps": [ - "创建 Mattermost 机器人账户并复制访问令牌。", - "填写服务器地址,并授予机器人访问目标团队和频道的权限。", - "保存并启用 Mattermost,然后提及机器人或发送私信。" - ], "fields": { "serverUrl": { "label": "服务器地址", - "placeholder": "https://mattermost.example.com", - "help": "填写 Mattermost 工作区的基础地址。" + "placeholder": "https://mattermost.example.com" }, "token": { "label": "机器人令牌", - "placeholder": "Mattermost 机器人令牌", - "help": "从 Mattermost 机器人账户创建。" + "placeholder": "Mattermost 机器人令牌" }, "teamId": { "label": "团队 ID", @@ -45,6 +34,78 @@ "allowFrom": { "label": "允许的用户", "placeholder": "用户 ID,用逗号分隔" + }, + "allowFromMatchMode": { + "label": "用户匹配方式", + "choices": { + "email": "邮箱", + "id": "用户 ID", + "username": "用户名" + } + }, + "groupAllowFrom": { + "label": "允许的频道" + }, + "replyInThread": { + "label": "在话题中回复", + "choices": { + "true": "开启", + "false": "关闭" + } + }, + "includeThreadContext": { + "label": "包含话题上下文", + "choices": { + "true": "开启", + "false": "关闭" + } + }, + "threadContextLimit": { + "label": "话题上下文上限" + }, + "streaming": { + "label": "流式输出", + "choices": { + "true": "开启", + "false": "关闭" + } + }, + "reactEmoji": { + "label": "已读表情" + }, + "doneEmoji": { + "label": "完成表情" + }, + "sendProgress": { + "label": "发送进度消息", + "choices": { + "true": "开启", + "false": "关闭" + } + }, + "sendToolHints": { + "label": "发送工具提示", + "choices": { + "true": "开启", + "false": "关闭" + } + }, + "dm_enabled": { + "label": "启用私聊", + "choices": { + "true": "开启", + "false": "关闭" + } + }, + "dm_policy": { + "label": "私聊权限", + "choices": { + "allowlist": "白名单", + "open": "全部" + } + }, + "dm_allowFrom": { + "label": "允许私聊的用户" } } } diff --git a/nanobot/channels/mattermost/webui/locales/zh-TW.json b/nanobot/channels/mattermost/webui/locales/zh-TW.json index af3e390c7..69f142c4f 100644 --- a/nanobot/channels/mattermost/webui/locales/zh-TW.json +++ b/nanobot/channels/mattermost/webui/locales/zh-TW.json @@ -1,26 +1,15 @@ { - "description": "在 Mattermost 頻道和私訊中使用 nanobot。", - "requirements": "Mattermost 伺服器網址、機器人權杖和頻道權限", "setup": { "docsLabel": "開啟 Mattermost 設定指南", "officialLabel": "開啟 Mattermost 機器人指南", - "tryIt": "在 Mattermost 頻道中提及機器人,或向它傳送私訊。", - "summary": "Mattermost 透過伺服器中的機器人帳戶連線,並監聽頻道和私訊。", - "steps": [ - "建立 Mattermost 機器人帳戶並複製存取權杖。", - "填入伺服器網址,並授予機器人存取目標團隊和頻道的權限。", - "儲存並啟用 Mattermost,然後提及機器人或傳送私訊。" - ], "fields": { "serverUrl": { "label": "伺服器網址", - "placeholder": "https://mattermost.example.com", - "help": "填入 Mattermost 工作區的基礎網址。" + "placeholder": "https://mattermost.example.com" }, "token": { "label": "機器人權杖", - "placeholder": "Mattermost 機器人權杖", - "help": "從 Mattermost 機器人帳戶建立。" + "placeholder": "Mattermost 機器人權杖" }, "teamId": { "label": "團隊 ID", @@ -45,6 +34,78 @@ "allowFrom": { "label": "允許的使用者", "placeholder": "使用者 ID,以逗號分隔" + }, + "allowFromMatchMode": { + "label": "用戶匹配方式", + "choices": { + "email": "信箱", + "id": "使用者 ID", + "username": "使用者名稱" + } + }, + "groupAllowFrom": { + "label": "允許的頻道" + }, + "replyInThread": { + "label": "在話題中回复", + "choices": { + "true": "開啟", + "false": "關閉" + } + }, + "includeThreadContext": { + "label": "包含話題上下文", + "choices": { + "true": "開啟", + "false": "關閉" + } + }, + "threadContextLimit": { + "label": "話題上下文上限" + }, + "streaming": { + "label": "串流輸出", + "choices": { + "true": "開啟", + "false": "關閉" + } + }, + "reactEmoji": { + "label": "已讀表情" + }, + "doneEmoji": { + "label": "完成表情" + }, + "sendProgress": { + "label": "發送進度訊息", + "choices": { + "true": "開啟", + "false": "關閉" + } + }, + "sendToolHints": { + "label": "發送工具提示", + "choices": { + "true": "開啟", + "false": "關閉" + } + }, + "dm_enabled": { + "label": "啟用私聊", + "choices": { + "true": "開啟", + "false": "關閉" + } + }, + "dm_policy": { + "label": "私聊權限", + "choices": { + "allowlist": "白名單", + "open": "全部" + } + }, + "dm_allowFrom": { + "label": "允許私聊的用戶" } } } diff --git a/nanobot/channels/mochat/manifest.py b/nanobot/channels/mochat/manifest.py index 6318e45a9..df0e750af 100644 --- a/nanobot/channels/mochat/manifest.py +++ b/nanobot/channels/mochat/manifest.py @@ -12,6 +12,21 @@ SETUP_SPEC = ChannelSetupSpec( "sessions": field("list"), "panels": field("list"), "allowFrom": field("list"), + "socketUrl": field(), + "socketPath": field(default="/socket.io"), + "socketDisableMsgpack": field("bool", default=False), + "socketReconnectDelayMs": field("int", default=1000), + "socketMaxReconnectDelayMs": field("int", default=10000), + "socketConnectTimeoutMs": field("int", default=10000), + "refreshIntervalMs": field("int", default=30000), + "watchTimeoutMs": field("int", default=25000), + "watchLimit": field("int", default=100), + "retryDelayMs": field("int", default=500), + "maxRetryAttempts": field("int", default=0), + "mention.requireInGroups": field("bool", default=False), + "groups": field("json", default={}), + "replyDelayMode": field(default="non-mention"), + "replyDelayMs": field("int", default=120000), }, required=(required("clawToken"),), official_url="https://mochat.io/", @@ -26,5 +41,5 @@ PLUGIN = ChannelPlugin( "python-socketio>=5.16.0,<6.0.0", "msgpack>=1.1.0,<2.0.0", ), - settings_visible=False, + webui="webui/index.ts", ) diff --git a/nanobot/channels/mochat/webui/index.ts b/nanobot/channels/mochat/webui/index.ts new file mode 100644 index 000000000..c37358589 --- /dev/null +++ b/nanobot/channels/mochat/webui/index.ts @@ -0,0 +1,23 @@ +import type { ChannelUiContribution } from "@/channel-plugins/types"; +import { chatAppGuideUrl } from "@/components/settings/channels/catalog"; + +export default { + presentation: { + logoUrl: "https://mochat.io/favicon.ico", + displayName: "MoChat", + initials: "MC", + color: "#111827", + setup: { + mode: "credentials", + docsUrl: chatAppGuideUrl("mochat"), + fields: [ + { key: "channels.mochat.clawToken", section: "credentials" }, + { key: "channels.mochat.baseUrl", section: "connection" }, + { key: "channels.mochat.agentUserId", section: "account" }, + { key: "channels.mochat.sessions", section: "access" }, + { key: "channels.mochat.panels", section: "access" }, + { key: "channels.mochat.allowFrom", section: "access" }, + ], + }, + }, +} satisfies ChannelUiContribution; diff --git a/nanobot/channels/mochat/webui/locales/en.json b/nanobot/channels/mochat/webui/locales/en.json new file mode 100644 index 000000000..02a7e047c --- /dev/null +++ b/nanobot/channels/mochat/webui/locales/en.json @@ -0,0 +1,85 @@ +{ + "setup": { + "docsLabel": "Open MoChat setup guide", + "officialLabel": "Open MoChat", + "fields": { + "clawToken": { + "label": "Claw token", + "placeholder": "MoChat Claw token" + }, + "baseUrl": { + "label": "Server URL", + "placeholder": "https://mochat.io" + }, + "agentUserId": { + "label": "Agent user ID", + "placeholder": "Optional agent user ID" + }, + "sessions": { + "label": "Sessions", + "placeholder": "Session IDs, comma separated" + }, + "panels": { + "label": "Panels", + "placeholder": "Panel IDs, comma separated" + }, + "allowFrom": { + "label": "Allowed users", + "placeholder": "User IDs, comma separated" + }, + "socketUrl": { + "label": "Socket URL" + }, + "socketPath": { + "label": "Socket path" + }, + "socketDisableMsgpack": { + "label": "Disable MessagePack", + "choices": { + "true": "On", + "false": "Off" + } + }, + "socketReconnectDelayMs": { + "label": "Reconnect delay" + }, + "socketMaxReconnectDelayMs": { + "label": "Maximum reconnect delay" + }, + "socketConnectTimeoutMs": { + "label": "Connection timeout" + }, + "refreshIntervalMs": { + "label": "Refresh interval" + }, + "watchTimeoutMs": { + "label": "Watch timeout" + }, + "watchLimit": { + "label": "Watch batch size" + }, + "retryDelayMs": { + "label": "Retry delay" + }, + "maxRetryAttempts": { + "label": "Maximum retries" + }, + "mention_requireInGroups": { + "label": "Require mentions in groups", + "choices": { + "true": "On", + "false": "Off" + } + }, + "groups": { + "label": "Group rules (JSON)" + }, + "replyDelayMode": { + "label": "Reply delay mode" + }, + "replyDelayMs": { + "label": "Reply delay" + } + } + } +} diff --git a/nanobot/channels/mochat/webui/locales/es.json b/nanobot/channels/mochat/webui/locales/es.json new file mode 100644 index 000000000..8f5f90a6a --- /dev/null +++ b/nanobot/channels/mochat/webui/locales/es.json @@ -0,0 +1,85 @@ +{ + "setup": { + "docsLabel": "Abrir la guía de configuración de MoChat", + "officialLabel": "Abrir MoChat", + "fields": { + "clawToken": { + "label": "Token de Claw", + "placeholder": "Token de Claw de MoChat" + }, + "baseUrl": { + "label": "URL del servidor", + "placeholder": "https://mochat.io" + }, + "agentUserId": { + "label": "ID de usuario del agente", + "placeholder": "ID de usuario del agente opcional" + }, + "sessions": { + "label": "Sesiones", + "placeholder": "IDs de sesión, separados por comas" + }, + "panels": { + "label": "Paneles", + "placeholder": "IDs de panel, separados por comas" + }, + "allowFrom": { + "label": "Usuarios permitidos", + "placeholder": "IDs de usuario, separados por comas" + }, + "socketUrl": { + "label": "URL del conector" + }, + "socketPath": { + "label": "Ruta del zócalo" + }, + "socketDisableMsgpack": { + "label": "Deshabilitar paquete de mensajes", + "choices": { + "true": "encendido", + "false": "Apagado" + } + }, + "socketReconnectDelayMs": { + "label": "Retardo de reconexión" + }, + "socketMaxReconnectDelayMs": { + "label": "Retardo máximo de reconexión" + }, + "socketConnectTimeoutMs": { + "label": "Tiempo de espera de conexión" + }, + "refreshIntervalMs": { + "label": "Intervalo de actualización" + }, + "watchTimeoutMs": { + "label": "Ver tiempo de espera" + }, + "watchLimit": { + "label": "Ver tamaño del lote" + }, + "retryDelayMs": { + "label": "Retraso de reintento" + }, + "maxRetryAttempts": { + "label": "Reintentos máximos" + }, + "mention_requireInGroups": { + "label": "Requerir menciones en grupos", + "choices": { + "true": "encendido", + "false": "Apagado" + } + }, + "groups": { + "label": "Reglas de grupo (JSON)" + }, + "replyDelayMode": { + "label": "Modo de retardo de respuesta" + }, + "replyDelayMs": { + "label": "Retraso en la respuesta" + } + } + } +} diff --git a/nanobot/channels/mochat/webui/locales/fr.json b/nanobot/channels/mochat/webui/locales/fr.json new file mode 100644 index 000000000..86bf05270 --- /dev/null +++ b/nanobot/channels/mochat/webui/locales/fr.json @@ -0,0 +1,85 @@ +{ + "setup": { + "docsLabel": "Ouvrir le guide de configuration MoChat", + "officialLabel": "Ouvrir MoChat", + "fields": { + "clawToken": { + "label": "Jeton Claw", + "placeholder": "Jeton Claw MoChat" + }, + "baseUrl": { + "label": "URL du serveur", + "placeholder": "https://mochat.io" + }, + "agentUserId": { + "label": "Identifiant utilisateur de l’agent", + "placeholder": "Identifiant utilisateur facultatif" + }, + "sessions": { + "label": "Sessions", + "placeholder": "Identifiants de session, séparés par des virgules" + }, + "panels": { + "label": "Panneaux", + "placeholder": "Identifiants de panneau, séparés par des virgules" + }, + "allowFrom": { + "label": "Utilisateurs autorisés", + "placeholder": "Identifiants utilisateur, séparés par des virgules" + }, + "socketUrl": { + "label": "URL de socket" + }, + "socketPath": { + "label": "Chemin de prise" + }, + "socketDisableMsgpack": { + "label": "Désactiver MessagePack", + "choices": { + "true": "Sur", + "false": "Désactivé" + } + }, + "socketReconnectDelayMs": { + "label": "Délai de reconnexion" + }, + "socketMaxReconnectDelayMs": { + "label": "Délai de reconnexion maximum" + }, + "socketConnectTimeoutMs": { + "label": "Délai de connexion" + }, + "refreshIntervalMs": { + "label": "Intervalle d'actualisation" + }, + "watchTimeoutMs": { + "label": "Expiration du délai de visionnage" + }, + "watchLimit": { + "label": "Surveiller la taille du lot" + }, + "retryDelayMs": { + "label": "Délai de nouvelle tentative" + }, + "maxRetryAttempts": { + "label": "Nombre maximal de tentatives" + }, + "mention_requireInGroups": { + "label": "Exiger des mentions dans les groupes", + "choices": { + "true": "Sur", + "false": "Désactivé" + } + }, + "groups": { + "label": "Règles de groupe (JSON)" + }, + "replyDelayMode": { + "label": "Mode de délai de réponse" + }, + "replyDelayMs": { + "label": "Délai de réponse" + } + } + } +} diff --git a/nanobot/channels/mochat/webui/locales/id.json b/nanobot/channels/mochat/webui/locales/id.json new file mode 100644 index 000000000..b40e3d973 --- /dev/null +++ b/nanobot/channels/mochat/webui/locales/id.json @@ -0,0 +1,85 @@ +{ + "setup": { + "docsLabel": "Buka panduan penyiapan MoChat", + "officialLabel": "Buka MoChat", + "fields": { + "clawToken": { + "label": "Token Claw", + "placeholder": "Token Claw MoChat" + }, + "baseUrl": { + "label": "URL server", + "placeholder": "https://mochat.io" + }, + "agentUserId": { + "label": "ID pengguna agen", + "placeholder": "ID pengguna agen opsional" + }, + "sessions": { + "label": "Sesi", + "placeholder": "ID sesi, pisahkan dengan koma" + }, + "panels": { + "label": "Panel", + "placeholder": "ID panel, pisahkan dengan koma" + }, + "allowFrom": { + "label": "Pengguna yang diizinkan", + "placeholder": "ID pengguna, pisahkan dengan koma" + }, + "socketUrl": { + "label": "URL soket" + }, + "socketPath": { + "label": "Jalur soket" + }, + "socketDisableMsgpack": { + "label": "Nonaktifkan MessagePack", + "choices": { + "true": "Aktif", + "false": "Mati" + } + }, + "socketReconnectDelayMs": { + "label": "Sambungkan kembali penundaan" + }, + "socketMaxReconnectDelayMs": { + "label": "Penundaan penyambungan kembali maksimum" + }, + "socketConnectTimeoutMs": { + "label": "Batas waktu koneksi habis" + }, + "refreshIntervalMs": { + "label": "Interval penyegaran" + }, + "watchTimeoutMs": { + "label": "Waktu tunggu tonton habis" + }, + "watchLimit": { + "label": "Perhatikan ukuran batch" + }, + "retryDelayMs": { + "label": "Coba lagi penundaan" + }, + "maxRetryAttempts": { + "label": "Percobaan ulang maksimum" + }, + "mention_requireInGroups": { + "label": "Memerlukan penyebutan dalam kelompok", + "choices": { + "true": "Aktif", + "false": "Mati" + } + }, + "groups": { + "label": "Aturan grup (JSON)" + }, + "replyDelayMode": { + "label": "Mode penundaan balasan" + }, + "replyDelayMs": { + "label": "Keterlambatan balasan" + } + } + } +} diff --git a/nanobot/channels/mochat/webui/locales/ja.json b/nanobot/channels/mochat/webui/locales/ja.json new file mode 100644 index 000000000..3b2a3ba96 --- /dev/null +++ b/nanobot/channels/mochat/webui/locales/ja.json @@ -0,0 +1,85 @@ +{ + "setup": { + "docsLabel": "MoChat 設定ガイドを開く", + "officialLabel": "MoChat を開く", + "fields": { + "clawToken": { + "label": "Claw トークン", + "placeholder": "MoChat Claw トークン" + }, + "baseUrl": { + "label": "サーバー URL", + "placeholder": "https://mochat.io" + }, + "agentUserId": { + "label": "エージェントのユーザー ID", + "placeholder": "任意のエージェントユーザー ID" + }, + "sessions": { + "label": "セッション", + "placeholder": "セッション ID(カンマ区切り)" + }, + "panels": { + "label": "パネル", + "placeholder": "パネル ID(カンマ区切り)" + }, + "allowFrom": { + "label": "許可するユーザー", + "placeholder": "ユーザー ID(カンマ区切り)" + }, + "socketUrl": { + "label": "ソケットURL" + }, + "socketPath": { + "label": "ソケットパス" + }, + "socketDisableMsgpack": { + "label": "メッセージパックを無効にする", + "choices": { + "true": "オン", + "false": "オフ" + } + }, + "socketReconnectDelayMs": { + "label": "再接続の遅延" + }, + "socketMaxReconnectDelayMs": { + "label": "最大再接続遅延" + }, + "socketConnectTimeoutMs": { + "label": "接続タイムアウト" + }, + "refreshIntervalMs": { + "label": "リフレッシュ間隔" + }, + "watchTimeoutMs": { + "label": "ウォッチタイムアウト" + }, + "watchLimit": { + "label": "バッチサイズを監視する" + }, + "retryDelayMs": { + "label": "再試行の遅延" + }, + "maxRetryAttempts": { + "label": "最大再試行回数" + }, + "mention_requireInGroups": { + "label": "グループでのメンションを必須にする", + "choices": { + "true": "オン", + "false": "オフ" + } + }, + "groups": { + "label": "グループルール(JSON)" + }, + "replyDelayMode": { + "label": "返信遅延モード" + }, + "replyDelayMs": { + "label": "返信遅延" + } + } + } +} diff --git a/nanobot/channels/mochat/webui/locales/ko.json b/nanobot/channels/mochat/webui/locales/ko.json new file mode 100644 index 000000000..93eac51c5 --- /dev/null +++ b/nanobot/channels/mochat/webui/locales/ko.json @@ -0,0 +1,85 @@ +{ + "setup": { + "docsLabel": "MoChat 설정 가이드 열기", + "officialLabel": "MoChat 열기", + "fields": { + "clawToken": { + "label": "Claw 토큰", + "placeholder": "MoChat Claw 토큰" + }, + "baseUrl": { + "label": "서버 URL", + "placeholder": "https://mochat.io" + }, + "agentUserId": { + "label": "에이전트 사용자 ID", + "placeholder": "선택 사항인 에이전트 사용자 ID" + }, + "sessions": { + "label": "세션", + "placeholder": "세션 ID, 쉼표로 구분" + }, + "panels": { + "label": "패널", + "placeholder": "패널 ID, 쉼표로 구분" + }, + "allowFrom": { + "label": "허용된 사용자", + "placeholder": "사용자 ID, 쉼표로 구분" + }, + "socketUrl": { + "label": "소켓 URL" + }, + "socketPath": { + "label": "소켓 경로" + }, + "socketDisableMsgpack": { + "label": "MessagePack 비활성화", + "choices": { + "true": "켜기", + "false": "끄기" + } + }, + "socketReconnectDelayMs": { + "label": "재연결 지연" + }, + "socketMaxReconnectDelayMs": { + "label": "최대 재연결 지연" + }, + "socketConnectTimeoutMs": { + "label": "연결 시간 초과" + }, + "refreshIntervalMs": { + "label": "새로 고침 간격" + }, + "watchTimeoutMs": { + "label": "시청 시간 초과" + }, + "watchLimit": { + "label": "시계 배치 크기" + }, + "retryDelayMs": { + "label": "재시도 지연" + }, + "maxRetryAttempts": { + "label": "최대 재시도" + }, + "mention_requireInGroups": { + "label": "그룹에서 멘션 필요", + "choices": { + "true": "켜기", + "false": "끄기" + } + }, + "groups": { + "label": "그룹 규칙(JSON)" + }, + "replyDelayMode": { + "label": "응답 지연 모드" + }, + "replyDelayMs": { + "label": "답변 지연" + } + } + } +} diff --git a/nanobot/channels/mochat/webui/locales/pt-BR.json b/nanobot/channels/mochat/webui/locales/pt-BR.json new file mode 100644 index 000000000..0f7be278a --- /dev/null +++ b/nanobot/channels/mochat/webui/locales/pt-BR.json @@ -0,0 +1,85 @@ +{ + "setup": { + "docsLabel": "Abrir o guia de configuração do MoChat", + "officialLabel": "Abrir o MoChat", + "fields": { + "clawToken": { + "label": "Token Claw", + "placeholder": "Token Claw do MoChat" + }, + "baseUrl": { + "label": "URL do servidor", + "placeholder": "https://mochat.io" + }, + "agentUserId": { + "label": "ID de usuário do agente", + "placeholder": "ID de usuário opcional do agente" + }, + "sessions": { + "label": "Sessões", + "placeholder": "IDs de sessão, separados por vírgulas" + }, + "panels": { + "label": "Painéis", + "placeholder": "IDs de painel, separados por vírgulas" + }, + "allowFrom": { + "label": "Usuários permitidos", + "placeholder": "IDs de usuário, separados por vírgulas" + }, + "socketUrl": { + "label": "URL do soquete" + }, + "socketPath": { + "label": "Caminho do soquete" + }, + "socketDisableMsgpack": { + "label": "Desativar MessagePack", + "choices": { + "true": "Ligado", + "false": "Desligado" + } + }, + "socketReconnectDelayMs": { + "label": "Atraso na reconexão" + }, + "socketMaxReconnectDelayMs": { + "label": "Atraso máximo de reconexão" + }, + "socketConnectTimeoutMs": { + "label": "Tempo limite de conexão" + }, + "refreshIntervalMs": { + "label": "Intervalo de atualização" + }, + "watchTimeoutMs": { + "label": "Tempo limite de exibição" + }, + "watchLimit": { + "label": "Observe o tamanho do lote" + }, + "retryDelayMs": { + "label": "Atraso na nova tentativa" + }, + "maxRetryAttempts": { + "label": "Máximo de tentativas" + }, + "mention_requireInGroups": { + "label": "Exigir menções em grupos", + "choices": { + "true": "Ligado", + "false": "Desligado" + } + }, + "groups": { + "label": "Regras de grupo (JSON)" + }, + "replyDelayMode": { + "label": "Modo de atraso de resposta" + }, + "replyDelayMs": { + "label": "Atraso na resposta" + } + } + } +} diff --git a/nanobot/channels/mochat/webui/locales/vi.json b/nanobot/channels/mochat/webui/locales/vi.json new file mode 100644 index 000000000..ab067c1d9 --- /dev/null +++ b/nanobot/channels/mochat/webui/locales/vi.json @@ -0,0 +1,85 @@ +{ + "setup": { + "docsLabel": "Mở hướng dẫn thiết lập MoChat", + "officialLabel": "Mở MoChat", + "fields": { + "clawToken": { + "label": "Mã Claw", + "placeholder": "Mã Claw của MoChat" + }, + "baseUrl": { + "label": "URL máy chủ", + "placeholder": "https://mochat.io" + }, + "agentUserId": { + "label": "ID người dùng của agent", + "placeholder": "ID người dùng agent không bắt buộc" + }, + "sessions": { + "label": "Phiên", + "placeholder": "ID phiên, phân tách bằng dấu phẩy" + }, + "panels": { + "label": "Bảng", + "placeholder": "ID bảng, phân tách bằng dấu phẩy" + }, + "allowFrom": { + "label": "Người dùng được phép", + "placeholder": "ID người dùng, phân tách bằng dấu phẩy" + }, + "socketUrl": { + "label": "URL ổ cắm" + }, + "socketPath": { + "label": "Đường dẫn ổ cắm" + }, + "socketDisableMsgpack": { + "label": "Tắt MessagePack", + "choices": { + "true": "Bật", + "false": "Tắt" + } + }, + "socketReconnectDelayMs": { + "label": "Độ trễ kết nối lại" + }, + "socketMaxReconnectDelayMs": { + "label": "Độ trễ kết nối lại tối đa" + }, + "socketConnectTimeoutMs": { + "label": "Hết thời gian kết nối" + }, + "refreshIntervalMs": { + "label": "Khoảng thời gian làm mới" + }, + "watchTimeoutMs": { + "label": "Hết thời gian xem" + }, + "watchLimit": { + "label": "Kích thước lô đồng hồ" + }, + "retryDelayMs": { + "label": "Trì hoãn thử lại" + }, + "maxRetryAttempts": { + "label": "Số lần thử lại tối đa" + }, + "mention_requireInGroups": { + "label": "Yêu cầu đề cập trong nhóm", + "choices": { + "true": "Bật", + "false": "Tắt" + } + }, + "groups": { + "label": "Quy tắc nhóm (JSON)" + }, + "replyDelayMode": { + "label": "Chế độ trì hoãn trả lời" + }, + "replyDelayMs": { + "label": "Trả lời chậm trễ" + } + } + } +} diff --git a/nanobot/channels/mochat/webui/locales/zh-CN.json b/nanobot/channels/mochat/webui/locales/zh-CN.json new file mode 100644 index 000000000..b71a1b0b3 --- /dev/null +++ b/nanobot/channels/mochat/webui/locales/zh-CN.json @@ -0,0 +1,85 @@ +{ + "setup": { + "docsLabel": "打开 MoChat 配置指南", + "officialLabel": "打开 MoChat", + "fields": { + "clawToken": { + "label": "Claw 令牌", + "placeholder": "MoChat Claw 令牌" + }, + "baseUrl": { + "label": "服务地址", + "placeholder": "https://mochat.io" + }, + "agentUserId": { + "label": "Agent 用户 ID", + "placeholder": "可选的 Agent 用户 ID" + }, + "sessions": { + "label": "会话", + "placeholder": "会话 ID,用逗号分隔" + }, + "panels": { + "label": "面板", + "placeholder": "面板 ID,用逗号分隔" + }, + "allowFrom": { + "label": "允许的用户", + "placeholder": "用户 ID,用逗号分隔" + }, + "socketUrl": { + "label": "Socket 地址" + }, + "socketPath": { + "label": "Socket 路径" + }, + "socketDisableMsgpack": { + "label": "禁用 MessagePack", + "choices": { + "true": "开启", + "false": "关闭" + } + }, + "socketReconnectDelayMs": { + "label": "重连延迟" + }, + "socketMaxReconnectDelayMs": { + "label": "最大重连延迟" + }, + "socketConnectTimeoutMs": { + "label": "连接超时" + }, + "refreshIntervalMs": { + "label": "刷新间隔" + }, + "watchTimeoutMs": { + "label": "拉取超时" + }, + "watchLimit": { + "label": "单次拉取数量" + }, + "retryDelayMs": { + "label": "重试延迟" + }, + "maxRetryAttempts": { + "label": "最大重试次数" + }, + "mention_requireInGroups": { + "label": "群组中需要提及", + "choices": { + "true": "开启", + "false": "关闭" + } + }, + "groups": { + "label": "群组规则(JSON)" + }, + "replyDelayMode": { + "label": "回复延迟方式" + }, + "replyDelayMs": { + "label": "回复延迟" + } + } + } +} diff --git a/nanobot/channels/mochat/webui/locales/zh-TW.json b/nanobot/channels/mochat/webui/locales/zh-TW.json new file mode 100644 index 000000000..1136c7bbb --- /dev/null +++ b/nanobot/channels/mochat/webui/locales/zh-TW.json @@ -0,0 +1,85 @@ +{ + "setup": { + "docsLabel": "開啟 MoChat 設定指南", + "officialLabel": "開啟 MoChat", + "fields": { + "clawToken": { + "label": "Claw 權杖", + "placeholder": "MoChat Claw 權杖" + }, + "baseUrl": { + "label": "服務位址", + "placeholder": "https://mochat.io" + }, + "agentUserId": { + "label": "Agent 使用者 ID", + "placeholder": "選填的 Agent 使用者 ID" + }, + "sessions": { + "label": "工作階段", + "placeholder": "工作階段 ID,以逗號分隔" + }, + "panels": { + "label": "面板", + "placeholder": "面板 ID,以逗號分隔" + }, + "allowFrom": { + "label": "允許的使用者", + "placeholder": "使用者 ID,以逗號分隔" + }, + "socketUrl": { + "label": "Socket 位址" + }, + "socketPath": { + "label": "Socket 路徑" + }, + "socketDisableMsgpack": { + "label": "禁用 MessagePack", + "choices": { + "true": "開啟", + "false": "關閉" + } + }, + "socketReconnectDelayMs": { + "label": "重連延遲" + }, + "socketMaxReconnectDelayMs": { + "label": "最大重連延遲" + }, + "socketConnectTimeoutMs": { + "label": "連線逾時" + }, + "refreshIntervalMs": { + "label": "刷新間隔" + }, + "watchTimeoutMs": { + "label": "拉取超時" + }, + "watchLimit": { + "label": "單次拉取數量" + }, + "retryDelayMs": { + "label": "重試延遲" + }, + "maxRetryAttempts": { + "label": "最大重試次數" + }, + "mention_requireInGroups": { + "label": "群組需要提及", + "choices": { + "true": "開啟", + "false": "關閉" + } + }, + "groups": { + "label": "群組規則(JSON)" + }, + "replyDelayMode": { + "label": "回覆延遲方式" + }, + "replyDelayMs": { + "label": "回覆延遲" + } + } + } +} diff --git a/nanobot/channels/msteams/manifest.py b/nanobot/channels/msteams/manifest.py index 5b298e4a7..fd074542a 100644 --- a/nanobot/channels/msteams/manifest.py +++ b/nanobot/channels/msteams/manifest.py @@ -11,6 +11,16 @@ SETUP_SPEC = ChannelSetupSpec( "tenantId": field(), "path": field(default="/api/messages"), "allowFrom": field("list"), + "host": field(default="0.0.0.0"), + "port": field("int", default=3978), + "replyInThread": field("bool", default=True), + "mentionOnlyResponse": field(default="Hi — what can I help with?"), + "validateInboundAuth": field("bool", default=True), + "refTtlDays": field("int", default=30), + "pruneWebChatRefs": field("bool", default=True), + "pruneNonPersonalRefs": field("bool", default=True), + "refTouchIntervalS": field("int", default=300), + "trustedServiceUrlHosts": field("list"), }, required=required_fields("appId", "appPassword"), official_url="https://dev.teams.microsoft.com/apps", diff --git a/nanobot/channels/msteams/webui/index.ts b/nanobot/channels/msteams/webui/index.ts index 7360fd0d8..378a5619f 100644 --- a/nanobot/channels/msteams/webui/index.ts +++ b/nanobot/channels/msteams/webui/index.ts @@ -3,19 +3,19 @@ import { chatAppGuideUrl } from "@/components/settings/channels/catalog"; export default { presentation: { + logoUrl: "https://teams.public.onecdn.static.microsoft/evergreen-assets/icons/microsoft_teams_logo_refresh_v2025.ico", displayName: "Microsoft Teams", initials: "MS", color: "#6264A7", - logoUrl: "https://www.microsoft.com/favicon.ico", setup: { mode: "credentials", docsUrl: chatAppGuideUrl("msteams"), fields: [ - { key: "channels.msteams.appId" }, - { key: "channels.msteams.appPassword" }, - { key: "channels.msteams.tenantId" }, - { key: "channels.msteams.path" }, - { key: "channels.msteams.allowFrom" }, + { key: "channels.msteams.appId", section: "credentials" }, + { key: "channels.msteams.appPassword", section: "credentials" }, + { key: "channels.msteams.tenantId", section: "account" }, + { key: "channels.msteams.path", section: "connection" }, + { key: "channels.msteams.allowFrom", section: "access" }, ], }, }, diff --git a/nanobot/channels/msteams/webui/locales/en.json b/nanobot/channels/msteams/webui/locales/en.json index 9f41278f2..cde8c51b6 100644 --- a/nanobot/channels/msteams/webui/locales/en.json +++ b/nanobot/channels/msteams/webui/locales/en.json @@ -1,26 +1,15 @@ { - "description": "Use nanobot from Microsoft Teams chats.", - "requirements": "Azure bot app credentials, public callback endpoint", "setup": { "docsLabel": "Open Teams setup", "officialLabel": "Open Teams developer portal", - "tryIt": "Install the Teams app and send a test message.", - "summary": "Teams receives messages through the Bot Framework callback URL. It needs a reachable HTTPS endpoint in production.", - "steps": [ - "Create an Azure Bot or Teams app and copy its App ID and client secret.", - "Expose the callback path over HTTPS and add it as the bot messaging endpoint.", - "Save and enable Teams, then install the app and send a test message." - ], "fields": { "appId": { "label": "App ID", - "placeholder": "Microsoft App ID", - "help": "Copy it from the Azure Bot or Teams app registration." + "placeholder": "Microsoft App ID" }, "appPassword": { "label": "Client secret", - "placeholder": "••••••", - "help": "Create a client secret for the Microsoft app." + "placeholder": "••••••" }, "tenantId": { "label": "Tenant ID", @@ -33,6 +22,52 @@ "allowFrom": { "label": "Allowed users", "placeholder": "Teams user IDs, comma separated" + }, + "host": { + "label": "Listen host" + }, + "port": { + "label": "Listen port" + }, + "replyInThread": { + "label": "Reply in thread", + "choices": { + "true": "On", + "false": "Off" + } + }, + "mentionOnlyResponse": { + "label": "Mention-only reply" + }, + "validateInboundAuth": { + "label": "Validate incoming requests", + "choices": { + "true": "On", + "false": "Off" + } + }, + "refTtlDays": { + "label": "Conversation lifetime" + }, + "pruneWebChatRefs": { + "label": "Remove Web Chat conversations", + "choices": { + "true": "On", + "false": "Off" + } + }, + "pruneNonPersonalRefs": { + "label": "Remove non-personal conversations", + "choices": { + "true": "On", + "false": "Off" + } + }, + "refTouchIntervalS": { + "label": "Conversation refresh interval" + }, + "trustedServiceUrlHosts": { + "label": "Trusted service hosts" } } } diff --git a/nanobot/channels/msteams/webui/locales/es.json b/nanobot/channels/msteams/webui/locales/es.json index d7eadcabf..7468b1291 100644 --- a/nanobot/channels/msteams/webui/locales/es.json +++ b/nanobot/channels/msteams/webui/locales/es.json @@ -1,26 +1,15 @@ { - "description": "Usa nanobot desde chats de Microsoft Teams.", - "requirements": "Credenciales de la app bot de Azure y endpoint público de callback", "setup": { "docsLabel": "Abrir guía de Teams", "officialLabel": "Abrir portal de desarrolladores de Teams", - "tryIt": "Instala la app de Teams y envía un mensaje de prueba.", - "summary": "Teams recibe mensajes mediante la URL de callback de Bot Framework. En producción necesita un endpoint HTTPS accesible.", - "steps": [ - "Crea un Azure Bot o una app de Teams y copia el App ID y el secreto de cliente.", - "Expón la ruta de callback por HTTPS y añádela como endpoint de mensajería.", - "Guarda y activa Teams; después instala la app y envía un mensaje de prueba." - ], "fields": { "appId": { "label": "App ID", - "placeholder": "Microsoft App ID", - "help": "Cópialo del registro de Azure Bot o la app de Teams." + "placeholder": "Microsoft App ID" }, "appPassword": { "label": "Secreto de cliente", - "placeholder": "••••••", - "help": "Crea un secreto de cliente para la app de Microsoft." + "placeholder": "••••••" }, "tenantId": { "label": "ID del tenant", @@ -33,6 +22,52 @@ "allowFrom": { "label": "Usuarios permitidos", "placeholder": "ID de usuario de Teams separados por comas" + }, + "host": { + "label": "Escuchar anfitrión" + }, + "port": { + "label": "Puerto de escucha" + }, + "replyInThread": { + "label": "Responder en el hilo", + "choices": { + "true": "encendido", + "false": "Apagado" + } + }, + "mentionOnlyResponse": { + "label": "Respuesta de solo mención" + }, + "validateInboundAuth": { + "label": "Validar solicitudes entrantes", + "choices": { + "true": "encendido", + "false": "Apagado" + } + }, + "refTtlDays": { + "label": "Duración de la conversación" + }, + "pruneWebChatRefs": { + "label": "Eliminar conversaciones de chat web", + "choices": { + "true": "encendido", + "false": "Apagado" + } + }, + "pruneNonPersonalRefs": { + "label": "Eliminar conversaciones no personales", + "choices": { + "true": "encendido", + "false": "Apagado" + } + }, + "refTouchIntervalS": { + "label": "Intervalo de actualización de la conversación" + }, + "trustedServiceUrlHosts": { + "label": "Anfitriones de servicios confiables" } } } diff --git a/nanobot/channels/msteams/webui/locales/fr.json b/nanobot/channels/msteams/webui/locales/fr.json index 0b8756399..e8cbc21bd 100644 --- a/nanobot/channels/msteams/webui/locales/fr.json +++ b/nanobot/channels/msteams/webui/locales/fr.json @@ -1,26 +1,15 @@ { - "description": "Utilisez nanobot depuis les conversations Microsoft Teams.", - "requirements": "Identifiants de l’application bot Azure et endpoint de rappel public", "setup": { "docsLabel": "Ouvrir le guide Teams", "officialLabel": "Ouvrir le portail développeur Teams", - "tryIt": "Installez l’application Teams et envoyez un message test.", - "summary": "Teams reçoit les messages via l’URL de rappel Bot Framework. Un endpoint HTTPS accessible est nécessaire en production.", - "steps": [ - "Créez un bot Azure ou une application Teams et copiez l’App ID et le secret client.", - "Exposez le chemin de rappel en HTTPS et définissez-le comme endpoint de messagerie.", - "Enregistrez et activez Teams, puis installez l’application et envoyez un message test." - ], "fields": { "appId": { "label": "App ID", - "placeholder": "Microsoft App ID", - "help": "Copiez-le depuis l’inscription du bot Azure ou de l’application Teams." + "placeholder": "Microsoft App ID" }, "appPassword": { "label": "Secret client", - "placeholder": "••••••", - "help": "Créez un secret client pour l’application Microsoft." + "placeholder": "••••••" }, "tenantId": { "label": "ID du locataire", @@ -33,6 +22,52 @@ "allowFrom": { "label": "Utilisateurs autorisés", "placeholder": "ID utilisateur Teams séparés par des virgules" + }, + "host": { + "label": "Écouter l'hôte" + }, + "port": { + "label": "Port d'écoute" + }, + "replyInThread": { + "label": "Répondre dans le fil de discussion", + "choices": { + "true": "Sur", + "false": "Désactivé" + } + }, + "mentionOnlyResponse": { + "label": "Réponse avec mention uniquement" + }, + "validateInboundAuth": { + "label": "Valider les demandes entrantes", + "choices": { + "true": "Sur", + "false": "Désactivé" + } + }, + "refTtlDays": { + "label": "Durée de vie des conversations" + }, + "pruneWebChatRefs": { + "label": "Supprimer les conversations de chat Web", + "choices": { + "true": "Sur", + "false": "Désactivé" + } + }, + "pruneNonPersonalRefs": { + "label": "Supprimer les conversations non personnelles", + "choices": { + "true": "Sur", + "false": "Désactivé" + } + }, + "refTouchIntervalS": { + "label": "Intervalle d'actualisation des conversations" + }, + "trustedServiceUrlHosts": { + "label": "Hôtes de services de confiance" } } } diff --git a/nanobot/channels/msteams/webui/locales/id.json b/nanobot/channels/msteams/webui/locales/id.json index fb7e15bd2..d305d9e31 100644 --- a/nanobot/channels/msteams/webui/locales/id.json +++ b/nanobot/channels/msteams/webui/locales/id.json @@ -1,26 +1,15 @@ { - "description": "Gunakan nanobot dari chat Microsoft Teams.", - "requirements": "Kredensial aplikasi bot Azure dan endpoint callback publik", "setup": { "docsLabel": "Buka panduan Teams", "officialLabel": "Buka portal pengembang Teams", - "tryIt": "Pasang aplikasi Teams dan kirim pesan uji.", - "summary": "Teams menerima pesan melalui URL callback Bot Framework. Untuk penggunaan di lingkungan produksi, alamat HTTPS harus dapat diakses dari luar.", - "steps": [ - "Buat Azure Bot atau aplikasi Teams dan salin App ID serta client secret.", - "Paparkan jalur callback melalui HTTPS dan jadikan endpoint pesan bot.", - "Simpan dan aktifkan Teams, lalu pasang aplikasi dan kirim pesan uji." - ], "fields": { "appId": { "label": "App ID", - "placeholder": "Microsoft App ID", - "help": "Salin dari pendaftaran Azure Bot atau aplikasi Teams." + "placeholder": "Microsoft App ID" }, "appPassword": { "label": "Client secret", - "placeholder": "••••••", - "help": "Buat client secret untuk aplikasi Microsoft." + "placeholder": "••••••" }, "tenantId": { "label": "Tenant ID", @@ -33,6 +22,52 @@ "allowFrom": { "label": "Pengguna yang diizinkan", "placeholder": "ID pengguna Teams, dipisahkan koma" + }, + "host": { + "label": "Dengarkan tuan rumah" + }, + "port": { + "label": "Dengarkan pelabuhan" + }, + "replyInThread": { + "label": "Balas di thread", + "choices": { + "true": "Aktif", + "false": "Mati" + } + }, + "mentionOnlyResponse": { + "label": "Balasan yang hanya disebutkan saja" + }, + "validateInboundAuth": { + "label": "Validasi permintaan masuk", + "choices": { + "true": "Aktif", + "false": "Mati" + } + }, + "refTtlDays": { + "label": "Percakapan seumur hidup" + }, + "pruneWebChatRefs": { + "label": "Hapus percakapan Obrolan Web", + "choices": { + "true": "Aktif", + "false": "Mati" + } + }, + "pruneNonPersonalRefs": { + "label": "Hapus percakapan non-pribadi", + "choices": { + "true": "Aktif", + "false": "Mati" + } + }, + "refTouchIntervalS": { + "label": "Interval penyegaran percakapan" + }, + "trustedServiceUrlHosts": { + "label": "Host layanan tepercaya" } } } diff --git a/nanobot/channels/msteams/webui/locales/ja.json b/nanobot/channels/msteams/webui/locales/ja.json index 905e54372..1809cc356 100644 --- a/nanobot/channels/msteams/webui/locales/ja.json +++ b/nanobot/channels/msteams/webui/locales/ja.json @@ -1,26 +1,15 @@ { - "description": "Microsoft Teams のチャットから nanobot を利用します。", - "requirements": "Azure ボットアプリの認証情報と公開コールバックエンドポイント", "setup": { "docsLabel": "Teams 設定ガイドを開く", "officialLabel": "Teams 開発者ポータルを開く", - "tryIt": "Teams アプリをインストールし、テストメッセージを送信します。", - "summary": "Teams は Bot Framework のコールバック URL でメッセージを受信します。本番環境では到達可能な HTTPS エンドポイントが必要です。", - "steps": [ - "Azure Bot または Teams アプリを作成し、App ID とクライアントシークレットをコピーします。", - "コールバックパスを HTTPS で公開し、ボットのメッセージングエンドポイントに設定します。", - "保存して Teams を有効にし、アプリをインストールしてテストメッセージを送信します。" - ], "fields": { "appId": { "label": "App ID", - "placeholder": "Microsoft App ID", - "help": "Azure Bot または Teams アプリ登録からコピーします。" + "placeholder": "Microsoft App ID" }, "appPassword": { "label": "クライアントシークレット", - "placeholder": "••••••", - "help": "Microsoft アプリ用のクライアントシークレットを作成します。" + "placeholder": "••••••" }, "tenantId": { "label": "テナント ID", @@ -33,6 +22,52 @@ "allowFrom": { "label": "許可するユーザー", "placeholder": "Teams ユーザー ID(カンマ区切り)" + }, + "host": { + "label": "リッスンホスト" + }, + "port": { + "label": "リッスンポート" + }, + "replyInThread": { + "label": "スレッド内で返信する", + "choices": { + "true": "オン", + "false": "オフ" + } + }, + "mentionOnlyResponse": { + "label": "メンションのみの返信" + }, + "validateInboundAuth": { + "label": "受信リクエストを検証する", + "choices": { + "true": "オン", + "false": "オフ" + } + }, + "refTtlDays": { + "label": "会話の存続期間" + }, + "pruneWebChatRefs": { + "label": "Web チャットの会話を削除する", + "choices": { + "true": "オン", + "false": "オフ" + } + }, + "pruneNonPersonalRefs": { + "label": "個人的ではない会話を削除する", + "choices": { + "true": "オン", + "false": "オフ" + } + }, + "refTouchIntervalS": { + "label": "会話の更新間隔" + }, + "trustedServiceUrlHosts": { + "label": "信頼できるサービスホスト" } } } diff --git a/nanobot/channels/msteams/webui/locales/ko.json b/nanobot/channels/msteams/webui/locales/ko.json index 739ad045a..b2c44abd5 100644 --- a/nanobot/channels/msteams/webui/locales/ko.json +++ b/nanobot/channels/msteams/webui/locales/ko.json @@ -1,26 +1,15 @@ { - "description": "Microsoft Teams 채팅에서 nanobot을 사용합니다.", - "requirements": "Azure 봇 앱 인증 정보 및 공개 콜백 엔드포인트", "setup": { "docsLabel": "Teams 설정 가이드 열기", "officialLabel": "Teams 개발자 포털 열기", - "tryIt": "Teams 앱을 설치하고 테스트 메시지를 보내세요.", - "summary": "Teams는 Bot Framework 콜백 URL로 메시지를 받습니다. 운영 환경에는 접근 가능한 HTTPS 엔드포인트가 필요합니다.", - "steps": [ - "Azure Bot 또는 Teams 앱을 만들고 App ID와 클라이언트 암호을 복사하세요.", - "콜백 경로를 HTTPS로 공개하고 봇 메시징 엔드포인트로 설정하세요.", - "저장하고 Teams를 활성화한 다음 앱을 설치하고 테스트 메시지를 보내세요." - ], "fields": { "appId": { "label": "App ID", - "placeholder": "Microsoft App ID", - "help": "Azure Bot 또는 Teams 앱 등록에서 복사하세요." + "placeholder": "Microsoft App ID" }, "appPassword": { "label": "클라이언트 암호", - "placeholder": "••••••", - "help": "Microsoft 앱의 클라이언트 암호를 생성하세요." + "placeholder": "••••••" }, "tenantId": { "label": "테넌트 ID", @@ -33,6 +22,52 @@ "allowFrom": { "label": "허용된 사용자", "placeholder": "Teams 사용자 ID, 쉼표로 구분" + }, + "host": { + "label": "호스트 듣기" + }, + "port": { + "label": "청취 포트" + }, + "replyInThread": { + "label": "스레드로 답장하기", + "choices": { + "true": "켜기", + "false": "끄기" + } + }, + "mentionOnlyResponse": { + "label": "언급 전용 답변" + }, + "validateInboundAuth": { + "label": "들어오는 요청의 유효성을 검사합니다.", + "choices": { + "true": "켜기", + "false": "끄기" + } + }, + "refTtlDays": { + "label": "대화 수명" + }, + "pruneWebChatRefs": { + "label": "웹 채팅 대화 제거", + "choices": { + "true": "켜기", + "false": "끄기" + } + }, + "pruneNonPersonalRefs": { + "label": "개인 대화가 아닌 대화 삭제", + "choices": { + "true": "켜기", + "false": "끄기" + } + }, + "refTouchIntervalS": { + "label": "대화 새로 고침 간격" + }, + "trustedServiceUrlHosts": { + "label": "신뢰할 수 있는 서비스 호스트" } } } diff --git a/nanobot/channels/msteams/webui/locales/pt-BR.json b/nanobot/channels/msteams/webui/locales/pt-BR.json index 1b7850a39..a26c6eb25 100644 --- a/nanobot/channels/msteams/webui/locales/pt-BR.json +++ b/nanobot/channels/msteams/webui/locales/pt-BR.json @@ -1,26 +1,15 @@ { - "description": "Use o nanobot em conversas do Microsoft Teams.", - "requirements": "Credenciais do app bot Azure e endpoint público de callback", "setup": { "docsLabel": "Abrir guia do Teams", "officialLabel": "Abrir portal de desenvolvedores do Teams", - "tryIt": "Instale o app do Teams e envie uma mensagem de teste.", - "summary": "O Teams recebe mensagens pela URL de callback do Bot Framework. Em produção, precisa de um endpoint HTTPS acessível.", - "steps": [ - "Crie um Azure Bot ou app Teams e copie o App ID e o segredo do cliente.", - "Exponha o caminho de callback por HTTPS e defina-o como endpoint de mensagens.", - "Salve e ative o Teams; depois, instale o app e envie uma mensagem de teste." - ], "fields": { "appId": { "label": "App ID", - "placeholder": "Microsoft App ID", - "help": "Copie do registro do Azure Bot ou do app Teams." + "placeholder": "Microsoft App ID" }, "appPassword": { "label": "Segredo do cliente", - "placeholder": "••••••", - "help": "Crie um segredo do cliente para o app Microsoft." + "placeholder": "••••••" }, "tenantId": { "label": "ID do locatário", @@ -33,6 +22,52 @@ "allowFrom": { "label": "Usuários permitidos", "placeholder": "IDs de usuário do Teams separados por vírgulas" + }, + "host": { + "label": "Ouça o apresentador" + }, + "port": { + "label": "Porta de escuta" + }, + "replyInThread": { + "label": "Responder no tópico", + "choices": { + "true": "Ligado", + "false": "Desligado" + } + }, + "mentionOnlyResponse": { + "label": "Resposta apenas com menção" + }, + "validateInboundAuth": { + "label": "Validar solicitações recebidas", + "choices": { + "true": "Ligado", + "false": "Desligado" + } + }, + "refTtlDays": { + "label": "Vida útil da conversa" + }, + "pruneWebChatRefs": { + "label": "Remover conversas do Web Chat", + "choices": { + "true": "Ligado", + "false": "Desligado" + } + }, + "pruneNonPersonalRefs": { + "label": "Remover conversas não pessoais", + "choices": { + "true": "Ligado", + "false": "Desligado" + } + }, + "refTouchIntervalS": { + "label": "Intervalo de atualização da conversa" + }, + "trustedServiceUrlHosts": { + "label": "Hosts de serviço confiáveis" } } } diff --git a/nanobot/channels/msteams/webui/locales/vi.json b/nanobot/channels/msteams/webui/locales/vi.json index 5c3be71c7..29b938d63 100644 --- a/nanobot/channels/msteams/webui/locales/vi.json +++ b/nanobot/channels/msteams/webui/locales/vi.json @@ -1,26 +1,15 @@ { - "description": "Sử dụng nanobot từ các cuộc trò chuyện Microsoft Teams.", - "requirements": "Thông tin xác thực bot Azure và endpoint callback công khai", "setup": { "docsLabel": "Mở hướng dẫn Teams", "officialLabel": "Mở cổng nhà phát triển Teams", - "tryIt": "Cài ứng dụng Teams và gửi tin nhắn thử.", - "summary": "Teams nhận tin nhắn qua URL callback của Bot Framework. Khi triển khai chính thức, cần một địa chỉ HTTPS có thể truy cập từ bên ngoài.", - "steps": [ - "Tạo Azure Bot hoặc ứng dụng Teams và sao chép App ID cùng client secret.", - "Công khai đường dẫn callback qua HTTPS và đặt làm endpoint nhắn tin của bot.", - "Lưu và bật Teams, sau đó cài ứng dụng và gửi tin nhắn thử." - ], "fields": { "appId": { "label": "App ID", - "placeholder": "Microsoft App ID", - "help": "Sao chép từ đăng ký Azure Bot hoặc ứng dụng Teams." + "placeholder": "Microsoft App ID" }, "appPassword": { "label": "Client secret", - "placeholder": "••••••", - "help": "Tạo client secret cho ứng dụng Microsoft." + "placeholder": "••••••" }, "tenantId": { "label": "Tenant ID", @@ -33,6 +22,52 @@ "allowFrom": { "label": "Người dùng được phép", "placeholder": "ID người dùng Teams, phân tách bằng dấu phẩy" + }, + "host": { + "label": "Nghe máy chủ" + }, + "port": { + "label": "Cổng nghe" + }, + "replyInThread": { + "label": "Trả lời trong chủ đề", + "choices": { + "true": "Bật", + "false": "Tắt" + } + }, + "mentionOnlyResponse": { + "label": "Trả lời chỉ đề cập" + }, + "validateInboundAuth": { + "label": "Xác thực các yêu cầu đến", + "choices": { + "true": "Bật", + "false": "Tắt" + } + }, + "refTtlDays": { + "label": "Cuộc trò chuyện trọn đời" + }, + "pruneWebChatRefs": { + "label": "Xóa cuộc hội thoại Trò chuyện trên web", + "choices": { + "true": "Bật", + "false": "Tắt" + } + }, + "pruneNonPersonalRefs": { + "label": "Xóa các cuộc trò chuyện không mang tính cá nhân", + "choices": { + "true": "Bật", + "false": "Tắt" + } + }, + "refTouchIntervalS": { + "label": "Khoảng thời gian làm mới cuộc hội thoại" + }, + "trustedServiceUrlHosts": { + "label": "Máy chủ dịch vụ đáng tin cậy" } } } diff --git a/nanobot/channels/msteams/webui/locales/zh-CN.json b/nanobot/channels/msteams/webui/locales/zh-CN.json index 9b8f46ace..14df1de3b 100644 --- a/nanobot/channels/msteams/webui/locales/zh-CN.json +++ b/nanobot/channels/msteams/webui/locales/zh-CN.json @@ -1,26 +1,15 @@ { - "description": "在 Microsoft Teams 会话中使用 nanobot。", - "requirements": "Azure 机器人应用凭据和公网回调地址", "setup": { "docsLabel": "打开 Teams 配置指南", "officialLabel": "打开 Teams 开发者后台", - "tryIt": "安装 Teams 应用并发送一条测试消息。", - "summary": "Teams 通过 Bot Framework 回调地址接收消息;生产环境需要可访问的 HTTPS 端点。", - "steps": [ - "创建 Azure Bot 或 Teams 应用,并复制 App ID 和客户端密钥。", - "通过 HTTPS 暴露回调路径,并将其设为机器人的消息端点。", - "保存并启用 Teams,然后安装应用并发送一条测试消息。" - ], "fields": { "appId": { "label": "App ID", - "placeholder": "Microsoft App ID", - "help": "从 Azure Bot 或 Teams 应用注册页面复制。" + "placeholder": "Microsoft App ID" }, "appPassword": { "label": "客户端密钥", - "placeholder": "••••••", - "help": "为 Microsoft 应用创建客户端密钥。" + "placeholder": "••••••" }, "tenantId": { "label": "租户 ID", @@ -33,6 +22,52 @@ "allowFrom": { "label": "允许的用户", "placeholder": "Teams 用户 ID,用逗号分隔" + }, + "host": { + "label": "监听地址" + }, + "port": { + "label": "监听端口" + }, + "replyInThread": { + "label": "在话题中回复", + "choices": { + "true": "开启", + "false": "关闭" + } + }, + "mentionOnlyResponse": { + "label": "仅被提及时的回复" + }, + "validateInboundAuth": { + "label": "验证入站请求", + "choices": { + "true": "开启", + "false": "关闭" + } + }, + "refTtlDays": { + "label": "会话保留天数" + }, + "pruneWebChatRefs": { + "label": "清理 Web Chat 会话", + "choices": { + "true": "开启", + "false": "关闭" + } + }, + "pruneNonPersonalRefs": { + "label": "清理非个人会话", + "choices": { + "true": "开启", + "false": "关闭" + } + }, + "refTouchIntervalS": { + "label": "会话刷新间隔" + }, + "trustedServiceUrlHosts": { + "label": "可信服务主机" } } } diff --git a/nanobot/channels/msteams/webui/locales/zh-TW.json b/nanobot/channels/msteams/webui/locales/zh-TW.json index 4f91f1f88..0a786e721 100644 --- a/nanobot/channels/msteams/webui/locales/zh-TW.json +++ b/nanobot/channels/msteams/webui/locales/zh-TW.json @@ -1,26 +1,15 @@ { - "description": "在 Microsoft Teams 對話中使用 nanobot。", - "requirements": "Azure 機器人應用程式憑證和公開回呼端點", "setup": { "docsLabel": "開啟 Teams 設定指南", "officialLabel": "開啟 Teams 開發者後台", - "tryIt": "安裝 Teams 應用程式並傳送一則測試訊息。", - "summary": "Teams 透過 Bot Framework 回呼網址接收訊息;正式環境需要可存取的 HTTPS 端點。", - "steps": [ - "建立 Azure Bot 或 Teams 應用程式,並複製 App ID 和用戶端金鑰。", - "透過 HTTPS 公開回呼路徑,並將其設為機器人的訊息端點。", - "儲存並啟用 Teams,然後安裝應用程式並傳送一則測試訊息。" - ], "fields": { "appId": { "label": "App ID", - "placeholder": "Microsoft App ID", - "help": "從 Azure Bot 或 Teams 應用程式註冊頁面複製。" + "placeholder": "Microsoft App ID" }, "appPassword": { "label": "用戶端金鑰", - "placeholder": "••••••", - "help": "為 Microsoft 應用程式建立用戶端金鑰。" + "placeholder": "••••••" }, "tenantId": { "label": "租用戶 ID", @@ -33,6 +22,52 @@ "allowFrom": { "label": "允許的使用者", "placeholder": "Teams 使用者 ID,以逗號分隔" + }, + "host": { + "label": "監聽地址" + }, + "port": { + "label": "監聽埠" + }, + "replyInThread": { + "label": "在話題中回复", + "choices": { + "true": "開啟", + "false": "關閉" + } + }, + "mentionOnlyResponse": { + "label": "僅被提及時的回复" + }, + "validateInboundAuth": { + "label": "驗證入站請求", + "choices": { + "true": "開啟", + "false": "關閉" + } + }, + "refTtlDays": { + "label": "會話保留天數" + }, + "pruneWebChatRefs": { + "label": "清理 Web Chat 會話", + "choices": { + "true": "開啟", + "false": "關閉" + } + }, + "pruneNonPersonalRefs": { + "label": "清理非個人會話", + "choices": { + "true": "開啟", + "false": "關閉" + } + }, + "refTouchIntervalS": { + "label": "會話刷新間隔" + }, + "trustedServiceUrlHosts": { + "label": "可信任服務主機" } } } diff --git a/nanobot/channels/napcat/manifest.py b/nanobot/channels/napcat/manifest.py index c4923d42f..19f87e9cd 100644 --- a/nanobot/channels/napcat/manifest.py +++ b/nanobot/channels/napcat/manifest.py @@ -10,6 +10,9 @@ SETUP_SPEC = ChannelSetupSpec( "accessToken": field("secret"), "allowFrom": field("list"), "groupPolicy": field("enum", choices=DIRECT_GROUP_POLICIES, default="mention"), + "groupPolicyOverrides": field("json", default={}), + "welcomeNewMembers": field("bool", default=True), + "maxImageBytes": field("int", default=20 * 1024 * 1024), }, required=(required("wsUrl"),), official_url="https://napneko.github.io/", diff --git a/nanobot/channels/napcat/webui/index.ts b/nanobot/channels/napcat/webui/index.ts index 11bfbc21a..22a16202e 100644 --- a/nanobot/channels/napcat/webui/index.ts +++ b/nanobot/channels/napcat/webui/index.ts @@ -3,18 +3,18 @@ import { chatAppGuideUrl } from "@/components/settings/channels/catalog"; export default { presentation: { + logoUrl: "https://napneko.github.io/assets/newnewlogo.png", displayName: "NapCat", initials: "NC", color: "#F97316", - logoUrl: "https://napneko.github.io/favicon.ico", setup: { mode: "credentials", docsUrl: chatAppGuideUrl("napcat"), fields: [ - { key: "channels.napcat.wsUrl" }, - { key: "channels.napcat.accessToken" }, - { key: "channels.napcat.groupPolicy" }, - { key: "channels.napcat.allowFrom" }, + { key: "channels.napcat.wsUrl", section: "connection" }, + { key: "channels.napcat.accessToken", section: "credentials" }, + { key: "channels.napcat.groupPolicy", section: "behavior" }, + { key: "channels.napcat.allowFrom", section: "access" }, ], }, }, diff --git a/nanobot/channels/napcat/webui/locales/en.json b/nanobot/channels/napcat/webui/locales/en.json index 891ca8056..ab719ffae 100644 --- a/nanobot/channels/napcat/webui/locales/en.json +++ b/nanobot/channels/napcat/webui/locales/en.json @@ -1,21 +1,11 @@ { - "description": "Connect nanobot through a NapCat gateway.", - "requirements": "NapCat WebSocket endpoint, optional access token", "setup": { "docsLabel": "Open NapCat setup", "officialLabel": "Open NapCat docs", - "tryIt": "Send a QQ test message through NapCat.", - "summary": "NapCat connects nanobot to QQ through a local or remote OneBot WebSocket endpoint.", - "steps": [ - "Start NapCat and enable a Forward WebSocket service.", - "Copy the WebSocket URL and optional access token into nanobot.", - "Save and enable NapCat, then send a QQ test message." - ], "fields": { "wsUrl": { "label": "WebSocket URL", - "placeholder": "ws://127.0.0.1:3001", - "help": "Use the Forward WebSocket URL from NapCat." + "placeholder": "ws://127.0.0.1:3001" }, "accessToken": { "label": "Access token", @@ -32,6 +22,19 @@ "allowFrom": { "label": "Allowed users", "placeholder": "QQ IDs, comma separated" + }, + "groupPolicyOverrides": { + "label": "Group behavior overrides (JSON)" + }, + "welcomeNewMembers": { + "label": "Welcome new members", + "choices": { + "true": "On", + "false": "Off" + } + }, + "maxImageBytes": { + "label": "Maximum image size" } } } diff --git a/nanobot/channels/napcat/webui/locales/es.json b/nanobot/channels/napcat/webui/locales/es.json index 81b524db2..e27277ab0 100644 --- a/nanobot/channels/napcat/webui/locales/es.json +++ b/nanobot/channels/napcat/webui/locales/es.json @@ -1,21 +1,11 @@ { - "description": "Conecta nanobot mediante una pasarela NapCat.", - "requirements": "Endpoint WebSocket de NapCat y token de acceso opcional", "setup": { "docsLabel": "Abrir guía de NapCat", "officialLabel": "Abrir documentación de NapCat", - "tryIt": "Envía un mensaje de prueba de QQ mediante NapCat.", - "summary": "NapCat conecta nanobot con QQ mediante un endpoint WebSocket OneBot local o remoto.", - "steps": [ - "Inicia NapCat y activa un servicio Forward WebSocket.", - "Copia la URL WebSocket y el token opcional en nanobot.", - "Guarda y activa NapCat; después envía un mensaje de prueba de QQ." - ], "fields": { "wsUrl": { "label": "URL WebSocket", - "placeholder": "ws://127.0.0.1:3001", - "help": "Usa la URL Forward WebSocket de NapCat." + "placeholder": "ws://127.0.0.1:3001" }, "accessToken": { "label": "Token de acceso", @@ -32,6 +22,19 @@ "allowFrom": { "label": "Usuarios permitidos", "placeholder": "ID de QQ separados por comas" + }, + "groupPolicyOverrides": { + "label": "Anulaciones de comportamiento de grupo (JSON)" + }, + "welcomeNewMembers": { + "label": "Bienvenidos nuevos miembros", + "choices": { + "true": "encendido", + "false": "Apagado" + } + }, + "maxImageBytes": { + "label": "Tamaño máximo de imagen" } } } diff --git a/nanobot/channels/napcat/webui/locales/fr.json b/nanobot/channels/napcat/webui/locales/fr.json index 48cf18149..fff3055b1 100644 --- a/nanobot/channels/napcat/webui/locales/fr.json +++ b/nanobot/channels/napcat/webui/locales/fr.json @@ -1,21 +1,11 @@ { - "description": "Connectez nanobot via une passerelle NapCat.", - "requirements": "Endpoint WebSocket NapCat et jeton d’accès facultatif", "setup": { "docsLabel": "Ouvrir le guide NapCat", "officialLabel": "Ouvrir la documentation NapCat", - "tryIt": "Envoyez un message test QQ via NapCat.", - "summary": "NapCat relie nanobot à QQ via un endpoint WebSocket OneBot local ou distant.", - "steps": [ - "Démarrez NapCat et activez un service Forward WebSocket.", - "Copiez l’URL WebSocket et le jeton facultatif dans nanobot.", - "Enregistrez et activez NapCat, puis envoyez un message test QQ." - ], "fields": { "wsUrl": { "label": "URL WebSocket", - "placeholder": "ws://127.0.0.1:3001", - "help": "Utilisez l’URL Forward WebSocket de NapCat." + "placeholder": "ws://127.0.0.1:3001" }, "accessToken": { "label": "Jeton d’accès", @@ -32,6 +22,19 @@ "allowFrom": { "label": "Utilisateurs autorisés", "placeholder": "ID QQ séparés par des virgules" + }, + "groupPolicyOverrides": { + "label": "Remplacements de comportement de groupe (JSON)" + }, + "welcomeNewMembers": { + "label": "Bienvenue aux nouveaux membres", + "choices": { + "true": "Sur", + "false": "Désactivé" + } + }, + "maxImageBytes": { + "label": "Taille maximale de l'image" } } } diff --git a/nanobot/channels/napcat/webui/locales/id.json b/nanobot/channels/napcat/webui/locales/id.json index 94ab438b1..40fafb91b 100644 --- a/nanobot/channels/napcat/webui/locales/id.json +++ b/nanobot/channels/napcat/webui/locales/id.json @@ -1,21 +1,11 @@ { - "description": "Hubungkan nanobot melalui gateway NapCat.", - "requirements": "Endpoint WebSocket NapCat dan token akses opsional", "setup": { "docsLabel": "Buka panduan NapCat", "officialLabel": "Buka dokumentasi NapCat", - "tryIt": "Kirim pesan uji QQ melalui NapCat.", - "summary": "NapCat menghubungkan nanobot ke QQ melalui endpoint OneBot WebSocket lokal atau jarak jauh.", - "steps": [ - "Mulai NapCat dan aktifkan layanan Forward WebSocket.", - "Salin URL WebSocket dan token opsional ke nanobot.", - "Simpan dan aktifkan NapCat, lalu kirim pesan uji QQ." - ], "fields": { "wsUrl": { "label": "URL WebSocket", - "placeholder": "ws://127.0.0.1:3001", - "help": "Gunakan URL Forward WebSocket dari NapCat." + "placeholder": "ws://127.0.0.1:3001" }, "accessToken": { "label": "Token akses", @@ -32,6 +22,19 @@ "allowFrom": { "label": "Pengguna yang diizinkan", "placeholder": "ID QQ, dipisahkan koma" + }, + "groupPolicyOverrides": { + "label": "Penggantian perilaku grup (JSON)" + }, + "welcomeNewMembers": { + "label": "Selamat datang anggota baru", + "choices": { + "true": "Aktif", + "false": "Mati" + } + }, + "maxImageBytes": { + "label": "Ukuran gambar maksimum" } } } diff --git a/nanobot/channels/napcat/webui/locales/ja.json b/nanobot/channels/napcat/webui/locales/ja.json index bf187ccfc..bb7b3c2ee 100644 --- a/nanobot/channels/napcat/webui/locales/ja.json +++ b/nanobot/channels/napcat/webui/locales/ja.json @@ -1,21 +1,11 @@ { - "description": "NapCat ゲートウェイ経由で nanobot を接続します。", - "requirements": "NapCat WebSocket エンドポイントと任意のアクセストークン", "setup": { "docsLabel": "NapCat 設定ガイドを開く", "officialLabel": "NapCat ドキュメントを開く", - "tryIt": "NapCat 経由で QQ のテストメッセージを送信します。", - "summary": "NapCat はローカルまたはリモートの OneBot WebSocket で nanobot を QQ に接続します。", - "steps": [ - "NapCat を起動し、Forward WebSocket サービスを有効にします。", - "WebSocket URL を nanobot にコピーします。アクセストークンを設定している場合は、あわせて入力してください。", - "保存して NapCat を有効にし、QQ のテストメッセージを送信します。" - ], "fields": { "wsUrl": { "label": "WebSocket URL", - "placeholder": "ws://127.0.0.1:3001", - "help": "NapCat の Forward WebSocket URL を使います。" + "placeholder": "ws://127.0.0.1:3001" }, "accessToken": { "label": "アクセストークン", @@ -32,6 +22,19 @@ "allowFrom": { "label": "許可するユーザー", "placeholder": "QQ ID(カンマ区切り)" + }, + "groupPolicyOverrides": { + "label": "グループ動作のオーバーライド (JSON)" + }, + "welcomeNewMembers": { + "label": "新しいメンバーを歓迎します", + "choices": { + "true": "オン", + "false": "オフ" + } + }, + "maxImageBytes": { + "label": "最大画像サイズ" } } } diff --git a/nanobot/channels/napcat/webui/locales/ko.json b/nanobot/channels/napcat/webui/locales/ko.json index cc3849f42..68ae78cb3 100644 --- a/nanobot/channels/napcat/webui/locales/ko.json +++ b/nanobot/channels/napcat/webui/locales/ko.json @@ -1,21 +1,11 @@ { - "description": "NapCat 게이트웨이를 통해 nanobot을 연결합니다.", - "requirements": "NapCat WebSocket 엔드포인트 및 선택적 액세스 토큰", "setup": { "docsLabel": "NapCat 설정 가이드 열기", "officialLabel": "NapCat 문서 열기", - "tryIt": "NapCat을 통해 QQ 테스트 메시지를 보내세요.", - "summary": "NapCat은 로컬 또는 원격 OneBot WebSocket으로 nanobot을 QQ에 연결합니다.", - "steps": [ - "NapCat을 시작하고 Forward WebSocket 서비스를 활성화하세요.", - "WebSocket URL을 nanobot에 복사하세요. 액세스 토큰을 설정했다면 함께 입력하세요.", - "저장하고 NapCat을 활성화한 다음 QQ 테스트 메시지를 보내세요." - ], "fields": { "wsUrl": { "label": "WebSocket URL", - "placeholder": "ws://127.0.0.1:3001", - "help": "NapCat의 Forward WebSocket URL을 사용하세요." + "placeholder": "ws://127.0.0.1:3001" }, "accessToken": { "label": "액세스 토큰", @@ -32,6 +22,19 @@ "allowFrom": { "label": "허용된 사용자", "placeholder": "QQ ID, 쉼표로 구분" + }, + "groupPolicyOverrides": { + "label": "그룹 동작 재정의(JSON)" + }, + "welcomeNewMembers": { + "label": "새로운 회원을 환영합니다", + "choices": { + "true": "켜기", + "false": "끄기" + } + }, + "maxImageBytes": { + "label": "최대 이미지 크기" } } } diff --git a/nanobot/channels/napcat/webui/locales/pt-BR.json b/nanobot/channels/napcat/webui/locales/pt-BR.json index 99ecc278d..e0b61014c 100644 --- a/nanobot/channels/napcat/webui/locales/pt-BR.json +++ b/nanobot/channels/napcat/webui/locales/pt-BR.json @@ -1,21 +1,11 @@ { - "description": "Conecte o nanobot por um gateway NapCat.", - "requirements": "Endpoint WebSocket do NapCat e token de acesso opcional", "setup": { "docsLabel": "Abrir guia do NapCat", "officialLabel": "Abrir documentação do NapCat", - "tryIt": "Envie uma mensagem de teste do QQ pelo NapCat.", - "summary": "O NapCat conecta o nanobot ao QQ por um endpoint WebSocket OneBot local ou remoto.", - "steps": [ - "Inicie o NapCat e ative um serviço Forward WebSocket.", - "Copie a URL WebSocket e o token opcional para o nanobot.", - "Salve e ative o NapCat; depois, envie uma mensagem de teste do QQ." - ], "fields": { "wsUrl": { "label": "URL WebSocket", - "placeholder": "ws://127.0.0.1:3001", - "help": "Use a URL Forward WebSocket do NapCat." + "placeholder": "ws://127.0.0.1:3001" }, "accessToken": { "label": "Token de acesso", @@ -32,6 +22,19 @@ "allowFrom": { "label": "Usuários permitidos", "placeholder": "IDs do QQ separados por vírgulas" + }, + "groupPolicyOverrides": { + "label": "Substituições de comportamento de grupo (JSON)" + }, + "welcomeNewMembers": { + "label": "Bem vindos novos membros", + "choices": { + "true": "Ligado", + "false": "Desligado" + } + }, + "maxImageBytes": { + "label": "Tamanho máximo da imagem" } } } diff --git a/nanobot/channels/napcat/webui/locales/vi.json b/nanobot/channels/napcat/webui/locales/vi.json index e1a182925..3e2279724 100644 --- a/nanobot/channels/napcat/webui/locales/vi.json +++ b/nanobot/channels/napcat/webui/locales/vi.json @@ -1,21 +1,11 @@ { - "description": "Kết nối nanobot qua gateway NapCat.", - "requirements": "Endpoint WebSocket NapCat và token truy cập tùy chọn", "setup": { "docsLabel": "Mở hướng dẫn NapCat", "officialLabel": "Mở tài liệu NapCat", - "tryIt": "Gửi tin nhắn thử QQ qua NapCat.", - "summary": "NapCat kết nối nanobot với QQ qua endpoint OneBot WebSocket cục bộ hoặc từ xa.", - "steps": [ - "Khởi động NapCat và bật dịch vụ Forward WebSocket.", - "Sao chép URL WebSocket và token tùy chọn vào nanobot.", - "Lưu và bật NapCat, sau đó gửi tin nhắn thử QQ." - ], "fields": { "wsUrl": { "label": "URL WebSocket", - "placeholder": "ws://127.0.0.1:3001", - "help": "Dùng URL Forward WebSocket từ NapCat." + "placeholder": "ws://127.0.0.1:3001" }, "accessToken": { "label": "Token truy cập", @@ -32,6 +22,19 @@ "allowFrom": { "label": "Người dùng được phép", "placeholder": "ID QQ, phân tách bằng dấu phẩy" + }, + "groupPolicyOverrides": { + "label": "Ghi đè hành vi nhóm (JSON)" + }, + "welcomeNewMembers": { + "label": "Chào mừng thành viên mới", + "choices": { + "true": "Bật", + "false": "Tắt" + } + }, + "maxImageBytes": { + "label": "Kích thước hình ảnh tối đa" } } } diff --git a/nanobot/channels/napcat/webui/locales/zh-CN.json b/nanobot/channels/napcat/webui/locales/zh-CN.json index f9c3f7da0..dd50823e4 100644 --- a/nanobot/channels/napcat/webui/locales/zh-CN.json +++ b/nanobot/channels/napcat/webui/locales/zh-CN.json @@ -1,21 +1,11 @@ { - "description": "通过 NapCat 网关连接 nanobot。", - "requirements": "NapCat WebSocket 地址和可选访问令牌", "setup": { "docsLabel": "打开 NapCat 配置指南", "officialLabel": "打开 NapCat 文档", - "tryIt": "通过 NapCat 发送一条 QQ 测试消息。", - "summary": "NapCat 通过本地或远程 OneBot WebSocket 地址将 nanobot 连接到 QQ。", - "steps": [ - "启动 NapCat 并启用正向 WebSocket 服务。", - "将 WebSocket 地址和可选访问令牌复制到 nanobot。", - "保存并启用 NapCat,然后发送一条 QQ 测试消息。" - ], "fields": { "wsUrl": { "label": "WebSocket 地址", - "placeholder": "ws://127.0.0.1:3001", - "help": "使用 NapCat 的正向 WebSocket 地址。" + "placeholder": "ws://127.0.0.1:3001" }, "accessToken": { "label": "访问令牌", @@ -32,6 +22,19 @@ "allowFrom": { "label": "允许的用户", "placeholder": "QQ ID,用逗号分隔" + }, + "groupPolicyOverrides": { + "label": "群组行为覆盖(JSON)" + }, + "welcomeNewMembers": { + "label": "欢迎新成员", + "choices": { + "true": "开启", + "false": "关闭" + } + }, + "maxImageBytes": { + "label": "图片大小上限" } } } diff --git a/nanobot/channels/napcat/webui/locales/zh-TW.json b/nanobot/channels/napcat/webui/locales/zh-TW.json index b44ab07fb..0433b580d 100644 --- a/nanobot/channels/napcat/webui/locales/zh-TW.json +++ b/nanobot/channels/napcat/webui/locales/zh-TW.json @@ -1,21 +1,11 @@ { - "description": "透過 NapCat 閘道連接 nanobot。", - "requirements": "NapCat WebSocket 網址和選填存取權杖", "setup": { "docsLabel": "開啟 NapCat 設定指南", "officialLabel": "開啟 NapCat 文件", - "tryIt": "透過 NapCat 傳送一則 QQ 測試訊息。", - "summary": "NapCat 透過本機或遠端 OneBot WebSocket 網址將 nanobot 連接到 QQ。", - "steps": [ - "啟動 NapCat 並啟用正向 WebSocket 服務。", - "將 WebSocket 網址和選填存取權杖複製到 nanobot。", - "儲存並啟用 NapCat,然後傳送一則 QQ 測試訊息。" - ], "fields": { "wsUrl": { "label": "WebSocket 網址", - "placeholder": "ws://127.0.0.1:3001", - "help": "使用 NapCat 的正向 WebSocket 網址。" + "placeholder": "ws://127.0.0.1:3001" }, "accessToken": { "label": "存取權杖", @@ -32,6 +22,19 @@ "allowFrom": { "label": "允許的使用者", "placeholder": "QQ ID,以逗號分隔" + }, + "groupPolicyOverrides": { + "label": "群组行为覆盖(JSON)" + }, + "welcomeNewMembers": { + "label": "歡迎新成員", + "choices": { + "true": "開啟", + "false": "關閉" + } + }, + "maxImageBytes": { + "label": "圖片大小上限" } } } diff --git a/nanobot/channels/qq/manifest.py b/nanobot/channels/qq/manifest.py index f5b053475..a3e6cf093 100644 --- a/nanobot/channels/qq/manifest.py +++ b/nanobot/channels/qq/manifest.py @@ -10,6 +10,10 @@ SETUP_SPEC = ChannelSetupSpec( "secret": field("secret"), "allowFrom": field("list"), "msgFormat": field("enum", choices={"plain", "markdown"}, default="plain"), + "ackMessage": field(default="⏳ Processing..."), + "mediaDir": field(), + "downloadChunkSize": field("int", default=1024 * 256), + "downloadMaxBytes": field("int", default=1024 * 1024 * 200), }, required=required_fields("appId", "secret"), official_url="https://q.qq.com/", diff --git a/nanobot/channels/qq/webui/index.ts b/nanobot/channels/qq/webui/index.ts index 8221659c2..0ddf9a6c7 100644 --- a/nanobot/channels/qq/webui/index.ts +++ b/nanobot/channels/qq/webui/index.ts @@ -3,18 +3,18 @@ import { chatAppGuideUrl } from "@/components/settings/channels/catalog"; export default { presentation: { + logoUrl: "https://im.qq.com/favicon.ico", displayName: "QQ", initials: "QQ", color: "#12B7F5", - logoUrl: "https://im.qq.com/favicon.ico", setup: { mode: "credentials", docsUrl: chatAppGuideUrl("qq"), fields: [ - { key: "channels.qq.appId" }, - { key: "channels.qq.secret" }, - { key: "channels.qq.allowFrom" }, - { key: "channels.qq.msgFormat" }, + { key: "channels.qq.appId", section: "credentials" }, + { key: "channels.qq.secret", section: "credentials" }, + { key: "channels.qq.allowFrom", section: "access" }, + { key: "channels.qq.msgFormat", section: "behavior" }, ], }, }, diff --git a/nanobot/channels/qq/webui/locales/en.json b/nanobot/channels/qq/webui/locales/en.json index 04310efd3..cb426f104 100644 --- a/nanobot/channels/qq/webui/locales/en.json +++ b/nanobot/channels/qq/webui/locales/en.json @@ -1,26 +1,15 @@ { - "description": "Use nanobot from QQ chats.", - "requirements": "QQ bot credentials and gateway", "setup": { "docsLabel": "Open QQ setup", "officialLabel": "Open QQ bot console", - "tryIt": "Send a direct or group test message from QQ.", - "summary": "QQ uses official bot credentials and a persistent WebSocket connection.", - "steps": [ - "Create a bot in QQ Open Platform and copy its App ID and Secret.", - "Choose the message format and optional sender allowlist.", - "Save and enable QQ, then send a direct or group test message." - ], "fields": { "appId": { "label": "App ID", - "placeholder": "QQ bot app ID", - "help": "Copy it from QQ Open Platform." + "placeholder": "QQ bot app ID" }, "secret": { "label": "Secret", - "placeholder": "••••••", - "help": "Save this before leaving the QQ credentials page." + "placeholder": "••••••" }, "allowFrom": { "label": "Allowed users", @@ -32,6 +21,18 @@ "plain": "Plain text", "markdown": "Markdown" } + }, + "ackMessage": { + "label": "Acknowledgement message" + }, + "mediaDir": { + "label": "Media directory" + }, + "downloadChunkSize": { + "label": "Download chunk size" + }, + "downloadMaxBytes": { + "label": "Maximum download size" } } } diff --git a/nanobot/channels/qq/webui/locales/es.json b/nanobot/channels/qq/webui/locales/es.json index 1c851c629..0d2f1d528 100644 --- a/nanobot/channels/qq/webui/locales/es.json +++ b/nanobot/channels/qq/webui/locales/es.json @@ -1,26 +1,15 @@ { - "description": "Usa nanobot desde chats de QQ.", - "requirements": "Credenciales del bot de QQ y pasarela", "setup": { "docsLabel": "Abrir guía de QQ", "officialLabel": "Abrir consola del bot de QQ", - "tryIt": "Envía un mensaje de prueba directo o grupal desde QQ.", - "summary": "QQ usa las credenciales oficiales del bot y una conexión WebSocket persistente.", - "steps": [ - "Crea un bot en QQ Open Platform y copia su App ID y Secret.", - "Elige el formato de mensajes y la lista opcional de remitentes.", - "Guarda y activa QQ; después envía un mensaje de prueba directo o grupal." - ], "fields": { "appId": { "label": "App ID", - "placeholder": "App ID del bot de QQ", - "help": "Cópialo de QQ Open Platform." + "placeholder": "App ID del bot de QQ" }, "secret": { "label": "Secret", - "placeholder": "••••••", - "help": "Guárdalo antes de salir de la página de credenciales de QQ." + "placeholder": "••••••" }, "allowFrom": { "label": "Usuarios permitidos", @@ -32,6 +21,18 @@ "plain": "Texto sin formato", "markdown": "Markdown" } + }, + "ackMessage": { + "label": "Mensaje de reconocimiento" + }, + "mediaDir": { + "label": "Directorio de medios" + }, + "downloadChunkSize": { + "label": "Descargar tamaño de fragmento" + }, + "downloadMaxBytes": { + "label": "Tamaño máximo de descarga" } } } diff --git a/nanobot/channels/qq/webui/locales/fr.json b/nanobot/channels/qq/webui/locales/fr.json index 79256cb3a..bf9d51b36 100644 --- a/nanobot/channels/qq/webui/locales/fr.json +++ b/nanobot/channels/qq/webui/locales/fr.json @@ -1,26 +1,15 @@ { - "description": "Utilisez nanobot depuis les conversations QQ.", - "requirements": "Identifiants du bot QQ et passerelle", "setup": { "docsLabel": "Ouvrir le guide QQ", "officialLabel": "Ouvrir la console du bot QQ", - "tryIt": "Envoyez un message test privé ou de groupe depuis QQ.", - "summary": "QQ utilise les identifiants officiels du bot et une connexion WebSocket persistante.", - "steps": [ - "Créez un bot sur QQ Open Platform et copiez son App ID et son Secret.", - "Choisissez le format des messages et la liste d’expéditeurs facultative.", - "Enregistrez et activez QQ, puis envoyez un message test privé ou de groupe." - ], "fields": { "appId": { "label": "App ID", - "placeholder": "App ID du bot QQ", - "help": "Copiez-le depuis QQ Open Platform." + "placeholder": "App ID du bot QQ" }, "secret": { "label": "Secret", - "placeholder": "••••••", - "help": "Enregistrez-le avant de quitter la page des identifiants QQ." + "placeholder": "••••••" }, "allowFrom": { "label": "Utilisateurs autorisés", @@ -32,6 +21,18 @@ "plain": "Texte brut", "markdown": "Markdown" } + }, + "ackMessage": { + "label": "Message d'accusé de réception" + }, + "mediaDir": { + "label": "Répertoire des médias" + }, + "downloadChunkSize": { + "label": "Taille du morceau de téléchargement" + }, + "downloadMaxBytes": { + "label": "Taille maximale de téléchargement" } } } diff --git a/nanobot/channels/qq/webui/locales/id.json b/nanobot/channels/qq/webui/locales/id.json index 0d8552ebd..0641dc835 100644 --- a/nanobot/channels/qq/webui/locales/id.json +++ b/nanobot/channels/qq/webui/locales/id.json @@ -1,26 +1,15 @@ { - "description": "Gunakan nanobot dari chat QQ.", - "requirements": "Kredensial bot QQ dan gateway", "setup": { "docsLabel": "Buka panduan QQ", "officialLabel": "Buka konsol bot QQ", - "tryIt": "Kirim pesan uji langsung atau grup dari QQ.", - "summary": "QQ menggunakan kredensial bot resmi dan koneksi WebSocket persisten.", - "steps": [ - "Buat bot di QQ Open Platform dan salin App ID serta Secret.", - "Pilih format pesan dan daftar pengirim opsional.", - "Simpan dan aktifkan QQ, lalu kirim pesan uji langsung atau grup." - ], "fields": { "appId": { "label": "App ID", - "placeholder": "App ID bot QQ", - "help": "Salin dari QQ Open Platform." + "placeholder": "App ID bot QQ" }, "secret": { "label": "Secret", - "placeholder": "••••••", - "help": "Simpan sebelum meninggalkan halaman kredensial QQ." + "placeholder": "••••••" }, "allowFrom": { "label": "Pengguna yang diizinkan", @@ -32,6 +21,18 @@ "plain": "Teks biasa", "markdown": "Markdown" } + }, + "ackMessage": { + "label": "Pesan pengakuan" + }, + "mediaDir": { + "label": "Direktori media" + }, + "downloadChunkSize": { + "label": "Unduh ukuran potongan" + }, + "downloadMaxBytes": { + "label": "Ukuran unduhan maksimum" } } } diff --git a/nanobot/channels/qq/webui/locales/ja.json b/nanobot/channels/qq/webui/locales/ja.json index 3bdb587cf..2efeba43b 100644 --- a/nanobot/channels/qq/webui/locales/ja.json +++ b/nanobot/channels/qq/webui/locales/ja.json @@ -1,26 +1,15 @@ { - "description": "QQ チャットから nanobot を利用します。", - "requirements": "QQ ボットの認証情報とゲートウェイ", "setup": { "docsLabel": "QQ 設定ガイドを開く", "officialLabel": "QQ ボットコンソールを開く", - "tryIt": "QQ から個人またはグループのテストメッセージを送信します。", - "summary": "QQ は公式ボット認証情報と常時接続の WebSocket を使用します。", - "steps": [ - "QQ Open Platform でボットを作成し、App ID と Secret をコピーします。", - "メッセージ形式と任意の送信者許可リストを選びます。", - "保存して QQ を有効にし、個人またはグループのテストメッセージを送信します。" - ], "fields": { "appId": { "label": "App ID", - "placeholder": "QQ ボット App ID", - "help": "QQ Open Platform からコピーします。" + "placeholder": "QQ ボット App ID" }, "secret": { "label": "Secret", - "placeholder": "••••••", - "help": "QQ の認証情報ページを離れる前に保存してください。" + "placeholder": "••••••" }, "allowFrom": { "label": "許可するユーザー", @@ -32,6 +21,18 @@ "plain": "プレーンテキスト", "markdown": "Markdown" } + }, + "ackMessage": { + "label": "確認メッセージ" + }, + "mediaDir": { + "label": "メディアディレクトリ" + }, + "downloadChunkSize": { + "label": "ダウンロードチャンクサイズ" + }, + "downloadMaxBytes": { + "label": "最大ダウンロードサイズ" } } } diff --git a/nanobot/channels/qq/webui/locales/ko.json b/nanobot/channels/qq/webui/locales/ko.json index ff84f890a..228f604d8 100644 --- a/nanobot/channels/qq/webui/locales/ko.json +++ b/nanobot/channels/qq/webui/locales/ko.json @@ -1,26 +1,15 @@ { - "description": "QQ 채팅에서 nanobot을 사용합니다.", - "requirements": "QQ 봇 인증 정보 및 게이트웨이", "setup": { "docsLabel": "QQ 설정 가이드 열기", "officialLabel": "QQ 봇 콘솔 열기", - "tryIt": "QQ에서 개인 또는 그룹 테스트 메시지를 보내세요.", - "summary": "QQ는 공식 봇 인증 정보과 지속적인 WebSocket 연결을 사용합니다.", - "steps": [ - "QQ Open Platform에서 봇을 만들고 App ID와 Secret을 복사하세요.", - "메시지 형식과 선택적 발신자 허용 목록을 고르세요.", - "저장하고 QQ를 활성화한 다음 개인 또는 그룹 테스트 메시지를 보내세요." - ], "fields": { "appId": { "label": "App ID", - "placeholder": "QQ 봇 App ID", - "help": "QQ Open Platform에서 복사하세요." + "placeholder": "QQ 봇 App ID" }, "secret": { "label": "Secret", - "placeholder": "••••••", - "help": "QQ 인증 정보 페이지를 떠나기 전에 저장하세요." + "placeholder": "••••••" }, "allowFrom": { "label": "허용된 사용자", @@ -32,6 +21,18 @@ "plain": "일반 텍스트", "markdown": "Markdown" } + }, + "ackMessage": { + "label": "확인 메시지" + }, + "mediaDir": { + "label": "미디어 디렉토리" + }, + "downloadChunkSize": { + "label": "청크 크기 다운로드" + }, + "downloadMaxBytes": { + "label": "최대 다운로드 크기" } } } diff --git a/nanobot/channels/qq/webui/locales/pt-BR.json b/nanobot/channels/qq/webui/locales/pt-BR.json index 026509f56..442a330c8 100644 --- a/nanobot/channels/qq/webui/locales/pt-BR.json +++ b/nanobot/channels/qq/webui/locales/pt-BR.json @@ -1,26 +1,15 @@ { - "description": "Use o nanobot em conversas do QQ.", - "requirements": "Credenciais do bot QQ e gateway", "setup": { "docsLabel": "Abrir guia do QQ", "officialLabel": "Abrir console do bot QQ", - "tryIt": "Envie uma mensagem de teste direta ou em grupo pelo QQ.", - "summary": "O QQ usa credenciais oficiais do bot e uma conexão WebSocket persistente.", - "steps": [ - "Crie um bot no QQ Open Platform e copie o App ID e o Secret.", - "Escolha o formato das mensagens e a lista opcional de remetentes.", - "Salve e ative o QQ; depois, envie uma mensagem de teste direta ou em grupo." - ], "fields": { "appId": { "label": "App ID", - "placeholder": "App ID do bot QQ", - "help": "Copie do QQ Open Platform." + "placeholder": "App ID do bot QQ" }, "secret": { "label": "Secret", - "placeholder": "••••••", - "help": "Salve antes de sair da página de credenciais do QQ." + "placeholder": "••••••" }, "allowFrom": { "label": "Usuários permitidos", @@ -32,6 +21,18 @@ "plain": "Texto simples", "markdown": "Markdown" } + }, + "ackMessage": { + "label": "Mensagem de confirmação" + }, + "mediaDir": { + "label": "Diretório de mídia" + }, + "downloadChunkSize": { + "label": "Baixar tamanho do pedaço" + }, + "downloadMaxBytes": { + "label": "Tamanho máximo de download" } } } diff --git a/nanobot/channels/qq/webui/locales/vi.json b/nanobot/channels/qq/webui/locales/vi.json index 5567666e7..18e84e154 100644 --- a/nanobot/channels/qq/webui/locales/vi.json +++ b/nanobot/channels/qq/webui/locales/vi.json @@ -1,26 +1,15 @@ { - "description": "Sử dụng nanobot từ các cuộc trò chuyện QQ.", - "requirements": "Thông tin xác thực bot QQ và gateway", "setup": { "docsLabel": "Mở hướng dẫn QQ", "officialLabel": "Mở bảng điều khiển bot QQ", - "tryIt": "Gửi tin nhắn thử riêng hoặc nhóm từ QQ.", - "summary": "QQ dùng thông tin xác thực bot chính thức và kết nối WebSocket lâu dài.", - "steps": [ - "Tạo bot trên QQ Open Platform và sao chép App ID cùng Secret.", - "Chọn định dạng tin nhắn và danh sách người gửi tùy chọn.", - "Lưu và bật QQ, sau đó gửi tin nhắn thử riêng hoặc nhóm." - ], "fields": { "appId": { "label": "App ID", - "placeholder": "App ID bot QQ", - "help": "Sao chép từ QQ Open Platform." + "placeholder": "App ID bot QQ" }, "secret": { "label": "Secret", - "placeholder": "••••••", - "help": "Lưu trước khi rời trang thông tin xác thực QQ." + "placeholder": "••••••" }, "allowFrom": { "label": "Người dùng được phép", @@ -32,6 +21,18 @@ "plain": "Văn bản thuần", "markdown": "Markdown" } + }, + "ackMessage": { + "label": "Thông báo xác nhận" + }, + "mediaDir": { + "label": "Thư mục phương tiện" + }, + "downloadChunkSize": { + "label": "Kích thước khối tải xuống" + }, + "downloadMaxBytes": { + "label": "Kích thước tải xuống tối đa" } } } diff --git a/nanobot/channels/qq/webui/locales/zh-CN.json b/nanobot/channels/qq/webui/locales/zh-CN.json index 3c065ade5..a1edc5f37 100644 --- a/nanobot/channels/qq/webui/locales/zh-CN.json +++ b/nanobot/channels/qq/webui/locales/zh-CN.json @@ -1,26 +1,15 @@ { - "description": "在 QQ 会话中使用 nanobot。", - "requirements": "QQ 机器人凭据和网关", "setup": { "docsLabel": "打开 QQ 配置指南", "officialLabel": "打开 QQ 机器人后台", - "tryIt": "从 QQ 发送一条私聊或群聊测试消息。", - "summary": "QQ 使用官方机器人凭据,通过 WebSocket 长连接收发消息。", - "steps": [ - "在 QQ 开放平台创建机器人并复制 App ID 和 Secret。", - "选择消息格式和可选的发送者白名单。", - "保存并启用 QQ,然后发送一条私聊或群聊测试消息。" - ], "fields": { "appId": { "label": "App ID", - "placeholder": "QQ 机器人 App ID", - "help": "从 QQ 开放平台复制。" + "placeholder": "QQ 机器人 App ID" }, "secret": { "label": "Secret", - "placeholder": "••••••", - "help": "离开 QQ 凭据页面前请妥善保存。" + "placeholder": "••••••" }, "allowFrom": { "label": "允许的用户", @@ -32,6 +21,18 @@ "plain": "纯文本", "markdown": "Markdown" } + }, + "ackMessage": { + "label": "处理中提示" + }, + "mediaDir": { + "label": "媒体目录" + }, + "downloadChunkSize": { + "label": "下载分块大小" + }, + "downloadMaxBytes": { + "label": "下载大小上限" } } } diff --git a/nanobot/channels/qq/webui/locales/zh-TW.json b/nanobot/channels/qq/webui/locales/zh-TW.json index b6932f020..c3f8a698a 100644 --- a/nanobot/channels/qq/webui/locales/zh-TW.json +++ b/nanobot/channels/qq/webui/locales/zh-TW.json @@ -1,26 +1,15 @@ { - "description": "在 QQ 對話中使用 nanobot。", - "requirements": "QQ 機器人憑證和閘道", "setup": { "docsLabel": "開啟 QQ 設定指南", "officialLabel": "開啟 QQ 機器人後台", - "tryIt": "從 QQ 傳送一則私聊或群聊測試訊息。", - "summary": "QQ 使用官方機器人憑證和 WebSocket 長連線。", - "steps": [ - "在 QQ 開放平台建立機器人並複製 App ID 和 Secret。", - "選擇訊息格式和選填的傳送者允許清單。", - "儲存並啟用 QQ,然後傳送一則私聊或群聊測試訊息。" - ], "fields": { "appId": { "label": "App ID", - "placeholder": "QQ 機器人 App ID", - "help": "從 QQ 開放平台複製。" + "placeholder": "QQ 機器人 App ID" }, "secret": { "label": "Secret", - "placeholder": "••••••", - "help": "離開 QQ 憑證頁面前請妥善儲存。" + "placeholder": "••••••" }, "allowFrom": { "label": "允許的使用者", @@ -32,6 +21,18 @@ "plain": "純文字", "markdown": "Markdown" } + }, + "ackMessage": { + "label": "處理中提示" + }, + "mediaDir": { + "label": "媒體目錄" + }, + "downloadChunkSize": { + "label": "下載分塊大小" + }, + "downloadMaxBytes": { + "label": "下載大小上限" } } } diff --git a/nanobot/channels/signal/manifest.py b/nanobot/channels/signal/manifest.py index 3beddfd2f..ff41af082 100644 --- a/nanobot/channels/signal/manifest.py +++ b/nanobot/channels/signal/manifest.py @@ -11,6 +11,13 @@ SETUP_SPEC = ChannelSetupSpec( "daemonPort": field("int", default=8080), "dm.allowFrom": field("list"), "group.allowFrom": field("list"), + "groupMessageBufferSize": field("int", default=20), + "attachmentsDir": field(), + "dm.enabled": field("bool", default=True), + "dm.policy": field("enum", choices={"open", "allowlist"}, default="allowlist"), + "group.enabled": field("bool", default=False), + "group.policy": field("enum", choices={"open", "allowlist"}, default="allowlist"), + "group.requireMention": field("bool", default=True), }, required=(required("phoneNumber"),), official_url="https://github.com/bbernhard/signal-cli-rest-api", diff --git a/nanobot/channels/signal/runtime.py b/nanobot/channels/signal/runtime.py index 18bebc6f3..1235ce5fe 100644 --- a/nanobot/channels/signal/runtime.py +++ b/nanobot/channels/signal/runtime.py @@ -301,7 +301,7 @@ def _partition_styles( class SignalDMConfig(Base): """Signal DM policy configuration.""" - enabled: bool = False + enabled: bool = True policy: str = "allowlist" # "open" or "allowlist" allow_from: list[str] = Field(default_factory=list) # Allowed phone numbers/UUIDs diff --git a/nanobot/channels/signal/tests/test_signal_channel.py b/nanobot/channels/signal/tests/test_signal_channel.py index ff9ddcacf..58b59dcff 100644 --- a/nanobot/channels/signal/tests/test_signal_channel.py +++ b/nanobot/channels/signal/tests/test_signal_channel.py @@ -1508,6 +1508,15 @@ async def test_handle_notification_no_source_skipped() -> None: # --------------------------------------------------------------------------- +def test_default_config_enables_private_dms_with_pairing() -> None: + config = SignalConfig(phone_number="+10000000000") + + assert config.dm.enabled is True + assert config.dm.policy == "allowlist" + assert config.dm.allow_from == [] + assert config.group.enabled is False + + def test_config_allow_from_aggregates_dm_and_group() -> None: config = SignalConfig( enabled=True, diff --git a/nanobot/channels/signal/webui/index.ts b/nanobot/channels/signal/webui/index.ts index 76c9a28bd..26aeea231 100644 --- a/nanobot/channels/signal/webui/index.ts +++ b/nanobot/channels/signal/webui/index.ts @@ -3,19 +3,19 @@ import { chatAppGuideUrl } from "@/components/settings/channels/catalog"; export default { presentation: { + logoUrl: "https://signal.org/favicon.ico", displayName: "Signal", initials: "SG", color: "#3A76F0", - logoUrl: "https://signal.org/favicon.ico", setup: { mode: "credentials", docsUrl: chatAppGuideUrl("signal"), fields: [ - { key: "channels.signal.phoneNumber" }, - { key: "channels.signal.daemonHost" }, - { key: "channels.signal.daemonPort" }, - { key: "channels.signal.dm.allowFrom" }, - { key: "channels.signal.group.allowFrom" }, + { key: "channels.signal.phoneNumber", section: "account" }, + { key: "channels.signal.daemonHost", section: "connection" }, + { key: "channels.signal.daemonPort", section: "connection" }, + { key: "channels.signal.dm.allowFrom", section: "access" }, + { key: "channels.signal.group.allowFrom", section: "access" }, ], }, }, diff --git a/nanobot/channels/signal/webui/locales/en.json b/nanobot/channels/signal/webui/locales/en.json index 25a8336e1..d088bd483 100644 --- a/nanobot/channels/signal/webui/locales/en.json +++ b/nanobot/channels/signal/webui/locales/en.json @@ -1,21 +1,11 @@ { - "description": "Use nanobot from Signal messages.", - "requirements": "signal-cli HTTP daemon, phone number, allowlist", "setup": { "docsLabel": "Open Signal setup", "officialLabel": "Open signal-cli guide", - "tryIt": "Send a Signal DM to the linked phone number.", - "summary": "Signal connects through a signal-cli HTTP daemon that is already linked to a Signal phone number.", - "steps": [ - "Install signal-cli-rest-api and link or register a Signal number.", - "Enter the daemon host, port, and linked phone number.", - "Save and enable Signal, then send a direct test message." - ], "fields": { "phoneNumber": { "label": "Phone number", - "placeholder": "+1234567890", - "help": "Use the Signal number registered with signal-cli." + "placeholder": "+1234567890" }, "daemonHost": { "label": "Daemon host", @@ -32,6 +22,47 @@ "group_allowFrom": { "label": "Allowed groups", "placeholder": "Group IDs" + }, + "groupMessageBufferSize": { + "label": "Group context messages" + }, + "attachmentsDir": { + "label": "Attachment directory" + }, + "dm_enabled": { + "label": "Enable direct messages", + "choices": { + "true": "On", + "false": "Off" + } + }, + "dm_policy": { + "label": "Direct message access", + "choices": { + "allowlist": "Allowlist", + "open": "Open" + } + }, + "group_enabled": { + "label": "Enable groups", + "choices": { + "true": "On", + "false": "Off" + } + }, + "group_policy": { + "label": "Group access", + "choices": { + "allowlist": "Allowlist", + "open": "Open" + } + }, + "group_requireMention": { + "label": "Require mention in groups", + "choices": { + "true": "On", + "false": "Off" + } } } } diff --git a/nanobot/channels/signal/webui/locales/es.json b/nanobot/channels/signal/webui/locales/es.json index 524bb8425..c3fe026e2 100644 --- a/nanobot/channels/signal/webui/locales/es.json +++ b/nanobot/channels/signal/webui/locales/es.json @@ -1,21 +1,11 @@ { - "description": "Usa nanobot desde mensajes de Signal.", - "requirements": "Daemon HTTP signal-cli, número de teléfono y lista de permitidos", "setup": { "docsLabel": "Abrir guía de Signal", "officialLabel": "Abrir guía de signal-cli", - "tryIt": "Envía un DM de Signal al número vinculado.", - "summary": "Signal se conecta mediante un daemon HTTP signal-cli ya vinculado a un número de Signal.", - "steps": [ - "Instala signal-cli-rest-api y vincula o registra un número de Signal.", - "Introduce el host, puerto y número vinculado.", - "Guarda y activa Signal; después envía un mensaje directo de prueba." - ], "fields": { "phoneNumber": { "label": "Número de teléfono", - "placeholder": "+1234567890", - "help": "Usa el número de Signal registrado con signal-cli." + "placeholder": "+1234567890" }, "daemonHost": { "label": "Host del daemon", @@ -32,6 +22,47 @@ "group_allowFrom": { "label": "Grupos permitidos", "placeholder": "ID de grupo" + }, + "groupMessageBufferSize": { + "label": "Mensajes de contexto grupal" + }, + "attachmentsDir": { + "label": "Directorio de archivos adjuntos" + }, + "dm_enabled": { + "label": "Habilitar mensajes directos", + "choices": { + "true": "encendido", + "false": "Apagado" + } + }, + "dm_policy": { + "label": "Acceso a mensajes directos", + "choices": { + "allowlist": "Lista de permitidos", + "open": "Abierto" + } + }, + "group_enabled": { + "label": "Habilitar grupos", + "choices": { + "true": "encendido", + "false": "Apagado" + } + }, + "group_policy": { + "label": "Acceso grupal", + "choices": { + "allowlist": "Lista de permitidos", + "open": "Abierto" + } + }, + "group_requireMention": { + "label": "Requerir mención en grupos", + "choices": { + "true": "encendido", + "false": "Apagado" + } } } } diff --git a/nanobot/channels/signal/webui/locales/fr.json b/nanobot/channels/signal/webui/locales/fr.json index 755c8c80d..931204ef3 100644 --- a/nanobot/channels/signal/webui/locales/fr.json +++ b/nanobot/channels/signal/webui/locales/fr.json @@ -1,21 +1,11 @@ { - "description": "Utilisez nanobot depuis les messages Signal.", - "requirements": "Service HTTP signal-cli, numéro de téléphone et liste d’autorisation", "setup": { "docsLabel": "Ouvrir le guide Signal", "officialLabel": "Ouvrir le guide signal-cli", - "tryIt": "Envoyez un message privé Signal au numéro associé.", - "summary": "Signal se connecte via un service HTTP signal-cli déjà associé à un numéro Signal.", - "steps": [ - "Installez signal-cli-rest-api et associez ou enregistrez un numéro Signal.", - "Saisissez l’hôte, le port et le numéro associé.", - "Enregistrez et activez Signal, puis envoyez un message privé test." - ], "fields": { "phoneNumber": { "label": "Numéro de téléphone", - "placeholder": "+1234567890", - "help": "Utilisez le numéro Signal enregistré avec signal-cli." + "placeholder": "+1234567890" }, "daemonHost": { "label": "Hôte du service", @@ -32,6 +22,47 @@ "group_allowFrom": { "label": "Groupes autorisés", "placeholder": "ID de groupe" + }, + "groupMessageBufferSize": { + "label": "Messages contextuels de groupe" + }, + "attachmentsDir": { + "label": "Répertoire des pièces jointes" + }, + "dm_enabled": { + "label": "Activer les messages directs", + "choices": { + "true": "Sur", + "false": "Désactivé" + } + }, + "dm_policy": { + "label": "Accès aux messages directs", + "choices": { + "allowlist": "Liste verte", + "open": "Ouvert" + } + }, + "group_enabled": { + "label": "Activer les groupes", + "choices": { + "true": "Sur", + "false": "Désactivé" + } + }, + "group_policy": { + "label": "Accès groupe", + "choices": { + "allowlist": "Liste verte", + "open": "Ouvert" + } + }, + "group_requireMention": { + "label": "Exiger une mention dans les groupes", + "choices": { + "true": "Sur", + "false": "Désactivé" + } } } } diff --git a/nanobot/channels/signal/webui/locales/id.json b/nanobot/channels/signal/webui/locales/id.json index 589d27c87..936986fca 100644 --- a/nanobot/channels/signal/webui/locales/id.json +++ b/nanobot/channels/signal/webui/locales/id.json @@ -1,21 +1,11 @@ { - "description": "Gunakan nanobot dari pesan Signal.", - "requirements": "Daemon HTTP signal-cli, nomor telepon, dan daftar izin", "setup": { "docsLabel": "Buka panduan Signal", "officialLabel": "Buka panduan signal-cli", - "tryIt": "Kirim DM Signal ke nomor yang ditautkan.", - "summary": "Signal terhubung melalui daemon HTTP signal-cli yang sudah ditautkan ke nomor Signal.", - "steps": [ - "Pasang signal-cli-rest-api dan tautkan atau daftarkan nomor Signal.", - "Masukkan host daemon, port, dan nomor yang ditautkan.", - "Simpan dan aktifkan Signal, lalu kirim pesan langsung uji." - ], "fields": { "phoneNumber": { "label": "Nomor telepon", - "placeholder": "+1234567890", - "help": "Gunakan nomor Signal yang terdaftar di signal-cli." + "placeholder": "+1234567890" }, "daemonHost": { "label": "Host daemon", @@ -32,6 +22,47 @@ "group_allowFrom": { "label": "Grup yang diizinkan", "placeholder": "ID grup" + }, + "groupMessageBufferSize": { + "label": "Pesan konteks grup" + }, + "attachmentsDir": { + "label": "Direktori lampiran" + }, + "dm_enabled": { + "label": "Aktifkan pesan langsung", + "choices": { + "true": "Aktif", + "false": "Mati" + } + }, + "dm_policy": { + "label": "Akses pesan langsung", + "choices": { + "allowlist": "Daftar yang diizinkan", + "open": "Buka" + } + }, + "group_enabled": { + "label": "Aktifkan grup", + "choices": { + "true": "Aktif", + "false": "Mati" + } + }, + "group_policy": { + "label": "Akses grup", + "choices": { + "allowlist": "Daftar yang diizinkan", + "open": "Buka" + } + }, + "group_requireMention": { + "label": "Perlu disebutkan dalam kelompok", + "choices": { + "true": "Aktif", + "false": "Mati" + } } } } diff --git a/nanobot/channels/signal/webui/locales/ja.json b/nanobot/channels/signal/webui/locales/ja.json index 6fb28b557..ce64f3be2 100644 --- a/nanobot/channels/signal/webui/locales/ja.json +++ b/nanobot/channels/signal/webui/locales/ja.json @@ -1,21 +1,11 @@ { - "description": "Signal メッセージから nanobot を利用します。", - "requirements": "signal-cli HTTP デーモン、電話番号、許可リスト", "setup": { "docsLabel": "Signal 設定ガイドを開く", "officialLabel": "signal-cli ガイドを開く", - "tryIt": "連携した電話番号に Signal の DM を送信します。", - "summary": "Signal は、Signal の電話番号に連携済みの signal-cli HTTP デーモン経由で接続します。", - "steps": [ - "signal-cli-rest-api をインストールし、Signal 番号を連携または登録します。", - "デーモンのホスト、ポート、連携済み電話番号を入力します。", - "保存して Signal を有効にし、DM でテストします。" - ], "fields": { "phoneNumber": { "label": "電話番号", - "placeholder": "+1234567890", - "help": "signal-cli に登録した Signal 番号を使います。" + "placeholder": "+1234567890" }, "daemonHost": { "label": "デーモンホスト", @@ -32,6 +22,47 @@ "group_allowFrom": { "label": "許可するグループ", "placeholder": "グループ ID" + }, + "groupMessageBufferSize": { + "label": "グループコンテキストメッセージ" + }, + "attachmentsDir": { + "label": "添付ファイルディレクトリ" + }, + "dm_enabled": { + "label": "ダイレクトメッセージを有効にする", + "choices": { + "true": "オン", + "false": "オフ" + } + }, + "dm_policy": { + "label": "ダイレクトメッセージへのアクセス", + "choices": { + "allowlist": "ホワイトリスト", + "open": "開く" + } + }, + "group_enabled": { + "label": "グループを有効にする", + "choices": { + "true": "オン", + "false": "オフ" + } + }, + "group_policy": { + "label": "グループアクセス", + "choices": { + "allowlist": "ホワイトリスト", + "open": "開く" + } + }, + "group_requireMention": { + "label": "グループ内での言及が必要", + "choices": { + "true": "オン", + "false": "オフ" + } } } } diff --git a/nanobot/channels/signal/webui/locales/ko.json b/nanobot/channels/signal/webui/locales/ko.json index 134fbd57c..112c515ac 100644 --- a/nanobot/channels/signal/webui/locales/ko.json +++ b/nanobot/channels/signal/webui/locales/ko.json @@ -1,21 +1,11 @@ { - "description": "Signal 메시지에서 nanobot을 사용합니다.", - "requirements": "signal-cli HTTP 데몬, 전화번호 및 허용 목록", "setup": { "docsLabel": "Signal 설정 가이드 열기", "officialLabel": "signal-cli 가이드 열기", - "tryIt": "연결된 전화번호로 Signal DM을 보내세요.", - "summary": "Signal은 Signal 전화번호에 연결된 signal-cli HTTP 데몬을 통해 접속합니다.", - "steps": [ - "signal-cli-rest-api를 설치하고 Signal 번호를 연결하거나 등록하세요.", - "데몬 호스트, 포트, 연결된 전화번호를 입력하세요.", - "저장하고 Signal을 활성화한 다음 DM으로 테스트하세요." - ], "fields": { "phoneNumber": { "label": "전화번호", - "placeholder": "+1234567890", - "help": "signal-cli에 등록된 Signal 번호를 사용하세요." + "placeholder": "+1234567890" }, "daemonHost": { "label": "데몬 호스트", @@ -32,6 +22,47 @@ "group_allowFrom": { "label": "허용된 그룹", "placeholder": "그룹 ID" + }, + "groupMessageBufferSize": { + "label": "그룹 상황 메시지" + }, + "attachmentsDir": { + "label": "첨부파일 디렉토리" + }, + "dm_enabled": { + "label": "다이렉트 메시지 활성화", + "choices": { + "true": "켜기", + "false": "끄기" + } + }, + "dm_policy": { + "label": "다이렉트 메시지 액세스", + "choices": { + "allowlist": "허용 목록", + "open": "열기" + } + }, + "group_enabled": { + "label": "그룹 활성화", + "choices": { + "true": "켜기", + "false": "끄기" + } + }, + "group_policy": { + "label": "그룹 액세스", + "choices": { + "allowlist": "허용 목록", + "open": "열기" + } + }, + "group_requireMention": { + "label": "그룹에서 멘션 필요", + "choices": { + "true": "켜기", + "false": "끄기" + } } } } diff --git a/nanobot/channels/signal/webui/locales/pt-BR.json b/nanobot/channels/signal/webui/locales/pt-BR.json index 8dac779f9..5ba66d0cc 100644 --- a/nanobot/channels/signal/webui/locales/pt-BR.json +++ b/nanobot/channels/signal/webui/locales/pt-BR.json @@ -1,21 +1,11 @@ { - "description": "Use o nanobot em mensagens do Signal.", - "requirements": "Daemon HTTP signal-cli, número de telefone e lista de permissão", "setup": { "docsLabel": "Abrir guia do Signal", "officialLabel": "Abrir guia do signal-cli", - "tryIt": "Envie uma DM do Signal ao número vinculado.", - "summary": "O Signal conecta por um daemon HTTP signal-cli já vinculado a um número Signal.", - "steps": [ - "Instale o signal-cli-rest-api e vincule ou registre um número Signal.", - "Informe o host, a porta e o número vinculado.", - "Salve e ative o Signal; depois, envie uma mensagem direta de teste." - ], "fields": { "phoneNumber": { "label": "Número de telefone", - "placeholder": "+1234567890", - "help": "Use o número Signal registrado no signal-cli." + "placeholder": "+1234567890" }, "daemonHost": { "label": "Host do daemon", @@ -32,6 +22,47 @@ "group_allowFrom": { "label": "Grupos permitidos", "placeholder": "IDs de grupo" + }, + "groupMessageBufferSize": { + "label": "Mensagens de contexto de grupo" + }, + "attachmentsDir": { + "label": "Diretório de anexos" + }, + "dm_enabled": { + "label": "Habilitar mensagens diretas", + "choices": { + "true": "Ligado", + "false": "Desligado" + } + }, + "dm_policy": { + "label": "Acesso direto a mensagens", + "choices": { + "allowlist": "Lista de permissões", + "open": "Abrir" + } + }, + "group_enabled": { + "label": "Habilitar grupos", + "choices": { + "true": "Ligado", + "false": "Desligado" + } + }, + "group_policy": { + "label": "Acesso ao grupo", + "choices": { + "allowlist": "Lista de permissões", + "open": "Abrir" + } + }, + "group_requireMention": { + "label": "Exigir menção em grupos", + "choices": { + "true": "Ligado", + "false": "Desligado" + } } } } diff --git a/nanobot/channels/signal/webui/locales/vi.json b/nanobot/channels/signal/webui/locales/vi.json index 460018035..de0d6149e 100644 --- a/nanobot/channels/signal/webui/locales/vi.json +++ b/nanobot/channels/signal/webui/locales/vi.json @@ -1,21 +1,11 @@ { - "description": "Sử dụng nanobot từ tin nhắn Signal.", - "requirements": "Dịch vụ HTTP signal-cli, số điện thoại và danh sách cho phép", "setup": { "docsLabel": "Mở hướng dẫn Signal", "officialLabel": "Mở hướng dẫn signal-cli", - "tryIt": "Gửi tin nhắn riêng Signal đến số đã liên kết.", - "summary": "Signal kết nối qua dịch vụ HTTP signal-cli đã liên kết với một số Signal.", - "steps": [ - "Cài signal-cli-rest-api và liên kết hoặc đăng ký một số Signal.", - "Nhập địa chỉ máy chủ, cổng và số điện thoại đã liên kết.", - "Lưu và bật Signal, sau đó gửi tin nhắn riêng thử." - ], "fields": { "phoneNumber": { "label": "Số điện thoại", - "placeholder": "+1234567890", - "help": "Dùng số Signal đã đăng ký với signal-cli." + "placeholder": "+1234567890" }, "daemonHost": { "label": "Máy chủ dịch vụ", @@ -32,6 +22,47 @@ "group_allowFrom": { "label": "Nhóm được phép", "placeholder": "ID nhóm" + }, + "groupMessageBufferSize": { + "label": "Nhóm tin nhắn ngữ cảnh" + }, + "attachmentsDir": { + "label": "Thư mục đính kèm" + }, + "dm_enabled": { + "label": "Bật tin nhắn trực tiếp", + "choices": { + "true": "Bật", + "false": "Tắt" + } + }, + "dm_policy": { + "label": "Truy cập tin nhắn trực tiếp", + "choices": { + "allowlist": "Danh sách cho phép", + "open": "Mở" + } + }, + "group_enabled": { + "label": "Bật nhóm", + "choices": { + "true": "Bật", + "false": "Tắt" + } + }, + "group_policy": { + "label": "Truy cập nhóm", + "choices": { + "allowlist": "Danh sách cho phép", + "open": "Mở" + } + }, + "group_requireMention": { + "label": "Yêu cầu đề cập trong nhóm", + "choices": { + "true": "Bật", + "false": "Tắt" + } } } } diff --git a/nanobot/channels/signal/webui/locales/zh-CN.json b/nanobot/channels/signal/webui/locales/zh-CN.json index 67b8a204a..2c47d5c64 100644 --- a/nanobot/channels/signal/webui/locales/zh-CN.json +++ b/nanobot/channels/signal/webui/locales/zh-CN.json @@ -1,21 +1,11 @@ { - "description": "通过 Signal 消息使用 nanobot。", - "requirements": "signal-cli HTTP 服务、电话号码和白名单", "setup": { "docsLabel": "打开 Signal 配置指南", "officialLabel": "打开 signal-cli 指南", - "tryIt": "向已关联的电话号码发送一条 Signal 私信。", - "summary": "Signal 通过已关联 Signal 电话号码的 signal-cli HTTP 服务连接。", - "steps": [ - "安装 signal-cli-rest-api,并关联或注册一个 Signal 号码。", - "填写服务主机、端口和已关联的电话号码。", - "保存并启用 Signal,然后发送一条私信测试。" - ], "fields": { "phoneNumber": { "label": "电话号码", - "placeholder": "+1234567890", - "help": "使用在 signal-cli 中注册的 Signal 号码。" + "placeholder": "+1234567890" }, "daemonHost": { "label": "服务主机", @@ -32,6 +22,47 @@ "group_allowFrom": { "label": "允许的群组", "placeholder": "群组 ID" + }, + "groupMessageBufferSize": { + "label": "群组上下文消息数" + }, + "attachmentsDir": { + "label": "附件目录" + }, + "dm_enabled": { + "label": "启用私聊", + "choices": { + "true": "开启", + "false": "关闭" + } + }, + "dm_policy": { + "label": "私聊权限", + "choices": { + "allowlist": "白名单", + "open": "全部" + } + }, + "group_enabled": { + "label": "启用群组", + "choices": { + "true": "开启", + "false": "关闭" + } + }, + "group_policy": { + "label": "群组权限", + "choices": { + "allowlist": "白名单", + "open": "全部" + } + }, + "group_requireMention": { + "label": "群组中需要提及", + "choices": { + "true": "开启", + "false": "关闭" + } } } } diff --git a/nanobot/channels/signal/webui/locales/zh-TW.json b/nanobot/channels/signal/webui/locales/zh-TW.json index 74e002e64..1a3fa8772 100644 --- a/nanobot/channels/signal/webui/locales/zh-TW.json +++ b/nanobot/channels/signal/webui/locales/zh-TW.json @@ -1,21 +1,11 @@ { - "description": "透過 Signal 訊息使用 nanobot。", - "requirements": "signal-cli HTTP 服務、電話號碼和允許清單", "setup": { "docsLabel": "開啟 Signal 設定指南", "officialLabel": "開啟 signal-cli 指南", - "tryIt": "向已關聯的電話號碼傳送一則 Signal 私訊。", - "summary": "Signal 透過已關聯 Signal 電話號碼的 signal-cli HTTP 服務連線。", - "steps": [ - "安裝 signal-cli-rest-api,並關聯或註冊一個 Signal 號碼。", - "填入服務主機、連接埠和已關聯的電話號碼。", - "儲存並啟用 Signal,然後傳送一則私訊測試。" - ], "fields": { "phoneNumber": { "label": "電話號碼", - "placeholder": "+1234567890", - "help": "使用在 signal-cli 中註冊的 Signal 號碼。" + "placeholder": "+1234567890" }, "daemonHost": { "label": "服務主機", @@ -32,6 +22,47 @@ "group_allowFrom": { "label": "允許的群組", "placeholder": "群組 ID" + }, + "groupMessageBufferSize": { + "label": "群組上下文訊息數" + }, + "attachmentsDir": { + "label": "附件目錄" + }, + "dm_enabled": { + "label": "啟用私聊", + "choices": { + "true": "開啟", + "false": "關閉" + } + }, + "dm_policy": { + "label": "私聊權限", + "choices": { + "allowlist": "白名單", + "open": "全部" + } + }, + "group_enabled": { + "label": "啟用群組", + "choices": { + "true": "開啟", + "false": "關閉" + } + }, + "group_policy": { + "label": "群組權限", + "choices": { + "allowlist": "白名單", + "open": "全部" + } + }, + "group_requireMention": { + "label": "群組需要提及", + "choices": { + "true": "開啟", + "false": "關閉" + } } } } diff --git a/nanobot/channels/slack/manifest.py b/nanobot/channels/slack/manifest.py index 13da98efd..1428ef030 100644 --- a/nanobot/channels/slack/manifest.py +++ b/nanobot/channels/slack/manifest.py @@ -10,10 +10,25 @@ SETUP_SPEC = ChannelSetupSpec( "appToken": field("secret"), "botToken": field("secret"), "groupPolicy": field("enum", choices=GROUP_POLICIES, default="mention"), + "mode": field("enum", choices={"socket"}, default="socket"), + "webhookPath": field(default="/slack/events"), + "replyInThread": field("bool", default=True), + "reactEmoji": field(default="eyes"), + "doneEmoji": field(default="white_check_mark"), + "includeThreadContext": field("bool", default=True), + "threadContextLimit": field("int", default=20), + "allowFrom": field("list"), + "groupAllowFrom": field("list"), + "groupRequireMention": field("bool", default=False), + "dm.enabled": field("bool", default=True), + "dm.policy": field("enum", choices={"open", "allowlist"}, default="open"), + "dm.allowFrom": field("list"), + "proxy": field(), }, required=required_fields("appToken", "botToken"), official_url="https://api.slack.com/apps", validator=validate, + verifies_connection=True, ) PLUGIN = ChannelPlugin( diff --git a/nanobot/channels/slack/runtime.py b/nanobot/channels/slack/runtime.py index eb81a9d6b..689071759 100644 --- a/nanobot/channels/slack/runtime.py +++ b/nanobot/channels/slack/runtime.py @@ -7,10 +7,10 @@ from typing import Any, Protocol, cast import httpx from pydantic import Field +from slack_sdk.socket_mode.aiohttp import SocketModeClient from slack_sdk.socket_mode.async_client import AsyncBaseSocketModeClient from slack_sdk.socket_mode.request import SocketModeRequest from slack_sdk.socket_mode.response import SocketModeResponse -from slack_sdk.socket_mode.websockets import SocketModeClient from slack_sdk.web.async_client import AsyncWebClient from slackify_markdown import slackify_markdown # pyright: ignore[reportMissingTypeStubs] @@ -82,6 +82,7 @@ class SlackConfig(Base): # instead of every message). No effect for "mention"/"open" policies. group_require_mention: bool = False dm: SlackDMConfig = Field(default_factory=SlackDMConfig) + proxy: str | None = None SLACK_MAX_MESSAGE_LEN = 39_000 # Slack API allows ~40k; leave margin @@ -144,10 +145,15 @@ class SlackChannel(BaseChannel): self._running = True - self._web_client = AsyncWebClient(token=self.config.bot_token) + proxy = self.config.proxy.strip() if self.config.proxy else "" + if proxy and "://" not in proxy: + proxy = f"http://{proxy}" + proxy = proxy or None + self._web_client = AsyncWebClient(token=self.config.bot_token, proxy=proxy) self._socket_client = SocketModeClient( app_token=self.config.app_token, web_client=self._web_client, + proxy=proxy, ) self._socket_client.socket_mode_request_listeners.append(self._on_socket_request) @@ -577,7 +583,19 @@ class SlackChannel(BaseChannel): timeout=SLACK_DOWNLOAD_TIMEOUT, follow_redirects=True, transport=PinnedDNSAsyncTransport(), - mounts=httpx_env_proxy_mounts(), + mounts=( + { + "all://": httpx.AsyncHTTPTransport( + proxy=httpx.Proxy( + self.config.proxy + if "://" in self.config.proxy + else f"http://{self.config.proxy}" + ) + ) + } + if self.config.proxy + else httpx_env_proxy_mounts() + ), event_hooks={"request": [_validate_slack_download_request]}, ) as client: response = await client.get( diff --git a/nanobot/channels/slack/tests/test_validation.py b/nanobot/channels/slack/tests/test_validation.py index f7ac4478a..8ddb8a185 100644 --- a/nanobot/channels/slack/tests/test_validation.py +++ b/nanobot/channels/slack/tests/test_validation.py @@ -34,6 +34,9 @@ def test_validate_channel_does_not_write_config(tmp_path, monkeypatch: pytest.Mo ) assert result["status"] == "connected" + checks = {check["id"]: check for check in result["checks"]} + assert checks["app_token_prefix"]["action_url"] == "https://api.slack.com/apps" + assert "action_url" not in checks["bot_token_prefix"] saved = load_config(config_path) assert saved.channels.slack["appToken"] == "xapp-old" assert saved.channels.slack["botToken"] == "xoxb-old" diff --git a/nanobot/channels/slack/validation.py b/nanobot/channels/slack/validation.py index 1ee378b1f..4b5e8efc1 100644 --- a/nanobot/channels/slack/validation.py +++ b/nanobot/channels/slack/validation.py @@ -19,6 +19,7 @@ def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dict checks, missing = required_checks("slack", values) app_token = string_value(values.get("appToken")) bot_token = string_value(values.get("botToken")) + proxy = string_value(values.get("proxy")) if app_token: checks.append( check( @@ -36,7 +37,6 @@ def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dict "Bot token", "pass" if bot_token.startswith("xoxb-") else "fail", "Bot tokens start with xoxb- after installing the Slack app.", - action_url=official_action("slack"), ) ) if bot_token.startswith("xoxb-"): @@ -44,6 +44,7 @@ def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dict data = http_post( "https://slack.com/api/auth.test", headers={"Authorization": f"Bearer {bot_token}"}, + proxy=proxy or None, ) if data.get("ok"): identity = { diff --git a/nanobot/channels/slack/webui/index.ts b/nanobot/channels/slack/webui/index.ts index 59bca5869..c2d0368a1 100644 --- a/nanobot/channels/slack/webui/index.ts +++ b/nanobot/channels/slack/webui/index.ts @@ -40,10 +40,10 @@ settings: export default { presentation: { + logoUrl: "https://slack.com/favicon.ico", displayName: "Slack", initials: "SL", color: "#4A154B", - logoUrl: "https://slack.com/favicon.ico", setup: { mode: "credentials", docsUrl: chatAppGuideUrl("slack"), @@ -51,13 +51,12 @@ export default { { id: "slack-manifest", copyText: SLACK_SOCKET_MODE_MANIFEST, - logoUrl: "https://slack.com/favicon.ico", }, ], fields: [ - { key: "channels.slack.appToken" }, - { key: "channels.slack.botToken" }, - { key: "channels.slack.groupPolicy" }, + { key: "channels.slack.appToken", section: "credentials" }, + { key: "channels.slack.botToken", section: "credentials" }, + { key: "channels.slack.groupPolicy", section: "behavior" }, ], }, }, diff --git a/nanobot/channels/slack/webui/locales/en.json b/nanobot/channels/slack/webui/locales/en.json index a8cd00fb3..ae32bc9a2 100644 --- a/nanobot/channels/slack/webui/locales/en.json +++ b/nanobot/channels/slack/webui/locales/en.json @@ -1,29 +1,18 @@ { - "description": "Use nanobot from Slack workspaces.", - "requirements": "Slack app token, bot token, workspace install", "setup": { "docsLabel": "Open Slack setup", "officialLabel": "Open Slack apps", - "tryIt": "Mention the Slack app or send it a direct message.", - "summary": "Slack uses Socket Mode by default, so it needs both app-level and bot-level tokens.", - "steps": [ - "Create a Slack app from the provided manifest and enable Socket Mode.", - "Install the app to your workspace and copy the app and bot tokens.", - "Save and enable Slack, then mention the app or send it a direct message." - ], "actions": { "slack-manifest": "Copy app manifest" }, "fields": { "appToken": { "label": "App token", - "placeholder": "xapp-...", - "help": "Create this in your Slack app’s Socket Mode settings." + "placeholder": "xapp-..." }, "botToken": { "label": "Bot token", - "placeholder": "xoxb-...", - "help": "Use the bot token after installing the Slack app." + "placeholder": "xoxb-..." }, "groupPolicy": { "label": "Group behavior", @@ -32,6 +21,72 @@ "open": "All messages", "allowlist": "Allowlist" } + }, + "mode": { + "label": "Connection mode", + "choices": { + "socket": "Socket Mode" + } + }, + "webhookPath": { + "label": "Webhook path" + }, + "replyInThread": { + "label": "Reply in thread", + "choices": { + "true": "On", + "false": "Off" + } + }, + "reactEmoji": { + "label": "Read emoji" + }, + "doneEmoji": { + "label": "Done emoji" + }, + "includeThreadContext": { + "label": "Include thread context", + "choices": { + "true": "On", + "false": "Off" + } + }, + "threadContextLimit": { + "label": "Thread context limit" + }, + "allowFrom": { + "label": "Allowed users" + }, + "groupAllowFrom": { + "label": "Allowed channels" + }, + "groupRequireMention": { + "label": "Require mentions in channels", + "choices": { + "true": "On", + "false": "Off" + } + }, + "dm_enabled": { + "label": "Enable direct messages", + "choices": { + "true": "On", + "false": "Off" + } + }, + "dm_policy": { + "label": "Direct message access", + "choices": { + "allowlist": "Allowlist", + "open": "Open" + } + }, + "dm_allowFrom": { + "label": "Allowed direct-message users" + }, + "proxy": { + "label": "Network proxy", + "placeholder": "http://127.0.0.1:7890" } } } diff --git a/nanobot/channels/slack/webui/locales/es.json b/nanobot/channels/slack/webui/locales/es.json index 5f342c327..f5e5b56fd 100644 --- a/nanobot/channels/slack/webui/locales/es.json +++ b/nanobot/channels/slack/webui/locales/es.json @@ -1,29 +1,18 @@ { - "description": "Usa nanobot desde espacios de Slack.", - "requirements": "Token de app Slack, token del bot e instalación en el espacio", "setup": { "docsLabel": "Abrir guía de Slack", "officialLabel": "Abrir aplicaciones de Slack", - "tryIt": "Menciona la app de Slack o envíale un mensaje directo.", - "summary": "Slack usa Socket Mode de forma predeterminada, por lo que necesita tokens de app y de bot.", - "steps": [ - "Crea una app de Slack con el manifiesto proporcionado y activa Socket Mode.", - "Instala la app en tu espacio y copia los tokens de app y bot.", - "Guarda y activa Slack; después menciona la app o envíale un mensaje directo." - ], "actions": { "slack-manifest": "Copiar manifiesto de la aplicación" }, "fields": { "appToken": { "label": "Token de la app", - "placeholder": "xapp-...", - "help": "Créalo en los ajustes de Socket Mode de tu aplicación de Slack." + "placeholder": "xapp-..." }, "botToken": { "label": "Token del bot", - "placeholder": "xoxb-...", - "help": "Usa el token del bot después de instalar la app." + "placeholder": "xoxb-..." }, "groupPolicy": { "label": "Comportamiento en grupos", @@ -32,6 +21,72 @@ "open": "Todos los mensajes", "allowlist": "Lista de permitidos" } + }, + "mode": { + "label": "Modo de conexión", + "choices": { + "socket": "Modo de enchufe" + } + }, + "webhookPath": { + "label": "Ruta del webhook" + }, + "replyInThread": { + "label": "Responder en el hilo", + "choices": { + "true": "encendido", + "false": "Apagado" + } + }, + "reactEmoji": { + "label": "Leer emojis" + }, + "doneEmoji": { + "label": "emoji hecho" + }, + "includeThreadContext": { + "label": "Incluir contexto de hilo", + "choices": { + "true": "encendido", + "false": "Apagado" + } + }, + "threadContextLimit": { + "label": "Límite de contexto del hilo" + }, + "allowFrom": { + "label": "Usuarios permitidos" + }, + "groupAllowFrom": { + "label": "Canales permitidos" + }, + "groupRequireMention": { + "label": "Requerir menciones en canales", + "choices": { + "true": "encendido", + "false": "Apagado" + } + }, + "dm_enabled": { + "label": "Habilitar mensajes directos", + "choices": { + "true": "encendido", + "false": "Apagado" + } + }, + "dm_policy": { + "label": "Acceso a mensajes directos", + "choices": { + "allowlist": "Lista de permitidos", + "open": "Abierto" + } + }, + "dm_allowFrom": { + "label": "Usuarios permitidos de mensajes directos" + }, + "proxy": { + "label": "Proxy de red", + "placeholder": "http://127.0.0.1:7890" } } } diff --git a/nanobot/channels/slack/webui/locales/fr.json b/nanobot/channels/slack/webui/locales/fr.json index f09f26efb..5bf13db9c 100644 --- a/nanobot/channels/slack/webui/locales/fr.json +++ b/nanobot/channels/slack/webui/locales/fr.json @@ -1,29 +1,18 @@ { - "description": "Utilisez nanobot depuis les espaces Slack.", - "requirements": "Jeton d’application Slack, jeton du bot et installation dans l’espace", "setup": { "docsLabel": "Ouvrir le guide Slack", "officialLabel": "Ouvrir les applications Slack", - "tryIt": "Mentionnez l’application Slack ou envoyez-lui un message privé.", - "summary": "Slack utilise Socket Mode par défaut et nécessite les jetons d’application et de bot.", - "steps": [ - "Créez une application Slack avec le manifeste fourni et activez Socket Mode.", - "Installez l’application dans votre espace et copiez les jetons d’application et de bot.", - "Enregistrez et activez Slack, puis mentionnez l’application ou envoyez-lui un message privé." - ], "actions": { "slack-manifest": "Copier le manifeste de l’application" }, "fields": { "appToken": { "label": "Jeton d’application", - "placeholder": "xapp-...", - "help": "Créez ce jeton dans les paramètres Socket Mode de votre application Slack." + "placeholder": "xapp-..." }, "botToken": { "label": "Jeton du bot", - "placeholder": "xoxb-...", - "help": "Utilisez le jeton du bot après l’installation de l’application." + "placeholder": "xoxb-..." }, "groupPolicy": { "label": "Comportement en groupe", @@ -32,6 +21,72 @@ "open": "Tous les messages", "allowlist": "Liste d’autorisation" } + }, + "mode": { + "label": "Mode de connexion", + "choices": { + "socket": "Mode prise" + } + }, + "webhookPath": { + "label": "Chemin du webhook" + }, + "replyInThread": { + "label": "Répondre dans le fil de discussion", + "choices": { + "true": "Sur", + "false": "Désactivé" + } + }, + "reactEmoji": { + "label": "Lire les emoji" + }, + "doneEmoji": { + "label": "Terminé emoji" + }, + "includeThreadContext": { + "label": "Inclure le contexte du fil de discussion", + "choices": { + "true": "Sur", + "false": "Désactivé" + } + }, + "threadContextLimit": { + "label": "Limite du contexte du fil de discussion" + }, + "allowFrom": { + "label": "Utilisateurs autorisés" + }, + "groupAllowFrom": { + "label": "Chaînes autorisées" + }, + "groupRequireMention": { + "label": "Exiger des mentions dans les chaînes", + "choices": { + "true": "Sur", + "false": "Désactivé" + } + }, + "dm_enabled": { + "label": "Activer les messages directs", + "choices": { + "true": "Sur", + "false": "Désactivé" + } + }, + "dm_policy": { + "label": "Accès aux messages directs", + "choices": { + "allowlist": "Liste verte", + "open": "Ouvert" + } + }, + "dm_allowFrom": { + "label": "Utilisateurs de messagerie directe autorisés" + }, + "proxy": { + "label": "Proxy réseau", + "placeholder": "http://127.0.0.1:7890" } } } diff --git a/nanobot/channels/slack/webui/locales/id.json b/nanobot/channels/slack/webui/locales/id.json index 9364344b4..dec3f4d11 100644 --- a/nanobot/channels/slack/webui/locales/id.json +++ b/nanobot/channels/slack/webui/locales/id.json @@ -1,29 +1,18 @@ { - "description": "Gunakan nanobot dari ruang kerja Slack.", - "requirements": "Token aplikasi Slack, token bot, dan aplikasi terpasang di ruang kerja", "setup": { "docsLabel": "Buka panduan Slack", "officialLabel": "Buka aplikasi Slack", - "tryIt": "Sebut aplikasi Slack atau kirim pesan langsung.", - "summary": "Slack menggunakan Socket Mode secara default sehingga memerlukan token aplikasi dan token bot.", - "steps": [ - "Buat aplikasi Slack dari manifes yang disediakan, lalu aktifkan Socket Mode.", - "Pasang aplikasi ke ruang kerja dan salin token aplikasi serta bot.", - "Simpan dan aktifkan Slack, lalu sebut aplikasi atau kirim DM." - ], "actions": { "slack-manifest": "Salin manifes aplikasi" }, "fields": { "appToken": { "label": "Token aplikasi", - "placeholder": "xapp-...", - "help": "Buat token di pengaturan Socket Mode aplikasi Slack Anda." + "placeholder": "xapp-..." }, "botToken": { "label": "Token bot", - "placeholder": "xoxb-...", - "help": "Gunakan token bot setelah memasang aplikasi Slack." + "placeholder": "xoxb-..." }, "groupPolicy": { "label": "Perilaku grup", @@ -32,6 +21,72 @@ "open": "Semua pesan", "allowlist": "Daftar izin" } + }, + "mode": { + "label": "Modus koneksi", + "choices": { + "socket": "Mode Soket" + } + }, + "webhookPath": { + "label": "Jalur webhook" + }, + "replyInThread": { + "label": "Balas di thread", + "choices": { + "true": "Aktif", + "false": "Mati" + } + }, + "reactEmoji": { + "label": "Baca emoji" + }, + "doneEmoji": { + "label": "Selesai emoji" + }, + "includeThreadContext": { + "label": "Sertakan konteks thread", + "choices": { + "true": "Aktif", + "false": "Mati" + } + }, + "threadContextLimit": { + "label": "Batas konteks thread" + }, + "allowFrom": { + "label": "Pengguna yang diizinkan" + }, + "groupAllowFrom": { + "label": "Saluran yang diizinkan" + }, + "groupRequireMention": { + "label": "Wajibkan penyebutan di saluran", + "choices": { + "true": "Aktif", + "false": "Mati" + } + }, + "dm_enabled": { + "label": "Aktifkan pesan langsung", + "choices": { + "true": "Aktif", + "false": "Mati" + } + }, + "dm_policy": { + "label": "Akses pesan langsung", + "choices": { + "allowlist": "Daftar yang diizinkan", + "open": "Buka" + } + }, + "dm_allowFrom": { + "label": "Mengizinkan pengguna pesan langsung" + }, + "proxy": { + "label": "Proxy jaringan", + "placeholder": "http://127.0.0.1:7890" } } } diff --git a/nanobot/channels/slack/webui/locales/ja.json b/nanobot/channels/slack/webui/locales/ja.json index a89dd0c49..08cbb6458 100644 --- a/nanobot/channels/slack/webui/locales/ja.json +++ b/nanobot/channels/slack/webui/locales/ja.json @@ -1,29 +1,18 @@ { - "description": "Slack ワークスペースから nanobot を利用します。", - "requirements": "Slack アプリトークン、ボットトークン、ワークスペースへのインストール", "setup": { "docsLabel": "Slack 設定ガイドを開く", "officialLabel": "Slack アプリを開く", - "tryIt": "Slack アプリをメンションするか、DM を送信します。", - "summary": "Slack は既定で Socket Mode を使うため、アプリレベルとボットレベルの両方のトークンが必要です。", - "steps": [ - "提供されたマニフェストから Slack アプリを作成し、Socket Mode を有効にします。", - "アプリをワークスペースにインストールし、アプリとボットのトークンをコピーします。", - "保存して Slack を有効にし、アプリをメンションするか DM を送信します。" - ], "actions": { "slack-manifest": "アプリマニフェストをコピー" }, "fields": { "appToken": { "label": "アプリトークン", - "placeholder": "xapp-...", - "help": "Slack アプリの Socket Mode 設定で作成します。" + "placeholder": "xapp-..." }, "botToken": { "label": "ボットトークン", - "placeholder": "xoxb-...", - "help": "Slack アプリのインストール後にボットトークンを使います。" + "placeholder": "xoxb-..." }, "groupPolicy": { "label": "グループでの動作", @@ -32,6 +21,72 @@ "open": "すべてのメッセージ", "allowlist": "許可リスト" } + }, + "mode": { + "label": "接続モード", + "choices": { + "socket": "ソケットモード" + } + }, + "webhookPath": { + "label": "Webhook パス" + }, + "replyInThread": { + "label": "スレッド内で返信する", + "choices": { + "true": "オン", + "false": "オフ" + } + }, + "reactEmoji": { + "label": "絵文字を読む" + }, + "doneEmoji": { + "label": "完了絵文字" + }, + "includeThreadContext": { + "label": "スレッドコンテキストを含める", + "choices": { + "true": "オン", + "false": "オフ" + } + }, + "threadContextLimit": { + "label": "スレッドコンテキストの制限" + }, + "allowFrom": { + "label": "許可されたユーザー" + }, + "groupAllowFrom": { + "label": "許可されたチャネル" + }, + "groupRequireMention": { + "label": "チャンネルでのメンションを必須にする", + "choices": { + "true": "オン", + "false": "オフ" + } + }, + "dm_enabled": { + "label": "ダイレクトメッセージを有効にする", + "choices": { + "true": "オン", + "false": "オフ" + } + }, + "dm_policy": { + "label": "ダイレクトメッセージへのアクセス", + "choices": { + "allowlist": "ホワイトリスト", + "open": "開く" + } + }, + "dm_allowFrom": { + "label": "許可されたダイレクトメッセージユーザー" + }, + "proxy": { + "label": "ネットワークプロキシ", + "placeholder": "http://127.0.0.1:7890" } } } diff --git a/nanobot/channels/slack/webui/locales/ko.json b/nanobot/channels/slack/webui/locales/ko.json index 4456f13fe..a68fefbb9 100644 --- a/nanobot/channels/slack/webui/locales/ko.json +++ b/nanobot/channels/slack/webui/locales/ko.json @@ -1,29 +1,18 @@ { - "description": "Slack 작업 공간에서 nanobot을 사용합니다.", - "requirements": "Slack 앱 토큰, 봇 토큰 및 작업 공간 설치", "setup": { "docsLabel": "Slack 설정 가이드 열기", "officialLabel": "Slack 앱 열기", - "tryIt": "Slack 앱을 멘션하거나 DM을 보내세요.", - "summary": "Slack은 기본적으로 Socket Mode를 사용하므로 앱 수준 토큰과 봇 토큰이 모두 필요합니다.", - "steps": [ - "제공된 앱 매니페스트로 Slack 앱을 만들고 Socket Mode를 활성화하세요.", - "앱을 작업 공간에 설치하고 앱 및 봇 토큰을 복사하세요.", - "저장하고 Slack을 활성화한 다음 앱을 멘션하거나 DM을 보내세요." - ], "actions": { "slack-manifest": "앱 매니페스트 복사" }, "fields": { "appToken": { "label": "앱 토큰", - "placeholder": "xapp-...", - "help": "Slack 앱의 Socket Mode 설정에서 생성하세요." + "placeholder": "xapp-..." }, "botToken": { "label": "봇 토큰", - "placeholder": "xoxb-...", - "help": "Slack 앱을 설치한 뒤 봇 토큰을 사용하세요." + "placeholder": "xoxb-..." }, "groupPolicy": { "label": "그룹 동작", @@ -32,6 +21,72 @@ "open": "모든 메시지", "allowlist": "허용 목록" } + }, + "mode": { + "label": "연결 모드", + "choices": { + "socket": "소켓 모드" + } + }, + "webhookPath": { + "label": "웹훅 경로" + }, + "replyInThread": { + "label": "스레드로 답장하기", + "choices": { + "true": "켜기", + "false": "끄기" + } + }, + "reactEmoji": { + "label": "이모티콘 읽기" + }, + "doneEmoji": { + "label": "이모티콘 완료" + }, + "includeThreadContext": { + "label": "스레드 컨텍스트 포함", + "choices": { + "true": "켜기", + "false": "끄기" + } + }, + "threadContextLimit": { + "label": "스레드 컨텍스트 제한" + }, + "allowFrom": { + "label": "허용된 사용자" + }, + "groupAllowFrom": { + "label": "허용된 채널" + }, + "groupRequireMention": { + "label": "채널에서 멘션 필요", + "choices": { + "true": "켜기", + "false": "끄기" + } + }, + "dm_enabled": { + "label": "다이렉트 메시지 활성화", + "choices": { + "true": "켜기", + "false": "끄기" + } + }, + "dm_policy": { + "label": "다이렉트 메시지 액세스", + "choices": { + "allowlist": "허용 목록", + "open": "열기" + } + }, + "dm_allowFrom": { + "label": "허용된 직접 메시지 사용자" + }, + "proxy": { + "label": "네트워크 프록시", + "placeholder": "http://127.0.0.1:7890" } } } diff --git a/nanobot/channels/slack/webui/locales/pt-BR.json b/nanobot/channels/slack/webui/locales/pt-BR.json index 365419034..d7fd594bc 100644 --- a/nanobot/channels/slack/webui/locales/pt-BR.json +++ b/nanobot/channels/slack/webui/locales/pt-BR.json @@ -1,29 +1,18 @@ { - "description": "Use o nanobot em workspaces do Slack.", - "requirements": "Token do app Slack, token do bot e instalação no workspace", "setup": { "docsLabel": "Abrir guia do Slack", "officialLabel": "Abrir aplicativos do Slack", - "tryIt": "Mencione o app Slack ou envie uma mensagem direta.", - "summary": "O Slack usa Socket Mode por padrão e precisa dos tokens do app e do bot.", - "steps": [ - "Crie um app Slack com o manifesto fornecido e ative o Socket Mode.", - "Instale o app no workspace e copie os tokens do app e do bot.", - "Salve e ative o Slack; depois, mencione o app ou envie uma DM." - ], "actions": { "slack-manifest": "Copiar manifesto do aplicativo" }, "fields": { "appToken": { "label": "Token do app", - "placeholder": "xapp-...", - "help": "Crie o token nas configurações de Socket Mode do seu aplicativo Slack." + "placeholder": "xapp-..." }, "botToken": { "label": "Token do bot", - "placeholder": "xoxb-...", - "help": "Use o token do bot após instalar o app Slack." + "placeholder": "xoxb-..." }, "groupPolicy": { "label": "Comportamento em grupos", @@ -32,6 +21,72 @@ "open": "Todas as mensagens", "allowlist": "Lista de permissão" } + }, + "mode": { + "label": "Modo de conexão", + "choices": { + "socket": "Modo de soquete" + } + }, + "webhookPath": { + "label": "Caminho do webhook" + }, + "replyInThread": { + "label": "Responder no tópico", + "choices": { + "true": "Ligado", + "false": "Desligado" + } + }, + "reactEmoji": { + "label": "Ler emoticons" + }, + "doneEmoji": { + "label": "Emoji pronto" + }, + "includeThreadContext": { + "label": "Incluir contexto do thread", + "choices": { + "true": "Ligado", + "false": "Desligado" + } + }, + "threadContextLimit": { + "label": "Limite de contexto do thread" + }, + "allowFrom": { + "label": "Usuários permitidos" + }, + "groupAllowFrom": { + "label": "Canais permitidos" + }, + "groupRequireMention": { + "label": "Exigir menções nos canais", + "choices": { + "true": "Ligado", + "false": "Desligado" + } + }, + "dm_enabled": { + "label": "Habilitar mensagens diretas", + "choices": { + "true": "Ligado", + "false": "Desligado" + } + }, + "dm_policy": { + "label": "Acesso direto a mensagens", + "choices": { + "allowlist": "Lista de permissões", + "open": "Abrir" + } + }, + "dm_allowFrom": { + "label": "Usuários de mensagens diretas permitidos" + }, + "proxy": { + "label": "Proxy de rede", + "placeholder": "http://127.0.0.1:7890" } } } diff --git a/nanobot/channels/slack/webui/locales/vi.json b/nanobot/channels/slack/webui/locales/vi.json index bda92d53c..b982affd5 100644 --- a/nanobot/channels/slack/webui/locales/vi.json +++ b/nanobot/channels/slack/webui/locales/vi.json @@ -1,29 +1,18 @@ { - "description": "Sử dụng nanobot trong không gian Slack.", - "requirements": "Token ứng dụng Slack, token bot và ứng dụng đã cài vào không gian làm việc", "setup": { "docsLabel": "Mở hướng dẫn Slack", "officialLabel": "Mở ứng dụng Slack", - "tryIt": "Nhắc ứng dụng Slack hoặc gửi tin nhắn riêng.", - "summary": "Slack mặc định dùng Socket Mode nên cần cả token ứng dụng và token bot.", - "steps": [ - "Tạo ứng dụng Slack từ bản khai được cung cấp và bật Socket Mode.", - "Cài ứng dụng vào không gian làm việc rồi sao chép token ứng dụng và token bot.", - "Lưu và bật Slack, sau đó nhắc ứng dụng hoặc gửi tin nhắn riêng." - ], "actions": { "slack-manifest": "Sao chép bản khai ứng dụng" }, "fields": { "appToken": { "label": "Token ứng dụng", - "placeholder": "xapp-...", - "help": "Tạo token trong phần cài đặt Socket Mode của ứng dụng Slack." + "placeholder": "xapp-..." }, "botToken": { "label": "Token bot", - "placeholder": "xoxb-...", - "help": "Dùng token bot sau khi cài ứng dụng Slack." + "placeholder": "xoxb-..." }, "groupPolicy": { "label": "Hành vi trong nhóm", @@ -32,6 +21,72 @@ "open": "Mọi tin nhắn", "allowlist": "Danh sách cho phép" } + }, + "mode": { + "label": "Chế độ kết nối", + "choices": { + "socket": "Chế độ ổ cắm" + } + }, + "webhookPath": { + "label": "Đường dẫn webhook" + }, + "replyInThread": { + "label": "Trả lời trong chủ đề", + "choices": { + "true": "Bật", + "false": "Tắt" + } + }, + "reactEmoji": { + "label": "Đọc biểu tượng cảm xúc" + }, + "doneEmoji": { + "label": "biểu tượng cảm xúc xong" + }, + "includeThreadContext": { + "label": "Bao gồm bối cảnh chủ đề", + "choices": { + "true": "Bật", + "false": "Tắt" + } + }, + "threadContextLimit": { + "label": "Giới hạn bối cảnh của chủ đề" + }, + "allowFrom": { + "label": "Người dùng được phép" + }, + "groupAllowFrom": { + "label": "Các kênh được phép" + }, + "groupRequireMention": { + "label": "Yêu cầu đề cập trong các kênh", + "choices": { + "true": "Bật", + "false": "Tắt" + } + }, + "dm_enabled": { + "label": "Bật tin nhắn trực tiếp", + "choices": { + "true": "Bật", + "false": "Tắt" + } + }, + "dm_policy": { + "label": "Truy cập tin nhắn trực tiếp", + "choices": { + "allowlist": "Danh sách cho phép", + "open": "Mở" + } + }, + "dm_allowFrom": { + "label": "Cho phép người dùng nhắn tin trực tiếp" + }, + "proxy": { + "label": "Proxy mạng", + "placeholder": "http://127.0.0.1:7890" } } } diff --git a/nanobot/channels/slack/webui/locales/zh-CN.json b/nanobot/channels/slack/webui/locales/zh-CN.json index fdaae0838..93894b3f1 100644 --- a/nanobot/channels/slack/webui/locales/zh-CN.json +++ b/nanobot/channels/slack/webui/locales/zh-CN.json @@ -1,29 +1,18 @@ { - "description": "在 Slack 工作区中使用 nanobot。", - "requirements": "Slack 应用令牌、机器人令牌和工作区安装", "setup": { "docsLabel": "打开 Slack 配置指南", "officialLabel": "打开 Slack 应用后台", - "tryIt": "提及 Slack 应用,或向它发送私信。", - "summary": "Slack 默认使用 Socket Mode,因此同时需要应用级令牌和机器人令牌。", - "steps": [ - "使用提供的 manifest 创建 Slack 应用并启用 Socket Mode。", - "将应用安装到工作区,并复制应用令牌和机器人令牌。", - "保存并启用 Slack,然后提及应用或发送私信。" - ], "actions": { "slack-manifest": "复制应用清单" }, "fields": { "appToken": { "label": "应用令牌", - "placeholder": "xapp-...", - "help": "在 Slack 应用的 Socket Mode 设置中创建。" + "placeholder": "xapp-..." }, "botToken": { "label": "机器人令牌", - "placeholder": "xoxb-...", - "help": "安装 Slack 应用后使用机器人令牌。" + "placeholder": "xoxb-..." }, "groupPolicy": { "label": "群组行为", @@ -32,6 +21,72 @@ "open": "所有消息", "allowlist": "白名单" } + }, + "mode": { + "label": "连接方式", + "choices": { + "socket": "Socket 模式" + } + }, + "webhookPath": { + "label": "Webhook 路径" + }, + "replyInThread": { + "label": "在话题中回复", + "choices": { + "true": "开启", + "false": "关闭" + } + }, + "reactEmoji": { + "label": "已读表情" + }, + "doneEmoji": { + "label": "完成表情" + }, + "includeThreadContext": { + "label": "包含话题上下文", + "choices": { + "true": "开启", + "false": "关闭" + } + }, + "threadContextLimit": { + "label": "话题上下文上限" + }, + "allowFrom": { + "label": "允许的用户" + }, + "groupAllowFrom": { + "label": "允许的频道" + }, + "groupRequireMention": { + "label": "频道中需要提及", + "choices": { + "true": "开启", + "false": "关闭" + } + }, + "dm_enabled": { + "label": "启用私聊", + "choices": { + "true": "开启", + "false": "关闭" + } + }, + "dm_policy": { + "label": "私聊权限", + "choices": { + "allowlist": "白名单", + "open": "全部" + } + }, + "dm_allowFrom": { + "label": "允许私聊的用户" + }, + "proxy": { + "label": "网络代理", + "placeholder": "http://127.0.0.1:7890" } } } diff --git a/nanobot/channels/slack/webui/locales/zh-TW.json b/nanobot/channels/slack/webui/locales/zh-TW.json index bd700196d..205b53e4d 100644 --- a/nanobot/channels/slack/webui/locales/zh-TW.json +++ b/nanobot/channels/slack/webui/locales/zh-TW.json @@ -1,29 +1,18 @@ { - "description": "在 Slack 工作區中使用 nanobot。", - "requirements": "Slack 應用程式權杖、機器人權杖和工作區安裝", "setup": { "docsLabel": "開啟 Slack 設定指南", "officialLabel": "開啟 Slack 應用程式後台", - "tryIt": "提及 Slack 應用程式,或向它傳送私訊。", - "summary": "Slack 預設使用 Socket Mode,因此同時需要應用程式層級權杖和機器人權杖。", - "steps": [ - "使用提供的應用程式資訊清單建立 Slack 應用程式,並啟用 Socket Mode。", - "將應用程式安裝到工作區,並複製應用程式權杖和機器人權杖。", - "儲存並啟用 Slack,然後提及應用程式或傳送私訊。" - ], "actions": { "slack-manifest": "複製應用程式資訊清單" }, "fields": { "appToken": { "label": "應用程式權杖", - "placeholder": "xapp-...", - "help": "在 Slack 應用程式的 Socket Mode 設定中建立。" + "placeholder": "xapp-..." }, "botToken": { "label": "機器人權杖", - "placeholder": "xoxb-...", - "help": "安裝 Slack 應用程式後使用機器人權杖。" + "placeholder": "xoxb-..." }, "groupPolicy": { "label": "群組行為", @@ -32,6 +21,72 @@ "open": "所有訊息", "allowlist": "允許清單" } + }, + "mode": { + "label": "連接方式", + "choices": { + "socket": "Socket 模式" + } + }, + "webhookPath": { + "label": "Webhook 路徑" + }, + "replyInThread": { + "label": "在話題中回复", + "choices": { + "true": "開啟", + "false": "關閉" + } + }, + "reactEmoji": { + "label": "已讀表情" + }, + "doneEmoji": { + "label": "完成表情" + }, + "includeThreadContext": { + "label": "包含話題上下文", + "choices": { + "true": "開啟", + "false": "關閉" + } + }, + "threadContextLimit": { + "label": "話題上下文上限" + }, + "allowFrom": { + "label": "允許的用戶" + }, + "groupAllowFrom": { + "label": "允許的頻道" + }, + "groupRequireMention": { + "label": "頻道中需要提及", + "choices": { + "true": "開啟", + "false": "關閉" + } + }, + "dm_enabled": { + "label": "啟用私聊", + "choices": { + "true": "開啟", + "false": "關閉" + } + }, + "dm_policy": { + "label": "私聊權限", + "choices": { + "allowlist": "白名單", + "open": "全部" + } + }, + "dm_allowFrom": { + "label": "允許私聊的用戶" + }, + "proxy": { + "label": "網路代理", + "placeholder": "http://127.0.0.1:7890" } } } diff --git a/nanobot/channels/telegram/manifest.py b/nanobot/channels/telegram/manifest.py index f02a7a401..93d806ee3 100644 --- a/nanobot/channels/telegram/manifest.py +++ b/nanobot/channels/telegram/manifest.py @@ -8,13 +8,29 @@ from nanobot.channels.telegram.validation import validate SETUP_SPEC = ChannelSetupSpec( fields={ "token": field("secret"), - "proxy": field("secret"), + "proxy": field(), "allowFrom": field("list"), "groupPolicy": field("enum", choices=GROUP_POLICIES, default="mention"), + "mode": field("enum", choices={"polling", "webhook"}, default="polling"), + "replyToMessage": field("bool", default=False), + "reactEmoji": field(default="👀"), + "connectionPoolSize": field("int", default=32), + "poolTimeout": field("float", default=5.0), + "streaming": field("bool", default=True), + "inlineKeyboards": field("bool", default=False), + "richMessages": field("bool", default=False), + "streamEditInterval": field("float", default=0.6), + "webhookUrl": field(), + "webhookListenHost": field(default="127.0.0.1"), + "webhookListenPort": field("int", default=8081), + "webhookPath": field(default="/telegram"), + "webhookSecretToken": field("secret"), + "webhookMaxConnections": field("int", default=4), }, required=(required("token"),), official_url="https://t.me/BotFather", validator=validate, + verifies_connection=True, ) PLUGIN = ChannelPlugin( diff --git a/nanobot/channels/telegram/runtime.py b/nanobot/channels/telegram/runtime.py index f104e35d2..532b04a1d 100644 --- a/nanobot/channels/telegram/runtime.py +++ b/nanobot/channels/telegram/runtime.py @@ -659,6 +659,8 @@ class TelegramChannel(BaseChannel): async def _start_app(self) -> None: """Build, initialize and start the Telegram application.""" proxy = self.config.proxy or None + if proxy and "://" not in proxy: + proxy = f"http://{proxy}" # Separate pools so long-polling (getUpdates) never starves outbound sends. api_request = HTTPXRequest( diff --git a/nanobot/channels/telegram/tests/test_validation.py b/nanobot/channels/telegram/tests/test_validation.py index 95c8278c1..81fe982ba 100644 --- a/nanobot/channels/telegram/tests/test_validation.py +++ b/nanobot/channels/telegram/tests/test_validation.py @@ -10,10 +10,10 @@ from nanobot.config.loader import save_config from nanobot.config.schema import Config -def test_telegram_setup_exposes_proxy_as_an_optional_secret() -> None: +def test_telegram_setup_exposes_proxy_as_an_optional_field() -> None: proxy = SETUP_SPEC.fields["proxy"] - assert proxy.kind == "secret" + assert proxy.kind == "string" assert "proxy" not in SETUP_SPEC.simple_required_fields @@ -58,6 +58,38 @@ def test_get_me_builds_http_client_with_explicit_proxy( assert captured["url"] == f"https://api.telegram.org/bot{token}/getMe" +def test_get_me_normalizes_proxy_without_a_scheme( + monkeypatch: pytest.MonkeyPatch, +) -> None: + captured: dict[str, object] = {} + + class FakeResponse: + def raise_for_status(self) -> None: + return None + + def json(self) -> dict: + return {"ok": True, "result": {"id": 42}} + + class FakeClient: + def __init__(self, **kwargs) -> None: + captured.update(kwargs) + + def __enter__(self): + return self + + def __exit__(self, *_args) -> None: + return None + + def get(self, _url: str) -> FakeResponse: + return FakeResponse() + + monkeypatch.setattr(telegram_validation.httpx, "Client", FakeClient) + + telegram_validation._get_me("123456:abcdefghijklmnopqrstuvwxyz", "127.0.0.1:7890") + + assert captured["proxy"] == "http://127.0.0.1:7890" + + def test_validate_telegram_bad_token_is_invalid(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None: config_path = tmp_path / "config.json" save_config(Config(), config_path) @@ -279,7 +311,7 @@ def test_validate_telegram_uses_proxy_submitted_with_new_token( assert captured == {"token": token, "proxy": proxy} -@pytest.mark.parametrize("proxy", ["127.0.0.1:7890", "http://[", "http://localhost:not-a-port"]) +@pytest.mark.parametrize("proxy", ["http://[", "http://localhost:not-a-port"]) def test_validate_telegram_rejects_invalid_proxy_without_trying_token( tmp_path, monkeypatch: pytest.MonkeyPatch, diff --git a/nanobot/channels/telegram/validation.py b/nanobot/channels/telegram/validation.py index 5931a5de6..67302566c 100644 --- a/nanobot/channels/telegram/validation.py +++ b/nanobot/channels/telegram/validation.py @@ -22,6 +22,8 @@ _SUPPORTED_PROXY_SCHEMES = {"http", "https", "socks5", "socks5h"} def _proxy_url_is_valid(proxy: str) -> bool: + if "://" not in proxy: + proxy = f"http://{proxy}" try: parsed = urlparse(proxy) hostname = parsed.hostname @@ -32,6 +34,8 @@ def _proxy_url_is_valid(proxy: str) -> bool: def _get_me(token: str, proxy: str | None) -> dict[str, Any]: + if proxy and "://" not in proxy: + proxy = f"http://{proxy}" client_kwargs: dict[str, Any] = {"timeout": _TIMEOUT_SECONDS} if proxy: client_kwargs.update(proxy=proxy, trust_env=False) @@ -74,7 +78,7 @@ def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dict "proxy_format", "Network proxy", "fail", - "Enter a full HTTP or SOCKS proxy URL.", + "Enter a valid HTTP or SOCKS proxy.", ) ) return status_from_checks("telegram", checks, missing) diff --git a/nanobot/channels/telegram/webui/index.ts b/nanobot/channels/telegram/webui/index.ts index 57d4cdc83..4def46c0b 100644 --- a/nanobot/channels/telegram/webui/index.ts +++ b/nanobot/channels/telegram/webui/index.ts @@ -3,18 +3,18 @@ import { chatAppGuideUrl } from "@/components/settings/channels/catalog"; export default { presentation: { + logoUrl: "https://telegram.org/favicon.ico", displayName: "Telegram", initials: "TG", color: "#229ED9", - logoUrl: "https://telegram.org/favicon.ico", setup: { mode: "credentials", docsUrl: chatAppGuideUrl("telegram"), fields: [ - { key: "channels.telegram.token" }, - { key: "channels.telegram.proxy" }, - { key: "channels.telegram.allowFrom" }, - { key: "channels.telegram.groupPolicy" }, + { key: "channels.telegram.token", section: "credentials" }, + { key: "channels.telegram.proxy", section: "connection" }, + { key: "channels.telegram.allowFrom", section: "access" }, + { key: "channels.telegram.groupPolicy", section: "behavior" }, ], }, }, diff --git a/nanobot/channels/telegram/webui/locales/en.json b/nanobot/channels/telegram/webui/locales/en.json index 72b01523b..faf5f0071 100644 --- a/nanobot/channels/telegram/webui/locales/en.json +++ b/nanobot/channels/telegram/webui/locales/en.json @@ -1,21 +1,11 @@ { - "description": "Chat with nanobot on Telegram.", - "requirements": "Bot token, allowed users, gateway", "setup": { "docsLabel": "Open Telegram setup", "officialLabel": "Open BotFather", - "tryIt": "Send /start or a short DM to your Telegram bot.", - "summary": "Add the bot token from BotFather to send and receive Telegram messages.", - "steps": [ - "Create a bot with BotFather and copy its token.", - "Add the token and choose who can message the bot.", - "Save and enable Telegram, then send the bot a direct message or mention it in a group." - ], "fields": { "token": { "label": "Bot token", - "placeholder": "123456:ABC...", - "help": "Create it with BotFather." + "placeholder": "123456:ABC..." }, "proxy": { "label": "Network proxy", @@ -23,8 +13,7 @@ }, "allowFrom": { "label": "Allowed users", - "placeholder": "* or Telegram user IDs", - "help": "Leave empty to use pairing codes." + "placeholder": "* or Telegram user IDs" }, "groupPolicy": { "label": "Group behavior", @@ -33,6 +22,71 @@ "open": "All messages", "allowlist": "Allowlist" } + }, + "mode": { + "label": "Connection mode", + "choices": { + "polling": "Long polling", + "webhook": "Webhook" + } + }, + "replyToMessage": { + "label": "Reply to message", + "choices": { + "true": "On", + "false": "Off" + } + }, + "reactEmoji": { + "label": "Read emoji" + }, + "connectionPoolSize": { + "label": "Connection pool size" + }, + "poolTimeout": { + "label": "Connection pool timeout" + }, + "streaming": { + "label": "Streaming", + "choices": { + "true": "On", + "false": "Off" + } + }, + "inlineKeyboards": { + "label": "Inline keyboards", + "choices": { + "true": "On", + "false": "Off" + } + }, + "richMessages": { + "label": "Rich messages", + "choices": { + "true": "On", + "false": "Off" + } + }, + "streamEditInterval": { + "label": "Stream update interval" + }, + "webhookUrl": { + "label": "Webhook URL" + }, + "webhookListenHost": { + "label": "Webhook listen host" + }, + "webhookListenPort": { + "label": "Webhook listen port" + }, + "webhookPath": { + "label": "Webhook path" + }, + "webhookSecretToken": { + "label": "Webhook secret token" + }, + "webhookMaxConnections": { + "label": "Maximum webhook connections" } } } diff --git a/nanobot/channels/telegram/webui/locales/es.json b/nanobot/channels/telegram/webui/locales/es.json index c3254e367..bdf9059ee 100644 --- a/nanobot/channels/telegram/webui/locales/es.json +++ b/nanobot/channels/telegram/webui/locales/es.json @@ -1,21 +1,11 @@ { - "description": "Chatea con nanobot desde Telegram.", - "requirements": "Token del bot, usuarios permitidos y pasarela", "setup": { "docsLabel": "Abrir guía de Telegram", "officialLabel": "Abrir BotFather", - "tryIt": "Envía /start o un DM corto a tu bot de Telegram.", - "summary": "Añade el token de bot obtenido en BotFather para enviar y recibir mensajes de Telegram.", - "steps": [ - "Crea un bot con BotFather y copia su token.", - "Añade el token y elige quién puede escribir al bot.", - "Guarda y activa Telegram; después envía un DM o menciona el bot en un grupo." - ], "fields": { "token": { "label": "Token del bot", - "placeholder": "123456:ABC...", - "help": "Créalo con BotFather." + "placeholder": "123456:ABC..." }, "proxy": { "label": "Proxy de red", @@ -23,8 +13,7 @@ }, "allowFrom": { "label": "Usuarios permitidos", - "placeholder": "* o ID de usuario de Telegram", - "help": "Déjalo vacío para usar códigos de vinculación." + "placeholder": "* o ID de usuario de Telegram" }, "groupPolicy": { "label": "Comportamiento en grupos", @@ -33,6 +22,71 @@ "open": "Todos los mensajes", "allowlist": "Lista de permitidos" } + }, + "mode": { + "label": "Modo de conexión", + "choices": { + "polling": "sondeo largo", + "webhook": "gancho web" + } + }, + "replyToMessage": { + "label": "Responder al mensaje", + "choices": { + "true": "encendido", + "false": "Apagado" + } + }, + "reactEmoji": { + "label": "Leer emojis" + }, + "connectionPoolSize": { + "label": "Tamaño del grupo de conexiones" + }, + "poolTimeout": { + "label": "Tiempo de espera del grupo de conexiones" + }, + "streaming": { + "label": "Transmisión", + "choices": { + "true": "encendido", + "false": "Apagado" + } + }, + "inlineKeyboards": { + "label": "teclados en línea", + "choices": { + "true": "encendido", + "false": "Apagado" + } + }, + "richMessages": { + "label": "Mensajes ricos", + "choices": { + "true": "encendido", + "false": "Apagado" + } + }, + "streamEditInterval": { + "label": "Intervalo de actualización de la transmisión" + }, + "webhookUrl": { + "label": "URL de webhook" + }, + "webhookListenHost": { + "label": "Anfitrión de escucha de webhook" + }, + "webhookListenPort": { + "label": "Puerto de escucha de webhook" + }, + "webhookPath": { + "label": "Ruta del webhook" + }, + "webhookSecretToken": { + "label": "Token secreto de webhook" + }, + "webhookMaxConnections": { + "label": "Conexiones máximas de webhooks" } } } diff --git a/nanobot/channels/telegram/webui/locales/fr.json b/nanobot/channels/telegram/webui/locales/fr.json index e1d1c995d..132bed936 100644 --- a/nanobot/channels/telegram/webui/locales/fr.json +++ b/nanobot/channels/telegram/webui/locales/fr.json @@ -1,21 +1,11 @@ { - "description": "Discutez avec nanobot depuis Telegram.", - "requirements": "Jeton du bot, utilisateurs autorisés et passerelle", "setup": { "docsLabel": "Ouvrir le guide Telegram", "officialLabel": "Ouvrir BotFather", - "tryIt": "Envoyez /start ou un court message privé à votre bot Telegram.", - "summary": "Ajoutez le jeton de bot obtenu auprès de BotFather pour envoyer et recevoir des messages Telegram.", - "steps": [ - "Créez un bot avec BotFather et copiez son jeton.", - "Ajoutez le jeton et choisissez qui peut contacter le bot.", - "Enregistrez et activez Telegram, puis envoyez un message privé ou mentionnez le bot dans un groupe." - ], "fields": { "token": { "label": "Jeton du bot", - "placeholder": "123456:ABC...", - "help": "Créez-le avec BotFather." + "placeholder": "123456:ABC..." }, "proxy": { "label": "Proxy réseau", @@ -23,8 +13,7 @@ }, "allowFrom": { "label": "Utilisateurs autorisés", - "placeholder": "* ou ID utilisateur Telegram", - "help": "Laissez vide pour utiliser les codes d’association." + "placeholder": "* ou ID utilisateur Telegram" }, "groupPolicy": { "label": "Comportement en groupe", @@ -33,6 +22,71 @@ "open": "Tous les messages", "allowlist": "Liste d’autorisation" } + }, + "mode": { + "label": "Mode de connexion", + "choices": { + "polling": "Sondage long", + "webhook": "Webhook" + } + }, + "replyToMessage": { + "label": "Répondre au message", + "choices": { + "true": "Sur", + "false": "Désactivé" + } + }, + "reactEmoji": { + "label": "Lire les emoji" + }, + "connectionPoolSize": { + "label": "Taille du pool de connexions" + }, + "poolTimeout": { + "label": "Expiration du délai du pool de connexions" + }, + "streaming": { + "label": "Diffusion en continu", + "choices": { + "true": "Sur", + "false": "Désactivé" + } + }, + "inlineKeyboards": { + "label": "Claviers en ligne", + "choices": { + "true": "Sur", + "false": "Désactivé" + } + }, + "richMessages": { + "label": "Messages riches", + "choices": { + "true": "Sur", + "false": "Désactivé" + } + }, + "streamEditInterval": { + "label": "Intervalle de mise à jour du flux" + }, + "webhookUrl": { + "label": "URL du webhook" + }, + "webhookListenHost": { + "label": "Hôte d'écoute du webhook" + }, + "webhookListenPort": { + "label": "Port d'écoute du webhook" + }, + "webhookPath": { + "label": "Chemin du webhook" + }, + "webhookSecretToken": { + "label": "Jeton secret Webhook" + }, + "webhookMaxConnections": { + "label": "Nombre maximal de connexions webhook" } } } diff --git a/nanobot/channels/telegram/webui/locales/id.json b/nanobot/channels/telegram/webui/locales/id.json index 73b6a4b87..049bd7084 100644 --- a/nanobot/channels/telegram/webui/locales/id.json +++ b/nanobot/channels/telegram/webui/locales/id.json @@ -1,21 +1,11 @@ { - "description": "Mengobrol dengan nanobot dari Telegram.", - "requirements": "Token bot, pengguna yang diizinkan, dan gateway", "setup": { "docsLabel": "Buka panduan Telegram", "officialLabel": "Buka BotFather", - "tryIt": "Kirim /start atau DM singkat ke bot Telegram Anda.", - "summary": "Tambahkan token bot dari BotFather untuk mengirim dan menerima pesan Telegram.", - "steps": [ - "Buat bot dengan BotFather dan salin tokennya.", - "Tambahkan token dan pilih siapa yang boleh mengirim pesan ke bot.", - "Simpan dan aktifkan Telegram, lalu kirim DM atau sebut bot di grup." - ], "fields": { "token": { "label": "Token bot", - "placeholder": "123456:ABC...", - "help": "Buat dengan BotFather." + "placeholder": "123456:ABC..." }, "proxy": { "label": "Proxy jaringan", @@ -23,8 +13,7 @@ }, "allowFrom": { "label": "Pengguna yang diizinkan", - "placeholder": "* atau ID pengguna Telegram", - "help": "Kosongkan untuk memakai kode pairing." + "placeholder": "* atau ID pengguna Telegram" }, "groupPolicy": { "label": "Perilaku grup", @@ -33,6 +22,71 @@ "open": "Semua pesan", "allowlist": "Daftar izin" } + }, + "mode": { + "label": "Modus koneksi", + "choices": { + "polling": "Jajak pendapat yang panjang", + "webhook": "kait web" + } + }, + "replyToMessage": { + "label": "Membalas pesan", + "choices": { + "true": "Aktif", + "false": "Mati" + } + }, + "reactEmoji": { + "label": "Baca emoji" + }, + "connectionPoolSize": { + "label": "Ukuran kumpulan koneksi" + }, + "poolTimeout": { + "label": "Batas waktu kumpulan koneksi habis" + }, + "streaming": { + "label": "Streaming", + "choices": { + "true": "Aktif", + "false": "Mati" + } + }, + "inlineKeyboards": { + "label": "Keyboard sebaris", + "choices": { + "true": "Aktif", + "false": "Mati" + } + }, + "richMessages": { + "label": "Pesan yang kaya", + "choices": { + "true": "Aktif", + "false": "Mati" + } + }, + "streamEditInterval": { + "label": "Interval pembaruan aliran" + }, + "webhookUrl": { + "label": "URL kait web" + }, + "webhookListenHost": { + "label": "Tuan rumah mendengarkan webhook" + }, + "webhookListenPort": { + "label": "Port mendengarkan webhook" + }, + "webhookPath": { + "label": "Jalur webhook" + }, + "webhookSecretToken": { + "label": "Token rahasia webhook" + }, + "webhookMaxConnections": { + "label": "Koneksi webhook maksimum" } } } diff --git a/nanobot/channels/telegram/webui/locales/ja.json b/nanobot/channels/telegram/webui/locales/ja.json index 82d283081..e5f6f1e59 100644 --- a/nanobot/channels/telegram/webui/locales/ja.json +++ b/nanobot/channels/telegram/webui/locales/ja.json @@ -1,21 +1,11 @@ { - "description": "Telegram で nanobot とチャットします。", - "requirements": "ボットトークン、許可するユーザー、ゲートウェイ", "setup": { "docsLabel": "Telegram 設定ガイドを開く", "officialLabel": "BotFather を開く", - "tryIt": "Telegram ボットに /start または短い DM を送信します。", - "summary": "Telegram でメッセージを送受信するには、BotFather で取得したボットトークンを入力してください。", - "steps": [ - "BotFather でボットを作成し、トークンをコピーします。", - "トークンを追加し、ボットに連絡できるユーザーを選びます。", - "保存して Telegram を有効にし、DM を送るかグループでメンションします。" - ], "fields": { "token": { "label": "ボットトークン", - "placeholder": "123456:ABC...", - "help": "BotFather で作成します。" + "placeholder": "123456:ABC..." }, "proxy": { "label": "ネットワークプロキシ", @@ -23,8 +13,7 @@ }, "allowFrom": { "label": "許可するユーザー", - "placeholder": "* または Telegram ユーザー ID", - "help": "ペアリングコードを使う場合は空欄にします。" + "placeholder": "* または Telegram ユーザー ID" }, "groupPolicy": { "label": "グループでの動作", @@ -33,6 +22,71 @@ "open": "すべてのメッセージ", "allowlist": "許可リスト" } + }, + "mode": { + "label": "接続モード", + "choices": { + "polling": "ロングポーリング", + "webhook": "Webhook" + } + }, + "replyToMessage": { + "label": "メッセージに返信する", + "choices": { + "true": "オン", + "false": "オフ" + } + }, + "reactEmoji": { + "label": "絵文字を読む" + }, + "connectionPoolSize": { + "label": "接続プールのサイズ" + }, + "poolTimeout": { + "label": "接続プールのタイムアウト" + }, + "streaming": { + "label": "ストリーミング", + "choices": { + "true": "オン", + "false": "オフ" + } + }, + "inlineKeyboards": { + "label": "インラインキーボード", + "choices": { + "true": "オン", + "false": "オフ" + } + }, + "richMessages": { + "label": "リッチメッセージ", + "choices": { + "true": "オン", + "false": "オフ" + } + }, + "streamEditInterval": { + "label": "ストリーム更新間隔" + }, + "webhookUrl": { + "label": "Webhook URL" + }, + "webhookListenHost": { + "label": "Webhook リッスン ホスト" + }, + "webhookListenPort": { + "label": "Webhook リッスン ポート" + }, + "webhookPath": { + "label": "Webhook パス" + }, + "webhookSecretToken": { + "label": "Webhook シークレット トークン" + }, + "webhookMaxConnections": { + "label": "Webhook 接続の最大数" } } } diff --git a/nanobot/channels/telegram/webui/locales/ko.json b/nanobot/channels/telegram/webui/locales/ko.json index 66d66cc5b..d148fe437 100644 --- a/nanobot/channels/telegram/webui/locales/ko.json +++ b/nanobot/channels/telegram/webui/locales/ko.json @@ -1,21 +1,11 @@ { - "description": "Telegram 채팅에서 nanobot과 대화합니다.", - "requirements": "봇 토큰, 허용된 사용자 및 게이트웨이", "setup": { "docsLabel": "Telegram 설정 가이드 열기", "officialLabel": "BotFather 열기", - "tryIt": "Telegram 봇에 /start 또는 짧은 DM을 보내세요.", - "summary": "Telegram 메시지를 주고받으려면 BotFather에서 발급받은 봇 토큰을 입력하세요.", - "steps": [ - "BotFather로 봇을 만들고 토큰을 복사하세요.", - "토큰을 추가하고 봇에 메시지를 보낼 사용자를 선택하세요.", - "저장하고 Telegram을 활성화한 다음 DM을 보내거나 그룹에서 멘션하세요." - ], "fields": { "token": { "label": "봇 토큰", - "placeholder": "123456:ABC...", - "help": "BotFather에서 생성하세요." + "placeholder": "123456:ABC..." }, "proxy": { "label": "네트워크 프록시", @@ -23,8 +13,7 @@ }, "allowFrom": { "label": "허용된 사용자", - "placeholder": "* 또는 Telegram 사용자 ID", - "help": "페어링 코드를 사용하려면 비워 두세요." + "placeholder": "* 또는 Telegram 사용자 ID" }, "groupPolicy": { "label": "그룹 동작", @@ -33,6 +22,71 @@ "open": "모든 메시지", "allowlist": "허용 목록" } + }, + "mode": { + "label": "연결 모드", + "choices": { + "polling": "긴 폴링", + "webhook": "웹훅" + } + }, + "replyToMessage": { + "label": "메시지에 답장하기", + "choices": { + "true": "켜기", + "false": "끄기" + } + }, + "reactEmoji": { + "label": "이모티콘 읽기" + }, + "connectionPoolSize": { + "label": "연결 풀 크기" + }, + "poolTimeout": { + "label": "연결 풀 시간 초과" + }, + "streaming": { + "label": "스트리밍", + "choices": { + "true": "켜기", + "false": "끄기" + } + }, + "inlineKeyboards": { + "label": "인라인 키보드", + "choices": { + "true": "켜기", + "false": "끄기" + } + }, + "richMessages": { + "label": "리치 메시지", + "choices": { + "true": "켜기", + "false": "끄기" + } + }, + "streamEditInterval": { + "label": "스트림 업데이트 간격" + }, + "webhookUrl": { + "label": "웹훅 URL" + }, + "webhookListenHost": { + "label": "웹훅 청취 호스트" + }, + "webhookListenPort": { + "label": "웹훅 수신 포트" + }, + "webhookPath": { + "label": "웹훅 경로" + }, + "webhookSecretToken": { + "label": "웹훅 비밀 토큰" + }, + "webhookMaxConnections": { + "label": "최대 웹훅 연결" } } } diff --git a/nanobot/channels/telegram/webui/locales/pt-BR.json b/nanobot/channels/telegram/webui/locales/pt-BR.json index 7db3344d3..9a5505450 100644 --- a/nanobot/channels/telegram/webui/locales/pt-BR.json +++ b/nanobot/channels/telegram/webui/locales/pt-BR.json @@ -1,21 +1,11 @@ { - "description": "Converse com o nanobot pelo Telegram.", - "requirements": "Token do bot, usuários permitidos e gateway", "setup": { "docsLabel": "Abrir guia do Telegram", "officialLabel": "Abrir BotFather", - "tryIt": "Envie /start ou uma DM curta ao seu bot do Telegram.", - "summary": "Adicione o token de bot obtido no BotFather para enviar e receber mensagens do Telegram.", - "steps": [ - "Crie um bot com o BotFather e copie o token.", - "Adicione o token e escolha quem pode enviar mensagens ao bot.", - "Salve e ative o Telegram; depois, envie uma DM ou mencione o bot em um grupo." - ], "fields": { "token": { "label": "Token do bot", - "placeholder": "123456:ABC...", - "help": "Crie-o com o BotFather." + "placeholder": "123456:ABC..." }, "proxy": { "label": "Proxy de rede", @@ -23,8 +13,7 @@ }, "allowFrom": { "label": "Usuários permitidos", - "placeholder": "* ou IDs de usuário do Telegram", - "help": "Deixe vazio para usar códigos de pareamento." + "placeholder": "* ou IDs de usuário do Telegram" }, "groupPolicy": { "label": "Comportamento em grupos", @@ -33,6 +22,71 @@ "open": "Todas as mensagens", "allowlist": "Lista de permissão" } + }, + "mode": { + "label": "Modo de conexão", + "choices": { + "polling": "Votação longa", + "webhook": "Webhook" + } + }, + "replyToMessage": { + "label": "Responder à mensagem", + "choices": { + "true": "Ligado", + "false": "Desligado" + } + }, + "reactEmoji": { + "label": "Ler emoticons" + }, + "connectionPoolSize": { + "label": "Tamanho do pool de conexões" + }, + "poolTimeout": { + "label": "Tempo limite do pool de conexões" + }, + "streaming": { + "label": "Transmissão", + "choices": { + "true": "Ligado", + "false": "Desligado" + } + }, + "inlineKeyboards": { + "label": "Teclados embutidos", + "choices": { + "true": "Ligado", + "false": "Desligado" + } + }, + "richMessages": { + "label": "Mensagens ricas", + "choices": { + "true": "Ligado", + "false": "Desligado" + } + }, + "streamEditInterval": { + "label": "Intervalo de atualização de fluxo" + }, + "webhookUrl": { + "label": "URL do webhook" + }, + "webhookListenHost": { + "label": "Host de escuta do webhook" + }, + "webhookListenPort": { + "label": "Porta de escuta do webhook" + }, + "webhookPath": { + "label": "Caminho do webhook" + }, + "webhookSecretToken": { + "label": "Token secreto do webhook" + }, + "webhookMaxConnections": { + "label": "Máximo de conexões de webhook" } } } diff --git a/nanobot/channels/telegram/webui/locales/vi.json b/nanobot/channels/telegram/webui/locales/vi.json index 3431b5223..71a28c498 100644 --- a/nanobot/channels/telegram/webui/locales/vi.json +++ b/nanobot/channels/telegram/webui/locales/vi.json @@ -1,21 +1,11 @@ { - "description": "Trò chuyện với nanobot từ Telegram.", - "requirements": "Token bot, người dùng được phép và gateway", "setup": { "docsLabel": "Mở hướng dẫn Telegram", "officialLabel": "Mở BotFather", - "tryIt": "Gửi /start hoặc tin nhắn riêng ngắn đến bot Telegram.", - "summary": "Thêm token bot lấy từ BotFather để gửi và nhận tin nhắn Telegram.", - "steps": [ - "Tạo bot bằng BotFather và sao chép token.", - "Thêm token và chọn người có thể nhắn cho bot.", - "Lưu và bật Telegram, sau đó gửi tin nhắn riêng hoặc nhắc bot trong nhóm." - ], "fields": { "token": { "label": "Token bot", - "placeholder": "123456:ABC...", - "help": "Tạo bằng BotFather." + "placeholder": "123456:ABC..." }, "proxy": { "label": "Proxy mạng", @@ -23,8 +13,7 @@ }, "allowFrom": { "label": "Người dùng được phép", - "placeholder": "* hoặc ID người dùng Telegram", - "help": "Để trống để dùng mã ghép nối." + "placeholder": "* hoặc ID người dùng Telegram" }, "groupPolicy": { "label": "Hành vi trong nhóm", @@ -33,6 +22,71 @@ "open": "Mọi tin nhắn", "allowlist": "Danh sách cho phép" } + }, + "mode": { + "label": "Chế độ kết nối", + "choices": { + "polling": "Bỏ phiếu dài", + "webhook": "Webhook" + } + }, + "replyToMessage": { + "label": "Trả lời tin nhắn", + "choices": { + "true": "Bật", + "false": "Tắt" + } + }, + "reactEmoji": { + "label": "Đọc biểu tượng cảm xúc" + }, + "connectionPoolSize": { + "label": "Kích thước nhóm kết nối" + }, + "poolTimeout": { + "label": "Hết thời gian chờ nhóm kết nối" + }, + "streaming": { + "label": "Truyền phát", + "choices": { + "true": "Bật", + "false": "Tắt" + } + }, + "inlineKeyboards": { + "label": "Bàn phím nội tuyến", + "choices": { + "true": "Bật", + "false": "Tắt" + } + }, + "richMessages": { + "label": "Tin nhắn phong phú", + "choices": { + "true": "Bật", + "false": "Tắt" + } + }, + "streamEditInterval": { + "label": "Khoảng thời gian cập nhật luồng" + }, + "webhookUrl": { + "label": "URL webhook" + }, + "webhookListenHost": { + "label": "Máy chủ lắng nghe Webhook" + }, + "webhookListenPort": { + "label": "Cổng nghe Webhook" + }, + "webhookPath": { + "label": "Đường dẫn webhook" + }, + "webhookSecretToken": { + "label": "Mã thông báo bí mật Webhook" + }, + "webhookMaxConnections": { + "label": "Kết nối webhook tối đa" } } } diff --git a/nanobot/channels/telegram/webui/locales/zh-CN.json b/nanobot/channels/telegram/webui/locales/zh-CN.json index c8e80ef62..64962d355 100644 --- a/nanobot/channels/telegram/webui/locales/zh-CN.json +++ b/nanobot/channels/telegram/webui/locales/zh-CN.json @@ -1,21 +1,11 @@ { - "description": "在 Telegram 中与 nanobot 聊天。", - "requirements": "机器人令牌、允许的用户和网关", "setup": { "docsLabel": "打开 Telegram 配置指南", "officialLabel": "打开 BotFather", - "tryIt": "向 Telegram 机器人发送 /start 或一条简短私信。", - "summary": "填写从 BotFather 获取的机器人令牌后,即可收发 Telegram 消息。", - "steps": [ - "使用 BotFather 创建机器人并复制令牌。", - "填写令牌并选择哪些用户可以向机器人发送消息。", - "保存并启用 Telegram,然后向机器人发送私信或在群组中提及它。" - ], "fields": { "token": { "label": "机器人令牌", - "placeholder": "123456:ABC...", - "help": "使用 BotFather 创建。" + "placeholder": "123456:ABC..." }, "proxy": { "label": "网络代理", @@ -23,8 +13,7 @@ }, "allowFrom": { "label": "允许的用户", - "placeholder": "* 或 Telegram 用户 ID", - "help": "留空则使用配对码。" + "placeholder": "* 或 Telegram 用户 ID" }, "groupPolicy": { "label": "群组行为", @@ -33,6 +22,71 @@ "open": "所有消息", "allowlist": "白名单" } + }, + "mode": { + "label": "连接方式", + "choices": { + "polling": "长轮询", + "webhook": "Webhook" + } + }, + "replyToMessage": { + "label": "引用回复", + "choices": { + "true": "开启", + "false": "关闭" + } + }, + "reactEmoji": { + "label": "已读表情" + }, + "connectionPoolSize": { + "label": "连接池大小" + }, + "poolTimeout": { + "label": "连接池超时" + }, + "streaming": { + "label": "流式输出", + "choices": { + "true": "开启", + "false": "关闭" + } + }, + "inlineKeyboards": { + "label": "内联键盘", + "choices": { + "true": "开启", + "false": "关闭" + } + }, + "richMessages": { + "label": "富文本消息", + "choices": { + "true": "开启", + "false": "关闭" + } + }, + "streamEditInterval": { + "label": "流式更新间隔" + }, + "webhookUrl": { + "label": "Webhook 地址" + }, + "webhookListenHost": { + "label": "Webhook 监听地址" + }, + "webhookListenPort": { + "label": "Webhook 监听端口" + }, + "webhookPath": { + "label": "Webhook 路径" + }, + "webhookSecretToken": { + "label": "Webhook 密钥" + }, + "webhookMaxConnections": { + "label": "Webhook 最大连接数" } } } diff --git a/nanobot/channels/telegram/webui/locales/zh-TW.json b/nanobot/channels/telegram/webui/locales/zh-TW.json index 6aeb9b3a8..e759698bb 100644 --- a/nanobot/channels/telegram/webui/locales/zh-TW.json +++ b/nanobot/channels/telegram/webui/locales/zh-TW.json @@ -1,21 +1,11 @@ { - "description": "在 Telegram 中與 nanobot 聊天。", - "requirements": "機器人權杖、允許的使用者和閘道", "setup": { "docsLabel": "開啟 Telegram 設定指南", "officialLabel": "開啟 BotFather", - "tryIt": "向 Telegram 機器人傳送 /start 或一則簡短私訊。", - "summary": "填入從 BotFather 取得的機器人權杖,才能收發 Telegram 訊息。", - "steps": [ - "使用 BotFather 建立機器人並複製權杖。", - "填入權杖並選擇哪些使用者可以向機器人傳送訊息。", - "儲存並啟用 Telegram,然後傳送私訊或在群組中提及機器人。" - ], "fields": { "token": { "label": "機器人權杖", - "placeholder": "123456:ABC...", - "help": "使用 BotFather 建立。" + "placeholder": "123456:ABC..." }, "proxy": { "label": "網路代理", @@ -23,8 +13,7 @@ }, "allowFrom": { "label": "允許的使用者", - "placeholder": "* 或 Telegram 使用者 ID", - "help": "留空則使用配對碼。" + "placeholder": "* 或 Telegram 使用者 ID" }, "groupPolicy": { "label": "群組行為", @@ -33,6 +22,71 @@ "open": "所有訊息", "allowlist": "允許清單" } + }, + "mode": { + "label": "連接方式", + "choices": { + "polling": "長輪詢", + "webhook": "Webhook" + } + }, + "replyToMessage": { + "label": "引用回覆", + "choices": { + "true": "開啟", + "false": "關閉" + } + }, + "reactEmoji": { + "label": "已讀表情" + }, + "connectionPoolSize": { + "label": "連線池大小" + }, + "poolTimeout": { + "label": "連接池逾時" + }, + "streaming": { + "label": "串流輸出", + "choices": { + "true": "開啟", + "false": "關閉" + } + }, + "inlineKeyboards": { + "label": "內聯鍵盤", + "choices": { + "true": "開啟", + "false": "關閉" + } + }, + "richMessages": { + "label": "富文本訊息", + "choices": { + "true": "開啟", + "false": "關閉" + } + }, + "streamEditInterval": { + "label": "串流更新間隔" + }, + "webhookUrl": { + "label": "Webhook 地址" + }, + "webhookListenHost": { + "label": "Webhook 監聽地址" + }, + "webhookListenPort": { + "label": "Webhook 監聽端口" + }, + "webhookPath": { + "label": "Webhook 路徑" + }, + "webhookSecretToken": { + "label": "Webhook 密鑰" + }, + "webhookMaxConnections": { + "label": "Webhook 最大連線數" } } } diff --git a/nanobot/channels/validation.py b/nanobot/channels/validation.py index 661664ca1..4432ffdee 100644 --- a/nanobot/channels/validation.py +++ b/nanobot/channels/validation.py @@ -135,9 +135,9 @@ def _merge_form_values( if not raw_key: continue field = raw_key[len(prefix):] if raw_key.startswith(prefix) else raw_key - if field in secrets and not _str(raw_value): + if field in secrets and raw_value is not None and not _str(raw_value): continue - _assign(merged, field, raw_value) + _assign(merged, field, "" if field in secrets and raw_value is None else raw_value) return merged @@ -341,16 +341,30 @@ def _message_from_response(data: dict[str, Any], fallback: str) -> str: return str(error) if error else fallback -def _http_get(url: str, *, headers: dict[str, str] | None = None) -> dict[str, Any]: - with httpx.Client(timeout=_TIMEOUT_SECONDS) as client: +def _http_get( + url: str, + *, + headers: dict[str, str] | None = None, + proxy: str | None = None, +) -> dict[str, Any]: + if proxy and "://" not in proxy: + proxy = f"http://{proxy}" + with httpx.Client(timeout=_TIMEOUT_SECONDS, proxy=proxy) as client: response = client.get(url, headers=headers) response.raise_for_status() data = response.json() return cast(dict[str, Any], data) if isinstance(data, dict) else {} -def _http_post(url: str, *, headers: dict[str, str] | None = None) -> dict[str, Any]: - with httpx.Client(timeout=_TIMEOUT_SECONDS) as client: +def _http_post( + url: str, + *, + headers: dict[str, str] | None = None, + proxy: str | None = None, +) -> dict[str, Any]: + if proxy and "://" not in proxy: + proxy = f"http://{proxy}" + with httpx.Client(timeout=_TIMEOUT_SECONDS, proxy=proxy) as client: response = client.post(url, headers=headers) response.raise_for_status() data = response.json() diff --git a/nanobot/channels/websocket/tests/test_websocket_http_routes.py b/nanobot/channels/websocket/tests/test_websocket_http_routes.py index 72ea672ed..9c61e051b 100644 --- a/nanobot/channels/websocket/tests/test_websocket_http_routes.py +++ b/nanobot/channels/websocket/tests/test_websocket_http_routes.py @@ -1344,6 +1344,67 @@ async def test_nanobot_feature_channel_action_can_apply_without_restart( assert body["last_action"]["message"].endswith("Matrix channel applied without restart.") +@pytest.mark.asyncio +async def test_nanobot_feature_install_only_does_not_start_channel( + bus: MagicMock, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + runtime_calls: list[tuple[str, str, str | None]] = [] + + def feature_action( + action: str, + query: dict[str, list[str]], + *, + allow_install: bool, + config_path: Path, + ) -> dict[str, Any]: + assert action == "enable" + assert query == {"name": ["whatsapp"], "install_only": ["true"]} + assert allow_install is True + return { + "features": [{ + "name": "whatsapp", + "type": "channel", + "enabled": False, + "installed": True, + "ready": False, + "status": "not_enabled", + }], + "enabled_count": 0, + "requires_restart": False, + } + + async def channel_feature_action( + action: str, + name: str, + instance_id: str | None, + ) -> dict[str, Any]: + runtime_calls.append((action, name, instance_id)) + return {"handled": True, "ok": True, "requires_restart": False} + + monkeypatch.setattr( + "nanobot.webui.settings_routes.nanobot_features_action", + feature_action, + ) + channel = _ch( + bus, + session_manager=_seed_session(tmp_path), + port=_free_port(), + channel_feature_action=channel_feature_action, + ) + + response = await _webui_mutate( + channel, + "settings.feature.enable", + {"name": "whatsapp", "install_only": True}, + ) + + assert response.status_code == 200 + assert runtime_calls == [] + assert response.json()["features"][0]["enabled"] is False + + @pytest.mark.asyncio async def test_channel_connect_runtime_import_error_is_not_reported_as_unsupported( bus: MagicMock, diff --git a/nanobot/channels/websocket/tests/test_websocket_runtime_lifecycle.py b/nanobot/channels/websocket/tests/test_websocket_runtime_lifecycle.py index f0a23a902..feee6e51f 100644 --- a/nanobot/channels/websocket/tests/test_websocket_runtime_lifecycle.py +++ b/nanobot/channels/websocket/tests/test_websocket_runtime_lifecycle.py @@ -2,7 +2,7 @@ from __future__ import annotations import asyncio import errno -from unittest.mock import MagicMock +from unittest.mock import AsyncMock, MagicMock import pytest @@ -44,6 +44,7 @@ class _FakeServer: def _channel() -> WebSocketChannel: gateway = MagicMock() gateway.session_manager = None + gateway.http.settings_routes.close = AsyncMock() return WebSocketChannel( {"enabled": True, "allowFrom": ["*"]}, MessageBus(), diff --git a/nanobot/channels/websocket/webui/WebSocketIcon.tsx b/nanobot/channels/websocket/webui/WebSocketIcon.tsx new file mode 100644 index 000000000..64133cb78 --- /dev/null +++ b/nanobot/channels/websocket/webui/WebSocketIcon.tsx @@ -0,0 +1,5 @@ +export function WebSocketIcon() { + return ( + + ); +} diff --git a/nanobot/channels/websocket/webui/index.ts b/nanobot/channels/websocket/webui/index.ts index 94f9509c2..ef055a513 100644 --- a/nanobot/channels/websocket/webui/index.ts +++ b/nanobot/channels/websocket/webui/index.ts @@ -1,14 +1,14 @@ -import { Network } from "lucide-react"; - import type { ChannelUiContribution } from "@/channel-plugins/types"; import { chatAppGuideUrl } from "@/components/settings/channels/catalog"; +import { WebSocketIcon } from "./WebSocketIcon"; + export default { presentation: { - displayName: "WebSocket", + displayName: "nanobot WebUI", initials: "WS", color: "#111827", - icon: Network, + icon: WebSocketIcon, setup: { mode: "webui", docsUrl: chatAppGuideUrl("websocket"), diff --git a/nanobot/channels/websocket/webui/locales/en.json b/nanobot/channels/websocket/webui/locales/en.json index cd21b2168..ddd3e7621 100644 --- a/nanobot/channels/websocket/webui/locales/en.json +++ b/nanobot/channels/websocket/webui/locales/en.json @@ -1,15 +1,6 @@ { - "description": "Use nanobot in your browser.", - "requirements": "Local gateway, WebSocket token", "setup": { "docsLabel": "Open WebSocket setup", - "officialLabel": "Open local WebUI", - "tryIt": "Open the WebUI and send a short message.", - "summary": "The WebUI connects to nanobot over WebSocket. Running nanobot webui sets up this connection automatically.", - "steps": [ - "Start nanobot with the webui command.", - "Open the local URL printed in the terminal.", - "Keep WebSocket enabled while using the browser workbench." - ] + "officialLabel": "Open local WebUI" } } diff --git a/nanobot/channels/websocket/webui/locales/es.json b/nanobot/channels/websocket/webui/locales/es.json index 6cb377203..3de5638c2 100644 --- a/nanobot/channels/websocket/webui/locales/es.json +++ b/nanobot/channels/websocket/webui/locales/es.json @@ -1,15 +1,6 @@ { - "description": "Usa nanobot en tu navegador.", - "requirements": "Pasarela local y token WebSocket", "setup": { "docsLabel": "Abrir guía de WebSocket", - "officialLabel": "Abrir WebUI local", - "tryIt": "Abre la WebUI y envía un mensaje corto.", - "summary": "La WebUI se conecta a nanobot mediante WebSocket. El comando nanobot webui configura esta conexión automáticamente.", - "steps": [ - "Inicia nanobot con el comando webui.", - "Abre la URL local mostrada en la terminal.", - "Mantén WebSocket activado mientras uses la WebUI." - ] + "officialLabel": "Abrir WebUI local" } } diff --git a/nanobot/channels/websocket/webui/locales/fr.json b/nanobot/channels/websocket/webui/locales/fr.json index 1bbf5aeed..6dca17f13 100644 --- a/nanobot/channels/websocket/webui/locales/fr.json +++ b/nanobot/channels/websocket/webui/locales/fr.json @@ -1,15 +1,6 @@ { - "description": "Utilisez nanobot dans votre navigateur.", - "requirements": "Passerelle locale et jeton WebSocket", "setup": { "docsLabel": "Ouvrir le guide WebSocket", - "officialLabel": "Ouvrir la WebUI locale", - "tryIt": "Ouvrez la WebUI et envoyez un court message.", - "summary": "La WebUI se connecte à nanobot via WebSocket. La commande nanobot webui configure automatiquement cette connexion.", - "steps": [ - "Démarrez nanobot avec la commande webui.", - "Ouvrez l’URL locale affichée dans le terminal.", - "Gardez WebSocket activé pendant l’utilisation de la WebUI." - ] + "officialLabel": "Ouvrir la WebUI locale" } } diff --git a/nanobot/channels/websocket/webui/locales/id.json b/nanobot/channels/websocket/webui/locales/id.json index d0407626b..dd91c4272 100644 --- a/nanobot/channels/websocket/webui/locales/id.json +++ b/nanobot/channels/websocket/webui/locales/id.json @@ -1,15 +1,6 @@ { - "description": "Gunakan nanobot di browser Anda.", - "requirements": "Gateway lokal dan token WebSocket", "setup": { "docsLabel": "Buka panduan WebSocket", - "officialLabel": "Buka WebUI lokal", - "tryIt": "Buka WebUI dan kirim pesan singkat.", - "summary": "WebUI terhubung ke nanobot melalui WebSocket. Perintah nanobot webui menyiapkan koneksi ini secara otomatis.", - "steps": [ - "Mulai nanobot dengan perintah webui.", - "Buka URL lokal yang ditampilkan di terminal.", - "Biarkan WebSocket aktif selama menggunakan WebUI." - ] + "officialLabel": "Buka WebUI lokal" } } diff --git a/nanobot/channels/websocket/webui/locales/ja.json b/nanobot/channels/websocket/webui/locales/ja.json index b8fcf1dd7..5290e1fee 100644 --- a/nanobot/channels/websocket/webui/locales/ja.json +++ b/nanobot/channels/websocket/webui/locales/ja.json @@ -1,15 +1,6 @@ { - "description": "ブラウザーで nanobot を利用します。", - "requirements": "ローカルゲートウェイと WebSocket トークン", "setup": { "docsLabel": "WebSocket 設定ガイドを開く", - "officialLabel": "ローカル WebUI を開く", - "tryIt": "WebUI を開き、短いメッセージを送信します。", - "summary": "WebUI は WebSocket 経由で nanobot に接続します。nanobot webui コマンドを実行すると、この接続が自動で設定されます。", - "steps": [ - "webui コマンドで nanobot を起動します。", - "ターミナルに表示されたローカル URL を開きます。", - "WebUI の使用中は WebSocket を有効にしておいてください。" - ] + "officialLabel": "ローカル WebUI を開く" } } diff --git a/nanobot/channels/websocket/webui/locales/ko.json b/nanobot/channels/websocket/webui/locales/ko.json index 47737c9e4..da2beb669 100644 --- a/nanobot/channels/websocket/webui/locales/ko.json +++ b/nanobot/channels/websocket/webui/locales/ko.json @@ -1,15 +1,6 @@ { - "description": "브라우저에서 nanobot을 사용합니다.", - "requirements": "로컬 게이트웨이 및 WebSocket 토큰", "setup": { "docsLabel": "WebSocket 설정 가이드 열기", - "officialLabel": "로컬 WebUI 열기", - "tryIt": "WebUI를 열고 짧은 메시지를 보내세요.", - "summary": "WebUI는 WebSocket으로 nanobot에 연결됩니다. nanobot webui 명령을 실행하면 이 연결이 자동으로 설정됩니다.", - "steps": [ - "webui 명령으로 nanobot을 시작하세요.", - "터미널에 표시된 로컬 URL을 여세요.", - "WebUI를 사용하는 동안 WebSocket을 활성화해 두세요." - ] + "officialLabel": "로컬 WebUI 열기" } } diff --git a/nanobot/channels/websocket/webui/locales/pt-BR.json b/nanobot/channels/websocket/webui/locales/pt-BR.json index 6ccc23aef..37bf12db5 100644 --- a/nanobot/channels/websocket/webui/locales/pt-BR.json +++ b/nanobot/channels/websocket/webui/locales/pt-BR.json @@ -1,15 +1,6 @@ { - "description": "Use o nanobot no navegador.", - "requirements": "Gateway local e token WebSocket", "setup": { "docsLabel": "Abrir guia do WebSocket", - "officialLabel": "Abrir WebUI local", - "tryIt": "Abra a WebUI e envie uma mensagem curta.", - "summary": "A WebUI se conecta ao nanobot por WebSocket. O comando nanobot webui configura essa conexão automaticamente.", - "steps": [ - "Inicie o nanobot com o comando webui.", - "Abra a URL local exibida no terminal.", - "Mantenha o WebSocket ativado enquanto usa a WebUI." - ] + "officialLabel": "Abrir WebUI local" } } diff --git a/nanobot/channels/websocket/webui/locales/vi.json b/nanobot/channels/websocket/webui/locales/vi.json index ee2892da1..560c9e9f8 100644 --- a/nanobot/channels/websocket/webui/locales/vi.json +++ b/nanobot/channels/websocket/webui/locales/vi.json @@ -1,15 +1,6 @@ { - "description": "Sử dụng nanobot trong trình duyệt.", - "requirements": "Gateway cục bộ và token WebSocket", "setup": { "docsLabel": "Mở hướng dẫn WebSocket", - "officialLabel": "Mở WebUI cục bộ", - "tryIt": "Mở WebUI và gửi một tin nhắn ngắn.", - "summary": "WebUI kết nối với nanobot qua WebSocket. Lệnh nanobot webui tự động thiết lập kết nối này.", - "steps": [ - "Khởi động nanobot bằng lệnh webui.", - "Mở URL cục bộ hiển thị trong terminal.", - "Giữ WebSocket bật khi sử dụng WebUI." - ] + "officialLabel": "Mở WebUI cục bộ" } } diff --git a/nanobot/channels/websocket/webui/locales/zh-CN.json b/nanobot/channels/websocket/webui/locales/zh-CN.json index 1fbda6f36..2ea487125 100644 --- a/nanobot/channels/websocket/webui/locales/zh-CN.json +++ b/nanobot/channels/websocket/webui/locales/zh-CN.json @@ -1,15 +1,6 @@ { - "description": "在浏览器中使用 nanobot。", - "requirements": "本地网关和 WebSocket 令牌", "setup": { "docsLabel": "打开 WebSocket 配置指南", - "officialLabel": "打开本地 WebUI", - "tryIt": "打开 WebUI 并发送一条简短消息。", - "summary": "WebUI 通过 WebSocket 连接 nanobot。运行 nanobot webui 时会自动配置此连接。", - "steps": [ - "使用 webui 命令启动 nanobot。", - "打开终端中显示的本地地址。", - "使用浏览器工作台期间请保持 WebSocket 启用。" - ] + "officialLabel": "打开本地 WebUI" } } diff --git a/nanobot/channels/websocket/webui/locales/zh-TW.json b/nanobot/channels/websocket/webui/locales/zh-TW.json index cd6ca63d8..f57999647 100644 --- a/nanobot/channels/websocket/webui/locales/zh-TW.json +++ b/nanobot/channels/websocket/webui/locales/zh-TW.json @@ -1,15 +1,6 @@ { - "description": "在瀏覽器中使用 nanobot。", - "requirements": "本機閘道和 WebSocket 權杖", "setup": { "docsLabel": "開啟 WebSocket 設定指南", - "officialLabel": "開啟本機 WebUI", - "tryIt": "開啟 WebUI 並傳送一則簡短訊息。", - "summary": "WebUI 透過 WebSocket 連接 nanobot。執行 nanobot webui 時會自動設定此連線。", - "steps": [ - "使用 webui 指令啟動 nanobot。", - "開啟終端機中顯示的本機網址。", - "使用 WebUI 時,請保持 WebSocket 啟用。" - ] + "officialLabel": "開啟本機 WebUI" } } diff --git a/nanobot/channels/wecom/manifest.py b/nanobot/channels/wecom/manifest.py index f56d12d3d..208964068 100644 --- a/nanobot/channels/wecom/manifest.py +++ b/nanobot/channels/wecom/manifest.py @@ -9,6 +9,7 @@ SETUP_SPEC = ChannelSetupSpec( "botId": field(), "secret": field("secret"), "allowFrom": field("list"), + "welcomeMessage": field(), }, required=required_fields("botId", "secret"), official_url="https://developer.work.weixin.qq.com/", diff --git a/nanobot/channels/wecom/runtime.py b/nanobot/channels/wecom/runtime.py index 8ce5b8cda..3fa4fb186 100644 --- a/nanobot/channels/wecom/runtime.py +++ b/nanobot/channels/wecom/runtime.py @@ -20,6 +20,7 @@ from nanobot.config.paths import get_media_dir from nanobot.config.schema import Base WECOM_AVAILABLE = importlib.util.find_spec("wecom_aibot_sdk") is not None +WECOM_WEBSOCKET_HOST = "openws.work.weixin.qq.com" # Inbound media safety limit (matching QQ channel defaults) WECOM_DOWNLOAD_MAX_BYTES = 1024 * 1024 * 200 # 200MB @@ -28,6 +29,14 @@ WECOM_DOWNLOAD_MAX_BYTES = 1024 * 1024 * 200 # 200MB _SAFE_NAME_RE = re.compile(r"[^\w.\-()\[\]()【】\u4e00-\u9fff]+", re.UNICODE) +def _bypass_system_proxy(host: str) -> None: + """Keep the WeCom SDK's WebSocket on its direct connection path.""" + for key in ("NO_PROXY", "no_proxy"): + entries = [entry.strip() for entry in os.environ.get(key, "").split(",") if entry.strip()] + if host not in entries: + os.environ[key] = ",".join([*entries, host]) + + def _sanitize_filename(name: str, fallback: str = "unnamed") -> str: """Sanitize filename to avoid traversal and problematic chars.""" def _clean(value: str) -> str: @@ -96,6 +105,10 @@ class WecomChannel(BaseChannel): self.logger.error("bot_id and secret not configured") return + # websockets 15+ automatically uses the system proxy. The current WeCom SDK + # doesn't expose its proxy argument and expects this endpoint to connect directly. + _bypass_system_proxy(WECOM_WEBSOCKET_HOST) + from wecom_aibot_sdk import WSClient, generate_req_id self._running = True diff --git a/nanobot/channels/wecom/tests/test_wecom_channel.py b/nanobot/channels/wecom/tests/test_wecom_channel.py index 41e9b0280..c0bf4b80e 100644 --- a/nanobot/channels/wecom/tests/test_wecom_channel.py +++ b/nanobot/channels/wecom/tests/test_wecom_channel.py @@ -23,8 +23,10 @@ from nanobot.bus.events import OutboundMessage from nanobot.bus.outbound_events import ProgressEvent from nanobot.bus.queue import MessageBus from nanobot.channels.wecom.runtime import ( + WECOM_WEBSOCKET_HOST, WecomChannel, WecomConfig, + _bypass_system_proxy, _sanitize_filename, ) @@ -58,6 +60,20 @@ def test_sdk_exposes_media_upload_api() -> None: assert callable(WSClient.upload_media) +def test_wecom_websocket_bypasses_system_proxy(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("NO_PROXY", "localhost,127.0.0.1") + + _bypass_system_proxy(WECOM_WEBSOCKET_HOST) + _bypass_system_proxy(WECOM_WEBSOCKET_HOST) + + assert os.environ["NO_PROXY"].split(",") == [ + "localhost", + "127.0.0.1", + WECOM_WEBSOCKET_HOST, + ] + assert os.environ["no_proxy"].split(",").count(WECOM_WEBSOCKET_HOST) == 1 + + def test_sanitize_filename_strips_path_traversal() -> None: assert _sanitize_filename("../../etc/passwd") == "passwd" diff --git a/nanobot/channels/wecom/webui/index.ts b/nanobot/channels/wecom/webui/index.ts index cddc80479..d8829be7a 100644 --- a/nanobot/channels/wecom/webui/index.ts +++ b/nanobot/channels/wecom/webui/index.ts @@ -3,17 +3,17 @@ import { chatAppGuideUrl } from "@/components/settings/channels/catalog"; export default { presentation: { + logoUrl: "https://work.weixin.qq.com/favicon.ico", displayName: "WeCom", initials: "WC", color: "#2F7DFF", - logoUrl: "https://work.weixin.qq.com/favicon.ico", setup: { mode: "credentials", docsUrl: chatAppGuideUrl("wecom"), fields: [ - { key: "channels.wecom.botId" }, - { key: "channels.wecom.secret" }, - { key: "channels.wecom.allowFrom" }, + { key: "channels.wecom.botId", section: "credentials" }, + { key: "channels.wecom.secret", section: "credentials" }, + { key: "channels.wecom.allowFrom", section: "access" }, ], }, }, diff --git a/nanobot/channels/wecom/webui/locales/en.json b/nanobot/channels/wecom/webui/locales/en.json index 739c4129f..eb1dc779a 100644 --- a/nanobot/channels/wecom/webui/locales/en.json +++ b/nanobot/channels/wecom/webui/locales/en.json @@ -1,30 +1,22 @@ { - "description": "Use nanobot from WeCom work chats.", - "requirements": "WeCom AI bot ID and secret", "setup": { "docsLabel": "Open WeCom setup", "officialLabel": "Open WeCom console", - "tryIt": "Send a test message to the WeCom bot.", - "summary": "WeCom needs an AI bot ID and secret from the WeCom admin console.", - "steps": [ - "Create an AI bot in WeCom and choose API mode.", - "Copy the Bot ID and Secret into nanobot.", - "Save and enable WeCom, then send a test message." - ], "fields": { "botId": { "label": "Bot ID", - "placeholder": "WeCom bot ID", - "help": "Copy it from the WeCom AI Bot API mode page." + "placeholder": "WeCom bot ID" }, "secret": { "label": "Secret", - "placeholder": "••••••", - "help": "Keep the WeCom bot secret private." + "placeholder": "••••••" }, "allowFrom": { "label": "Allowed users", "placeholder": "User IDs, comma separated" + }, + "welcomeMessage": { + "label": "Welcome message" } } } diff --git a/nanobot/channels/wecom/webui/locales/es.json b/nanobot/channels/wecom/webui/locales/es.json index cfec1bd41..e53ea1119 100644 --- a/nanobot/channels/wecom/webui/locales/es.json +++ b/nanobot/channels/wecom/webui/locales/es.json @@ -1,30 +1,22 @@ { - "description": "Usa nanobot desde chats de trabajo de WeCom.", - "requirements": "Bot ID y Secret del bot de IA de WeCom", "setup": { "docsLabel": "Abrir guía de WeCom", "officialLabel": "Abrir consola de WeCom", - "tryIt": "Envía un mensaje de prueba al bot de WeCom.", - "summary": "WeCom necesita el ID y el secreto de un bot de IA desde la consola de administración.", - "steps": [ - "Crea un bot de IA en WeCom y elige el modo API.", - "Copia el Bot ID y el Secret en nanobot.", - "Guarda y activa WeCom; después envía un mensaje de prueba." - ], "fields": { "botId": { "label": "Bot ID", - "placeholder": "Bot ID de WeCom", - "help": "Cópialo de la página del modo API del bot de IA de WeCom." + "placeholder": "Bot ID de WeCom" }, "secret": { "label": "Secret", - "placeholder": "••••••", - "help": "Mantén privado el secreto del bot de WeCom." + "placeholder": "••••••" }, "allowFrom": { "label": "Usuarios permitidos", "placeholder": "ID de usuario separados por comas" + }, + "welcomeMessage": { + "label": "Mensaje de bienvenida" } } } diff --git a/nanobot/channels/wecom/webui/locales/fr.json b/nanobot/channels/wecom/webui/locales/fr.json index 898f05633..aaf4c85ef 100644 --- a/nanobot/channels/wecom/webui/locales/fr.json +++ b/nanobot/channels/wecom/webui/locales/fr.json @@ -1,30 +1,22 @@ { - "description": "Utilisez nanobot dans les conversations professionnelles WeCom.", - "requirements": "Bot ID et Secret du bot IA WeCom", "setup": { "docsLabel": "Ouvrir le guide WeCom", "officialLabel": "Ouvrir la console WeCom", - "tryIt": "Envoyez un message test au bot WeCom.", - "summary": "WeCom nécessite l’ID et le secret d’un bot IA depuis la console d’administration.", - "steps": [ - "Créez un bot IA dans WeCom et choisissez le mode API.", - "Copiez le Bot ID et le Secret dans nanobot.", - "Enregistrez et activez WeCom, puis envoyez un message test." - ], "fields": { "botId": { "label": "Bot ID", - "placeholder": "Bot ID WeCom", - "help": "Copiez-le depuis la page du mode API du bot IA WeCom." + "placeholder": "Bot ID WeCom" }, "secret": { "label": "Secret", - "placeholder": "••••••", - "help": "Gardez le secret du bot WeCom confidentiel." + "placeholder": "••••••" }, "allowFrom": { "label": "Utilisateurs autorisés", "placeholder": "ID utilisateur séparés par des virgules" + }, + "welcomeMessage": { + "label": "Message de bienvenue" } } } diff --git a/nanobot/channels/wecom/webui/locales/id.json b/nanobot/channels/wecom/webui/locales/id.json index 06d077148..ca511e3f8 100644 --- a/nanobot/channels/wecom/webui/locales/id.json +++ b/nanobot/channels/wecom/webui/locales/id.json @@ -1,30 +1,22 @@ { - "description": "Gunakan nanobot dari chat kerja WeCom.", - "requirements": "Bot ID dan Secret bot AI WeCom", "setup": { "docsLabel": "Buka panduan WeCom", "officialLabel": "Buka konsol WeCom", - "tryIt": "Kirim pesan uji ke bot WeCom.", - "summary": "WeCom memerlukan ID dan secret bot AI dari konsol admin.", - "steps": [ - "Buat bot AI di WeCom dan pilih mode API.", - "Salin Bot ID dan Secret ke nanobot.", - "Simpan dan aktifkan WeCom, lalu kirim pesan uji." - ], "fields": { "botId": { "label": "Bot ID", - "placeholder": "Bot ID WeCom", - "help": "Salin dari halaman mode API Bot AI WeCom." + "placeholder": "Bot ID WeCom" }, "secret": { "label": "Secret", - "placeholder": "••••••", - "help": "Jaga kerahasiaan secret bot WeCom." + "placeholder": "••••••" }, "allowFrom": { "label": "Pengguna yang diizinkan", "placeholder": "ID pengguna, dipisahkan koma" + }, + "welcomeMessage": { + "label": "Pesan selamat datang" } } } diff --git a/nanobot/channels/wecom/webui/locales/ja.json b/nanobot/channels/wecom/webui/locales/ja.json index 2eebed6e8..da3bf2e5c 100644 --- a/nanobot/channels/wecom/webui/locales/ja.json +++ b/nanobot/channels/wecom/webui/locales/ja.json @@ -1,30 +1,22 @@ { - "description": "WeCom の業務チャットから nanobot を利用します。", - "requirements": "WeCom AI ボットの Bot ID と Secret", "setup": { "docsLabel": "WeCom 設定ガイドを開く", "officialLabel": "WeCom コンソールを開く", - "tryIt": "WeCom ボットにテストメッセージを送信します。", - "summary": "WeCom 管理コンソールの AI ボット ID とシークレットが必要です。", - "steps": [ - "WeCom で AI ボットを作成し、API モードを選択します。", - "Bot ID と Secret を nanobot にコピーします。", - "保存して WeCom を有効にし、テストメッセージを送信します。" - ], "fields": { "botId": { "label": "Bot ID", - "placeholder": "WeCom Bot ID", - "help": "WeCom AI ボットの API モードページからコピーします。" + "placeholder": "WeCom Bot ID" }, "secret": { "label": "Secret", - "placeholder": "••••••", - "help": "WeCom ボットのシークレットは安全に保管してください。" + "placeholder": "••••••" }, "allowFrom": { "label": "許可するユーザー", "placeholder": "ユーザー ID(カンマ区切り)" + }, + "welcomeMessage": { + "label": "ウェルカムメッセージ" } } } diff --git a/nanobot/channels/wecom/webui/locales/ko.json b/nanobot/channels/wecom/webui/locales/ko.json index 8f1262dac..33a756ba7 100644 --- a/nanobot/channels/wecom/webui/locales/ko.json +++ b/nanobot/channels/wecom/webui/locales/ko.json @@ -1,30 +1,22 @@ { - "description": "WeCom 업무 채팅에서 nanobot을 사용합니다.", - "requirements": "WeCom AI 봇의 Bot ID와 Secret", "setup": { "docsLabel": "WeCom 설정 가이드 열기", "officialLabel": "WeCom 콘솔 열기", - "tryIt": "WeCom 봇에 테스트 메시지를 보내세요.", - "summary": "WeCom 관리 콘솔의 AI 봇 ID와 Secret이 필요합니다.", - "steps": [ - "WeCom에서 AI 봇을 만들고 API 모드를 선택하세요.", - "Bot ID와 Secret을 nanobot에 복사하세요.", - "저장하고 WeCom을 활성화한 다음 테스트 메시지를 보내세요." - ], "fields": { "botId": { "label": "Bot ID", - "placeholder": "WeCom Bot ID", - "help": "WeCom AI 봇 API 모드 페이지에서 복사하세요." + "placeholder": "WeCom Bot ID" }, "secret": { "label": "Secret", - "placeholder": "••••••", - "help": "WeCom 봇 Secret을 안전하게 보관하세요." + "placeholder": "••••••" }, "allowFrom": { "label": "허용된 사용자", "placeholder": "사용자 ID, 쉼표로 구분" + }, + "welcomeMessage": { + "label": "환영 메시지" } } } diff --git a/nanobot/channels/wecom/webui/locales/pt-BR.json b/nanobot/channels/wecom/webui/locales/pt-BR.json index 00c23eef2..7e8e0aa21 100644 --- a/nanobot/channels/wecom/webui/locales/pt-BR.json +++ b/nanobot/channels/wecom/webui/locales/pt-BR.json @@ -1,30 +1,22 @@ { - "description": "Use o nanobot em conversas de trabalho do WeCom.", - "requirements": "Bot ID e Secret do bot de IA do WeCom", "setup": { "docsLabel": "Abrir guia do WeCom", "officialLabel": "Abrir console do WeCom", - "tryIt": "Envie uma mensagem de teste ao bot do WeCom.", - "summary": "O WeCom precisa do ID e do segredo de um bot de IA do console administrativo.", - "steps": [ - "Crie um bot de IA no WeCom e escolha o modo API.", - "Copie o Bot ID e o Secret para o nanobot.", - "Salve e ative o WeCom; depois, envie uma mensagem de teste." - ], "fields": { "botId": { "label": "Bot ID", - "placeholder": "Bot ID do WeCom", - "help": "Copie da página do modo API do bot de IA do WeCom." + "placeholder": "Bot ID do WeCom" }, "secret": { "label": "Secret", - "placeholder": "••••••", - "help": "Mantenha privado o segredo do bot do WeCom." + "placeholder": "••••••" }, "allowFrom": { "label": "Usuários permitidos", "placeholder": "IDs de usuário separados por vírgulas" + }, + "welcomeMessage": { + "label": "Mensagem de boas-vindas" } } } diff --git a/nanobot/channels/wecom/webui/locales/vi.json b/nanobot/channels/wecom/webui/locales/vi.json index baddb8d8a..20feb67fb 100644 --- a/nanobot/channels/wecom/webui/locales/vi.json +++ b/nanobot/channels/wecom/webui/locales/vi.json @@ -1,30 +1,22 @@ { - "description": "Sử dụng nanobot trong các cuộc trò chuyện công việc WeCom.", - "requirements": "Bot ID và Secret của bot AI WeCom", "setup": { "docsLabel": "Mở hướng dẫn WeCom", "officialLabel": "Mở bảng điều khiển WeCom", - "tryIt": "Gửi tin nhắn thử đến bot WeCom.", - "summary": "WeCom cần ID và secret của bot AI từ bảng điều khiển quản trị.", - "steps": [ - "Tạo bot AI trong WeCom và chọn chế độ API.", - "Sao chép Bot ID và Secret vào nanobot.", - "Lưu và bật WeCom, sau đó gửi tin nhắn thử." - ], "fields": { "botId": { "label": "Bot ID", - "placeholder": "Bot ID WeCom", - "help": "Sao chép từ trang chế độ API của bot AI WeCom." + "placeholder": "Bot ID WeCom" }, "secret": { "label": "Secret", - "placeholder": "••••••", - "help": "Giữ kín khóa Secret của bot WeCom." + "placeholder": "••••••" }, "allowFrom": { "label": "Người dùng được phép", "placeholder": "ID người dùng, phân tách bằng dấu phẩy" + }, + "welcomeMessage": { + "label": "Tin nhắn chào mừng" } } } diff --git a/nanobot/channels/wecom/webui/locales/zh-CN.json b/nanobot/channels/wecom/webui/locales/zh-CN.json index 8ac79bbe7..ac158388c 100644 --- a/nanobot/channels/wecom/webui/locales/zh-CN.json +++ b/nanobot/channels/wecom/webui/locales/zh-CN.json @@ -1,31 +1,23 @@ { "displayName": "企业微信", - "description": "在企业微信工作会话中使用 nanobot。", - "requirements": "企业微信 AI 机器人的 Bot ID 和 Secret", "setup": { "docsLabel": "打开企业微信配置指南", "officialLabel": "打开企业微信管理后台", - "tryIt": "向企业微信机器人发送一条测试消息。", - "summary": "企业微信需要管理后台中 AI 机器人的 Bot ID 和 Secret。", - "steps": [ - "在企业微信中创建 AI 机器人并选择 API 模式。", - "将 Bot ID 和 Secret 复制到 nanobot。", - "保存并启用企业微信,然后发送一条测试消息。" - ], "fields": { "botId": { "label": "Bot ID", - "placeholder": "企业微信 Bot ID", - "help": "从企业微信 AI 机器人 API 模式页面复制。" + "placeholder": "企业微信 Bot ID" }, "secret": { "label": "Secret", - "placeholder": "••••••", - "help": "请妥善保管企业微信机器人 Secret。" + "placeholder": "••••••" }, "allowFrom": { "label": "允许的用户", "placeholder": "用户 ID,用逗号分隔" + }, + "welcomeMessage": { + "label": "欢迎消息" } } } diff --git a/nanobot/channels/wecom/webui/locales/zh-TW.json b/nanobot/channels/wecom/webui/locales/zh-TW.json index 0c84afe3c..5f1a13753 100644 --- a/nanobot/channels/wecom/webui/locales/zh-TW.json +++ b/nanobot/channels/wecom/webui/locales/zh-TW.json @@ -1,31 +1,23 @@ { "displayName": "企業微信", - "description": "在企業微信工作對話中使用 nanobot。", - "requirements": "企業微信 AI 機器人的 Bot ID 和 Secret", "setup": { "docsLabel": "開啟企業微信設定指南", "officialLabel": "開啟企業微信管理後台", - "tryIt": "向企業微信機器人傳送一則測試訊息。", - "summary": "企業微信需要管理後台中 AI 機器人的 Bot ID 和 Secret。", - "steps": [ - "在企業微信中建立 AI 機器人並選擇 API 模式。", - "將 Bot ID 和 Secret 複製到 nanobot。", - "儲存並啟用企業微信,然後傳送一則測試訊息。" - ], "fields": { "botId": { "label": "Bot ID", - "placeholder": "企業微信 Bot ID", - "help": "從企業微信 AI 機器人 API 模式頁面複製。" + "placeholder": "企業微信 Bot ID" }, "secret": { "label": "Secret", - "placeholder": "••••••", - "help": "請妥善保管企業微信機器人 Secret。" + "placeholder": "••••••" }, "allowFrom": { "label": "允許的使用者", "placeholder": "使用者 ID,以逗號分隔" + }, + "welcomeMessage": { + "label": "歡迎消息" } } } diff --git a/nanobot/channels/weixin/manifest.py b/nanobot/channels/weixin/manifest.py index 7e683484d..03c19121b 100644 --- a/nanobot/channels/weixin/manifest.py +++ b/nanobot/channels/weixin/manifest.py @@ -8,7 +8,8 @@ from nanobot.channels.weixin.validation import validate SETUP_SPEC = ChannelSetupSpec( fields={ - "token": field("secret"), + # QR-managed credentials must not be exposed to generic WebUI autosave. + "token": field("secret", writable=False, snapshot=False), "allowFrom": field("list"), "baseUrl": field(default="https://ilinkai.weixin.qq.com"), "cdnBaseUrl": field(default="https://novac2c.cdn.weixin.qq.com/c2c"), diff --git a/nanobot/channels/weixin/tests/test_weixin_channel.py b/nanobot/channels/weixin/tests/test_weixin_channel.py index cac4e1d55..8b5379837 100644 --- a/nanobot/channels/weixin/tests/test_weixin_channel.py +++ b/nanobot/channels/weixin/tests/test_weixin_channel.py @@ -55,6 +55,14 @@ def no_qr_poll_delay(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(weixin_mod, "asyncio", AsyncioProxy()) +@pytest.fixture(autouse=True) +def isolate_config_file(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None: + """Keep mocked QR credentials out of the user's real config file.""" + config_path = tmp_path / "config.json" + config_path.write_text("{}", encoding="utf-8") + monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path) + + def test_make_headers_includes_route_tag_when_configured() -> None: bus = MessageBus() channel = WeixinChannel( diff --git a/nanobot/channels/weixin/webui/WeixinConnectFlow.tsx b/nanobot/channels/weixin/webui/WeixinConnectFlow.tsx index f4211e755..523465b6b 100644 --- a/nanobot/channels/weixin/webui/WeixinConnectFlow.tsx +++ b/nanobot/channels/weixin/webui/WeixinConnectFlow.tsx @@ -69,18 +69,22 @@ function weixinConnectMessage( export function WeixinConnectFlow({ token, feature, + authRecoveryActive = false, idleLabel, connectRequestId, onFeaturesUpdate, -}: ChannelPluginConnectFlowProps) { +}: ChannelPluginConnectFlowProps & { authRecoveryActive?: boolean }) { const { t } = useTranslation(); const tx = channelTranslator(t, "weixin"); const [verificationCode, setVerificationCode] = useState(""); - const authExpired = feature.runtime_error === WEIXIN_AUTH_EXPIRED_MESSAGE; + const authExpired = authRecoveryActive + || feature.runtime_error === WEIXIN_AUTH_EXPIRED_MESSAGE; const scanAgainLabel = t("settings.channels.scanAgain", { defaultValue: "Scan again", }); + if (feature.configured && !authExpired) return null; + const renderVerification = ({ connect, busy, @@ -134,9 +138,11 @@ export function WeixinConnectFlow({ t(key, { defaultValue: fallback }); const channelTx = channelTranslator(t, "weixin"); - const runtimeError = weixinRuntimeError(feature.runtime_error, channelTx); + const authExpired = feature.runtime_error === WEIXIN_AUTH_EXPIRED_MESSAGE; + const [authRecoveryActive, setAuthRecoveryActive] = useState(authExpired); + const runtimeError = weixinRuntimeError(feature.runtime_error, channelTx) + ?? (authRecoveryActive ? channelTx("custom.expired", WEIXIN_AUTH_EXPIRED_MESSAGE) : undefined); const displayName = channelTx("displayName", "WeChat"); const enabledBusy = actionKey === `enable:${feature.name}`; const missingSupport = feature.enabled && !feature.installed; const [visibleSecrets, setVisibleSecrets] = useState>({}); + const [advancedOpen, setAdvancedOpen] = useState(false); + const advancedPanelId = useId(); const [touchedFields, setTouchedFields] = useState>(() => new Set()); const [saving, setSaving] = useState(false); const [saveRevision, setSaveRevision] = useState(0); @@ -76,8 +81,6 @@ export function WeixinPanel({ const primaryFields = localizeBooleanFields(setupFields.primary, onLabel, offLabel); const advancedFields = localizeBooleanFields(setupFields.advanced, onLabel, offLabel); const editableFields = [...primaryFields, ...advancedFields]; - const docsUrl = docsUrlWithBase(chatAppGuideUrl("wechat"), chatAppsDocsUrl) - ?? chatAppGuideUrl("wechat"); const [fieldValues, setFieldValues] = useState>(() => defaultChannelFieldValues(editableFields, feature.config_values), ); @@ -96,6 +99,14 @@ export function WeixinPanel({ onFeaturesUpdate, }; + useEffect(() => { + if (authExpired) { + setAuthRecoveryActive(true); + } else if (feature.runtime_status === "running") { + setAuthRecoveryActive(false); + } + }, [authExpired, feature.runtime_status]); + useEffect(() => { const nextValues = defaultChannelFieldValues(editableFields, feature.config_values); for (const key of touchedFieldsRef.current) { @@ -180,33 +191,44 @@ export function WeixinPanel({ }; return ( - ); @@ -311,7 +317,9 @@ function weixinSetupFields( feature: NanobotFeatureInfo, locale: string, ): { primary: ChannelConfigField[]; advanced: ChannelConfigField[] } { - const fields = feature.setup?.fields ?? []; + const fields = (feature.setup?.fields ?? []).filter( + (field) => field.key !== WEIXIN_QR_TOKEN_FIELD_KEY, + ); const fieldsByKey = new Map(fields.map((field) => [field.key, field])); const messages = channelLocaleMessages("weixin", normalizeLocale(locale))?.setup; const knownKeys = new Set([ @@ -336,7 +344,7 @@ function weixinSetupFields( function weixinConfigField( field: ChannelSetupContractField, - copy: { label: string; placeholder?: string; help?: string; choices?: Record } + copy: { label: string; placeholder?: string; choices?: Record } | undefined, ): ChannelConfigField { const choices = field.kind === "bool" ? ["true", "false"] : field.choices; @@ -344,7 +352,6 @@ function weixinConfigField( key: field.key, label: copy?.label ?? fieldLabel(field.field), placeholder: copy?.placeholder, - help: copy?.help, secret: field.kind === "secret", optional: !field.required, inputType: field.kind === "int" ? "number" : undefined, @@ -367,70 +374,6 @@ function fieldLabel(value: string): string { return spaced ? spaced[0].toUpperCase() + spaced.slice(1) : value; } -function WeixinLogo({ showBrandLogos }: { showBrandLogos: boolean }) { - const logoUrls = useMemo(() => logoFallbackUrls("https://weixin.qq.com/favicon.ico"), []); - const { logoUrl, onLogoError, onLogoLoad } = useLogoFallback(logoUrls); - if (showBrandLogos && logoUrl) { - return ( - - - - ); - } - return ( - - WX - - ); -} - -function WeixinGuideLink({ url, label }: { url: string; label: string }) { - const logoUrls = useMemo(() => logoFallbackUrls("https://weixin.qq.com/favicon.ico"), []); - const { logoUrl, onLogoError, onLogoLoad } = useLogoFallback(logoUrls); - return ( - - - {logoUrl ? ( - - ) : ( - "WX" - )} - - {label} - - - ); -} - function weixinRuntimeError( error: string | undefined, tx: (key: string, fallback: string) => string, diff --git a/nanobot/channels/weixin/webui/index.tsx b/nanobot/channels/weixin/webui/index.tsx index 5fb35ca77..35ef192cf 100644 --- a/nanobot/channels/weixin/webui/index.tsx +++ b/nanobot/channels/weixin/webui/index.tsx @@ -25,10 +25,10 @@ export default { wechat: {}, }, presentation: { + logoUrl: "https://weixin.qq.com/favicon.ico", displayName: "WeChat", initials: "WX", color: "#07C160", - logoUrl: "https://weixin.qq.com/favicon.ico", setup: { mode: "connect", command: "nanobot channels login weixin", diff --git a/nanobot/channels/weixin/webui/locales/en.json b/nanobot/channels/weixin/webui/locales/en.json index f34695156..fda191024 100644 --- a/nanobot/channels/weixin/webui/locales/en.json +++ b/nanobot/channels/weixin/webui/locales/en.json @@ -1,17 +1,8 @@ { - "description": "Use nanobot from WeChat conversations.", - "requirements": "WeChat channel setup and gateway", "setup": { "primaryAction": "Connect WeChat", "docsLabel": "Open WeChat setup", "officialLabel": "Open WeChat", - "tryIt": "After the QR login finishes, send a WeChat DM to the connected account.", - "summary": "WeChat signs in with a QR code and saves the account state locally.", - "steps": [ - "Click Connect and scan the QR code with WeChat on your phone.", - "Keep the local gateway running while WeChat receives messages.", - "Send a direct test message to confirm the account is connected." - ], "fields": { "allowFrom": { "label": "Allowed users", @@ -40,7 +31,6 @@ "custom": { "qrAlt": "WeChat login QR code", "scanTitle": "Scan with WeChat", - "scanDescription": "Use WeChat on your phone to scan this code. nanobot saves the account state locally after login.", "waiting": "Waiting for you to scan with WeChat…", "connected": "WeChat is connected.", "stopped": "WeChat login stopped.", diff --git a/nanobot/channels/weixin/webui/locales/es.json b/nanobot/channels/weixin/webui/locales/es.json index a3f996d3e..d90df2dc0 100644 --- a/nanobot/channels/weixin/webui/locales/es.json +++ b/nanobot/channels/weixin/webui/locales/es.json @@ -1,17 +1,8 @@ { - "description": "Usa nanobot desde conversaciones de WeChat.", - "requirements": "Configuración del canal WeChat y pasarela", "setup": { "primaryAction": "Conectar WeChat", "docsLabel": "Abrir guía de WeChat", "officialLabel": "Abrir WeChat", - "tryIt": "Tras iniciar sesión por QR, envía un DM al usuario conectado.", - "summary": "WeChat inicia sesión con un QR y guarda el estado de la cuenta localmente.", - "steps": [ - "Haz clic en Conectar y escanea el QR con WeChat.", - "Mantén la pasarela local en ejecución mientras WeChat recibe mensajes.", - "Envía un mensaje directo de prueba para confirmar la conexión." - ], "fields": { "allowFrom": { "label": "Usuarios permitidos", @@ -21,26 +12,53 @@ "label": "Token", "placeholder": "Guardado al iniciar sesión por QR" }, - "sendProgress": { "label": "Enviar progreso" }, - "sendToolHints": { "label": "Enviar resúmenes de actividad de las herramientas" }, - "streaming": { "label": "Usar API de streaming" }, - "replyProgressMessages": { "label": "Enviar progreso estructurado" }, - "replyProgressMaxMessages": { "label": "Límite de progreso estructurado" }, - "contextMessageBudget": { "label": "Máximo de mensajes de contexto" }, - "blockStreaming": { "label": "Enviar respuestas por bloques" }, - "blockStreamingMinChars": { "label": "Mínimo de caracteres por bloque" }, - "blockStreamingMaxMessages": { "label": "Límite de mensajes por bloques" }, - "baseUrl": { "label": "URL de la API" }, - "cdnBaseUrl": { "label": "URL de la CDN" }, - "routeTag": { "label": "Etiqueta de ruta" }, - "stateDir": { "label": "Directorio de estado" }, - "pollTimeout": { "label": "Tiempo de espera de consulta (segundos)" } + "sendProgress": { + "label": "Enviar progreso" + }, + "sendToolHints": { + "label": "Enviar resúmenes de actividad de las herramientas" + }, + "streaming": { + "label": "Usar API de streaming" + }, + "replyProgressMessages": { + "label": "Enviar progreso estructurado" + }, + "replyProgressMaxMessages": { + "label": "Límite de progreso estructurado" + }, + "contextMessageBudget": { + "label": "Máximo de mensajes de contexto" + }, + "blockStreaming": { + "label": "Enviar respuestas por bloques" + }, + "blockStreamingMinChars": { + "label": "Mínimo de caracteres por bloque" + }, + "blockStreamingMaxMessages": { + "label": "Límite de mensajes por bloques" + }, + "baseUrl": { + "label": "URL de la API" + }, + "cdnBaseUrl": { + "label": "URL de la CDN" + }, + "routeTag": { + "label": "Etiqueta de ruta" + }, + "stateDir": { + "label": "Directorio de estado" + }, + "pollTimeout": { + "label": "Tiempo de espera de consulta (segundos)" + } } }, "custom": { "qrAlt": "Código QR de inicio de WeChat", "scanTitle": "Escanea con WeChat", - "scanDescription": "Escanea este código con WeChat en tu teléfono. nanobot guarda el estado de la cuenta localmente después de iniciar sesión.", "waiting": "Esperando a que escanees el código con WeChat…", "connected": "WeChat está conectado.", "stopped": "Inicio de sesión en WeChat detenido.", diff --git a/nanobot/channels/weixin/webui/locales/fr.json b/nanobot/channels/weixin/webui/locales/fr.json index 22ee6376b..e2988a5d4 100644 --- a/nanobot/channels/weixin/webui/locales/fr.json +++ b/nanobot/channels/weixin/webui/locales/fr.json @@ -1,17 +1,8 @@ { - "description": "Utilisez nanobot depuis les conversations WeChat.", - "requirements": "Configuration du canal WeChat et passerelle", "setup": { "primaryAction": "Connecter WeChat", "docsLabel": "Ouvrir le guide WeChat", "officialLabel": "Ouvrir WeChat", - "tryIt": "Après la connexion par QR code, envoyez un message privé au compte connecté.", - "summary": "WeChat se connecte par QR code et enregistre localement l’état du compte.", - "steps": [ - "Cliquez sur Connecter et scannez le QR code avec WeChat.", - "Gardez la passerelle locale active pendant la réception des messages.", - "Envoyez un message privé test pour confirmer la connexion." - ], "fields": { "allowFrom": { "label": "Utilisateurs autorisés", @@ -21,26 +12,53 @@ "label": "Jeton", "placeholder": "Enregistré après la connexion QR" }, - "sendProgress": { "label": "Envoyer la progression" }, - "sendToolHints": { "label": "Envoyer un résumé de l’activité des outils" }, - "streaming": { "label": "Utiliser l’API de streaming" }, - "replyProgressMessages": { "label": "Envoyer la progression structurée" }, - "replyProgressMaxMessages": { "label": "Limite de progression structurée" }, - "contextMessageBudget": { "label": "Nombre maximal de messages de contexte" }, - "blockStreaming": { "label": "Envoyer la réponse par blocs" }, - "blockStreamingMinChars": { "label": "Taille minimale d’un bloc" }, - "blockStreamingMaxMessages": { "label": "Limite de messages par blocs" }, - "baseUrl": { "label": "URL de l’API" }, - "cdnBaseUrl": { "label": "URL du CDN" }, - "routeTag": { "label": "Étiquette de routage" }, - "stateDir": { "label": "Répertoire d’état" }, - "pollTimeout": { "label": "Délai d’interrogation (secondes)" } + "sendProgress": { + "label": "Envoyer la progression" + }, + "sendToolHints": { + "label": "Envoyer un résumé de l’activité des outils" + }, + "streaming": { + "label": "Utiliser l’API de streaming" + }, + "replyProgressMessages": { + "label": "Envoyer la progression structurée" + }, + "replyProgressMaxMessages": { + "label": "Limite de progression structurée" + }, + "contextMessageBudget": { + "label": "Nombre maximal de messages de contexte" + }, + "blockStreaming": { + "label": "Envoyer la réponse par blocs" + }, + "blockStreamingMinChars": { + "label": "Taille minimale d’un bloc" + }, + "blockStreamingMaxMessages": { + "label": "Limite de messages par blocs" + }, + "baseUrl": { + "label": "URL de l’API" + }, + "cdnBaseUrl": { + "label": "URL du CDN" + }, + "routeTag": { + "label": "Étiquette de routage" + }, + "stateDir": { + "label": "Répertoire d’état" + }, + "pollTimeout": { + "label": "Délai d’interrogation (secondes)" + } } }, "custom": { "qrAlt": "QR code de connexion WeChat", "scanTitle": "Scanner avec WeChat", - "scanDescription": "Scannez ce code avec WeChat. nanobot enregistre localement l’état du compte après la connexion.", "waiting": "En attente de lecture du QR code avec WeChat…", "connected": "WeChat est connecté.", "stopped": "Connexion WeChat arrêtée.", diff --git a/nanobot/channels/weixin/webui/locales/id.json b/nanobot/channels/weixin/webui/locales/id.json index ba2047503..b89f560ff 100644 --- a/nanobot/channels/weixin/webui/locales/id.json +++ b/nanobot/channels/weixin/webui/locales/id.json @@ -1,17 +1,8 @@ { - "description": "Gunakan nanobot dari percakapan WeChat.", - "requirements": "Pengaturan kanal WeChat dan gateway", "setup": { "primaryAction": "Hubungkan WeChat", "docsLabel": "Buka panduan WeChat", "officialLabel": "Buka WeChat", - "tryIt": "Setelah login QR, kirim DM ke akun yang terhubung.", - "summary": "WeChat login dengan kode QR dan menyimpan status akun secara lokal.", - "steps": [ - "Klik Hubungkan dan pindai QR dengan WeChat.", - "Biarkan gateway lokal berjalan saat WeChat menerima pesan.", - "Kirim pesan langsung uji untuk memastikan akun terhubung." - ], "fields": { "allowFrom": { "label": "Pengguna yang diizinkan", @@ -21,26 +12,53 @@ "label": "Token", "placeholder": "Disimpan saat login QR" }, - "sendProgress": { "label": "Kirim progres" }, - "sendToolHints": { "label": "Kirim ringkasan aktivitas alat" }, - "streaming": { "label": "Gunakan API streaming" }, - "replyProgressMessages": { "label": "Kirim progres terstruktur" }, - "replyProgressMaxMessages": { "label": "Batas progres terstruktur" }, - "contextMessageBudget": { "label": "Jumlah maksimum pesan konteks" }, - "blockStreaming": { "label": "Kirim respons per blok" }, - "blockStreamingMinChars": { "label": "Jumlah minimum karakter per blok" }, - "blockStreamingMaxMessages": { "label": "Batas pesan blok" }, - "baseUrl": { "label": "URL API" }, - "cdnBaseUrl": { "label": "URL CDN" }, - "routeTag": { "label": "Tag rute" }, - "stateDir": { "label": "Direktori status" }, - "pollTimeout": { "label": "Batas waktu polling (detik)" } + "sendProgress": { + "label": "Kirim progres" + }, + "sendToolHints": { + "label": "Kirim ringkasan aktivitas alat" + }, + "streaming": { + "label": "Gunakan API streaming" + }, + "replyProgressMessages": { + "label": "Kirim progres terstruktur" + }, + "replyProgressMaxMessages": { + "label": "Batas progres terstruktur" + }, + "contextMessageBudget": { + "label": "Jumlah maksimum pesan konteks" + }, + "blockStreaming": { + "label": "Kirim respons per blok" + }, + "blockStreamingMinChars": { + "label": "Jumlah minimum karakter per blok" + }, + "blockStreamingMaxMessages": { + "label": "Batas pesan blok" + }, + "baseUrl": { + "label": "URL API" + }, + "cdnBaseUrl": { + "label": "URL CDN" + }, + "routeTag": { + "label": "Tag rute" + }, + "stateDir": { + "label": "Direktori status" + }, + "pollTimeout": { + "label": "Batas waktu polling (detik)" + } } }, "custom": { "qrAlt": "Kode QR login WeChat", "scanTitle": "Pindai dengan WeChat", - "scanDescription": "Pindai dengan WeChat di ponsel. nanobot menyimpan status akun secara lokal setelah login.", "waiting": "Menunggu Anda memindai kode dengan WeChat…", "connected": "WeChat sudah terhubung.", "stopped": "Login WeChat dihentikan.", diff --git a/nanobot/channels/weixin/webui/locales/ja.json b/nanobot/channels/weixin/webui/locales/ja.json index 8b975eb1b..9983a074e 100644 --- a/nanobot/channels/weixin/webui/locales/ja.json +++ b/nanobot/channels/weixin/webui/locales/ja.json @@ -1,17 +1,8 @@ { - "description": "WeChat の会話から nanobot を利用します。", - "requirements": "WeChat チャンネル設定とゲートウェイ", "setup": { "primaryAction": "WeChat に接続", "docsLabel": "WeChat 設定ガイドを開く", "officialLabel": "WeChat を開く", - "tryIt": "QR ログイン後、接続したアカウントに WeChat の DM を送信します。", - "summary": "WeChat は QR コードでログインし、アカウント状態をローカルに保存します。", - "steps": [ - "接続をクリックし、スマートフォンの WeChat で QR コードを読み取ります。", - "WeChat がメッセージを受信する間、ローカルゲートウェイを起動しておきます。", - "DM でテストし、アカウントの接続を確認します。" - ], "fields": { "allowFrom": { "label": "許可するユーザー", @@ -21,26 +12,53 @@ "label": "トークン", "placeholder": "QR ログインで保存" }, - "sendProgress": { "label": "進捗を送信" }, - "sendToolHints": { "label": "ツールの動作概要を送信" }, - "streaming": { "label": "ストリーミング API を使用" }, - "replyProgressMessages": { "label": "構造化された進捗を送信" }, - "replyProgressMaxMessages": { "label": "構造化進捗の上限" }, - "contextMessageBudget": { "label": "コンテキストに含めるメッセージ数の上限" }, - "blockStreaming": { "label": "応答をブロック単位で送信" }, - "blockStreamingMinChars": { "label": "1 ブロックの最小文字数" }, - "blockStreamingMaxMessages": { "label": "ブロックメッセージの上限" }, - "baseUrl": { "label": "API URL" }, - "cdnBaseUrl": { "label": "CDN URL" }, - "routeTag": { "label": "ルートタグ" }, - "stateDir": { "label": "状態ディレクトリ" }, - "pollTimeout": { "label": "ポーリングのタイムアウト(秒)" } + "sendProgress": { + "label": "進捗を送信" + }, + "sendToolHints": { + "label": "ツールの動作概要を送信" + }, + "streaming": { + "label": "ストリーミング API を使用" + }, + "replyProgressMessages": { + "label": "構造化された進捗を送信" + }, + "replyProgressMaxMessages": { + "label": "構造化進捗の上限" + }, + "contextMessageBudget": { + "label": "コンテキストに含めるメッセージ数の上限" + }, + "blockStreaming": { + "label": "応答をブロック単位で送信" + }, + "blockStreamingMinChars": { + "label": "1 ブロックの最小文字数" + }, + "blockStreamingMaxMessages": { + "label": "ブロックメッセージの上限" + }, + "baseUrl": { + "label": "API URL" + }, + "cdnBaseUrl": { + "label": "CDN URL" + }, + "routeTag": { + "label": "ルートタグ" + }, + "stateDir": { + "label": "状態ディレクトリ" + }, + "pollTimeout": { + "label": "ポーリングのタイムアウト(秒)" + } } }, "custom": { "qrAlt": "WeChat ログイン QR コード", "scanTitle": "WeChat でスキャン", - "scanDescription": "スマートフォンの WeChat でスキャンしてください。ログイン後、nanobot が状態をローカルに保存します。", "waiting": "WeChat で QR コードを読み取ってください…", "connected": "WeChat に接続しました。", "stopped": "WeChat ログインを停止しました。", diff --git a/nanobot/channels/weixin/webui/locales/ko.json b/nanobot/channels/weixin/webui/locales/ko.json index 6ca496925..3180ddc9d 100644 --- a/nanobot/channels/weixin/webui/locales/ko.json +++ b/nanobot/channels/weixin/webui/locales/ko.json @@ -1,17 +1,8 @@ { - "description": "WeChat 대화에서 nanobot을 사용합니다.", - "requirements": "WeChat 채널 설정 및 게이트웨이", "setup": { "primaryAction": "WeChat 연결", "docsLabel": "WeChat 설정 가이드 열기", "officialLabel": "WeChat 열기", - "tryIt": "QR 로그인 후 연결된 계정으로 WeChat DM을 보내세요.", - "summary": "WeChat은 QR 코드로 로그인하고 계정 상태를 로컬에 저장합니다.", - "steps": [ - "연결을 클릭하고 휴대폰 WeChat으로 QR 코드를 스캔하세요.", - "WeChat이 메시지를 받는 동안 로컬 게이트웨이를 실행해 두세요.", - "DM으로 테스트해 계정 연결을 확인하세요." - ], "fields": { "allowFrom": { "label": "허용된 사용자", @@ -21,26 +12,53 @@ "label": "토큰", "placeholder": "QR 로그인으로 저장됨" }, - "sendProgress": { "label": "진행 상황 보내기" }, - "sendToolHints": { "label": "도구 실행 요약 보내기" }, - "streaming": { "label": "스트리밍 API 사용" }, - "replyProgressMessages": { "label": "구조화된 진행 상황 보내기" }, - "replyProgressMaxMessages": { "label": "구조화된 진행 메시지 한도" }, - "contextMessageBudget": { "label": "컨텍스트에 포함할 최대 메시지 수" }, - "blockStreaming": { "label": "응답을 블록으로 보내기" }, - "blockStreamingMinChars": { "label": "블록당 최소 글자 수" }, - "blockStreamingMaxMessages": { "label": "블록 메시지 한도" }, - "baseUrl": { "label": "API URL" }, - "cdnBaseUrl": { "label": "CDN URL" }, - "routeTag": { "label": "경로 태그" }, - "stateDir": { "label": "상태 디렉터리" }, - "pollTimeout": { "label": "폴링 제한 시간(초)" } + "sendProgress": { + "label": "진행 상황 보내기" + }, + "sendToolHints": { + "label": "도구 실행 요약 보내기" + }, + "streaming": { + "label": "스트리밍 API 사용" + }, + "replyProgressMessages": { + "label": "구조화된 진행 상황 보내기" + }, + "replyProgressMaxMessages": { + "label": "구조화된 진행 메시지 한도" + }, + "contextMessageBudget": { + "label": "컨텍스트에 포함할 최대 메시지 수" + }, + "blockStreaming": { + "label": "응답을 블록으로 보내기" + }, + "blockStreamingMinChars": { + "label": "블록당 최소 글자 수" + }, + "blockStreamingMaxMessages": { + "label": "블록 메시지 한도" + }, + "baseUrl": { + "label": "API URL" + }, + "cdnBaseUrl": { + "label": "CDN URL" + }, + "routeTag": { + "label": "경로 태그" + }, + "stateDir": { + "label": "상태 디렉터리" + }, + "pollTimeout": { + "label": "폴링 제한 시간(초)" + } } }, "custom": { "qrAlt": "WeChat 로그인 QR 코드", "scanTitle": "WeChat으로 스캔", - "scanDescription": "휴대폰 WeChat으로 스캔하세요. 로그인 후 nanobot이 계정 상태를 로컬에 저장합니다.", "waiting": "WeChat으로 QR 코드를 스캔해 주세요…", "connected": "WeChat이 연결되었습니다.", "stopped": "WeChat 로그인이 중지되었습니다.", diff --git a/nanobot/channels/weixin/webui/locales/pt-BR.json b/nanobot/channels/weixin/webui/locales/pt-BR.json index 36388eee4..1b3a6e600 100644 --- a/nanobot/channels/weixin/webui/locales/pt-BR.json +++ b/nanobot/channels/weixin/webui/locales/pt-BR.json @@ -1,17 +1,8 @@ { - "description": "Use o nanobot em conversas do WeChat.", - "requirements": "Configuração do canal WeChat e gateway", "setup": { "primaryAction": "Conectar WeChat", "docsLabel": "Abrir guia do WeChat", "officialLabel": "Abrir WeChat", - "tryIt": "Após o login por QR, envie uma DM à conta conectada.", - "summary": "O WeChat entra por QR code e salva o estado da conta localmente.", - "steps": [ - "Clique em Conectar e escaneie o QR com o WeChat.", - "Mantenha o gateway local ativo enquanto o WeChat recebe mensagens.", - "Envie uma mensagem direta de teste para confirmar a conexão." - ], "fields": { "allowFrom": { "label": "Usuários permitidos", @@ -21,26 +12,53 @@ "label": "Token", "placeholder": "Salvo pelo login via QR" }, - "sendProgress": { "label": "Enviar progresso" }, - "sendToolHints": { "label": "Enviar resumos da atividade das ferramentas" }, - "streaming": { "label": "Usar API de streaming" }, - "replyProgressMessages": { "label": "Enviar progresso estruturado" }, - "replyProgressMaxMessages": { "label": "Limite de progresso estruturado" }, - "contextMessageBudget": { "label": "Máximo de mensagens de contexto" }, - "blockStreaming": { "label": "Enviar resposta em blocos" }, - "blockStreamingMinChars": { "label": "Mínimo de caracteres por bloco" }, - "blockStreamingMaxMessages": { "label": "Limite de mensagens em blocos" }, - "baseUrl": { "label": "URL da API" }, - "cdnBaseUrl": { "label": "URL da CDN" }, - "routeTag": { "label": "Etiqueta de rota" }, - "stateDir": { "label": "Diretório de estado" }, - "pollTimeout": { "label": "Tempo limite da consulta (segundos)" } + "sendProgress": { + "label": "Enviar progresso" + }, + "sendToolHints": { + "label": "Enviar resumos da atividade das ferramentas" + }, + "streaming": { + "label": "Usar API de streaming" + }, + "replyProgressMessages": { + "label": "Enviar progresso estruturado" + }, + "replyProgressMaxMessages": { + "label": "Limite de progresso estruturado" + }, + "contextMessageBudget": { + "label": "Máximo de mensagens de contexto" + }, + "blockStreaming": { + "label": "Enviar resposta em blocos" + }, + "blockStreamingMinChars": { + "label": "Mínimo de caracteres por bloco" + }, + "blockStreamingMaxMessages": { + "label": "Limite de mensagens em blocos" + }, + "baseUrl": { + "label": "URL da API" + }, + "cdnBaseUrl": { + "label": "URL da CDN" + }, + "routeTag": { + "label": "Etiqueta de rota" + }, + "stateDir": { + "label": "Diretório de estado" + }, + "pollTimeout": { + "label": "Tempo limite da consulta (segundos)" + } } }, "custom": { "qrAlt": "QR code de login do WeChat", "scanTitle": "Escaneie com o WeChat", - "scanDescription": "Escaneie com o WeChat no celular. O nanobot salva o estado localmente após o login.", "waiting": "Aguardando você escanear o código com o WeChat…", "connected": "WeChat está conectado.", "stopped": "Login do WeChat interrompido.", diff --git a/nanobot/channels/weixin/webui/locales/vi.json b/nanobot/channels/weixin/webui/locales/vi.json index df43f8013..becf9636d 100644 --- a/nanobot/channels/weixin/webui/locales/vi.json +++ b/nanobot/channels/weixin/webui/locales/vi.json @@ -1,17 +1,8 @@ { - "description": "Sử dụng nanobot từ các cuộc trò chuyện WeChat.", - "requirements": "Cài đặt kênh WeChat và gateway", "setup": { "primaryAction": "Kết nối WeChat", "docsLabel": "Mở hướng dẫn WeChat", "officialLabel": "Mở WeChat", - "tryIt": "Sau khi đăng nhập QR, gửi tin nhắn riêng đến tài khoản đã kết nối.", - "summary": "WeChat đăng nhập bằng mã QR và lưu trạng thái tài khoản cục bộ.", - "steps": [ - "Nhấn Kết nối và quét QR bằng WeChat.", - "Giữ gateway cục bộ chạy khi WeChat nhận tin nhắn.", - "Gửi tin nhắn riêng thử để xác nhận kết nối." - ], "fields": { "allowFrom": { "label": "Người dùng được phép", @@ -21,26 +12,53 @@ "label": "Token", "placeholder": "Được lưu khi đăng nhập QR" }, - "sendProgress": { "label": "Gửi thông báo tiến độ" }, - "sendToolHints": { "label": "Gửi tóm tắt hoạt động công cụ" }, - "streaming": { "label": "Dùng API truyền theo luồng" }, - "replyProgressMessages": { "label": "Gửi tiến độ theo từng bước" }, - "replyProgressMaxMessages": { "label": "Số thông báo tiến độ tối đa" }, - "contextMessageBudget": { "label": "Số tin nhắn ngữ cảnh tối đa" }, - "blockStreaming": { "label": "Gửi phản hồi theo khối" }, - "blockStreamingMinChars": { "label": "Số ký tự tối thiểu mỗi phần" }, - "blockStreamingMaxMessages": { "label": "Giới hạn tin nhắn theo khối" }, - "baseUrl": { "label": "URL API" }, - "cdnBaseUrl": { "label": "URL CDN" }, - "routeTag": { "label": "Thẻ định tuyến" }, - "stateDir": { "label": "Thư mục trạng thái" }, - "pollTimeout": { "label": "Thời gian chờ thăm dò (giây)" } + "sendProgress": { + "label": "Gửi thông báo tiến độ" + }, + "sendToolHints": { + "label": "Gửi tóm tắt hoạt động công cụ" + }, + "streaming": { + "label": "Dùng API truyền theo luồng" + }, + "replyProgressMessages": { + "label": "Gửi tiến độ theo từng bước" + }, + "replyProgressMaxMessages": { + "label": "Số thông báo tiến độ tối đa" + }, + "contextMessageBudget": { + "label": "Số tin nhắn ngữ cảnh tối đa" + }, + "blockStreaming": { + "label": "Gửi phản hồi theo khối" + }, + "blockStreamingMinChars": { + "label": "Số ký tự tối thiểu mỗi phần" + }, + "blockStreamingMaxMessages": { + "label": "Giới hạn tin nhắn theo khối" + }, + "baseUrl": { + "label": "URL API" + }, + "cdnBaseUrl": { + "label": "URL CDN" + }, + "routeTag": { + "label": "Thẻ định tuyến" + }, + "stateDir": { + "label": "Thư mục trạng thái" + }, + "pollTimeout": { + "label": "Thời gian chờ thăm dò (giây)" + } } }, "custom": { "qrAlt": "Mã QR đăng nhập WeChat", "scanTitle": "Quét bằng WeChat", - "scanDescription": "Quét bằng WeChat trên điện thoại. nanobot lưu trạng thái cục bộ sau khi đăng nhập.", "waiting": "Đang chờ bạn quét mã bằng WeChat…", "connected": "WeChat đã kết nối.", "stopped": "Đăng nhập WeChat đã dừng.", diff --git a/nanobot/channels/weixin/webui/locales/zh-CN.json b/nanobot/channels/weixin/webui/locales/zh-CN.json index 5053c44d7..9df8144dd 100644 --- a/nanobot/channels/weixin/webui/locales/zh-CN.json +++ b/nanobot/channels/weixin/webui/locales/zh-CN.json @@ -1,18 +1,9 @@ { "displayName": "微信", - "description": "在微信会话中使用 nanobot。", - "requirements": "微信渠道配置和网关", "setup": { "primaryAction": "连接微信", "docsLabel": "打开微信配置指南", "officialLabel": "打开微信", - "tryIt": "二维码登录完成后,向已连接的账户发送一条微信私信。", - "summary": "微信通过二维码登录,并将账户状态保存在本地。", - "steps": [ - "点击连接,用手机微信扫描二维码。", - "微信接收消息期间请保持本地网关运行。", - "发送一条私信测试,确认账户已连接。" - ], "fields": { "allowFrom": { "label": "允许的用户", @@ -22,26 +13,53 @@ "label": "令牌", "placeholder": "二维码登录后自动保存" }, - "sendProgress": { "label": "发送进度消息" }, - "sendToolHints": { "label": "发送工具执行提示" }, - "streaming": { "label": "使用流式 API" }, - "replyProgressMessages": { "label": "发送结构化进度" }, - "replyProgressMaxMessages": { "label": "结构化进度消息上限" }, - "contextMessageBudget": { "label": "上下文消息数量上限" }, - "blockStreaming": { "label": "分块发送回复" }, - "blockStreamingMinChars": { "label": "最小分块字符数" }, - "blockStreamingMaxMessages": { "label": "分块消息上限" }, - "baseUrl": { "label": "API 地址" }, - "cdnBaseUrl": { "label": "CDN 地址" }, - "routeTag": { "label": "路由标签" }, - "stateDir": { "label": "状态目录" }, - "pollTimeout": { "label": "轮询超时(秒)" } + "sendProgress": { + "label": "发送进度消息" + }, + "sendToolHints": { + "label": "发送工具执行提示" + }, + "streaming": { + "label": "使用流式 API" + }, + "replyProgressMessages": { + "label": "发送结构化进度" + }, + "replyProgressMaxMessages": { + "label": "结构化进度消息上限" + }, + "contextMessageBudget": { + "label": "上下文消息数量上限" + }, + "blockStreaming": { + "label": "分块发送回复" + }, + "blockStreamingMinChars": { + "label": "最小分块字符数" + }, + "blockStreamingMaxMessages": { + "label": "分块消息上限" + }, + "baseUrl": { + "label": "API 地址" + }, + "cdnBaseUrl": { + "label": "CDN 地址" + }, + "routeTag": { + "label": "路由标签" + }, + "stateDir": { + "label": "状态目录" + }, + "pollTimeout": { + "label": "轮询超时(秒)" + } } }, "custom": { "qrAlt": "微信登录二维码", "scanTitle": "使用微信扫码", - "scanDescription": "用手机微信扫描此二维码。登录后,nanobot 会将账户状态保存在本地。", "waiting": "等待用微信扫码…", "connected": "微信已连接。", "stopped": "微信登录已停止。", diff --git a/nanobot/channels/weixin/webui/locales/zh-TW.json b/nanobot/channels/weixin/webui/locales/zh-TW.json index 76414db17..2b4a74486 100644 --- a/nanobot/channels/weixin/webui/locales/zh-TW.json +++ b/nanobot/channels/weixin/webui/locales/zh-TW.json @@ -1,18 +1,9 @@ { "displayName": "微信", - "description": "在微信對話中使用 nanobot。", - "requirements": "微信管道設定和閘道", "setup": { "primaryAction": "連接微信", "docsLabel": "開啟微信設定指南", "officialLabel": "開啟微信", - "tryIt": "QR Code登入完成後,向已連接的帳戶傳送一則微信私訊。", - "summary": "微信透過QR Code登入,並將帳戶狀態儲存在本機。", - "steps": [ - "點選連接,用手機微信掃描QR Code。", - "微信接收訊息期間請保持本機閘道執行。", - "傳送一則私訊測試,確認帳戶已連接。" - ], "fields": { "allowFrom": { "label": "允許的使用者", @@ -22,26 +13,53 @@ "label": "權杖", "placeholder": "QR Code登入後自動儲存" }, - "sendProgress": { "label": "傳送進度訊息" }, - "sendToolHints": { "label": "傳送工具執行摘要" }, - "streaming": { "label": "使用串流 API" }, - "replyProgressMessages": { "label": "傳送結構化進度" }, - "replyProgressMaxMessages": { "label": "結構化進度訊息上限" }, - "contextMessageBudget": { "label": "上下文訊息數量上限" }, - "blockStreaming": { "label": "分塊傳送回覆" }, - "blockStreamingMinChars": { "label": "最小分塊字元數" }, - "blockStreamingMaxMessages": { "label": "分塊訊息上限" }, - "baseUrl": { "label": "API 位址" }, - "cdnBaseUrl": { "label": "CDN 位址" }, - "routeTag": { "label": "路由標籤" }, - "stateDir": { "label": "狀態目錄" }, - "pollTimeout": { "label": "輪詢逾時(秒)" } + "sendProgress": { + "label": "傳送進度訊息" + }, + "sendToolHints": { + "label": "傳送工具執行摘要" + }, + "streaming": { + "label": "使用串流 API" + }, + "replyProgressMessages": { + "label": "傳送結構化進度" + }, + "replyProgressMaxMessages": { + "label": "結構化進度訊息上限" + }, + "contextMessageBudget": { + "label": "上下文訊息數量上限" + }, + "blockStreaming": { + "label": "分塊傳送回覆" + }, + "blockStreamingMinChars": { + "label": "最小分塊字元數" + }, + "blockStreamingMaxMessages": { + "label": "分塊訊息上限" + }, + "baseUrl": { + "label": "API 位址" + }, + "cdnBaseUrl": { + "label": "CDN 位址" + }, + "routeTag": { + "label": "路由標籤" + }, + "stateDir": { + "label": "狀態目錄" + }, + "pollTimeout": { + "label": "輪詢逾時(秒)" + } } }, "custom": { "qrAlt": "微信登入QR Code", "scanTitle": "使用微信掃描 QR Code", - "scanDescription": "用手機微信掃描此QR Code。登入後,nanobot 會將帳戶狀態儲存在本機。", "waiting": "等待使用微信掃描 QR Code…", "connected": "微信已連接。", "stopped": "微信登入已停止。", diff --git a/nanobot/channels/weixin/webui/presentation.ts b/nanobot/channels/weixin/webui/presentation.ts index ad04026b1..f97913b16 100644 --- a/nanobot/channels/weixin/webui/presentation.ts +++ b/nanobot/channels/weixin/webui/presentation.ts @@ -4,9 +4,10 @@ export const WEIXIN_PRIMARY_FIELD_KEYS = [ "channels.weixin.streaming", ] as const; +export const WEIXIN_QR_TOKEN_FIELD_KEY = "channels.weixin.token"; + export const WEIXIN_ADVANCED_FIELD_KEYS = [ "channels.weixin.allowFrom", - "channels.weixin.token", "channels.weixin.replyProgressMessages", "channels.weixin.replyProgressMaxMessages", "channels.weixin.contextMessageBudget", diff --git a/nanobot/channels/whatsapp/connect.py b/nanobot/channels/whatsapp/connect.py new file mode 100644 index 000000000..41eb4de43 --- /dev/null +++ b/nanobot/channels/whatsapp/connect.py @@ -0,0 +1,338 @@ +"""WhatsApp-owned interactive QR connection flow.""" + +from __future__ import annotations + +import asyncio +import os +import secrets +import time +from contextlib import suppress +from dataclasses import dataclass +from pathlib import Path +from typing import TYPE_CHECKING, Any, cast + +from nanobot.channels.connect import ChannelConnectError, QueryParams, query_first +from nanobot.config.loader import load_config + +if TYPE_CHECKING: + from nanobot.channels.whatsapp.runtime import WhatsAppChannel + + +_NATIVE_STOP_TIMEOUT_SECONDS = 10.0 +_DATABASE_REPLACE_TIMEOUT_SECONDS = 10.0 +_FINALIZE_POLL_WAIT_SECONDS = 0.05 + + +@dataclass(slots=True) +class WhatsAppConnectSession: + id: str + channel: WhatsAppChannel + client: Any + result: asyncio.Future[None] + connect_task: asyncio.Task[asyncio.Task[Any] | None] + target_path: Path + pending_path: Path + created_wall: float + deadline: float + qr_url: str = "" + finalize_task: asyncio.Task[None] | None = None + + +class WhatsAppConnectStore: + """In-memory WhatsApp linked-device sessions for the WebUI.""" + + def __init__(self) -> None: + self._sessions: dict[str, WhatsAppConnectSession] = {} + + async def handle(self, action: str, query: QueryParams) -> dict[str, Any]: + if action == "start": + force = (query_first(query, "force") or "").strip().lower() in { + "1", + "true", + "yes", + } + return await self.start(force=force) + + session_id = (query_first(query, "session_id") or "").strip() + if not session_id: + raise ChannelConnectError("missing WhatsApp connect session") + if action == "poll": + return await self.poll(session_id) + if action == "cancel": + return await self.cancel(session_id) + raise ChannelConnectError(f"unsupported WhatsApp connect action: {action}", status=404) + + async def start(self, *, force: bool = False) -> dict[str, Any]: + await self._cleanup() + channel, target_path = self._build_channel() + if not force and self._local_state_present(target_path): + return { + "session_id": "", + "status": "succeeded", + "message": "WhatsApp is already connected.", + "interval_ms": 2000, + } + + session_id = secrets.token_urlsafe(18) + pending_path = target_path.with_name(f".{target_path.name}.{session_id}.connect") + pending_path.parent.mkdir(parents=True, exist_ok=True) + self._remove_database(pending_path) + channel.config.database_path = str(pending_path) + now_wall = time.time() + + async def capture_qr(qr_data: bytes) -> None: + session = self._sessions.get(session_id) + if session is not None: + session.qr_url = qr_data.decode("utf-8") + + client, result = channel.connect_open_client(capture_qr) + connect_task = asyncio.create_task( + self._connect(channel, client, result), + name=f"whatsapp-connect-{session_id}", + ) + session = WhatsAppConnectSession( + id=session_id, + channel=channel, + client=client, + result=result, + connect_task=connect_task, + target_path=target_path, + pending_path=pending_path, + created_wall=now_wall, + deadline=time.monotonic() + 600, + ) + self._sessions[session_id] = session + + qr_wait = asyncio.create_task(self._wait_for_qr(session)) + try: + await asyncio.wait( + {qr_wait, connect_task}, + timeout=3, + return_when=asyncio.FIRST_COMPLETED, + ) + finally: + if not qr_wait.done(): + qr_wait.cancel() + return self._pending_payload(session) + + async def poll(self, session_id: str) -> dict[str, Any]: + await self._cleanup() + session = self._sessions.get(session_id) + if session is None: + return { + "session_id": session_id, + "status": "expired", + "message": "This WhatsApp login has expired. Start again.", + } + if not session.result.done(): + return self._pending_payload(session) + + finalize_task = session.finalize_task + if finalize_task is None: + finalize_task = asyncio.create_task( + self._finalize_session(session), + name=f"whatsapp-connect-finalize-{session.id}", + ) + session.finalize_task = finalize_task + if not finalize_task.done(): + # Finish fast clients in this request without letting native shutdown + # block the polling response path. + await asyncio.wait({finalize_task}, timeout=_FINALIZE_POLL_WAIT_SECONDS) + if not finalize_task.done(): + payload = self._pending_payload(session) + payload["qr_url"] = "" + payload["message"] = "Finishing the WhatsApp connection." + return payload + + self._sessions.pop(session_id, None) + try: + finalize_task.result() + except Exception as exc: + return { + "session_id": session_id, + "status": "failed", + "message": f"WhatsApp QR login failed: {exc}", + } + return { + "session_id": session_id, + "status": "succeeded", + "message": "WhatsApp is connected.", + } + + async def _finalize_session(self, session: WhatsAppConnectSession) -> None: + try: + session.result.result() + await self._close_session(session) + await self._commit_database(session.pending_path, session.target_path) + except BaseException: + await self._close_session(session) + self._remove_database(session.pending_path) + raise + + async def cancel(self, session_id: str) -> dict[str, Any]: + session = self._sessions.pop(session_id, None) + if session is not None: + await self._discard_session(session) + return { + "session_id": session_id, + "status": "cancelled", + "message": "WhatsApp login cancelled.", + } + + async def _cleanup(self) -> None: + expired = [ + session_id + for session_id, session in self._sessions.items() + if time.monotonic() >= session.deadline + ] + for session_id in expired: + session = self._sessions.pop(session_id) + await self._discard_session(session) + + async def close(self) -> None: + """Stop every login client before the gateway event loop closes.""" + sessions = tuple(self._sessions.values()) + self._sessions.clear() + for session in sessions: + await self._discard_session(session) + + async def _discard_session(self, session: WhatsAppConnectSession) -> None: + finalize_task = session.finalize_task + if ( + finalize_task is not None + and finalize_task is not asyncio.current_task() + ): + if not finalize_task.done(): + finalize_task.cancel() + await asyncio.gather(finalize_task, return_exceptions=True) + else: + await self._close_session(session) + self._remove_database(session.pending_path) + + @staticmethod + async def _connect( + channel: WhatsAppChannel, + client: Any, + result: asyncio.Future[None], + ) -> asyncio.Task[Any] | None: + try: + return await channel.connect_start_client(client, result) + except asyncio.CancelledError: + raise + except Exception as exc: + if not result.done(): + result.set_exception(exc) + return None + + @staticmethod + async def _wait_for_qr(session: WhatsAppConnectSession) -> None: + while not session.qr_url and not session.result.done(): + await asyncio.sleep(0.05) + + @staticmethod + async def _close_session(session: WhatsAppConnectSession) -> None: + if not session.result.done(): + session.result.cancel() + if not session.connect_task.done(): + session.connect_task.cancel() + with suppress(Exception, asyncio.CancelledError): + await session.connect_task + native_task: asyncio.Task[Any] | None = None + if session.connect_task.done() and not session.connect_task.cancelled(): + with suppress(Exception, asyncio.CancelledError): + native_task = session.connect_task.result() + client_native_task = getattr(session.client, "connect_task", None) + if native_task is None and isinstance(client_native_task, asyncio.Task): + native_task = cast(asyncio.Task[Any], client_native_task) + with suppress(Exception): + await asyncio.wait_for(session.client.stop(), timeout=5) + if native_task is not None: + if not native_task.done(): + try: + # Stop only signals neonize's Go worker. Wait for that worker + # to return so Windows releases its SQLite file handle before + # the temporary login database is promoted. + await asyncio.wait_for( + asyncio.shield(native_task), + timeout=_NATIVE_STOP_TIMEOUT_SECONDS, + ) + except TimeoutError: + native_task.cancel() + await asyncio.gather(native_task, return_exceptions=True) + + @staticmethod + def _build_channel() -> tuple[WhatsAppChannel, Path]: + from nanobot.bus.queue import MessageBus + from nanobot.channels.whatsapp.runtime import WhatsAppChannel + + section = getattr(load_config().channels, "whatsapp", None) + if section is not None and hasattr(section, "model_dump"): + config = section.model_dump(mode="json", by_alias=True) + elif isinstance(section, dict): + config = dict(cast(dict[str, Any], section)) + else: + config = {} + channel = WhatsAppChannel(config, MessageBus()) + return channel, channel.connect_database_path() + + @staticmethod + def _local_state_present(path: Path) -> bool: + try: + return path.is_file() and path.stat().st_size > 0 + except OSError: + return False + + @classmethod + async def _commit_database(cls, pending: Path, target: Path) -> None: + if not cls._local_state_present(pending): + raise RuntimeError("WhatsApp connected but did not create a local session database") + target.parent.mkdir(parents=True, exist_ok=True) + for pending_file, target_file in cls._database_files(pending, target): + if pending_file.exists(): + await cls._replace_database_file(pending_file, target_file) + elif target_file != target and target_file.exists(): + target_file.unlink() + + @staticmethod + async def _replace_database_file(source: Path, target: Path) -> None: + deadline = time.monotonic() + _DATABASE_REPLACE_TIMEOUT_SECONDS + while True: + try: + os.replace(source, target) + return + except PermissionError as exc: + if time.monotonic() >= deadline: + raise RuntimeError( + "WhatsApp paired, but its local session database is still in use" + ) from exc + await asyncio.sleep(0.1) + + @classmethod + def _remove_database(cls, path: Path) -> None: + for candidate, _ in cls._database_files(path, path): + with suppress(OSError): + candidate.unlink() + + @staticmethod + def _database_files(source: Path, target: Path) -> tuple[tuple[Path, Path], ...]: + return ( + (source, target), + (source.with_name(source.name + "-shm"), target.with_name(target.name + "-shm")), + (source.with_name(source.name + "-wal"), target.with_name(target.name + "-wal")), + ) + + @staticmethod + def _pending_payload(session: WhatsAppConnectSession) -> dict[str, Any]: + payload: dict[str, Any] = { + "session_id": session.id, + "status": "pending", + "interval_ms": 2000, + "expires_at_ms": int((session.created_wall + 600) * 1000), + "message": "Waiting for the WhatsApp scan.", + } + if session.qr_url: + payload["qr_url"] = session.qr_url + return payload + + +__all__ = ["WhatsAppConnectStore"] diff --git a/nanobot/channels/whatsapp/manifest.py b/nanobot/channels/whatsapp/manifest.py index e874804ec..00535ae0b 100644 --- a/nanobot/channels/whatsapp/manifest.py +++ b/nanobot/channels/whatsapp/manifest.py @@ -8,6 +8,7 @@ from nanobot.channels.whatsapp.validation import validate SETUP_SPEC = ChannelSetupSpec( fields={ + "proxy": field(), "allowFrom": field("list", snapshot=False), "groupPolicy": field( "enum", @@ -16,6 +17,7 @@ SETUP_SPEC = ChannelSetupSpec( snapshot=False, ), "databasePath": field(writable=False, snapshot=False), + "lidMappings": field("json", writable=False, snapshot=False), }, official_url="https://faq.whatsapp.com/", validator=validate, @@ -25,11 +27,12 @@ PLUGIN = ChannelPlugin( name="whatsapp", display_name="WhatsApp", runtime=f"{__package__}.runtime:WhatsAppChannel", + connector=f"{__package__}.connect:WhatsAppConnectStore", setup=SETUP_SPEC, management=ChannelManagementSpec(local_state_present=local_state_present), dependencies=( - "neonize>=0.3.18.post0,<0.4.0", + "neonize>=0.4.3.post0,<0.5.0", "segno>=1.6.1,<2.0.0", ), - webui="webui/index.ts", + webui="webui/index.tsx", ) diff --git a/nanobot/channels/whatsapp/runtime.py b/nanobot/channels/whatsapp/runtime.py index 7a24e920c..73eb89863 100644 --- a/nanobot/channels/whatsapp/runtime.py +++ b/nanobot/channels/whatsapp/runtime.py @@ -9,6 +9,7 @@ import re import secrets import time from collections import OrderedDict +from collections.abc import Awaitable, Callable from contextlib import suppress from pathlib import Path from typing import Any, Literal, NamedTuple, cast @@ -32,6 +33,7 @@ class WhatsAppConfig(Base): allow_from: list[str] = Field(default_factory=list) group_policy: Literal["open", "mention"] = "open" database_path: str = "" + proxy: str = "" lid_mappings: dict[str, str] = Field(default_factory=dict) @@ -325,6 +327,10 @@ class WhatsAppChannel(BaseChannel): configured = self.config.database_path.strip() return Path(configured).expanduser() if configured else _default_database_path() + def connect_database_path(self) -> Path: + """Return the session database target used by package-owned setup flows.""" + return self._database_path() + def _load_lid_mappings(self) -> dict[str, str]: mapping: dict[str, str] = {} for lid, phone in self.config.lid_mappings.items(): @@ -339,19 +345,52 @@ class WhatsAppChannel(BaseChannel): db_path.parent.mkdir(parents=True, exist_ok=True) return api.NewAClient(str(db_path)) + async def _connect_client(self, client: Any) -> Any: + proxy = self.config.proxy.strip() + if not proxy: + return await client.connect() + if "://" not in proxy: + proxy = f"http://{proxy}" + from neonize._binder import ProxySettings + + return await client.connect(ProxySettings(proxy_address=proxy)) + + def connect_open_client( + self, + qr_handler: Callable[[bytes], Awaitable[None]] | None = None, + ) -> tuple[Any, asyncio.Future[None]]: + """Create a login-only client for CLI or package-owned WebUI setup.""" + client = self._new_client() + result = asyncio.get_running_loop().create_future() + self._register_handlers( + client, + login_result=result, + handle_messages=False, + qr_handler=qr_handler, + ) + return client, result + + async def connect_start_client( + self, + client: Any, + result: asyncio.Future[None], + ) -> asyncio.Task[Any] | None: + """Start a login client and watch neonize's optional background task.""" + connect_task = await self._connect_client(client) + self._fail_login_on_connect_task_done(connect_task, result) + return connect_task + async def login(self, force: bool = False) -> bool: db_path = self._database_path() if force: self._reset_database(db_path) - client = self._new_client() - login_result = asyncio.get_running_loop().create_future() - self._register_handlers(client, login_result=login_result, handle_messages=False) + client, login_result = self.connect_open_client() + connect_task: asyncio.Task[Any] | None = None try: self.logger.info("Starting WhatsApp login with neonize...") - connect_task = await client.connect() - self._fail_login_on_connect_task_done(connect_task, login_result) + connect_task = await self.connect_start_client(client, login_result) await login_result self.logger.info("WhatsApp login complete") return True @@ -359,6 +398,10 @@ class WhatsAppChannel(BaseChannel): self.logger.error("WhatsApp login failed: {}", exc) return False finally: + if connect_task is not None and not connect_task.done(): + connect_task.cancel() + with suppress(Exception, asyncio.CancelledError): + await connect_task with suppress(Exception): await client.stop() @@ -371,7 +414,7 @@ class WhatsAppChannel(BaseChannel): try: self.logger.info("Connecting WhatsApp channel with neonize...") - await client.connect() + await self._connect_client(client) await client.idle() except asyncio.CancelledError: raise @@ -523,11 +566,15 @@ class WhatsAppChannel(BaseChannel): *, login_result: asyncio.Future[None] | None = None, handle_messages: bool, + qr_handler: Callable[[bytes], Awaitable[None]] | None = None, ) -> None: api = _load_neonize() @client.qr async def _on_qr(_: Any, qr_data: bytes) -> None: + if qr_handler is not None: + await qr_handler(qr_data) + return import segno self.logger.info("Scan the WhatsApp QR code with Linked Devices") diff --git a/nanobot/channels/whatsapp/tests/test_connect.py b/nanobot/channels/whatsapp/tests/test_connect.py new file mode 100644 index 000000000..c75f4c292 --- /dev/null +++ b/nanobot/channels/whatsapp/tests/test_connect.py @@ -0,0 +1,226 @@ +from __future__ import annotations + +import asyncio +import os +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +import pytest + +from nanobot.channels.whatsapp.connect import WhatsAppConnectStore + + +class _FakeClient: + def __init__( + self, + channel: "_FakeChannel", + *, + complete: bool, + stop_gate: asyncio.Event | None = None, + linger_until_stopped: bool = False, + ) -> None: + self.channel = channel + self.complete = complete + self.result: asyncio.Future[None] | None = None + self.qr_handler: Any = None + self.stopped = False + self.stop_gate = stop_gate + self.linger_until_stopped = linger_until_stopped + self.native_stop = asyncio.Event() + self.native_released = False + self.connect_task: asyncio.Task[None] | None = None + + async def connect(self) -> None: + await self.qr_handler(b"whatsapp-qr-payload") + if self.complete: + Path(self.channel.config.database_path).write_bytes(b"new-session") + assert self.result is not None + self.result.set_result(None) + if self.linger_until_stopped: + await self.native_stop.wait() + self.native_released = True + return + await asyncio.Event().wait() + + async def stop(self) -> None: + if self.stop_gate is not None: + await self.stop_gate.wait() + self.native_stop.set() + self.stopped = True + + +class _FakeChannel: + def __init__( + self, + *, + complete: bool, + stop_gate: asyncio.Event | None = None, + linger_until_stopped: bool = False, + ) -> None: + self.config = SimpleNamespace(database_path="") + self.client = _FakeClient( + self, + complete=complete, + stop_gate=stop_gate, + linger_until_stopped=linger_until_stopped, + ) + + def connect_open_client( + self, + qr_handler: Any, + ) -> tuple[_FakeClient, asyncio.Future[None]]: + result = asyncio.get_running_loop().create_future() + self.client.result = result + self.client.qr_handler = qr_handler + return self.client, result + + async def connect_start_client( + self, + client: _FakeClient, + _result: asyncio.Future[None], + ) -> asyncio.Task[None] | None: + if client.linger_until_stopped: + client.connect_task = asyncio.create_task(client.connect()) + await asyncio.sleep(0) + return client.connect_task + await client.connect() + return None + + +@pytest.mark.asyncio +async def test_whatsapp_connect_commits_new_session_after_scan( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +) -> None: + target = tmp_path / "neonize.db" + target.write_bytes(b"old-session") + channel = _FakeChannel(complete=True) + store = WhatsAppConnectStore() + monkeypatch.setattr(store, "_build_channel", lambda: (channel, target)) + + started = await store.start(force=True) + completed = await store.poll(started["session_id"]) + + assert started["status"] == "pending" + assert started["qr_url"] == "whatsapp-qr-payload" + assert completed["status"] == "succeeded" + assert target.read_bytes() == b"new-session" + assert channel.client.stopped is True + + +@pytest.mark.asyncio +async def test_whatsapp_connect_cancel_preserves_existing_session( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +) -> None: + target = tmp_path / "neonize.db" + target.write_bytes(b"working-session") + channel = _FakeChannel(complete=False) + store = WhatsAppConnectStore() + monkeypatch.setattr(store, "_build_channel", lambda: (channel, target)) + + started = await store.start(force=True) + pending_path = Path(channel.config.database_path) + pending_path.write_bytes(b"partial-session") + cancelled = await store.cancel(started["session_id"]) + + assert cancelled["status"] == "cancelled" + assert target.read_bytes() == b"working-session" + assert not pending_path.exists() + assert channel.client.stopped is True + + +@pytest.mark.asyncio +async def test_whatsapp_connect_clears_qr_while_finishing_login( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +) -> None: + target = tmp_path / "neonize.db" + stop_gate = asyncio.Event() + channel = _FakeChannel(complete=True, stop_gate=stop_gate) + store = WhatsAppConnectStore() + monkeypatch.setattr(store, "_build_channel", lambda: (channel, target)) + + started = await store.start(force=True) + finishing = await store.poll(started["session_id"]) + + assert finishing["status"] == "pending" + assert finishing["qr_url"] == "" + + stop_gate.set() + await asyncio.sleep(0) + completed = await store.poll(started["session_id"]) + + assert completed["status"] == "succeeded" + assert target.read_bytes() == b"new-session" + + +@pytest.mark.asyncio +async def test_whatsapp_connect_waits_for_native_client_before_committing( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +) -> None: + target = tmp_path / "neonize.db" + channel = _FakeChannel(complete=True, linger_until_stopped=True) + store = WhatsAppConnectStore() + monkeypatch.setattr(store, "_build_channel", lambda: (channel, target)) + + started = await store.start(force=True) + completed: dict[str, Any] = {"status": "pending"} + for _ in range(10): + completed = await store.poll(started["session_id"]) + if completed["status"] != "pending": + break + await asyncio.sleep(0) + + assert completed["status"] == "succeeded" + assert channel.client.native_released is True + assert target.read_bytes() == b"new-session" + + +@pytest.mark.asyncio +async def test_whatsapp_connect_retries_transient_windows_database_lock( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +) -> None: + pending = tmp_path / ".neonize.db.connect" + target = tmp_path / "neonize.db" + pending.write_bytes(b"new-session") + replace = os.replace + attempts = 0 + + def replace_after_release(source: Path, destination: Path) -> None: + nonlocal attempts + attempts += 1 + if attempts == 1: + raise PermissionError(32, "file is in use", str(source), str(destination)) + replace(source, destination) + + monkeypatch.setattr(os, "replace", replace_after_release) + + await WhatsAppConnectStore._commit_database(pending, target) + + assert attempts == 2 + assert target.read_bytes() == b"new-session" + + +@pytest.mark.asyncio +async def test_whatsapp_connect_store_closes_pending_login( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +) -> None: + target = tmp_path / "neonize.db" + channel = _FakeChannel(complete=False) + store = WhatsAppConnectStore() + monkeypatch.setattr(store, "_build_channel", lambda: (channel, target)) + + started = await store.start(force=True) + pending_path = Path(channel.config.database_path) + pending_path.write_bytes(b"partial-session") + + await store.close() + + assert started["status"] == "pending" + assert not pending_path.exists() + assert channel.client.stopped is True diff --git a/nanobot/channels/whatsapp/tests/test_whatsapp_channel.py b/nanobot/channels/whatsapp/tests/test_whatsapp_channel.py index e3b80fa7a..ff3ee9063 100644 --- a/nanobot/channels/whatsapp/tests/test_whatsapp_channel.py +++ b/nanobot/channels/whatsapp/tests/test_whatsapp_channel.py @@ -128,6 +128,36 @@ def _patch_receipt_type(monkeypatch): return ReceiptType +@pytest.mark.asyncio +async def test_connect_client_normalizes_proxy_without_a_scheme(monkeypatch) -> None: + class ProxySettings: + def __init__(self, *, proxy_address: str) -> None: + self.proxy_address = proxy_address + + monkeypatch.setitem( + sys.modules, + "neonize._binder", + SimpleNamespace(ProxySettings=ProxySettings), + ) + channel = _make_channel({"proxy": "127.0.0.1:23458"}) + client = SimpleNamespace(connect=AsyncMock(return_value=None)) + + await channel._connect_client(client) + + settings = client.connect.await_args.args[0] + assert settings.proxy_address == "http://127.0.0.1:23458" + + +@pytest.mark.asyncio +async def test_connect_client_without_proxy_uses_default_connection() -> None: + channel = _make_channel({"proxy": ""}) + client = SimpleNamespace(connect=AsyncMock(return_value=None)) + + await channel._connect_client(client) + + client.connect.assert_awaited_once_with() + + class _FakeLoginClient: def __init__(self) -> None: self.handlers = {} diff --git a/nanobot/channels/whatsapp/webui/WhatsAppConnectFlow.tsx b/nanobot/channels/whatsapp/webui/WhatsAppConnectFlow.tsx new file mode 100644 index 000000000..c4ba7d895 --- /dev/null +++ b/nanobot/channels/whatsapp/webui/WhatsAppConnectFlow.tsx @@ -0,0 +1,45 @@ +import { useTranslation } from "react-i18next"; + +import { channelTranslator } from "@/channel-plugins/i18n"; +import type { ChannelPluginConnectFlowProps } from "@/channel-plugins/types"; +import { ChannelQrConnectFlow } from "@/components/settings/channels/ChannelQrConnectFlow"; + +export function WhatsAppConnectFlow({ + token, + idleLabel, + connectRequestId, + onFeaturesUpdate, +}: ChannelPluginConnectFlowProps) { + const { t } = useTranslation(); + const tx = channelTranslator(t, "whatsapp"); + + return ( + + ); +} diff --git a/nanobot/channels/whatsapp/webui/index.ts b/nanobot/channels/whatsapp/webui/index.ts deleted file mode 100644 index fd5ccfc8d..000000000 --- a/nanobot/channels/whatsapp/webui/index.ts +++ /dev/null @@ -1,20 +0,0 @@ -import type { ChannelUiContribution } from "@/channel-plugins/types"; -import { chatAppGuideUrl } from "@/components/settings/channels/catalog"; - -export default { - presentation: { - displayName: "WhatsApp", - initials: "WA", - color: "#25D366", - logoUrl: "https://www.whatsapp.com/favicon.ico", - setup: { - mode: "connect", - command: "nanobot channels login whatsapp", - docsUrl: chatAppGuideUrl("whatsapp"), - manualFields: [ - { key: "channels.whatsapp.allowFrom" }, - { key: "channels.whatsapp.groupPolicy" }, - ], - }, - }, -} satisfies ChannelUiContribution; diff --git a/nanobot/channels/whatsapp/webui/index.tsx b/nanobot/channels/whatsapp/webui/index.tsx new file mode 100644 index 000000000..fe18712b1 --- /dev/null +++ b/nanobot/channels/whatsapp/webui/index.tsx @@ -0,0 +1,27 @@ +import { MessageCircle } from "lucide-react"; + +import type { ChannelUiContribution } from "@/channel-plugins/types"; +import { chatAppGuideUrl } from "@/components/settings/channels/catalog"; + +import { WhatsAppConnectFlow } from "./WhatsAppConnectFlow"; + +export default { + presentation: { + logoUrl: "https://static.whatsapp.net/rsrc.php/y1/r/FJbTMJqMap7.svg", + displayName: "WhatsApp", + initials: "WA", + color: "#25D366", + icon: MessageCircle, + setup: { + mode: "connect", + docsUrl: chatAppGuideUrl("whatsapp"), + manualFields: [ + { key: "channels.whatsapp.proxy", section: "connection" }, + { key: "channels.whatsapp.allowFrom", section: "access" }, + { key: "channels.whatsapp.groupPolicy", section: "behavior" }, + ], + }, + }, + ConnectFlow: WhatsAppConnectFlow, + canConnectBeforeConfigured: true, +} satisfies ChannelUiContribution; diff --git a/nanobot/channels/whatsapp/webui/locales/en.json b/nanobot/channels/whatsapp/webui/locales/en.json index 34fbf56a9..d480464e1 100644 --- a/nanobot/channels/whatsapp/webui/locales/en.json +++ b/nanobot/channels/whatsapp/webui/locales/en.json @@ -1,17 +1,8 @@ { - "description": "Use nanobot from WhatsApp conversations.", - "requirements": "WhatsApp connection setup and gateway", "setup": { "primaryAction": "Connect WhatsApp", "docsLabel": "Open WhatsApp setup", "officialLabel": "Open WhatsApp help", - "tryIt": "After terminal login finishes, send a WhatsApp DM to the connected account.", - "summary": "WhatsApp is connected by scanning a QR code from the account that should run the bot.", - "steps": [ - "Run the WhatsApp login command shown below.", - "Scan the QR code in the terminal with WhatsApp on your phone.", - "Return here after login, enable WhatsApp, then send a direct test message." - ], "fields": { "allowFrom": { "label": "Allowed contacts", @@ -24,7 +15,22 @@ "open": "All messages", "allowlist": "Allowlist" } + }, + "proxy": { + "label": "Network proxy", + "placeholder": "http://127.0.0.1:7890" } } + }, + "custom": { + "qrAlt": "WhatsApp linking QR code", + "scanTitle": "Link WhatsApp", + "scanDescription": "In WhatsApp, open Linked devices, choose Link a device, then scan this code.", + "waiting": "Waiting for WhatsApp…", + "connected": "WhatsApp is connected.", + "stopped": "The WhatsApp connection attempt stopped. Start again to get a new code.", + "connecting": "Connecting…", + "scanAgain": "Link another account", + "connect": "Link WhatsApp" } } diff --git a/nanobot/channels/whatsapp/webui/locales/es.json b/nanobot/channels/whatsapp/webui/locales/es.json index 7719f9d50..a89e7cfe4 100644 --- a/nanobot/channels/whatsapp/webui/locales/es.json +++ b/nanobot/channels/whatsapp/webui/locales/es.json @@ -1,17 +1,8 @@ { - "description": "Usa nanobot desde conversaciones de WhatsApp.", - "requirements": "Configuración de conexión de WhatsApp y pasarela", "setup": { "primaryAction": "Conectar WhatsApp", "docsLabel": "Abrir guía de WhatsApp", "officialLabel": "Abrir la ayuda de WhatsApp", - "tryIt": "Tras iniciar sesión en la terminal, envía un DM a la cuenta conectada.", - "summary": "WhatsApp se conecta escaneando un QR con la cuenta que ejecutará el bot.", - "steps": [ - "Ejecuta el comando de inicio de WhatsApp mostrado abajo.", - "Escanea el QR de la terminal con WhatsApp en tu teléfono.", - "Vuelve aquí tras iniciar sesión, activa WhatsApp y envía un mensaje directo de prueba." - ], "fields": { "allowFrom": { "label": "Contactos permitidos", @@ -24,7 +15,22 @@ "open": "Todos los mensajes", "allowlist": "Lista de permitidos" } + }, + "proxy": { + "label": "Proxy de red", + "placeholder": "http://127.0.0.1:7890" } } + }, + "custom": { + "qrAlt": "Código QR para vincular WhatsApp", + "scanTitle": "Vincular WhatsApp", + "scanDescription": "En WhatsApp, abre Dispositivos vinculados, elige Vincular un dispositivo y escanea este código.", + "waiting": "Esperando a WhatsApp…", + "connected": "WhatsApp está conectado.", + "stopped": "El intento de conexión se detuvo. Inicia de nuevo para obtener otro código.", + "connecting": "Conectando…", + "scanAgain": "Vincular otra cuenta", + "connect": "Vincular WhatsApp" } } diff --git a/nanobot/channels/whatsapp/webui/locales/fr.json b/nanobot/channels/whatsapp/webui/locales/fr.json index d6c20e100..75bfe0c7c 100644 --- a/nanobot/channels/whatsapp/webui/locales/fr.json +++ b/nanobot/channels/whatsapp/webui/locales/fr.json @@ -1,17 +1,8 @@ { - "description": "Utilisez nanobot depuis les conversations WhatsApp.", - "requirements": "Configuration de la connexion WhatsApp et passerelle", "setup": { "primaryAction": "Connecter WhatsApp", "docsLabel": "Ouvrir le guide WhatsApp", "officialLabel": "Ouvrir l’aide WhatsApp", - "tryIt": "Après la connexion dans le terminal, envoyez un message privé au compte connecté.", - "summary": "WhatsApp se connecte en scannant un QR code avec le compte qui exécutera le bot.", - "steps": [ - "Exécutez la commande de connexion WhatsApp ci-dessous.", - "Scannez le QR code du terminal avec WhatsApp sur votre téléphone.", - "Revenez ici après la connexion, activez WhatsApp et envoyez un message privé test." - ], "fields": { "allowFrom": { "label": "Contacts autorisés", @@ -24,7 +15,22 @@ "open": "Tous les messages", "allowlist": "Liste d’autorisation" } + }, + "proxy": { + "label": "Proxy réseau", + "placeholder": "http://127.0.0.1:7890" } } + }, + "custom": { + "qrAlt": "QR code d’association WhatsApp", + "scanTitle": "Associer WhatsApp", + "scanDescription": "Dans WhatsApp, ouvrez Appareils connectés, choisissez Connecter un appareil, puis scannez ce code.", + "waiting": "En attente de WhatsApp…", + "connected": "WhatsApp est connecté.", + "stopped": "La tentative de connexion s’est arrêtée. Recommencez pour obtenir un nouveau code.", + "connecting": "Connexion…", + "scanAgain": "Associer un autre compte", + "connect": "Associer WhatsApp" } } diff --git a/nanobot/channels/whatsapp/webui/locales/id.json b/nanobot/channels/whatsapp/webui/locales/id.json index a5f1ebd3f..014f74650 100644 --- a/nanobot/channels/whatsapp/webui/locales/id.json +++ b/nanobot/channels/whatsapp/webui/locales/id.json @@ -1,17 +1,8 @@ { - "description": "Gunakan nanobot dari percakapan WhatsApp.", - "requirements": "Pengaturan koneksi WhatsApp dan gateway", "setup": { "primaryAction": "Hubungkan WhatsApp", "docsLabel": "Buka panduan WhatsApp", "officialLabel": "Buka bantuan WhatsApp", - "tryIt": "Setelah login terminal selesai, kirim DM ke akun yang terhubung.", - "summary": "WhatsApp terhubung dengan memindai kode QR dari akun yang akan menjalankan bot.", - "steps": [ - "Jalankan perintah login WhatsApp yang ditampilkan di bawah.", - "Pindai kode QR di terminal dengan WhatsApp di ponsel.", - "Kembali ke sini setelah login, aktifkan WhatsApp, lalu kirim pesan langsung uji." - ], "fields": { "allowFrom": { "label": "Kontak yang diizinkan", @@ -24,7 +15,22 @@ "open": "Semua pesan", "allowlist": "Daftar izin" } + }, + "proxy": { + "label": "Proxy jaringan", + "placeholder": "http://127.0.0.1:7890" } } + }, + "custom": { + "qrAlt": "Kode QR penautan WhatsApp", + "scanTitle": "Tautkan WhatsApp", + "scanDescription": "Di WhatsApp, buka Perangkat tertaut, pilih Tautkan perangkat, lalu pindai kode ini.", + "waiting": "Menunggu WhatsApp…", + "connected": "WhatsApp terhubung.", + "stopped": "Upaya koneksi berhenti. Mulai lagi untuk mendapatkan kode baru.", + "connecting": "Menghubungkan…", + "scanAgain": "Tautkan akun lain", + "connect": "Tautkan WhatsApp" } } diff --git a/nanobot/channels/whatsapp/webui/locales/ja.json b/nanobot/channels/whatsapp/webui/locales/ja.json index 7c04b3eaa..111500951 100644 --- a/nanobot/channels/whatsapp/webui/locales/ja.json +++ b/nanobot/channels/whatsapp/webui/locales/ja.json @@ -1,17 +1,8 @@ { - "description": "WhatsApp の会話から nanobot を利用します。", - "requirements": "WhatsApp 接続設定とゲートウェイ", "setup": { "primaryAction": "WhatsApp に接続", "docsLabel": "WhatsApp 設定ガイドを開く", "officialLabel": "WhatsApp ヘルプを開く", - "tryIt": "ターミナルでのログイン後、接続したアカウントに WhatsApp の DM を送信します。", - "summary": "ボットを動かす WhatsApp アカウントで QR コードを読み取って接続します。", - "steps": [ - "下に表示された WhatsApp ログインコマンドを実行します。", - "スマートフォンの WhatsApp でターミナルの QR コードを読み取ります。", - "ログイン後に戻り、WhatsApp を有効にして DM でテストします。" - ], "fields": { "allowFrom": { "label": "許可する連絡先", @@ -24,7 +15,22 @@ "open": "すべてのメッセージ", "allowlist": "許可リスト" } + }, + "proxy": { + "label": "ネットワークプロキシ", + "placeholder": "http://127.0.0.1:7890" } } + }, + "custom": { + "qrAlt": "WhatsApp リンク用 QR コード", + "scanTitle": "WhatsApp をリンク", + "scanDescription": "WhatsApp でリンク済みデバイスを開き、デバイスをリンクを選んでこのコードを読み取ります。", + "waiting": "WhatsApp を待機中…", + "connected": "WhatsApp に接続しました。", + "stopped": "接続が停止しました。新しいコードを取得するには再開してください。", + "connecting": "接続中…", + "scanAgain": "別のアカウントをリンク", + "connect": "WhatsApp をリンク" } } diff --git a/nanobot/channels/whatsapp/webui/locales/ko.json b/nanobot/channels/whatsapp/webui/locales/ko.json index 431dbc395..3e449cca8 100644 --- a/nanobot/channels/whatsapp/webui/locales/ko.json +++ b/nanobot/channels/whatsapp/webui/locales/ko.json @@ -1,17 +1,8 @@ { - "description": "WhatsApp 대화에서 nanobot을 사용합니다.", - "requirements": "WhatsApp 연결 설정 및 게이트웨이", "setup": { "primaryAction": "WhatsApp 연결", "docsLabel": "WhatsApp 설정 가이드 열기", "officialLabel": "WhatsApp 도움말 열기", - "tryIt": "터미널 로그인이 끝나면 연결된 계정으로 WhatsApp DM을 보내세요.", - "summary": "봇을 실행할 WhatsApp 계정으로 QR 코드를 스캔해 연결합니다.", - "steps": [ - "아래 표시된 WhatsApp 로그인 명령을 실행하세요.", - "휴대폰 WhatsApp으로 터미널의 QR 코드를 스캔하세요.", - "로그인 후 여기로 돌아와 WhatsApp을 활성화하고 DM으로 테스트하세요." - ], "fields": { "allowFrom": { "label": "허용된 연락처", @@ -24,7 +15,22 @@ "open": "모든 메시지", "allowlist": "허용 목록" } + }, + "proxy": { + "label": "네트워크 프록시", + "placeholder": "http://127.0.0.1:7890" } } + }, + "custom": { + "qrAlt": "WhatsApp 연결 QR 코드", + "scanTitle": "WhatsApp 연결", + "scanDescription": "WhatsApp에서 연결된 기기를 열고 기기 연결을 선택한 다음 이 코드를 스캔하세요.", + "waiting": "WhatsApp 대기 중…", + "connected": "WhatsApp이 연결되었습니다.", + "stopped": "연결 시도가 중지되었습니다. 새 코드를 받으려면 다시 시작하세요.", + "connecting": "연결 중…", + "scanAgain": "다른 계정 연결", + "connect": "WhatsApp 연결" } } diff --git a/nanobot/channels/whatsapp/webui/locales/pt-BR.json b/nanobot/channels/whatsapp/webui/locales/pt-BR.json index cde9c5da2..157f2ed48 100644 --- a/nanobot/channels/whatsapp/webui/locales/pt-BR.json +++ b/nanobot/channels/whatsapp/webui/locales/pt-BR.json @@ -1,17 +1,8 @@ { - "description": "Use o nanobot em conversas do WhatsApp.", - "requirements": "Configuração da conexão do WhatsApp e gateway", "setup": { "primaryAction": "Conectar WhatsApp", "docsLabel": "Abrir guia do WhatsApp", "officialLabel": "Abrir ajuda do WhatsApp", - "tryIt": "Após o login no terminal, envie uma DM à conta conectada.", - "summary": "O WhatsApp conecta ao escanear um QR code com a conta que executará o bot.", - "steps": [ - "Execute o comando de login do WhatsApp mostrado abaixo.", - "Escaneie o QR code do terminal com o WhatsApp no celular.", - "Volte aqui após o login, ative o WhatsApp e envie uma mensagem direta de teste." - ], "fields": { "allowFrom": { "label": "Contatos permitidos", @@ -24,7 +15,22 @@ "open": "Todas as mensagens", "allowlist": "Lista de permissão" } + }, + "proxy": { + "label": "Proxy de rede", + "placeholder": "http://127.0.0.1:7890" } } + }, + "custom": { + "qrAlt": "QR code para vincular o WhatsApp", + "scanTitle": "Vincular WhatsApp", + "scanDescription": "No WhatsApp, abra Aparelhos conectados, escolha Conectar um aparelho e escaneie este código.", + "waiting": "Aguardando o WhatsApp…", + "connected": "O WhatsApp está conectado.", + "stopped": "A tentativa de conexão parou. Inicie novamente para obter outro código.", + "connecting": "Conectando…", + "scanAgain": "Vincular outra conta", + "connect": "Vincular WhatsApp" } } diff --git a/nanobot/channels/whatsapp/webui/locales/vi.json b/nanobot/channels/whatsapp/webui/locales/vi.json index 1018123d5..0cd7fd947 100644 --- a/nanobot/channels/whatsapp/webui/locales/vi.json +++ b/nanobot/channels/whatsapp/webui/locales/vi.json @@ -1,17 +1,8 @@ { - "description": "Sử dụng nanobot từ các cuộc trò chuyện WhatsApp.", - "requirements": "Cài đặt kết nối WhatsApp và gateway", "setup": { "primaryAction": "Kết nối WhatsApp", "docsLabel": "Mở hướng dẫn WhatsApp", "officialLabel": "Mở trợ giúp WhatsApp", - "tryIt": "Sau khi đăng nhập terminal, gửi tin nhắn riêng đến tài khoản đã kết nối.", - "summary": "WhatsApp kết nối bằng cách quét mã QR từ tài khoản sẽ chạy bot.", - "steps": [ - "Chạy lệnh đăng nhập WhatsApp hiển thị bên dưới.", - "Quét mã QR trong terminal bằng WhatsApp trên điện thoại.", - "Sau khi đăng nhập, quay lại đây, bật WhatsApp và gửi tin nhắn riêng thử." - ], "fields": { "allowFrom": { "label": "Liên hệ được phép", @@ -24,7 +15,22 @@ "open": "Mọi tin nhắn", "allowlist": "Danh sách cho phép" } + }, + "proxy": { + "label": "Proxy mạng", + "placeholder": "http://127.0.0.1:7890" } } + }, + "custom": { + "qrAlt": "Mã QR liên kết WhatsApp", + "scanTitle": "Liên kết WhatsApp", + "scanDescription": "Trong WhatsApp, mở Thiết bị đã liên kết, chọn Liên kết thiết bị rồi quét mã này.", + "waiting": "Đang chờ WhatsApp…", + "connected": "WhatsApp đã kết nối.", + "stopped": "Kết nối đã dừng. Hãy bắt đầu lại để nhận mã mới.", + "connecting": "Đang kết nối…", + "scanAgain": "Liên kết tài khoản khác", + "connect": "Liên kết WhatsApp" } } diff --git a/nanobot/channels/whatsapp/webui/locales/zh-CN.json b/nanobot/channels/whatsapp/webui/locales/zh-CN.json index 7883c9311..9295f2622 100644 --- a/nanobot/channels/whatsapp/webui/locales/zh-CN.json +++ b/nanobot/channels/whatsapp/webui/locales/zh-CN.json @@ -1,17 +1,8 @@ { - "description": "在 WhatsApp 会话中使用 nanobot。", - "requirements": "WhatsApp 连接配置和网关", "setup": { "primaryAction": "连接 WhatsApp", "docsLabel": "打开 WhatsApp 配置指南", "officialLabel": "打开 WhatsApp 帮助", - "tryIt": "终端登录完成后,向已连接的账户发送一条 WhatsApp 私信。", - "summary": "使用要运行机器人的 WhatsApp 账户扫描二维码即可完成连接。", - "steps": [ - "运行下方显示的 WhatsApp 登录命令。", - "用手机 WhatsApp 扫描终端中的二维码。", - "登录后返回这里,启用 WhatsApp,然后发送一条私信测试。" - ], "fields": { "allowFrom": { "label": "允许的联系人", @@ -24,7 +15,22 @@ "open": "所有消息", "allowlist": "白名单" } + }, + "proxy": { + "label": "网络代理", + "placeholder": "http://127.0.0.1:7890" } } + }, + "custom": { + "qrAlt": "WhatsApp 关联二维码", + "scanTitle": "关联 WhatsApp", + "scanDescription": "在 WhatsApp 中打开“已关联的设备”,选择“关联设备”,然后扫描此二维码。", + "waiting": "正在等待 WhatsApp 扫码…", + "connected": "WhatsApp 已连接。", + "stopped": "WhatsApp 连接已停止。请重新开始以获取新二维码。", + "connecting": "正在连接…", + "scanAgain": "关联其他账户", + "connect": "关联 WhatsApp" } } diff --git a/nanobot/channels/whatsapp/webui/locales/zh-TW.json b/nanobot/channels/whatsapp/webui/locales/zh-TW.json index 3eed6f4b6..7757227d5 100644 --- a/nanobot/channels/whatsapp/webui/locales/zh-TW.json +++ b/nanobot/channels/whatsapp/webui/locales/zh-TW.json @@ -1,17 +1,8 @@ { - "description": "在 WhatsApp 對話中使用 nanobot。", - "requirements": "WhatsApp 連接設定和閘道", "setup": { "primaryAction": "連接 WhatsApp", "docsLabel": "開啟 WhatsApp 設定指南", "officialLabel": "開啟 WhatsApp 說明", - "tryIt": "終端機登入完成後,向已連接的帳戶傳送一則 WhatsApp 私訊。", - "summary": "使用要執行機器人的 WhatsApp 帳戶掃描QR Code即可完成連接。", - "steps": [ - "執行下方顯示的 WhatsApp 登入指令。", - "用手機 WhatsApp 掃描終端機中的QR Code。", - "登入後返回這裡,啟用 WhatsApp,然後傳送一則私訊測試。" - ], "fields": { "allowFrom": { "label": "允許的聯絡人", @@ -24,7 +15,22 @@ "open": "所有訊息", "allowlist": "允許清單" } + }, + "proxy": { + "label": "網路代理", + "placeholder": "http://127.0.0.1:7890" } } + }, + "custom": { + "qrAlt": "WhatsApp 連結QR Code", + "scanTitle": "連結 WhatsApp", + "scanDescription": "在 WhatsApp 中開啟「已連結裝置」,選擇「連結裝置」,然後掃描此QR Code。", + "waiting": "正在等待 WhatsApp 掃描…", + "connected": "WhatsApp 已連接。", + "stopped": "WhatsApp 連接已停止。請重新開始以取得新的QR Code。", + "connecting": "正在連接…", + "scanAgain": "連結其他帳戶", + "connect": "連結 WhatsApp" } } diff --git a/nanobot/optional_features.py b/nanobot/optional_features.py index c3dac6f89..0724763c2 100644 --- a/nanobot/optional_features.py +++ b/nanobot/optional_features.py @@ -451,6 +451,7 @@ def optional_features_payload( ), "type": "channel" if is_channel else "feature", "installed": installed, + "requires_dependencies": has_dependencies, "install_supported": has_dependencies or is_channel, "requires_restart": _feature_requires_restart(name, is_channel=is_channel), } @@ -639,6 +640,104 @@ def _combined_channel_runtime_state( return "stopped" +def _install_feature_dependencies( + name: str, + dependencies: list[str] | None, + *, + allow_install: bool, + runner: Any, +) -> bool: + """Ensure one feature's declared dependencies are present. + + Returns ``True`` only when this call ran an installer. Package-install + authorization belongs here so every WebUI action gets the same policy. + """ + if not dependencies or extra_installed(name, dependencies): + return False + if not allow_install: + raise OptionalFeatureError( + "Installing optional features from a remote WebUI is disabled. " + "Run this action from localhost or set tools.webuiAllowRemotePackageInstall to true.", + status=403, + ) + result = install_extra( + name, + dependencies, + runner=runner, + ) + if not result.ok: + failed = command_text(result.failed_cmd or result.pip_cmd) + detail = f": {result.output}" if result.output else "" + raise OptionalFeatureError(f"Failed: {failed}{detail}", status=500) + return True + + +def install_optional_feature_support( + name: str, + *, + config_path: Path | None = None, + allow_install: bool = True, + runner: Any = run_install_command, +) -> dict[str, Any]: + """Install channel dependencies without enabling or changing configuration.""" + from nanobot.channels.registry import discover_plugins + from nanobot.config.loader import get_config_path, load_config + + config_path = config_path or get_config_path() + extras = optional_dependency_groups() + channel_plugins = discover_plugins() + known = set(channel_plugins) | set(extras) + if name not in known: + available = ", ".join(sorted(known)) + raise OptionalFeatureError(f"Unknown feature: {name}. Available: {available}", status=404) + + channel_plugin = channel_plugins.get(name) + if channel_plugin is None: + raise OptionalFeatureError( + "Install-only actions are supported for channel features only.", + status=400, + ) + dependencies = _feature_dependencies(name, channel_plugin, extras) + installed_now = _install_feature_dependencies( + name, + dependencies, + allow_install=allow_install, + runner=runner, + ) + if dependencies and not extra_installed(name, dependencies): + raise OptionalFeatureError( + f"Installed support for channel '{name}', but its dependencies are still unavailable.", + status=500, + ) + + payload = optional_features_payload(config=load_config(config_path)) + feature = next( + (item for item in payload["features"] if item.get("name") == name), + None, + ) + if feature is None or not feature.get("installed"): + raise OptionalFeatureError( + f"Channel '{name}' dependencies are still unavailable after installation.", + status=500, + ) + message = ( + f"Installed support for channel '{name}'" + if installed_now + else f"Support for channel '{name}' is already installed" + ) + payload["last_action"] = { + "ok": True, + "message": message, + "enabled": bool(feature.get("enabled")), + "installed": True, + } + # A dependency can replace a module that is already imported by the + # gateway (for example neonize during WhatsApp setup). Keep the gateway + # running, but require a restart before the channel can use the new code. + payload["requires_restart"] = installed_now + return payload + + def enable_optional_feature( name: str, *, @@ -671,22 +770,12 @@ def enable_optional_feature( channel_plugin = channel_plugins.get(name) dependencies = _feature_dependencies(name, channel_plugin, extras) - if dependencies and not extra_installed(name, dependencies): - if not allow_install: - raise OptionalFeatureError( - "Installing optional features from a remote WebUI is disabled. " - "Run this action from localhost or set tools.webuiAllowRemotePackageInstall to true.", - status=403, - ) - result = install_extra( - name, - dependencies, - runner=runner, - ) - if not result.ok: - failed = command_text(result.failed_cmd or result.pip_cmd) - detail = f": {result.output}" if result.output else "" - raise OptionalFeatureError(f"Failed: {failed}{detail}", status=500) + _install_feature_dependencies( + name, + dependencies, + allow_install=allow_install, + runner=runner, + ) channel_cls: Any | None = None target_instance_id: str | None = None diff --git a/nanobot/pairing/store.py b/nanobot/pairing/store.py index 260b2cb0f..9affe2588 100644 --- a/nanobot/pairing/store.py +++ b/nanobot/pairing/store.py @@ -285,10 +285,11 @@ def get_approved(channel: str) -> list[str]: def format_pairing_reply(code: str) -> str: """Return the pairing-code message sent to unrecognised DM senders.""" return ( - "Hi there! This assistant only responds to approved users.\n\n" + "Hi! This is your private nanobot.\n\n" f"Your pairing code is: `{code}`\n\n" - "To get access, ask the owner to approve this request in the nanobot WebUI.\n" - f"If the WebUI is not available, the owner can also send `/pairing approve {code}`." + "Open the nanobot WebUI and enter this code to pair your chat account.\n" + f"Without the WebUI, approve it from an already paired chat with " + f"`/pairing approve {code}`." ) diff --git a/nanobot/webui/inbound_commands.py b/nanobot/webui/inbound_commands.py index 8416f3c4f..ae5541f37 100644 --- a/nanobot/webui/inbound_commands.py +++ b/nanobot/webui/inbound_commands.py @@ -973,6 +973,7 @@ class WebUICommandRouter: self.request_tasks.clear() self.request_locks.clear() self.request_operations.clear() + await self._http_router.settings_routes.close() self.gateway.tokens.clear() self.gateway.endpoint.clear() self._temporary_chats.close() diff --git a/nanobot/webui/nanobot_features_api.py b/nanobot/webui/nanobot_features_api.py index 3dc430b9d..2ad76f8f6 100644 --- a/nanobot/webui/nanobot_features_api.py +++ b/nanobot/webui/nanobot_features_api.py @@ -9,6 +9,7 @@ from nanobot.optional_features import ( OptionalFeatureError, disable_optional_feature, enable_optional_feature, + install_optional_feature_support, optional_features_payload, ) from nanobot.webui.http_utils import query_first @@ -42,9 +43,24 @@ def nanobot_features_action( ) -> dict[str, Any]: name = (query_first(query, "name") or "").strip() instance_id = nanobot_feature_instance_target(query) + raw_install_only = query_first(query, "install_only") + install_only = False + if raw_install_only is not None: + normalized = raw_install_only.strip().lower() + if normalized not in {"1", "0", "true", "false", "yes", "no"}: + raise OptionalFeatureError("install_only must be boolean") + install_only = normalized in {"1", "true", "yes"} + if action != "enable": + raise OptionalFeatureError("install_only is only supported for enable actions") if not name: raise OptionalFeatureError("missing feature name") if action == "enable": + if install_only: + return install_optional_feature_support( + name, + config_path=config_path, + allow_install=allow_install, + ) return enable_optional_feature( name, config_path=config_path, diff --git a/nanobot/webui/settings_routes.py b/nanobot/webui/settings_routes.py index 5b38494db..3512756e6 100644 --- a/nanobot/webui/settings_routes.py +++ b/nanobot/webui/settings_routes.py @@ -258,6 +258,10 @@ class WebUISettingsRouter: ) self._system = system_domain.SystemSettingsHandler(settings, logger) + async def close(self) -> None: + """Release state owned by settings domains.""" + await self._system.close() + async def dispatch( self, connection: Any, diff --git a/nanobot/webui/settings_system.py b/nanobot/webui/settings_system.py index 8588bd483..02f9ab119 100644 --- a/nanobot/webui/settings_system.py +++ b/nanobot/webui/settings_system.py @@ -4,6 +4,7 @@ from __future__ import annotations import asyncio import inspect +import json import re import time from collections.abc import Callable, Iterable, Mapping @@ -265,6 +266,8 @@ def coerce_channel_value( allowed = None if kind in {"string", "secret"}: + if kind == "secret" and raw_value is None: + return "" value = raw_value.strip() if isinstance(raw_value, str) else str(raw_value) if kind == "secret" and not value: return _SKIP_FIELD @@ -291,6 +294,25 @@ def coerce_channel_value( except (TypeError, ValueError) as exc: raise WebUISettingsError(f"'{raw_key}' must be a number") from exc + if kind == "float": + if raw_value in (None, ""): + return _SKIP_FIELD + try: + return float(raw_value) + except (TypeError, ValueError) as exc: + raise WebUISettingsError(f"'{raw_key}' must be a number") from exc + + if kind == "json": + if raw_value in (None, ""): + return _SKIP_FIELD + try: + value = json.loads(raw_value) if isinstance(raw_value, str) else raw_value + except (TypeError, ValueError) as exc: + raise WebUISettingsError(f"'{raw_key}' must be valid JSON") from exc + if not isinstance(value, dict): + raise WebUISettingsError(f"'{raw_key}' must be a JSON object") + return cast(dict[str, Any], value) + if kind == "bool": if isinstance(raw_value, bool): return raw_value @@ -366,6 +388,24 @@ class SystemSettingsHandler: self.logger = logger self._channel_connectors: dict[str, Any] = {} + async def close(self) -> None: + """Release channel-owned setup sessions during gateway shutdown.""" + connectors = tuple(self._channel_connectors.items()) + self._channel_connectors.clear() + for channel_name, connector in connectors: + close = getattr(connector, "close", None) + if not callable(close): + continue + try: + result = close() + if inspect.isawaitable(result): + await result + except Exception: + self.logger.exception( + "failed to close {} WebUI connector", + channel_name, + ) + async def handle( self, action: str, @@ -524,6 +564,11 @@ class SystemSettingsHandler: action: str, operations: SystemSettingsOperations, ) -> SettingsRouteResult: + install_only = ( + action == "enable" + and (query_first(request.query, "install_only") or "").strip().lower() + in {"1", "true", "yes"} + ) try: payload = await asyncio.to_thread( self._nanobot_features_action, @@ -546,12 +591,13 @@ class SystemSettingsHandler: action, ) return SettingsRouteResult.failure(status, message) - payload = await self._apply_feature_runtime_change( - action, - request.query, - payload, - operations, - ) + if not install_only: + payload = await self._apply_feature_runtime_change( + action, + request.query, + payload, + operations, + ) payload = self._with_channel_runtime_status(payload, operations) return SettingsRouteResult.success( payload, diff --git a/tests/channels/test_channel_contracts.py b/tests/channels/test_channel_contracts.py index a726c0e1d..bb0909d7a 100644 --- a/tests/channels/test_channel_contracts.py +++ b/tests/channels/test_channel_contracts.py @@ -572,4 +572,7 @@ def test_channel_setup_contract_owns_fields_and_validation() -> None: "choices": [], "required": True, }], + "requirements": [ + {"alternatives": [["channels.setup_contract.token"]]}, + ], } diff --git a/tests/channels/test_channel_plugins.py b/tests/channels/test_channel_plugins.py index edef3a1d4..aadce9c44 100644 --- a/tests/channels/test_channel_plugins.py +++ b/tests/channels/test_channel_plugins.py @@ -292,7 +292,7 @@ def test_special_setup_validation_is_owned_by_channel_package(name: str): assert plugin.setup.validator.__module__ == f"nanobot.channels.{name}.validation" -@pytest.mark.parametrize("name", ["feishu", "weixin"]) +@pytest.mark.parametrize("name", ["feishu", "weixin", "whatsapp"]) def test_interactive_connector_is_owned_by_channel_package(name: str): plugin = load_channel_package(name) @@ -582,6 +582,9 @@ def test_plugin_setup_contract_drives_feature_payload(monkeypatch: pytest.Monkey "required": False, }, ], + "requirements": [ + {"alternatives": [["channels.setupplugin.token"]]}, + ], "official_url": "https://plugin.example/setup", } assert feature["configured_fields"] == [ @@ -630,10 +633,11 @@ def test_plugin_contract_error_is_isolated_in_feature_payload(monkeypatch): "type": "channel", "capabilities": [], "settings_visible": True, - "setup": {"fields": []}, + "setup": {"fields": [], "requirements": []}, "enabled": False, "configured": False, "installed": True, + "requires_dependencies": False, "ready": False, "status": "invalid_config", "install_supported": True, @@ -842,10 +846,7 @@ def test_discover_plugins_excludes_internal_helpers(): names = discover_plugins() - assert "_feishu_ws" not in names assert "_setup" not in names - assert "setup" not in names - assert "_feishu_instances" not in names def test_discover_enabled_imports_only_enabled_packages(): @@ -1880,6 +1881,47 @@ def test_enable_optional_feature_reports_install_failure(monkeypatch, tmp_path): assert not config_path.exists() +def test_install_only_adds_channel_support_without_enabling_it(monkeypatch, tmp_path): + from nanobot.optional_features import InstallResult + from nanobot.webui.nanobot_features_api import nanobot_features_action + + config_path = tmp_path / "config.json" + config_path.write_text( + json.dumps({"channels": {"fakeplugin": {"enabled": False, "marker": "keep"}}}), + encoding="utf-8", + ) + before = config_path.read_bytes() + _stub_channel_registry( + monkeypatch, + _channel_plugin(_FakePlugin, dependencies=("fake-sdk>=1",)), + ) + monkeypatch.setattr("nanobot.optional_features.optional_dependency_groups", lambda: {}) + installed = False + + def extra_installed(_name: str, _dependencies: list[str] | None) -> bool: + return installed + + def install_extra(name: str, dependencies: list[str], *, runner) -> InstallResult: + nonlocal installed + installed = True + return InstallResult(True, f"{name} support", ["pip", *dependencies]) + + monkeypatch.setattr("nanobot.optional_features.extra_installed", extra_installed) + monkeypatch.setattr("nanobot.optional_features.install_extra", install_extra) + + payload = nanobot_features_action( + "enable", + {"name": ["fakeplugin"], "install_only": ["true"]}, + config_path=config_path, + ) + + feature = payload["features"][0] + assert config_path.read_bytes() == before + assert feature["installed"] is True + assert feature["enabled"] is False + assert payload["requires_restart"] is True + + def test_disable_optional_feature_rejects_unknown_features_and_non_channels( monkeypatch, tmp_path, @@ -2022,6 +2064,7 @@ def test_optional_features_payload_counts_enabled_channel_with_missing_dependenc assert matrix["name"] == "matrix" assert matrix["enabled"] is True assert matrix["installed"] is False + assert matrix["requires_dependencies"] is True assert matrix["ready"] is False assert payload["enabled_count"] == 1 @@ -2303,50 +2346,21 @@ def test_optional_features_payload_lists_feishu_instances(monkeypatch): assert feishu["enabled"] is True assert feishu["configured"] is True assert payload["enabled_count"] == 1 - assert feishu["instances"] == [ - { - "id": "default", - "name": "nanobot", - "display_name": "Voraflare Bot", - "avatar_url": "https://example.com/bot.png", - "enabled": True, - "configured": True, - "config_values": { - "channels.feishu.appId": "cli_default", - "channels.feishu.domain": "feishu", - "channels.feishu.groupPolicy": "mention", - "channels.feishu.topicIsolation": "true", - }, - "configured_fields": [ - "channels.feishu.appId", - "channels.feishu.appSecret", - "channels.feishu.domain", - "channels.feishu.groupPolicy", - "channels.feishu.topicIsolation", - ], - }, - { - "id": "product", - "name": "Product bot", - "display_name": "Product bot", - "avatar_url": "", - "enabled": False, - "configured": True, - "config_values": { - "channels.feishu.appId": "cli_product", - "channels.feishu.domain": "feishu", - "channels.feishu.groupPolicy": "mention", - "channels.feishu.topicIsolation": "true", - }, - "configured_fields": [ - "channels.feishu.appId", - "channels.feishu.appSecret", - "channels.feishu.domain", - "channels.feishu.groupPolicy", - "channels.feishu.topicIsolation", - ], - }, + instances = feishu["instances"] + assert [ + (item["id"], item["name"], item["display_name"], item["avatar_url"], item["enabled"]) + for item in instances + ] == [ + ("default", "nanobot", "Voraflare Bot", "https://example.com/bot.png", True), + ("product", "Product bot", "Product bot", "", False), ] + assert [item["configured"] for item in instances] == [True, True] + assert instances[0]["config_values"]["channels.feishu.appId"] == "cli_default" + assert instances[1]["config_values"]["channels.feishu.appId"] == "cli_product" + assert all( + "channels.feishu.appSecret" in item["configured_fields"] + for item in instances + ) def test_optional_features_payload_does_not_refresh_saved_feishu_identity(monkeypatch, tmp_path): @@ -2699,7 +2713,7 @@ def test_optional_dependency_metadata_for_enable(): "wecom": ("wecom-aibot-sdk-python>=0.1.7,<0.2.0",), "weixin": ("qrcode[pil]>=8.0", "pycryptodome>=3.20.0"), "whatsapp": ( - "neonize>=0.3.18.post0,<0.4.0", + "neonize>=0.4.3.post0,<0.5.0", "segno>=1.6.1,<2.0.0", ), } diff --git a/tests/channels/test_channel_setup.py b/tests/channels/test_channel_setup.py index 39c89d5fb..2cbb2277c 100644 --- a/tests/channels/test_channel_setup.py +++ b/tests/channels/test_channel_setup.py @@ -33,17 +33,58 @@ EXPECTED_CHANNELS = { "whatsapp", } +INTERNAL_CHANNEL_FIELDS = { + "feishu": {"instanceId", "identityKey"}, + "signal": {"allowFrom"}, + "weixin": {"token"}, + "whatsapp": {"databasePath", "lidMappings"}, + # nanobot WebUI owns this transport and intentionally has no channel dialog. + "websocket": { + "allowFrom", + "host", + "maxMessageBytes", + "path", + "pingIntervalS", + "pingTimeoutS", + "port", + "publicWsUrl", + "sslCertfile", + "sslKeyfile", + "streaming", + "token", + "tokenIssuePath", + "tokenIssueSecret", + "tokenTtlS", + "trustedProxyAuth", + "unixSocketPath", + "websocketRequiresToken", + }, +} + + +def _flatten_channel_fields(value: object, prefix: str = "") -> set[str]: + if not isinstance(value, dict): + return {prefix} if prefix else set() + if not value: + return {prefix} if prefix else set() + fields: set[str] = set() + for key, nested in value.items(): + path = f"{prefix}.{key}" if prefix else key + fields.update(_flatten_channel_fields(nested, path)) + return fields + def test_channel_setup_spec_derives_route_and_secret_metadata() -> None: slack = channel_setup_spec("slack") assert slack is not None assert slack.secrets == {"appToken", "botToken"} - assert slack.route_field_types == { - "appToken": "secret", - "botToken": "secret", - "groupPolicy": ("enum", {"mention", "open", "allowlist"}), - } + assert slack.route_field_types["appToken"] == "secret" + assert slack.route_field_types["botToken"] == "secret" + assert slack.route_field_types["groupPolicy"] == ( + "enum", + {"mention", "open", "allowlist"}, + ) assert slack.simple_required_fields == ("appToken", "botToken") assert slack.fields["groupPolicy"].default == "mention" group_policy = next( @@ -73,7 +114,7 @@ def test_channel_setup_spec_separates_writable_and_snapshot_fields() -> None: assert matrix is not None assert discord is not None - assert "allowFrom" not in matrix.route_field_types + assert "allowFrom" in matrix.route_field_types assert "allowFrom" in matrix.snapshot_fields assert "allowFrom" in discord.route_field_types assert "allowFrom" not in discord.snapshot_fields @@ -87,6 +128,7 @@ def test_webui_forms_have_writable_mattermost_and_whatsapp_contracts() -> None: assert whatsapp is not None assert mattermost.route_field_types["serverUrl"] == "string" assert mattermost.route_field_types["token"] == "secret" + assert whatsapp.route_field_types["proxy"] == "string" assert whatsapp.route_field_types["allowFrom"] == "list" assert whatsapp.route_field_types["groupPolicy"] == ( "enum", @@ -94,6 +136,19 @@ def test_webui_forms_have_writable_mattermost_and_whatsapp_contracts() -> None: ) +def test_weixin_token_is_managed_only_by_qr_login() -> None: + weixin = channel_setup_spec("weixin") + + assert weixin is not None + assert weixin.simple_required_fields == ("token",) + assert "token" not in weixin.route_field_types + assert "token" not in weixin.snapshot_fields + assert all( + field["field"] != "token" + for field in weixin.to_public_dict("weixin")["fields"] + ) + + def test_every_channel_is_a_self_contained_package() -> None: channel_dir = Path(channel_setup_module.__file__).parent package_names = {path.parent.name for path in channel_dir.glob("*/manifest.py")} @@ -127,6 +182,13 @@ def test_channel_locales_cover_authoritative_setup_contracts() -> None: ) setup_messages = english["setup"] field_messages = setup_messages.get("fields", {}) + contract_message_keys = { + re.sub(r"[^A-Za-z0-9_-]+", "_", field_name) + for field_name in plugin.setup.fields + } + assert not set(field_messages) - contract_message_keys, ( + f"{name} has locale copy for fields outside its setup contract" + ) for field_name, field in plugin.setup.fields.items(): if not field.writable: continue @@ -136,6 +198,26 @@ def test_channel_locales_cover_authoritative_setup_contracts() -> None: assert setup_messages.get("officialLabel"), f"{name} has no localized official label" +def test_every_runtime_channel_field_has_a_webui_contract() -> None: + for name, plugin in discover_plugins().items(): + runtime_fields = _flatten_channel_fields(plugin.load_channel_class().default_config()) + runtime_fields.discard("enabled") + setup = plugin.setup + assert setup is not None + contract_fields = set(setup.fields) + internal_fields = INTERNAL_CHANNEL_FIELDS.get(name, set()) + + assert not runtime_fields - contract_fields - internal_fields, ( + f"{name} runtime fields missing from WebUI contract: " + f"{sorted(runtime_fields - contract_fields - internal_fields)}" + ) + assert not { + field_name + for field_name in runtime_fields - internal_fields + if field_name not in setup.route_field_types + }, f"{name} has user-configurable runtime fields that WebUI cannot save" + + def test_channel_manifests_only_import_contract_modules() -> None: channel_dir = Path(channel_setup_module.__file__).parent allowed_imports = { @@ -184,6 +266,24 @@ def test_weixin_package_manifest_owns_runtime_and_webui_metadata() -> None: assert plugin.webui == "webui/index.tsx" +def test_whatsapp_package_manifest_owns_browser_connector() -> None: + plugin = load_channel_package("whatsapp") + + assert plugin is not None + assert plugin.connector == "nanobot.channels.whatsapp.connect:WhatsAppConnectStore" + assert plugin.webui == "webui/index.tsx" + + +def test_mochat_package_manifest_exposes_required_setup() -> None: + plugin = load_channel_package("mochat") + + assert plugin is not None + assert plugin.webui == "webui/index.ts" + assert plugin.settings_visible is True + assert plugin.setup is not None + assert plugin.setup.simple_required_fields == ("clawToken",) + + def test_package_manifests_do_not_import_runtimes() -> None: code = f""" import sys diff --git a/tests/pairing/test_store.py b/tests/pairing/test_store.py index 0f681bd9b..cb9e8fd77 100644 --- a/tests/pairing/test_store.py +++ b/tests/pairing/test_store.py @@ -64,6 +64,8 @@ class TestFormatPairingReply: assert "nanobot WebUI" in reply assert "ABCD-EFGH" in reply assert "/pairing approve ABCD-EFGH" in reply + assert "private nanobot" in reply + assert "approved users" not in reply class TestApproveDeny: diff --git a/tests/webui/test_settings_routes.py b/tests/webui/test_settings_routes.py index 3fd98c94e..b655bebf9 100644 --- a/tests/webui/test_settings_routes.py +++ b/tests/webui/test_settings_routes.py @@ -59,6 +59,24 @@ def _mutation_request(path: str, payload: dict[str, object]) -> SimpleNamespace: return request +@pytest.mark.asyncio +async def test_close_releases_channel_connectors() -> None: + router = _router() + closed = False + + class Connector: + async def close(self) -> None: + nonlocal closed + closed = True + + router._system._channel_connectors["whatsapp"] = Connector() + + await router.close() + + assert closed is True + assert router._system._channel_connectors == {} + + @pytest.mark.asyncio async def test_mcp_list_serializes_local_runtime_failure_snapshot(tmp_path) -> None: config_path = tmp_path / "config.json" diff --git a/tests/webui/test_settings_system.py b/tests/webui/test_settings_system.py index 79af2ca4f..353e92765 100644 --- a/tests/webui/test_settings_system.py +++ b/tests/webui/test_settings_system.py @@ -1,8 +1,10 @@ from __future__ import annotations +from nanobot.channels.registry import load_channel_plugin from nanobot.config.schema import Config from nanobot.webui.settings_system import ( coerce_channel_value, + save_channel_config_values, system_settings_payload, update_agent_system_settings, ) @@ -42,3 +44,24 @@ def test_system_domain_validates_channel_field_values() -> None: ] assert coerce_channel_value("enabled", "yes", "bool") is True assert coerce_channel_value("port", "8765", "int") == 8765 + assert coerce_channel_value("delay", "0.6", "float") == 0.6 + assert coerce_channel_value("overrides", '{"123": "open"}', "json") == { + "123": "open" + } + assert coerce_channel_value("token", None, "secret") == "" + + +def test_channel_secret_is_cleared_only_by_explicit_null() -> None: + config = Config.model_validate({ + "channels": {"matrix": {"password": "saved-password"}}, + }) + + saved = save_channel_config_values( + config, + "matrix", + {"channels.matrix.password": None}, + load_channel_plugin=load_channel_plugin, + ) + + assert saved == ["channels.matrix.password"] + assert config.channels.matrix["password"] == "" diff --git a/webui/src/channel-plugins/i18n.ts b/webui/src/channel-plugins/i18n.ts index 10984e1da..e686eb490 100644 --- a/webui/src/channel-plugins/i18n.ts +++ b/webui/src/channel-plugins/i18n.ts @@ -3,21 +3,17 @@ import type { TFunction } from "i18next"; type ChannelFieldMessages = { label: string; placeholder?: string; - help?: string; choices?: Record; }; export type ChannelMessages = { displayName?: string; - description: string; - requirements: string; setup: { primaryAction?: string; docsLabel?: string; officialLabel?: string; - summary?: string; - tryIt?: string; - steps: string[]; + presetLabel?: string; + sections?: Record; fields?: Record; actions?: Record; presets?: Record; diff --git a/webui/src/channel-plugins/types.ts b/webui/src/channel-plugins/types.ts index af6977f5a..e97fe7281 100644 --- a/webui/src/channel-plugins/types.ts +++ b/webui/src/channel-plugins/types.ts @@ -6,14 +6,24 @@ import type { NanobotFeaturesPayload, } from "@/lib/types"; +export type ChannelFeatureActionOptions = { + confirmed?: boolean; + installOnly?: boolean; +}; + +export type ChannelFeatureAction = ( + action: "enable" | "disable", + name: string, + options?: ChannelFeatureActionOptions, +) => void; + export type ChannelPluginPanelProps = { connectRequestId?: number; token: string; feature: NanobotFeatureInfo; actionKey: string | null; - chatAppsDocsUrl?: string; showBrandLogos: boolean; - onAction: (action: "enable" | "disable", name: string) => void; + onAction: ChannelFeatureAction; onFeaturesUpdate: (payload: NanobotFeaturesPayload) => void; }; diff --git a/webui/src/components/settings/SettingsPage.tsx b/webui/src/components/settings/SettingsPage.tsx index 8b4ab8a32..c4ea93646 100644 --- a/webui/src/components/settings/SettingsPage.tsx +++ b/webui/src/components/settings/SettingsPage.tsx @@ -680,12 +680,16 @@ export function SettingsPage({ /> { if (!open) setNanobotFeatureConfirm(null); }} - onConfirm={(feature) => handleNanobotFeatureAction("enable", feature.name, true)} + onConfirm={(feature) => handleNanobotFeatureAction("enable", feature.name, { + confirmed: true, + installOnly: nanobotFeatureConfirm?.installOnly, + })} /> link.url); + if (!links.length) return null; + const label = t("settings.channels.help", { defaultValue: "Help" }); + return ( + + + + + + + + + {label} + + + {links.map((link) => ( + + + {link.label ?? label} + + + + ))} + + + + ); +} diff --git a/webui/src/components/settings/channels/ChannelIdentity.tsx b/webui/src/components/settings/channels/ChannelIdentity.tsx index 1afcb6f47..dfb7c8bd3 100644 --- a/webui/src/components/settings/channels/ChannelIdentity.tsx +++ b/webui/src/components/settings/channels/ChannelIdentity.tsx @@ -1,5 +1,5 @@ import { useMemo, type ReactNode } from "react"; -import type { useTranslation } from "react-i18next"; +import { useTranslation } from "react-i18next"; import { channelFieldMessageKey, @@ -12,14 +12,17 @@ import { } from "@/channel-plugins/registry"; import type { ChannelConfigField, + ChannelFieldPresentation, ChannelSetupPresentation, } from "@/components/settings/channels/catalog"; +import { channelValidationMessage } from "@/components/settings/channels/validationMessages"; import { useLogoFallback } from "@/hooks/useLogoFallback"; import { normalizeLocale } from "@/i18n/config"; import { logoFallbackUrls } from "@/lib/provider-brand"; import type { ChannelRuntimeStatus, NanobotFeatureInfo } from "@/lib/types"; -export type ChannelFilter = "all" | "on" | "off"; +export const CHANNEL_SETUP_PANEL_CLASS_NAME = + "min-h-full rounded-panel bg-settings-surface p-6"; export function channelSetup( feature: NanobotFeatureInfo, @@ -35,25 +38,23 @@ export function channelSetup( key, label: copy?.label ?? fieldLabel(key.split(".").at(-1) ?? key), placeholder: copy?.placeholder, - help: copy?.help, }; }; + const localizePresentedField = ( + field: ChannelFieldPresentation, + ): ChannelConfigField => ({ + ...localizeField(field.key), + section: field.section, + }); const presentation: ChannelSetupPresentation = { ...definition, primaryActionLabel: setupMessages?.primaryAction, docsLabel: setupMessages?.docsLabel, officialLabel: setupMessages?.officialLabel, - summary: - setupMessages?.summary - ?? "Enable turns on this channel in nanobot, but this integration still needs platform-specific setup before it can receive messages.", - tryIt: setupMessages?.tryIt, - steps: setupMessages?.steps ?? [ - `Open ~/.nanobot/config.json and find channels.${feature.name}.`, - "Add the credentials required by that platform, using the channel documentation as the source of truth.", - "Restart nanobot, then send a small test message from that platform.", - ], - fields: definition?.fields?.map((field) => localizeField(field.key)), - manualFields: definition?.manualFields?.map((field) => localizeField(field.key)), + presetLabel: setupMessages?.presetLabel, + sectionLabels: setupMessages?.sections, + fields: definition?.fields?.map(localizePresentedField), + manualFields: definition?.manualFields?.map(localizePresentedField), actions: definition?.actions?.map((action) => ({ ...action, label: setupMessages?.actions?.[action.id] ?? fieldLabel(action.id), @@ -83,9 +84,11 @@ export function channelSetup( ...copy, key: field.key, label: copy.label, + section: copy.section ?? (field.required ? "credentials" : "advanced"), secret: field.kind === "secret", optional: !field.required, - inputType: field.kind === "int" ? "number" : undefined, + kind: field.kind, + inputType: channelFieldInputType(field.field, field.kind), defaultValue: field.default_value, options: field.kind === "enum" || field.kind === "bool" @@ -106,11 +109,24 @@ export function channelSetup( officialLabel: presentation.officialLabel ?? (contract.official_url ? "Open official setup" : undefined), + requirements: contract.requirements, fields: fields.length ? fields : undefined, manualFields: manual.length ? manual : undefined, }; } +function channelFieldInputType( + field: string, + kind: string, +): ChannelConfigField["inputType"] { + if (kind === "int" || kind === "float") return "number"; + const normalized = field.toLowerCase(); + if (normalized.includes("url")) return "url"; + if (normalized.includes("email") || normalized.includes("address")) return "email"; + if (normalized.includes("phone")) return "tel"; + return undefined; +} + function fieldLabel(value: string): string { const spaced = value .replace(/([a-z0-9])([A-Z])/g, "$1 $2") @@ -126,21 +142,14 @@ export function ChannelLogo({ feature: NanobotFeatureInfo; showBrandLogos: boolean; }) { - const presentation = channelUiPresentation(feature.name, feature.webui); + const presentation = channelUiPresentation(feature.name, feature.webui) + ?? channelUiPresentation(feature.name); const initials = presentation?.initials ?? feature.display_name.slice(0, 2).toUpperCase(); const color = presentation?.color ?? "#6B7280"; const Icon = presentation?.icon; const logoUrls = useMemo(() => logoFallbackUrls(presentation?.logoUrl), [presentation?.logoUrl]); const { logoUrl, onLogoError, onLogoLoad } = useLogoFallback(logoUrls); - if (feature.name === "websocket") { - return ( - - - - ); - } - if (showBrandLogos && logoUrl) { return ( ["t"]): string { - const fallback = - `Use nanobot from ${channelDisplayName(feature)}.`; - return channelTranslator(t, channelUiOwner(feature.name))("description", fallback); -} - -export function channelRequirements(feature: NanobotFeatureInfo, t: ReturnType["t"]): string { - const fallback = - "Channel credentials and gateway settings"; - return channelTranslator(t, channelUiOwner(feature.name))("requirements", fallback); -} - -export function channelMatchesFilter(feature: NanobotFeatureInfo, filter: ChannelFilter): boolean { - if (filter === "on") return channelIsRunning(feature); - if (filter === "off") return !channelIsRunning(feature); - return true; -} - export function channelIsRunning(feature: NanobotFeatureInfo): boolean { return feature.runtime_status === "running"; } @@ -232,27 +223,11 @@ export function channelStatusLabel( } if (channelIsRunning(feature)) return tx("settings.values.on", "On"); if (feature.enabled) return tx("settings.channels.runtimeStopped", "Not running"); + if (feature.configured === false) return tx("settings.channels.needsConfig", "Needs setup"); + if (feature.configured === true) return tx("settings.nanobotFeatures.ready", "Ready"); return tx("settings.values.off", "Off"); } -export function channelSearchText( - feature: NanobotFeatureInfo, - t?: ReturnType["t"], -): string { - return [ - t ? localizedChannelDisplayName(feature, t) : undefined, - channelDisplayName(feature), - feature.display_name, - feature.name, - feature.status, - t ? channelDescription(feature, t) : undefined, - t ? channelRequirements(feature, t) : undefined, - ] - .join(" ") - .toLowerCase(); -} - - export function ChannelStatusBadge({ children, status, @@ -281,10 +256,11 @@ export function ChannelRuntimeError({ message?: string; className?: string; }) { + const { t } = useTranslation(); if (!message) return null; return (
- {message} + {channelValidationMessage(message, t)}
); } diff --git a/webui/src/components/settings/channels/ChannelInstancesPanel.tsx b/webui/src/components/settings/channels/ChannelInstancesPanel.tsx index 28dd140c4..ece8fd078 100644 --- a/webui/src/components/settings/channels/ChannelInstancesPanel.tsx +++ b/webui/src/components/settings/channels/ChannelInstancesPanel.tsx @@ -13,17 +13,12 @@ import { defaultChannelFieldValues, } from "@/components/settings/channels/CredentialForm"; import { + CHANNEL_SETUP_PANEL_CLASS_NAME, ChannelLogo, ChannelRuntimeError, - ChannelStatusBadge, channelSetup, - channelStatusLabel, localizedChannelDisplayName, } from "@/components/settings/channels/ChannelIdentity"; -import { - ChannelGuideLink, - ChannelSetupSteps, -} from "@/components/settings/channels/ChannelSetupParts"; import { Button } from "@/components/ui/button"; import { useLogoFallback } from "@/hooks/useLogoFallback"; import { @@ -41,7 +36,6 @@ import { cn } from "@/lib/utils"; import { useClient } from "@/providers/ClientProvider"; export type ChannelInstancesPanelCustomization = { - countLabel?: (runningCount: number) => string; toggleAriaLabel?: (instance: NanobotChannelInstanceInfo) => string; configuredLabel?: string; needsSetupLabel?: string; @@ -53,14 +47,12 @@ export type ChannelInstancesPanelCustomization = { export function ChannelInstancesPanel({ feature, showBrandLogos, - chatAppsDocsUrl, instances: providedInstances, onFeaturesUpdate, customization = {}, }: { feature: NanobotFeatureInfo; showBrandLogos: boolean; - chatAppsDocsUrl?: string; instances?: NanobotChannelInstanceInfo[]; onFeaturesUpdate: (payload: NanobotFeaturesPayload) => void; customization?: ChannelInstancesPanelCustomization; @@ -70,8 +62,9 @@ export function ChannelInstancesPanel({ const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback }); const displayName = localizedChannelDisplayName(feature, t); const instances = providedInstances ?? feature.instances ?? []; - const [selectedId, setSelectedId] = useState(null); - const [busyInstanceId, setBusyInstanceId] = useState(null); + const [editor, setEditor] = useState<{ id: string; expanded: boolean } | null>(null); + const selectedId = editor?.id; + const [pendingToggle, setPendingToggle] = useState<{ id: string; checked: boolean } | null>(null); const [notice, setNotice] = useState(null); const selected = selectedId ? instances.find((instance) => instance.id === selectedId) : undefined; const setup = useMemo( @@ -87,9 +80,9 @@ export function ChannelInstancesPanel({ ); const [visibleSecrets, setVisibleSecrets] = useState>({}); const [savingFields, setSavingFields] = useState(false); - const configuredCount = instances.filter((instance) => instance.configured).length; - const runningCount = instances.filter((instance) => instance.runtime_status === "running").length; - const selectedValuesKey = JSON.stringify(selected?.config_values ?? {}); + const selectedValuesKey = JSON.stringify( + defaultChannelFieldValues(instanceFields, selected?.config_values), + ); const selectedConfiguredFields = useMemo( () => new Set(selected?.configured_fields ?? []), [selected?.configured_fields], @@ -97,17 +90,18 @@ export function ChannelInstancesPanel({ useEffect(() => { if (selectedId && !instances.some((instance) => instance.id === selectedId)) { - setSelectedId(null); + setEditor(null); } }, [instances, selectedId]); useEffect(() => { setFieldValues(defaultChannelFieldValues(instanceFields, selected?.config_values)); setVisibleSecrets({}); - }, [instanceFields, selected?.id, selectedValuesKey]); + }, [selected?.id, selectedValuesKey]); const toggleInstance = async (instance: NanobotChannelInstanceInfo, checked: boolean) => { - setBusyInstanceId(instance.id); + if (pendingToggle || savingFields) return; + setPendingToggle({ id: instance.id, checked }); setNotice(null); try { const payload = checked @@ -117,12 +111,12 @@ export function ChannelInstancesPanel({ } catch (err) { setNotice((err as Error).message); } finally { - setBusyInstanceId(null); + setPendingToggle(null); } }; const saveSelectedInstanceSettings = async () => { - if (!selected) return; + if (!selected || pendingToggle || savingFields) return; setSavingFields(true); setNotice(null); try { @@ -144,35 +138,24 @@ export function ChannelInstancesPanel({ }; return ( -