refactor: remove LINE, WhatsApp and Discord channels
Remove LINE, WhatsApp bridge/native and Discord adapters and configuration. Drop unused SDKs, the Discord fork override and the native WhatsApp build target. Clean up migration support and docs; preserve shared credential and voice coverage. Validated with full Go tests, static checks, docs lint and a Linux amd64 build.
This commit is contained in:
1 parent
e7d4293052
commit
7b56867f8a
128 files changed
+289
-5875
No files matched your search
@@ -14,7 +14,7 @@ assignees: ''
|
||||
- **Go Version:** (e.g., go 1.22)
|
||||
- **AI Model & Provider:** (e.g., GPT-4o via OpenAI / DeepSeek via SiliconFlow)
|
||||
- **Operating System:** (e.g., Ubuntu 22.04 / macOS / Android Termux)
|
||||
- **Channels:** (e.g., Discord, Telegram, Feishu, ...)
|
||||
- **Channels:** (e.g., Weixin, Telegram, Feishu, ...)
|
||||
|
||||
## 📸 Steps to Reproduce
|
||||
1.
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
- **Hardware:** <!-- e.g. Raspberry Pi 5, Orange Pi, PC-->
|
||||
- **OS:** <!-- e.g. Debian 12, Ubuntu 22.04 -->
|
||||
- **Model/Provider:** <!-- e.g. OpenAI GPT-4o, Kimi k2, DeepSeek-V3 -->
|
||||
- **Channels:** <!-- e.g. Discord, Telegram, Feishu, ... -->
|
||||
- **Channels:** <!-- e.g. Weixin, Telegram, Feishu, ... -->
|
||||
|
||||
|
||||
## 📸 Evidence (Optional)
|
||||
|
||||
@@ -62,9 +62,6 @@ linters:
|
||||
- usestdlibvars
|
||||
- usetesting
|
||||
settings:
|
||||
gomoddirectives:
|
||||
replace-allow-list:
|
||||
- github.com/bwmarrin/discordgo
|
||||
errcheck:
|
||||
check-type-assertions: true
|
||||
check-blank: true
|
||||
|
||||
@@ -208,24 +208,6 @@ else
|
||||
endif
|
||||
@echo "Build complete: $(BUILD_DIR)/$(BINARY_NAME)$(EXT)"
|
||||
|
||||
## build-whatsapp-native: Build with WhatsApp native (whatsmeow) support; larger binary
|
||||
build-whatsapp-native: generate
|
||||
## @echo "Building $(BINARY_NAME) with WhatsApp native for $(PLATFORM)/$(ARCH)..."
|
||||
@echo "Building for multiple platforms..."
|
||||
@mkdir -p $(BUILD_DIR)
|
||||
GOOS=linux GOARCH=amd64 $(GO) build -tags $(GO_BUILD_TAGS),whatsapp_native -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-linux-amd64 ./$(CMD_DIR)
|
||||
GOOS=linux GOARCH=arm GOARM=7 $(GO) build -tags $(GO_BUILD_TAGS),whatsapp_native -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-linux-arm ./$(CMD_DIR)
|
||||
GOOS=linux GOARCH=arm64 $(GO) build -tags $(GO_BUILD_TAGS),whatsapp_native -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-linux-arm64 ./$(CMD_DIR)
|
||||
GOOS=linux GOARCH=loong64 $(GO) build -tags $(GO_BUILD_TAGS),whatsapp_native -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-linux-loong64 ./$(CMD_DIR)
|
||||
GOOS=linux GOARCH=riscv64 $(GO) build -tags $(GO_BUILD_TAGS),whatsapp_native -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-linux-riscv64 ./$(CMD_DIR)
|
||||
GOOS=linux GOARCH=mipsle GOMIPS=softfloat $(GO) build -tags $(GO_BUILD_TAGS),whatsapp_native -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-linux-mipsle ./$(CMD_DIR)
|
||||
$(call PATCH_MIPS_FLAGS,$(BUILD_DIR)/$(BINARY_NAME)-linux-mipsle)
|
||||
GOOS=darwin GOARCH=arm64 $(GO) build -tags $(GO_BUILD_TAGS),whatsapp_native -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-darwin-arm64 ./$(CMD_DIR)
|
||||
GOOS=windows GOARCH=amd64 $(GO) build -tags $(GO_BUILD_TAGS),whatsapp_native -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-windows-amd64.exe ./$(CMD_DIR)
|
||||
## @$(GO) build $(GOFLAGS) -tags whatsapp_native -ldflags "$(LDFLAGS)" -o $(BINARY_PATH) ./$(CMD_DIR)
|
||||
@echo "Build complete"
|
||||
## @ln -sf $(BINARY_NAME)-$(PLATFORM)-$(ARCH) $(BUILD_DIR)/$(BINARY_NAME)
|
||||
|
||||
## build-linux-arm: Build for Linux ARMv7 (e.g. Raspberry Pi Zero 2 W 32-bit)
|
||||
build-linux-arm: generate
|
||||
@echo "Building for linux/arm (GOARM=7)..."
|
||||
|
||||
@@ -381,13 +381,10 @@ Talk to your PicoClaw through 19+ messaging platforms:
|
||||
| Channel | Setup | Protocol | Docs |
|
||||
|---------|-------|----------|------|
|
||||
| **Telegram** | Easy (bot token) | Long polling | [Guide](docs/channels/telegram/README.md) |
|
||||
| **Discord** | Easy (bot token + intents) | WebSocket | [Guide](docs/channels/discord/README.md) |
|
||||
| **WhatsApp** | Easy (QR scan or bridge URL) | Native / Bridge | [Guide](docs/guides/chat-apps.md#whatsapp) |
|
||||
| **Weixin** | Easy (Native QR scan) | iLink API | [Guide](docs/guides/chat-apps.md#weixin) |
|
||||
| **QQ** | Easy (AppID + AppSecret) | WebSocket | [Guide](docs/channels/qq/README.md) |
|
||||
| **DingTalk** | Medium (client credentials) | Stream | [Guide](docs/channels/dingtalk/README.md) |
|
||||
| **Feishu / Lark** | Medium (App ID + Secret) | WebSocket/SDK | [Guide](docs/channels/feishu/README.md) |
|
||||
| **LINE** | Medium (credentials + webhook) | Webhook | [Guide](docs/channels/line/README.md) |
|
||||
| **WeCom** | Easy (QR login or manual) | WebSocket | [Guide](docs/channels/wecom/README.md) |
|
||||
| **OneBot** | Medium (WebSocket URL) | OneBot v11 | [Guide](docs/channels/onebot/README.md) |
|
||||
| **MQTT** | Easy (broker + agent_id) | MQTT pub/sub | [Guide](docs/channels/mqtt/README.md) |
|
||||
|
||||
+1
-1
@@ -48,7 +48,7 @@
|
||||
|
||||
|
||||
* **Channel**
|
||||
* **IM Matrix**: QQ, WeChat (Work), DingTalk, Feishu (Lark), Telegram, Discord, WhatsApp, LINE, Email, KOOK, Signal, ...
|
||||
* **IM Matrix**: QQ, WeChat (Work), DingTalk, Feishu (Lark), Telegram, Email, KOOK, Signal, ...
|
||||
* **Standards**: Support for the **OneBot** protocol.
|
||||
* [**attachment**](https://github.com/sipeed/picoclaw/issues/348): Native handling of images, audio, and video attachments.
|
||||
|
||||
|
||||
@@ -122,19 +122,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"discord": {
|
||||
"enabled": false,
|
||||
"type": "discord",
|
||||
"allow_from": [],
|
||||
"group_trigger": {
|
||||
"mention_only": false
|
||||
},
|
||||
"reasoning_channel_id": "",
|
||||
"settings": {
|
||||
"token": "YOUR_DISCORD_BOT_TOKEN",
|
||||
"proxy": ""
|
||||
}
|
||||
},
|
||||
"qq": {
|
||||
"enabled": false,
|
||||
"type": "qq",
|
||||
@@ -145,17 +132,6 @@
|
||||
"app_secret": "YOUR_QQ_APP_SECRET"
|
||||
}
|
||||
},
|
||||
"whatsapp": {
|
||||
"enabled": false,
|
||||
"type": "whatsapp",
|
||||
"allow_from": [],
|
||||
"reasoning_channel_id": "",
|
||||
"settings": {
|
||||
"bridge_url": "ws://localhost:3001",
|
||||
"use_native": false,
|
||||
"session_store_path": ""
|
||||
}
|
||||
},
|
||||
"feishu": {
|
||||
"enabled": false,
|
||||
"type": "feishu",
|
||||
@@ -184,17 +160,6 @@
|
||||
"client_secret": "YOUR_CLIENT_SECRET"
|
||||
}
|
||||
},
|
||||
"line": {
|
||||
"enabled": false,
|
||||
"type": "line",
|
||||
"allow_from": [],
|
||||
"reasoning_channel_id": "",
|
||||
"settings": {
|
||||
"channel_secret": "YOUR_LINE_CHANNEL_SECRET",
|
||||
"channel_access_token": "YOUR_LINE_CHANNEL_ACCESS_TOKEN",
|
||||
"webhook_path": "/webhook/line"
|
||||
}
|
||||
},
|
||||
"onebot": {
|
||||
"enabled": false,
|
||||
"type": "onebot",
|
||||
|
||||
@@ -89,11 +89,11 @@ This means dispatch rules must match the normalized shape, for example:
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "discord-mentions",
|
||||
"name": "feishu-mentions",
|
||||
"agent": "support",
|
||||
"when": {
|
||||
"channel": "discord",
|
||||
"space": "guild:t001",
|
||||
"channel": "feishu",
|
||||
"chat": "oc_group001",
|
||||
"mentioned": true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,11 +88,11 @@ type ResolvedRoute struct {
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "discord-mentions",
|
||||
"name": "feishu-mentions",
|
||||
"agent": "support",
|
||||
"when": {
|
||||
"channel": "discord",
|
||||
"space": "guild:t001",
|
||||
"channel": "feishu",
|
||||
"chat": "oc_group001",
|
||||
"mentioned": true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,7 +77,7 @@ For compatibility, the allocator also emits legacy aliases such as:
|
||||
|
||||
```text
|
||||
agent:main:direct:user123
|
||||
agent:main:discord:channel:c001
|
||||
agent:main:feishu:channel:c001
|
||||
agent:main:pico:direct:pico:session-123
|
||||
```
|
||||
|
||||
|
||||
@@ -77,7 +77,7 @@ sk_v1_<sha256>
|
||||
|
||||
```text
|
||||
agent:main:direct:user123
|
||||
agent:main:discord:channel:c001
|
||||
agent:main:feishu:channel:c001
|
||||
agent:main:pico:direct:pico:session-123
|
||||
```
|
||||
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
> Retour au [README](../../project/README.fr.md)
|
||||
|
||||
# Discord
|
||||
|
||||
Discord est une application gratuite de chat vocal, vidéo et textuel conçue pour les communautés. PicoClaw se connecte aux serveurs Discord via l'API Bot Discord, avec prise en charge de la réception et de l'envoi de messages.
|
||||
|
||||
## Configuration
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"discord": {
|
||||
"enabled": true,
|
||||
"type": "discord",
|
||||
"token": "YOUR_BOT_TOKEN",
|
||||
"allow_from": ["YOUR_USER_ID"],
|
||||
"group_trigger": {
|
||||
"mention_only": false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Champ | Type | Requis | Description |
|
||||
| ------------- | ------ | ------ | --------------------------------------------------------------------------- |
|
||||
| enabled | bool | Oui | Activer ou non le canal Discord |
|
||||
| token | string | Oui | Token du bot Discord |
|
||||
| allow_from | array | Non | Liste blanche d'identifiants utilisateur ; vide signifie tous les utilisateurs |
|
||||
| group_trigger | object | Non | Paramètres de déclenchement de groupe (exemple : { "mention_only": false }) |
|
||||
|
||||
## Configuration initiale
|
||||
|
||||
1. Accéder au [Portail des développeurs Discord](https://discord.com/developers/applications) et créer une nouvelle application
|
||||
2. Activer les Intents :
|
||||
- Message Content Intent
|
||||
- Server Members Intent
|
||||
3. Obtenir le Token du bot
|
||||
4. Renseigner le Token du bot dans le fichier de configuration
|
||||
5. Inviter le bot sur le serveur et lui accorder les permissions nécessaires (ex. envoyer des messages, lire l'historique des messages)
|
||||
@@ -1,40 +0,0 @@
|
||||
> [README](../../project/README.ja.md) に戻る
|
||||
|
||||
# Discord
|
||||
|
||||
Discord はコミュニティ向けに設計された無料の音声・ビデオ・テキストチャットアプリケーションです。PicoClaw は Discord Bot API を通じて Discord サーバーに接続し、メッセージの受信と送信をサポートします。
|
||||
|
||||
## 設定
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"discord": {
|
||||
"enabled": true,
|
||||
"type": "discord",
|
||||
"token": "YOUR_BOT_TOKEN",
|
||||
"allow_from": ["YOUR_USER_ID"],
|
||||
"group_trigger": {
|
||||
"mention_only": false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| フィールド | 型 | 必須 | 説明 |
|
||||
| ------------- | ------ | ------ | ----------------------------------------------------------------- |
|
||||
| enabled | bool | はい | Discord チャンネルを有効にするかどうか |
|
||||
| token | string | はい | Discord ボットトークン |
|
||||
| allow_from | array | いいえ | 許可するユーザーIDのリスト。空の場合はすべてのユーザーを許可 |
|
||||
| group_trigger | object | いいえ | グループトリガー設定(例: { "mention_only": false }) |
|
||||
|
||||
## セットアップ手順
|
||||
|
||||
1. [Discord 開発者ポータル](https://discord.com/developers/applications) にアクセスして新しいアプリケーションを作成する
|
||||
2. Intents を有効にする:
|
||||
- Message Content Intent
|
||||
- Server Members Intent
|
||||
3. Bot トークンを取得する
|
||||
4. 設定ファイルに Bot トークンを入力する
|
||||
5. ボットをサーバーに招待し、必要な権限を付与する(例: メッセージの送信、メッセージ履歴の読み取りなど)
|
||||
@@ -1,70 +0,0 @@
|
||||
> Back to [README](../../../README.md)
|
||||
|
||||
# Discord
|
||||
|
||||
Discord is a free voice, video, and text chat application designed for communities. PicoClaw connects to Discord servers via the Discord Bot API, supporting both receiving and sending messages.
|
||||
|
||||
## Configuration
|
||||
|
||||
```json
|
||||
{
|
||||
"agents": {
|
||||
"defaults": {
|
||||
"tool_feedback": {
|
||||
"enabled": true,
|
||||
"max_args_length": 300
|
||||
}
|
||||
}
|
||||
},
|
||||
"channel_list": {
|
||||
"discord": {
|
||||
"enabled": true,
|
||||
"type": "discord",
|
||||
"token": "YOUR_BOT_TOKEN",
|
||||
"allow_from": ["YOUR_USER_ID"],
|
||||
"placeholder": {
|
||||
"enabled": true,
|
||||
"text": ["Thinking... 💭"]
|
||||
},
|
||||
"group_trigger": {
|
||||
"mention_only": false
|
||||
},
|
||||
"reasoning_channel_id": ""
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
| -------------------- | ------ | -------- | --------------------------------------------------------------------------- |
|
||||
| enabled | bool | Yes | Whether to enable the Discord channel |
|
||||
| token | string | Yes | Discord Bot Token |
|
||||
| allow_from | array | No | Allowlist of user IDs; empty means all users are allowed |
|
||||
| placeholder | object | No | Placeholder message config shown while the agent is working |
|
||||
| group_trigger | object | No | Group trigger settings (example: { "mention_only": false }) |
|
||||
| reasoning_channel_id | string | No | Optional target channel ID for reasoning/thinking output |
|
||||
|
||||
## Visible Execution Feedback
|
||||
|
||||
Discord can show three different kinds of "working" feedback:
|
||||
|
||||
1. Typing indicator: automatic, no extra config needed.
|
||||
2. Placeholder message: enable `channel_list.discord.placeholder.enabled` to send a visible `Thinking...` message that is later edited into the final reply.
|
||||
3. Tool execution feedback: enable `agents.defaults.tool_feedback.enabled` to send a short message before each tool call, for example:
|
||||
|
||||
```text
|
||||
🔧 `web_search`
|
||||
Checking the latest PicoClaw release notes before I answer.
|
||||
```
|
||||
|
||||
If you only see `Bot is typing`, check that `placeholder.enabled` or `tool_feedback.enabled` is actually set in your runtime config.
|
||||
|
||||
## Setup
|
||||
|
||||
1. Go to the [Discord Developer Portal](https://discord.com/developers/applications) and create a new application
|
||||
2. Enable Intents:
|
||||
- Message Content Intent
|
||||
- Server Members Intent
|
||||
3. Obtain the Bot Token
|
||||
4. Fill in the Bot Token in the configuration file
|
||||
5. Invite the bot to your server and grant the necessary permissions (e.g. Send Messages, Read Message History)
|
||||
@@ -1,40 +0,0 @@
|
||||
> Voltar ao [README](../../project/README.pt-br.md)
|
||||
|
||||
# Discord
|
||||
|
||||
Discord é um aplicativo gratuito de chat de voz, vídeo e texto projetado para comunidades. O PicoClaw se conecta a servidores Discord via Discord Bot API, com suporte para receber e enviar mensagens.
|
||||
|
||||
## Configuração
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"discord": {
|
||||
"enabled": true,
|
||||
"type": "discord",
|
||||
"token": "YOUR_BOT_TOKEN",
|
||||
"allow_from": ["YOUR_USER_ID"],
|
||||
"group_trigger": {
|
||||
"mention_only": false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
| ------------- | ------ | ----------- | --------------------------------------------------------------------------- |
|
||||
| enabled | bool | Sim | Se o canal Discord deve ser habilitado |
|
||||
| token | string | Sim | Token do Bot Discord |
|
||||
| allow_from | array | Não | Lista de IDs de usuários permitidos; vazio significa todos os usuários |
|
||||
| group_trigger | object | Não | Configurações de gatilho de grupo (exemplo: { "mention_only": false }) |
|
||||
|
||||
## Configuração inicial
|
||||
|
||||
1. Acesse o [Portal de Desenvolvedores do Discord](https://discord.com/developers/applications) e crie uma nova aplicação
|
||||
2. Habilite os Intents:
|
||||
- Message Content Intent
|
||||
- Server Members Intent
|
||||
3. Obtenha o Token do Bot
|
||||
4. Preencha o Token do Bot no arquivo de configuração
|
||||
5. Convide o bot para o servidor e conceda as permissões necessárias (ex. enviar mensagens, ler histórico de mensagens)
|
||||
@@ -1,40 +0,0 @@
|
||||
> Quay lại [README](../../project/README.vi.md)
|
||||
|
||||
# Discord
|
||||
|
||||
Discord là ứng dụng chat thoại, video và văn bản miễn phí được thiết kế cho cộng đồng. PicoClaw kết nối với máy chủ Discord qua Discord Bot API, hỗ trợ nhận và gửi tin nhắn.
|
||||
|
||||
## Cấu hình
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"discord": {
|
||||
"enabled": true,
|
||||
"type": "discord",
|
||||
"token": "YOUR_BOT_TOKEN",
|
||||
"allow_from": ["YOUR_USER_ID"],
|
||||
"group_trigger": {
|
||||
"mention_only": false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Trường | Kiểu | Bắt buộc | Mô tả |
|
||||
| ------------- | ------ | -------- | --------------------------------------------------------------------------- |
|
||||
| enabled | bool | Có | Có bật kênh Discord hay không |
|
||||
| token | string | Có | Token Bot Discord |
|
||||
| allow_from | array | Không | Danh sách trắng ID người dùng; để trống nghĩa là cho phép tất cả |
|
||||
| group_trigger | object | Không | Cài đặt kích hoạt nhóm (ví dụ: { "mention_only": false }) |
|
||||
|
||||
## Hướng dẫn thiết lập
|
||||
|
||||
1. Truy cập [Discord Developer Portal](https://discord.com/developers/applications) và tạo ứng dụng mới
|
||||
2. Bật các Intents:
|
||||
- Message Content Intent
|
||||
- Server Members Intent
|
||||
3. Lấy Bot Token
|
||||
4. Điền Bot Token vào file cấu hình
|
||||
5. Mời bot vào máy chủ và cấp các quyền cần thiết (ví dụ: gửi tin nhắn, đọc lịch sử tin nhắn)
|
||||
@@ -1,40 +0,0 @@
|
||||
> 返回 [README](../../project/README.zh.md)
|
||||
|
||||
# Discord
|
||||
|
||||
Discord 是一个专为社区设计的免费语音、视频和文本聊天应用。PicoClaw 通过 Discord Bot API 连接到 Discord 服务器,支持接收和发送消息。
|
||||
|
||||
## 配置
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"discord": {
|
||||
"enabled": true,
|
||||
"type": "discord",
|
||||
"token": "YOUR_BOT_TOKEN",
|
||||
"allow_from": ["YOUR_USER_ID"],
|
||||
"group_trigger": {
|
||||
"mention_only": false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| 字段 | 类型 | 必填 | 描述 |
|
||||
| ------------ | ------ | ---- | -------------------------------- |
|
||||
| enabled | bool | 是 | 是否启用 Discord 频道 |
|
||||
| token | string | 是 | Discord 机器人 Token |
|
||||
| allow_from | array | 否 | 用户ID白名单,空表示允许所有用户 |
|
||||
| group_trigger | object | 否 | 群组触发设置(示例: { "mention_only": false }) |
|
||||
|
||||
## 设置流程
|
||||
|
||||
1. 前往 [Discord 开发者门户](https://discord.com/developers/applications) 创建一个新的应用
|
||||
2. 启用 Intents:
|
||||
- Message Content Intent
|
||||
- Server Members Intent
|
||||
3. 获取 Bot Token
|
||||
4. 将 Bot Token 填入配置文件中
|
||||
5. 邀请机器人加入服务器并授予必要权限(例如发送消息、读取消息历史等)
|
||||
@@ -50,4 +50,4 @@ Feishu (nom international : Lark) est une plateforme de collaboration d'entrepri
|
||||
|
||||
## Limitations de plateforme
|
||||
|
||||
> ⚠️ **Le canal Feishu ne prend pas en charge les appareils 32 bits.** Le SDK Feishu ne fournit que des builds 64 bits. Les architectures 32 bits (armv6, armv7, mipsle, etc.) ne peuvent pas utiliser le canal Feishu. Pour la messagerie sur des appareils 32 bits, utilisez Telegram, Discord ou OneBot.
|
||||
> ⚠️ **Le canal Feishu ne prend pas en charge les appareils 32 bits.** Le SDK Feishu ne fournit que des builds 64 bits. Les architectures 32 bits (armv6, armv7, mipsle, etc.) ne peuvent pas utiliser le canal Feishu. Pour la messagerie sur des appareils 32 bits, utilisez Telegram ou OneBot.
|
||||
@@ -50,4 +50,4 @@
|
||||
|
||||
## プラットフォーム制限
|
||||
|
||||
> ⚠️ **飛書チャネルは 32 ビットデバイスをサポートしていません。** 飛書 SDK は 64 ビットビルドのみ提供しています。armv6 / armv7 / mipsle などの 32 ビットアーキテクチャでは飛書チャネルを使用できません。32 ビットデバイスでのメッセージングには、Telegram、Discord、または OneBot をご利用ください。
|
||||
> ⚠️ **飛書チャネルは 32 ビットデバイスをサポートしていません。** 飛書 SDK は 64 ビットビルドのみ提供しています。armv6 / armv7 / mipsle などの 32 ビットアーキテクチャでは飛書チャネルを使用できません。32 ビットデバイスでのメッセージングには、Telegram、または OneBot をご利用ください。
|
||||
@@ -50,4 +50,4 @@ Feishu (international name: Lark) is an enterprise collaboration platform by Byt
|
||||
|
||||
## Platform Limitations
|
||||
|
||||
> ⚠️ **Feishu channel does not support 32-bit devices.** The Feishu SDK only provides 64-bit builds. Devices running armv6, armv7, mipsle, or other 32-bit architectures cannot use the Feishu channel. For messaging on 32-bit devices, use Telegram, Discord, or OneBot instead.
|
||||
> ⚠️ **Feishu channel does not support 32-bit devices.** The Feishu SDK only provides 64-bit builds. Devices running armv6, armv7, mipsle, or other 32-bit architectures cannot use the Feishu channel. For messaging on 32-bit devices, use Telegram, or OneBot instead.
|
||||
@@ -50,4 +50,4 @@ Feishu (nome internacional: Lark) é uma plataforma de colaboração empresarial
|
||||
|
||||
## Limitações de Plataforma
|
||||
|
||||
> ⚠️ **O canal Feishu não suporta dispositivos 32 bits.** O SDK do Feishu fornece apenas builds 64 bits. Arquiteturas 32 bits (armv6, armv7, mipsle, etc.) não podem usar o canal Feishu. Para mensagens em dispositivos 32 bits, use Telegram, Discord ou OneBot.
|
||||
> ⚠️ **O canal Feishu não suporta dispositivos 32 bits.** O SDK do Feishu fornece apenas builds 64 bits. Arquiteturas 32 bits (armv6, armv7, mipsle, etc.) não podem usar o canal Feishu. Para mensagens em dispositivos 32 bits, use Telegram ou OneBot.
|
||||
@@ -50,4 +50,4 @@ Feishu (tên quốc tế: Lark) là nền tảng cộng tác doanh nghiệp củ
|
||||
|
||||
## Giới hạn nền tảng
|
||||
|
||||
> ⚠️ **Kênh Feishu không hỗ trợ thiết bị 32 bit.** SDK Feishu chỉ cung cấp bản build 64 bit. Các kiến trúc 32 bit (armv6, armv7, mipsle, v.v.) không thể sử dụng kênh Feishu. Để nhắn tin trên thiết bị 32 bit, hãy dùng Telegram, Discord hoặc OneBot.
|
||||
> ⚠️ **Kênh Feishu không hỗ trợ thiết bị 32 bit.** SDK Feishu chỉ cung cấp bản build 64 bit. Các kiến trúc 32 bit (armv6, armv7, mipsle, v.v.) không thể sử dụng kênh Feishu. Để nhắn tin trên thiết bị 32 bit, hãy dùng Telegram hoặc OneBot.
|
||||
@@ -45,4 +45,4 @@
|
||||
|
||||
## 平台限制
|
||||
|
||||
> ⚠️ **飞书通道不支持 32 位设备。** 飞书官方 SDK 仅提供 64 位构建,armv6 / armv7 / mipsle 等 32 位架构无法使用飞书通道。如需在 32 位设备上接入即时通讯,请改用 Telegram、Discord 或 OneBot 等通道。
|
||||
> ⚠️ **飞书通道不支持 32 位设备。** 飞书官方 SDK 仅提供 64 位构建,armv6 / armv7 / mipsle 等 32 位架构无法使用飞书通道。如需在 32 位设备上接入即时通讯,请改用 Telegram 或 OneBot 等通道。
|
||||
@@ -1,41 +0,0 @@
|
||||
> Retour au [README](../../project/README.fr.md)
|
||||
|
||||
# Line
|
||||
|
||||
PicoClaw prend en charge LINE via l'API LINE Messaging avec des callbacks webhook.
|
||||
|
||||
## Configuration
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"line": {
|
||||
"enabled": true,
|
||||
"type": "line",
|
||||
"channel_secret": "YOUR_CHANNEL_SECRET",
|
||||
"channel_access_token": "YOUR_CHANNEL_ACCESS_TOKEN",
|
||||
"webhook_path": "/webhook/line",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Champ | Type | Requis | Description |
|
||||
| -------------------- | ------ | ------ | ------------------------------------------------------------------------ |
|
||||
| enabled | bool | Oui | Activer ou non le canal LINE |
|
||||
| channel_secret | string | Oui | Channel Secret de l'API LINE Messaging |
|
||||
| channel_access_token | string | Oui | Channel Access Token de l'API LINE Messaging |
|
||||
| webhook_path | string | Non | Chemin du webhook (par défaut : /webhook/line) |
|
||||
| allow_from | array | Non | Liste blanche d'ID utilisateurs ; vide signifie tous les utilisateurs |
|
||||
|
||||
## Procédure de configuration
|
||||
|
||||
1. Rendez-vous sur la [LINE Developers Console](https://developers.line.biz/console/) et créez un fournisseur de services ainsi qu'un canal Messaging API
|
||||
2. Obtenez le Channel Secret et le Channel Access Token
|
||||
3. Configurez le webhook :
|
||||
- LINE exige que les webhooks utilisent HTTPS. Vous devez donc déployer un serveur compatible HTTPS ou utiliser un outil de proxy inverse comme ngrok pour exposer votre serveur local sur Internet
|
||||
- PicoClaw utilise un serveur HTTP Gateway partagé pour recevoir les callbacks webhook de tous les canaux, écoutant par défaut sur 127.0.0.1:18790
|
||||
- Définissez l'URL du webhook sur `https://your-domain.com/webhook/line`, puis configurez un proxy inverse de votre domaine externe vers le Gateway local (port par défaut 18790)
|
||||
- Activez le webhook et vérifiez l'URL
|
||||
4. Renseignez le Channel Secret et le Channel Access Token dans le fichier de configuration
|
||||
@@ -1,41 +0,0 @@
|
||||
> [README](../../project/README.ja.md) に戻る
|
||||
|
||||
# Line
|
||||
|
||||
PicoClaw は LINE Messaging API と Webhook コールバックを通じて LINE をサポートします。
|
||||
|
||||
## 設定
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"line": {
|
||||
"enabled": true,
|
||||
"type": "line",
|
||||
"channel_secret": "YOUR_CHANNEL_SECRET",
|
||||
"channel_access_token": "YOUR_CHANNEL_ACCESS_TOKEN",
|
||||
"webhook_path": "/webhook/line",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| フィールド | 型 | 必須 | 説明 |
|
||||
| -------------------- | ------ | ------ | ------------------------------------------------------------------ |
|
||||
| enabled | bool | はい | LINE チャンネルを有効にするかどうか |
|
||||
| channel_secret | string | はい | LINE Messaging API の Channel Secret |
|
||||
| channel_access_token | string | はい | LINE Messaging API の Channel Access Token |
|
||||
| webhook_path | string | いいえ | Webhook のパス(デフォルト: /webhook/line) |
|
||||
| allow_from | array | いいえ | ユーザーIDのホワイトリスト。空の場合は全ユーザーを許可 |
|
||||
|
||||
## セットアップ手順
|
||||
|
||||
1. [LINE Developers Console](https://developers.line.biz/console/) にアクセスし、サービスプロバイダーと Messaging API チャンネルを作成する
|
||||
2. Channel Secret と Channel Access Token を取得する
|
||||
3. Webhook を設定する:
|
||||
- LINE は Webhook に HTTPS が必要なため、HTTPS 対応サーバーをデプロイするか、ngrok などのリバースプロキシツールを使用してローカルサーバーをインターネットに公開する必要があります
|
||||
- PicoClaw は共有の Gateway HTTP サーバーを使用してすべてのチャンネルの Webhook コールバックを受信します。デフォルトのリッスンアドレスは 127.0.0.1:18790 です
|
||||
- Webhook URL を `https://your-domain.com/webhook/line` に設定し、外部ドメインをローカルの Gateway(デフォルトポート 18790)にリバースプロキシする
|
||||
- Webhook を有効にして URL を検証する
|
||||
4. Channel Secret と Channel Access Token を設定ファイルに入力する
|
||||
@@ -1,41 +0,0 @@
|
||||
> Back to [README](../../../README.md)
|
||||
|
||||
# Line
|
||||
|
||||
PicoClaw supports LINE through the LINE Messaging API with webhook callbacks.
|
||||
|
||||
## Configuration
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"line": {
|
||||
"enabled": true,
|
||||
"type": "line",
|
||||
"channel_secret": "YOUR_CHANNEL_SECRET",
|
||||
"channel_access_token": "YOUR_CHANNEL_ACCESS_TOKEN",
|
||||
"webhook_path": "/webhook/line",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
| -------------------- | ------ | -------- | ------------------------------------------------------------------ |
|
||||
| enabled | bool | Yes | Whether to enable the LINE channel |
|
||||
| channel_secret | string | Yes | Channel Secret for the LINE Messaging API |
|
||||
| channel_access_token | string | Yes | Channel Access Token for the LINE Messaging API |
|
||||
| webhook_path | string | No | Webhook path (default: /webhook/line) |
|
||||
| allow_from | array | No | User ID whitelist; empty means all users are allowed |
|
||||
|
||||
## Setup
|
||||
|
||||
1. Go to the [LINE Developers Console](https://developers.line.biz/console/) and create a provider and a Messaging API channel
|
||||
2. Obtain the Channel Secret and Channel Access Token
|
||||
3. Configure the webhook:
|
||||
- LINE requires webhooks to use HTTPS, so you need to deploy a server with HTTPS support, or use a reverse proxy tool like ngrok to expose your local server to the internet
|
||||
- PicoClaw uses a shared Gateway HTTP server to receive webhook callbacks for all channels, listening on 127.0.0.1:18790 by default
|
||||
- Set the Webhook URL to `https://your-domain.com/webhook/line`, then reverse-proxy your external domain to the local Gateway (default port 18790)
|
||||
- Enable the webhook and verify the URL
|
||||
4. Fill in the Channel Secret and Channel Access Token in the configuration file
|
||||
@@ -1,41 +0,0 @@
|
||||
> Voltar ao [README](../../project/README.pt-br.md)
|
||||
|
||||
# Line
|
||||
|
||||
O PicoClaw suporta o LINE por meio da LINE Messaging API com callbacks de webhook.
|
||||
|
||||
## Configuração
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"line": {
|
||||
"enabled": true,
|
||||
"type": "line",
|
||||
"channel_secret": "YOUR_CHANNEL_SECRET",
|
||||
"channel_access_token": "YOUR_CHANNEL_ACCESS_TOKEN",
|
||||
"webhook_path": "/webhook/line",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
| -------------------- | ------ | ----------- | ---------------------------------------------------------------------- |
|
||||
| enabled | bool | Sim | Se o canal LINE deve ser habilitado |
|
||||
| channel_secret | string | Sim | Channel Secret da LINE Messaging API |
|
||||
| channel_access_token | string | Sim | Channel Access Token da LINE Messaging API |
|
||||
| webhook_path | string | Não | Caminho do webhook (padrão: /webhook/line) |
|
||||
| allow_from | array | Não | Lista de permissão de IDs de usuário; vazio permite todos |
|
||||
|
||||
## Configuração passo a passo
|
||||
|
||||
1. Acesse o [LINE Developers Console](https://developers.line.biz/console/) e crie um provedor de serviços e um canal Messaging API
|
||||
2. Obtenha o Channel Secret e o Channel Access Token
|
||||
3. Configure o webhook:
|
||||
- O LINE exige que os webhooks usem HTTPS, portanto é necessário implantar um servidor com suporte a HTTPS ou usar uma ferramenta de proxy reverso como o ngrok para expor seu servidor local à internet
|
||||
- O PicoClaw usa um servidor HTTP Gateway compartilhado para receber callbacks de webhook de todos os canais, escutando em 127.0.0.1:18790 por padrão
|
||||
- Defina a URL do webhook como `https://your-domain.com/webhook/line` e configure um proxy reverso do seu domínio externo para o Gateway local (porta padrão 18790)
|
||||
- Ative o webhook e verifique a URL
|
||||
4. Preencha o Channel Secret e o Channel Access Token no arquivo de configuração
|
||||
@@ -1,41 +0,0 @@
|
||||
> Quay lại [README](../../project/README.vi.md)
|
||||
|
||||
# Line
|
||||
|
||||
PicoClaw hỗ trợ LINE thông qua LINE Messaging API kết hợp với webhook callback.
|
||||
|
||||
## Cấu hình
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"line": {
|
||||
"enabled": true,
|
||||
"type": "line",
|
||||
"channel_secret": "YOUR_CHANNEL_SECRET",
|
||||
"channel_access_token": "YOUR_CHANNEL_ACCESS_TOKEN",
|
||||
"webhook_path": "/webhook/line",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Trường | Kiểu | Bắt buộc | Mô tả |
|
||||
| -------------------- | ------ | -------- | ---------------------------------------------------------------------- |
|
||||
| enabled | bool | Có | Có bật kênh LINE hay không |
|
||||
| channel_secret | string | Có | Channel Secret của LINE Messaging API |
|
||||
| channel_access_token | string | Có | Channel Access Token của LINE Messaging API |
|
||||
| webhook_path | string | Không | Đường dẫn webhook (mặc định: /webhook/line) |
|
||||
| allow_from | array | Không | Danh sách trắng ID người dùng; để trống cho phép tất cả |
|
||||
|
||||
## Quy trình thiết lập
|
||||
|
||||
1. Truy cập [LINE Developers Console](https://developers.line.biz/console/) và tạo một nhà cung cấp dịch vụ cùng một kênh Messaging API
|
||||
2. Lấy Channel Secret và Channel Access Token
|
||||
3. Cấu hình webhook:
|
||||
- LINE yêu cầu webhook phải sử dụng HTTPS, vì vậy bạn cần triển khai máy chủ hỗ trợ HTTPS hoặc dùng công cụ reverse proxy như ngrok để expose máy chủ cục bộ ra internet
|
||||
- PicoClaw sử dụng máy chủ HTTP Gateway dùng chung để nhận webhook callback cho tất cả các kênh, mặc định lắng nghe tại 127.0.0.1:18790
|
||||
- Đặt Webhook URL thành `https://your-domain.com/webhook/line`, sau đó reverse proxy tên miền bên ngoài về Gateway cục bộ (cổng mặc định 18790)
|
||||
- Bật webhook và xác minh URL
|
||||
4. Điền Channel Secret và Channel Access Token vào file cấu hình
|
||||
@@ -1,41 +0,0 @@
|
||||
> 返回 [README](../../project/README.zh.md)
|
||||
|
||||
# Line
|
||||
|
||||
PicoClaw 通过 LINE Messaging API 配合 Webhook 回调功能实现对 LINE 的支持。
|
||||
|
||||
## 配置
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"line": {
|
||||
"enabled": true,
|
||||
"type": "line",
|
||||
"channel_secret": "YOUR_CHANNEL_SECRET",
|
||||
"channel_access_token": "YOUR_CHANNEL_ACCESS_TOKEN",
|
||||
"webhook_path": "/webhook/line",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| 字段 | 类型 | 必填 | 描述 |
|
||||
| -------------------- | ------ | ---- | ------------------------------------------ |
|
||||
| enabled | bool | 是 | 是否启用 LINE Channel |
|
||||
| channel_secret | string | 是 | LINE Messaging API 的 Channel Secret |
|
||||
| channel_access_token | string | 是 | LINE Messaging API 的 Channel Access Token |
|
||||
| webhook_path | string | 否 | Webhook 的路径 (默认为 /webhook/line) |
|
||||
| allow_from | array | 否 | 用户ID白名单,空表示允许所有用户 |
|
||||
|
||||
## 设置流程
|
||||
|
||||
1. 前往 [LINE Developers Console](https://developers.line.biz/console/) 创建一个服务提供商和一个 Messaging API Channel
|
||||
2. 获取 Channel Secret 和 Channel Access Token
|
||||
3. 配置Webhook:
|
||||
- LINE 要求 Webhook 必须使用 HTTPS 协议,因此需要部署一个支持 HTTPS 的服务器,或者使用反向代理工具如 ngrok 将本地服务器暴露到公网
|
||||
- PicoClaw 现在使用共享的 Gateway HTTP 服务器来接收所有渠道的 webhook 回调,默认监听地址为 127.0.0.1:18790
|
||||
- 将 Webhook URL 设置为 `https://your-domain.com/webhook/line`,然后将外部域名反向代理到本机的 Gateway(默认端口 18790)
|
||||
- 启用 Webhook 并验证 URL
|
||||
4. 将 Channel Secret 和 Channel Access Token 填入配置文件中
|
||||
@@ -20,8 +20,8 @@ The user's intent reaches the model **as soon as the current tool finishes**, no
|
||||
graph TD
|
||||
subgraph External Callers
|
||||
TG[Telegram]
|
||||
DC[Discord]
|
||||
SL[Discord]
|
||||
DC[Feishu]
|
||||
SL[Feishu]
|
||||
end
|
||||
|
||||
subgraph AgentLoop
|
||||
@@ -53,7 +53,7 @@ graph TD
|
||||
|
||||
### Message routing and worker pool
|
||||
|
||||
Channels (Telegram, Discord, etc.) publish messages to the `MessageBus` via `PublishInbound`. The `Run()` loop consumes messages from the bus and routes each one based on its **session key**:
|
||||
Channels (Telegram, Feishu, etc.) publish messages to the `MessageBus` via `PublishInbound`. The `Run()` loop consumes messages from the bus and routes each one based on its **session key**:
|
||||
|
||||
- **No active turn for the session**: The session key is atomically reserved via `LoadOrStore(sessionKey, struct{}{})`, and a **worker goroutine** is spawned to process the full turn lifecycle.
|
||||
- **Active turn exists for the session**: The message is enqueued directly into the steering queue via `enqueueSteeringMessage`. It will be picked up by the existing worker's steering drain loop.
|
||||
|
||||
+1
-160
@@ -4,19 +4,15 @@
|
||||
|
||||
## 💬 Applications de Chat
|
||||
|
||||
Communiquez avec votre PicoClaw via Telegram, Discord, WhatsApp, QQ, DingTalk, LINE, WeCom, Feishu, OneBot, MQTT.
|
||||
Communiquez avec votre PicoClaw via Telegram, QQ, DingTalk, WeCom, Feishu, OneBot, MQTT.
|
||||
|
||||
> **Note** : Tous les canaux basés sur les webhooks (LINE, WeCom, etc.) sont servis sur un seul serveur HTTP Gateway partagé (`gateway.host`:`gateway.port`, par défaut `127.0.0.1:18790`). Il n'y a pas de ports par canal à configurer. Note : Feishu utilise le mode WebSocket/SDK et n'utilise pas le serveur HTTP webhook partagé.
|
||||
|
||||
| Canal | Difficulté | Description | Documentation |
|
||||
| -------------------- | ------------------ | ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
|
||||
| **Telegram** | ⭐ Facile | Recommandé, transcription vocale, long polling (pas d'IP publique requise) | [Documentation](../channels/telegram/README.fr.md) |
|
||||
| **Discord** | ⭐ Facile | Socket Mode, groupes/DM, écosystème bot riche | [Documentation](../channels/discord/README.fr.md) |
|
||||
| **WhatsApp** | ⭐ Facile | Natif (scan QR) ou Bridge URL | [Documentation](#whatsapp) |
|
||||
| **Weixin** | ⭐ Facile | Scan QR natif (API Tencent iLink) | [Documentation](#weixin) |
|
||||
| **QQ** | ⭐⭐ Moyen | API bot officielle, communauté chinoise | [Documentation](../channels/qq/README.fr.md) |
|
||||
| **DingTalk** | ⭐⭐ Moyen | Mode Stream (pas d'IP publique requise), entreprise | [Documentation](../channels/dingtalk/README.fr.md) |
|
||||
| **LINE** | ⭐⭐⭐ Avancé | HTTPS Webhook requis | [Documentation](../channels/line/README.fr.md) |
|
||||
| **WeCom (企业微信)** | ⭐⭐⭐ Avancé | Bot groupe (Webhook), app personnalisée (API), AI Bot | [Guide](../channels/wecom/README.fr.md) |
|
||||
| **Feishu (飞书)** | ⭐⭐⭐ Avancé | Collaboration entreprise, fonctionnalités riches | [Documentation](../channels/feishu/README.fr.md) |
|
||||
| **OneBot** | ⭐⭐ Moyen | Compatible NapCat/Go-CQHTTP, écosystème communautaire | [Documentation](../channels/onebot/README.fr.md) |
|
||||
@@ -72,110 +68,6 @@ Vous pouvez aussi gerer les competences installees directement depuis Telegram :
|
||||
|
||||
</details>
|
||||
|
||||
<a id="discord"></a>
|
||||
<details>
|
||||
<summary><b>Discord</b></summary>
|
||||
|
||||
**1. Créer un bot**
|
||||
|
||||
* Allez sur <https://discord.com/developers/applications>
|
||||
* Créez une application → Bot → Add Bot
|
||||
* Copiez le token du bot
|
||||
|
||||
**2. Activer les intents**
|
||||
|
||||
* Dans les paramètres du Bot, activez **MESSAGE CONTENT INTENT**
|
||||
* (Optionnel) Activez **SERVER MEMBERS INTENT** si vous prévoyez d'utiliser des listes d'autorisation basées sur les données des membres
|
||||
|
||||
**3. Obtenir votre identifiant utilisateur**
|
||||
* Paramètres Discord → Avancé → activez **Developer Mode**
|
||||
* Clic droit sur votre avatar → **Copy User ID**
|
||||
|
||||
**4. Configurer**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"discord": {
|
||||
"enabled": true,
|
||||
"type": "discord",
|
||||
"token": "YOUR_BOT_TOKEN",
|
||||
"allow_from": ["YOUR_USER_ID"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**5. Inviter le bot**
|
||||
|
||||
* OAuth2 → URL Generator
|
||||
* Scopes : `bot`
|
||||
* Bot Permissions : `Send Messages`, `Read Message History`
|
||||
* Ouvrez l'URL d'invitation générée et ajoutez le bot à votre serveur
|
||||
|
||||
**Mode déclenchement en groupe (optionnel)**
|
||||
|
||||
Par défaut, le bot répond à tous les messages dans un canal de serveur. Pour limiter les réponses aux @mentions uniquement, ajoutez :
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"discord": {
|
||||
"group_trigger": { "mention_only": true }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Vous pouvez également déclencher par préfixes de mots-clés (par ex. `!bot`) :
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"discord": {
|
||||
"group_trigger": { "prefixes": ["!bot"] }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**6. Lancer**
|
||||
|
||||
```bash
|
||||
picoclaw gateway
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<a id="whatsapp"></a>
|
||||
<details>
|
||||
<summary><b>WhatsApp</b> (natif via whatsmeow)</summary>
|
||||
|
||||
PicoClaw peut se connecter à WhatsApp de deux manières :
|
||||
|
||||
- **Natif (recommandé) :** En processus via [whatsmeow](https://github.com/tulir/whatsmeow). Pas de bridge séparé. Définissez `"use_native": true` et laissez `bridge_url` vide. Au premier lancement, scannez le code QR avec WhatsApp (Appareils liés). La session est stockée dans votre workspace (par ex. `workspace/whatsapp/`). Le canal natif est **optionnel** pour garder le binaire par défaut léger ; compilez avec `-tags whatsapp_native` (par ex. `make build-whatsapp-native` ou `go build -tags whatsapp_native ./cmd/...`).
|
||||
- **Bridge :** Connectez-vous à un bridge WebSocket externe. Définissez `bridge_url` (par ex. `ws://localhost:3001`) et gardez `use_native` à false.
|
||||
|
||||
**Configurer (natif)**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"whatsapp": {
|
||||
"enabled": true,
|
||||
"type": "whatsapp",
|
||||
"use_native": true,
|
||||
"session_store_path": "",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Si `session_store_path` est vide, la session est stockée dans `<workspace>/whatsapp/`. Lancez `picoclaw gateway` ; au premier lancement, scannez le code QR affiché dans le terminal avec WhatsApp → Appareils liés.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="weixin"></a>
|
||||
<details>
|
||||
<summary><b>Weixin</b> (WeChat Personnel)</summary>
|
||||
@@ -291,56 +183,6 @@ picoclaw gateway
|
||||
```
|
||||
</details>
|
||||
|
||||
<a id="line"></a>
|
||||
<details>
|
||||
<summary><b>LINE</b></summary>
|
||||
|
||||
**1. Créer un compte officiel LINE**
|
||||
|
||||
- Allez sur [LINE Developers Console](https://developers.line.biz/)
|
||||
- Créez un provider → Créez un canal Messaging API
|
||||
- Copiez le **Channel Secret** et le **Channel Access Token**
|
||||
|
||||
**2. Configurer**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"line": {
|
||||
"enabled": true,
|
||||
"type": "line",
|
||||
"channel_secret": "YOUR_CHANNEL_SECRET",
|
||||
"channel_access_token": "YOUR_CHANNEL_ACCESS_TOKEN",
|
||||
"webhook_path": "/webhook/line",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> Le webhook LINE est servi sur le serveur Gateway partagé (`gateway.host`:`gateway.port`, par défaut `127.0.0.1:18790`).
|
||||
|
||||
**3. Configurer l'URL du Webhook**
|
||||
|
||||
LINE nécessite HTTPS pour les webhooks. Utilisez un reverse proxy ou un tunnel :
|
||||
|
||||
```bash
|
||||
# Exemple avec ngrok (le port par défaut du gateway est 18790)
|
||||
ngrok http 18790
|
||||
```
|
||||
|
||||
Puis définissez l'URL du Webhook dans la console LINE Developers à `https://your-domain/webhook/line` et activez **Use webhook**.
|
||||
|
||||
**4. Lancer**
|
||||
|
||||
```bash
|
||||
picoclaw gateway
|
||||
```
|
||||
|
||||
> Dans les discussions de groupe, le bot ne répond que lorsqu'il est @mentionné. Les réponses citent le message original.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="wecom"></a>
|
||||
<details>
|
||||
<summary><b>WeCom (企业微信)</b></summary>
|
||||
@@ -378,7 +220,6 @@ Voir le [Guide de Configuration WeCom](../channels/wecom/README.fr.md) pour les
|
||||
}
|
||||
```
|
||||
|
||||
> Le webhook WeCom est servi sur le serveur Gateway partagé (`gateway.host`:`gateway.port`, par défaut `127.0.0.1:18790`).
|
||||
|
||||
**Configuration rapide - WeCom App :**
|
||||
|
||||
|
||||
@@ -6,19 +6,15 @@
|
||||
|
||||
PicoClaw は複数のチャットプラットフォームをサポートしており、Agent をどこにでも接続できます。
|
||||
|
||||
> **注意**: すべての Webhook ベースのチャネル(LINE、WeCom など)は、共有 Gateway HTTP サーバー(`gateway.host`:`gateway.port`、デフォルト `127.0.0.1:18790`)上で提供されます。チャネルごとにポートを設定する必要はありません。注意:飛書(Feishu)は WebSocket/SDK モードを使用し、共有 HTTP Webhook サーバーは使用しません。
|
||||
|
||||
### チャネル一覧
|
||||
|
||||
| チャネル | セットアップ難易度 | 特徴 | ドキュメント |
|
||||
| -------------------- | ------------------ | ----------------------------------------- | --------------------------------------------------------------------------------------------------------------- |
|
||||
| **Telegram** | ⭐ 簡単 | 推奨、音声テキスト変換対応、ロングポーリング(公開 IP 不要) | [ドキュメント](../channels/telegram/README.ja.md) |
|
||||
| **Discord** | ⭐ 簡単 | Socket Mode、グループ/DM 対応、Bot エコシステム充実 | [ドキュメント](../channels/discord/README.ja.md) |
|
||||
| **WhatsApp** | ⭐ 簡単 | ネイティブ (QR スキャン) または Bridge URL | [ドキュメント](#whatsapp) |
|
||||
| **微信 (Weixin)** | ⭐ 簡単 | ネイティブ QR スキャン(Tencent iLink API)| [ドキュメント](#weixin) |
|
||||
| **QQ** | ⭐⭐ 中程度 | 公式ボット API、中国コミュニティ向け | [ドキュメント](../channels/qq/README.ja.md) |
|
||||
| **DingTalk** | ⭐⭐ 中程度 | Stream モード(公開 IP 不要)、企業向け | [ドキュメント](../channels/dingtalk/README.ja.md) |
|
||||
| **LINE** | ⭐⭐⭐ やや難 | HTTPS Webhook が必要 | [ドキュメント](../channels/line/README.ja.md) |
|
||||
| **WeCom (企業微信)** | ⭐⭐⭐ やや難 | グループ Bot (Webhook)、カスタムアプリ (API)、AI Bot 対応 | [ガイド](../channels/wecom/README.ja.md) |
|
||||
| **Feishu (飛書)** | ⭐⭐⭐ やや難 | エンタープライズコラボレーション、機能豊富 | [ドキュメント](../channels/feishu/README.ja.md) |
|
||||
| **OneBot** | ⭐⭐ 中程度 | NapCat/Go-CQHTTP 互換、コミュニティエコシステム充実 | [ドキュメント](../channels/onebot/README.ja.md) |
|
||||
@@ -68,111 +64,6 @@ Telegram 側はコマンドメニュー登録機能を保持し、汎用コマ
|
||||
|
||||
</details>
|
||||
|
||||
<a id="discord"></a>
|
||||
<details>
|
||||
<summary><b>Discord</b></summary>
|
||||
|
||||
**1. Bot を作成**
|
||||
|
||||
* <https://discord.com/developers/applications> にアクセス
|
||||
* アプリケーションを作成 → Bot → Bot を追加
|
||||
* Bot Token をコピー
|
||||
|
||||
**2. Intents を有効化**
|
||||
|
||||
* Bot 設定で **MESSAGE CONTENT INTENT** を有効化
|
||||
* (オプション)メンバーデータに基づくホワイトリストが必要な場合は **SERVER MEMBERS INTENT** を有効化
|
||||
|
||||
**3. User ID を取得**
|
||||
|
||||
* Discord 設定 → 詳細設定 → **開発者モード** を有効化
|
||||
* アバターを右クリック → **ユーザー ID をコピー**
|
||||
|
||||
**4. 設定**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"discord": {
|
||||
"enabled": true,
|
||||
"type": "discord",
|
||||
"token": "YOUR_BOT_TOKEN",
|
||||
"allow_from": ["YOUR_USER_ID"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**5. Bot を招待**
|
||||
|
||||
* OAuth2 → URL Generator
|
||||
* Scopes: `bot`
|
||||
* Bot Permissions: `Send Messages`, `Read Message History`
|
||||
* 生成された招待リンクを開き、Bot をサーバーに追加
|
||||
|
||||
**オプション:グループトリガーモード**
|
||||
|
||||
デフォルトでは Bot はサーバーチャネル内のすべてのメッセージに応答します。@メンション時のみ応答するには:
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"discord": {
|
||||
"group_trigger": { "mention_only": true }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
キーワードプレフィックスでトリガーすることもできます(例: `!bot`):
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"discord": {
|
||||
"group_trigger": { "prefixes": ["!bot"] }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**6. 実行**
|
||||
|
||||
```bash
|
||||
picoclaw gateway
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<a id="whatsapp"></a>
|
||||
<details>
|
||||
<summary><b>WhatsApp</b>(ネイティブ whatsmeow)</summary>
|
||||
|
||||
PicoClaw は 2 つの WhatsApp 接続方式をサポートしています:
|
||||
|
||||
- **ネイティブ(推奨):** プロセス内で [whatsmeow](https://github.com/tulir/whatsmeow) を使用。独立した Bridge は不要です。`"use_native": true` に設定し、`bridge_url` を空にします。初回実行時に WhatsApp で QR コードをスキャン(リンクデバイス)。セッションはワークスペース配下(例: `workspace/whatsapp/`)に保存されます。ネイティブチャネルは**オプション**ビルドで、`-tags whatsapp_native` でコンパイルします(例: `make build-whatsapp-native` または `go build -tags whatsapp_native ./cmd/...`)。
|
||||
- **Bridge:** 外部 WebSocket Bridge に接続。`bridge_url`(例: `ws://localhost:3001`)を設定し、`use_native` を false のままにします。
|
||||
|
||||
**設定(ネイティブ)**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"whatsapp": {
|
||||
"enabled": true,
|
||||
"type": "whatsapp",
|
||||
"use_native": true,
|
||||
"session_store_path": "",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`session_store_path` が空の場合、セッションは `<workspace>/whatsapp/` に保存されます。`picoclaw gateway` を実行し、初回実行時にターミナルに表示される QR コードをスキャンしてください(WhatsApp → リンクデバイス)。
|
||||
|
||||
</details>
|
||||
|
||||
<a id="weixin"></a>
|
||||
<details>
|
||||
<summary><b>微信 (Weixin)</b></summary>
|
||||
@@ -289,56 +180,6 @@ picoclaw gateway
|
||||
|
||||
</details>
|
||||
|
||||
<a id="line"></a>
|
||||
<details>
|
||||
<summary><b>LINE</b></summary>
|
||||
|
||||
**1. LINE 公式アカウントを作成**
|
||||
|
||||
- [LINE Developers Console](https://developers.line.biz/) にアクセス
|
||||
- Provider を作成 → Messaging API チャネルを作成
|
||||
- **Channel Secret** と **Channel Access Token** をコピー
|
||||
|
||||
**2. 設定**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"line": {
|
||||
"enabled": true,
|
||||
"type": "line",
|
||||
"channel_secret": "YOUR_CHANNEL_SECRET",
|
||||
"channel_access_token": "YOUR_CHANNEL_ACCESS_TOKEN",
|
||||
"webhook_path": "/webhook/line",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> LINE Webhook は共有 Gateway サーバー(`gateway.host`:`gateway.port`、デフォルト `127.0.0.1:18790`)上で提供されます。
|
||||
|
||||
**3. Webhook URL を設定**
|
||||
|
||||
LINE は HTTPS Webhook が必要です。リバースプロキシまたはトンネルを使用してください:
|
||||
|
||||
```bash
|
||||
# 例:ngrok を使用(Gateway デフォルトポートは 18790)
|
||||
ngrok http 18790
|
||||
```
|
||||
|
||||
LINE Developers Console で Webhook URL を `https://your-domain/webhook/line` に設定し、**Use webhook** を有効にしてください。
|
||||
|
||||
**4. 実行**
|
||||
|
||||
```bash
|
||||
picoclaw gateway
|
||||
```
|
||||
|
||||
> グループチャットでは、Bot は @メンション時のみ応答します。返信は元のメッセージを引用します。
|
||||
|
||||
</details>
|
||||
|
||||
<a id="feishu"></a>
|
||||
<details>
|
||||
<summary><b>Feishu (飛書)</b></summary>
|
||||
@@ -419,7 +260,6 @@ PicoClaw は 3 種類の WeCom 統合をサポートしています:
|
||||
}
|
||||
```
|
||||
|
||||
> WeCom Webhook は共有 Gateway サーバー(`gateway.host`:`gateway.port`、デフォルト `127.0.0.1:18790`)上で提供されます。
|
||||
|
||||
**クイックセットアップ — カスタムアプリ:**
|
||||
|
||||
|
||||
+1
-158
@@ -4,19 +4,16 @@
|
||||
|
||||
## 💬 Chat Apps
|
||||
|
||||
Talk to your picoclaw through Telegram, Discord, WhatsApp, QQ, DingTalk, LINE, WeCom, Feishu, OneBot, MQTT
|
||||
Talk to your picoclaw through Telegram, QQ, DingTalk, WeCom, Feishu, OneBot, MQTT
|
||||
|
||||
> **Note**: Channels that rely on HTTP callbacks share a single Gateway HTTP server (`gateway.host`:`gateway.port`, default `127.0.0.1:18790`). Socket/stream-based channels such as Feishu, DingTalk, and WeCom do not rely on the shared webhook server for inbound delivery.
|
||||
|
||||
| Channel | Difficulty | Description | Documentation |
|
||||
| -------------------- | ------------------ | ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
|
||||
| **Telegram** | ⭐ Easy | Recommended, voice-to-text, long polling (no public IP needed) | [Docs](../channels/telegram/README.md) |
|
||||
| **Discord** | ⭐ Easy | Socket Mode, group/DM support, rich bot ecosystem | [Docs](../channels/discord/README.md) |
|
||||
| **WhatsApp** | ⭐ Easy | Native (QR scan) or Bridge URL | [Docs](#whatsapp) |
|
||||
| **Weixin** | ⭐ Easy | Native QR scan (Tencent iLink API) | [Docs](#weixin) |
|
||||
| **QQ** | ⭐⭐ Medium | Official bot API, Chinese community | [Docs](../channels/qq/README.md) |
|
||||
| **DingTalk** | ⭐⭐ Medium | Stream mode (no public IP needed), enterprise | [Docs](../channels/dingtalk/README.md) |
|
||||
| **LINE** | ⭐⭐⭐ Advanced | HTTPS Webhook required | [Docs](../channels/line/README.md) |
|
||||
| **WeCom (企业微信)** | ⭐⭐⭐ Advanced | Official AI Bot over WebSocket, streaming + media | [Docs](../channels/wecom/README.md) |
|
||||
| **Feishu (飞书)** | ⭐⭐⭐ Advanced | Enterprise collaboration, feature-rich | [Docs](../channels/feishu/README.md) |
|
||||
| **OneBot** | ⭐⭐ Medium | NapCat/Go-CQHTTP compatible, community ecosystem | [Docs](../channels/onebot/README.md) |
|
||||
@@ -78,110 +75,6 @@ You can set use_markdown_v2: true to enable enhanced formatting options. This al
|
||||
|
||||
</details>
|
||||
|
||||
<a id="discord"></a>
|
||||
<details>
|
||||
<summary><b>Discord</b></summary>
|
||||
|
||||
**1. Create a bot**
|
||||
|
||||
* Go to <https://discord.com/developers/applications>
|
||||
* Create an application → Bot → Add Bot
|
||||
* Copy the bot token
|
||||
|
||||
**2. Enable intents**
|
||||
|
||||
* In the Bot settings, enable **MESSAGE CONTENT INTENT**
|
||||
* (Optional) Enable **SERVER MEMBERS INTENT** if you plan to use allow lists based on member data
|
||||
|
||||
**3. Get your User ID**
|
||||
* Discord Settings → Advanced → enable **Developer Mode**
|
||||
* Right-click your avatar → **Copy User ID**
|
||||
|
||||
**4. Configure**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"discord": {
|
||||
"enabled": true,
|
||||
"type": "discord",
|
||||
"token": "YOUR_BOT_TOKEN",
|
||||
"allow_from": ["YOUR_USER_ID"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**5. Invite the bot**
|
||||
|
||||
* OAuth2 → URL Generator
|
||||
* Scopes: `bot`
|
||||
* Bot Permissions: `Send Messages`, `Read Message History`
|
||||
* Open the generated invite URL and add the bot to your server
|
||||
|
||||
**Optional: Group trigger mode**
|
||||
|
||||
By default the bot responds to all messages in a server channel. To restrict responses to @-mentions only, add:
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"discord": {
|
||||
"group_trigger": { "mention_only": true }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
You can also trigger by keyword prefixes (e.g. `!bot`):
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"discord": {
|
||||
"group_trigger": { "prefixes": ["!bot"] }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**6. Run**
|
||||
|
||||
```bash
|
||||
picoclaw gateway
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<a id="whatsapp"></a>
|
||||
<details>
|
||||
<summary><b>WhatsApp</b> (native via whatsmeow)</summary>
|
||||
|
||||
PicoClaw can connect to WhatsApp in two ways:
|
||||
|
||||
- **Native (recommended):** In-process using [whatsmeow](https://github.com/tulir/whatsmeow). No separate bridge. Set `"use_native": true` and leave `bridge_url` empty. On first run, scan the QR code with WhatsApp (Linked Devices). Session is stored under your workspace (e.g. `workspace/whatsapp/`). The native channel is **optional** to keep the default binary small; build with `-tags whatsapp_native` (e.g. `make build-whatsapp-native` or `go build -tags whatsapp_native ./cmd/...`).
|
||||
- **Bridge:** Connect to an external WebSocket bridge. Set `bridge_url` (e.g. `ws://localhost:3001`) and keep `use_native` false.
|
||||
|
||||
**Configure (native)**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"whatsapp": {
|
||||
"enabled": true,
|
||||
"type": "whatsapp",
|
||||
"use_native": true,
|
||||
"session_store_path": "",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
If `session_store_path` is empty, the session is stored in `<workspace>/whatsapp/`. Run `picoclaw gateway`; on first run, scan the QR code printed in the terminal with WhatsApp → Linked Devices.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="weixin"></a>
|
||||
<details>
|
||||
<summary><b>Weixin</b> (WeChat Personal)</summary>
|
||||
@@ -297,56 +190,6 @@ picoclaw gateway
|
||||
```
|
||||
</details>
|
||||
|
||||
<a id="line"></a>
|
||||
<details>
|
||||
<summary><b>LINE</b></summary>
|
||||
|
||||
**1. Create a LINE Official Account**
|
||||
|
||||
- Go to [LINE Developers Console](https://developers.line.biz/)
|
||||
- Create a provider → Create a Messaging API channel
|
||||
- Copy **Channel Secret** and **Channel Access Token**
|
||||
|
||||
**2. Configure**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"line": {
|
||||
"enabled": true,
|
||||
"type": "line",
|
||||
"channel_secret": "YOUR_CHANNEL_SECRET",
|
||||
"channel_access_token": "YOUR_CHANNEL_ACCESS_TOKEN",
|
||||
"webhook_path": "/webhook/line",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> LINE webhook is served on the shared Gateway server (`gateway.host`:`gateway.port`, default `127.0.0.1:18790`).
|
||||
|
||||
**3. Set up Webhook URL**
|
||||
|
||||
LINE requires HTTPS for webhooks. Use a reverse proxy or tunnel:
|
||||
|
||||
```bash
|
||||
# Example with ngrok (gateway default port is 18790)
|
||||
ngrok http 18790
|
||||
```
|
||||
|
||||
Then set the Webhook URL in LINE Developers Console to `https://your-domain/webhook/line` and enable **Use webhook**.
|
||||
|
||||
**4. Run**
|
||||
|
||||
```bash
|
||||
picoclaw gateway
|
||||
```
|
||||
|
||||
> In group chats, the bot responds only when @mentioned. Replies quote the original message.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="wecom"></a>
|
||||
<details>
|
||||
<summary><b>WeCom (企业微信)</b></summary>
|
||||
|
||||
+1
-157
@@ -4,18 +4,14 @@
|
||||
|
||||
## 💬 Aplikasi Sembang
|
||||
|
||||
Berbual dengan picoclaw anda melalui Telegram, Discord, WhatsApp, QQ, DingTalk, LINE, WeCom, Feishu, OneBot, MQTT
|
||||
Berbual dengan picoclaw anda melalui Telegram, QQ, DingTalk, WeCom, Feishu, OneBot, MQTT
|
||||
|
||||
> **Nota**: Semua saluran berasaskan webhook (LINE, WeCom, dan sebagainya) diservis pada satu pelayan HTTP Gateway yang dikongsi (`gateway.host`:`gateway.port`, lalai `127.0.0.1:18790`). Tiada port khusus per saluran untuk dikonfigurasikan. Nota: Feishu menggunakan mod WebSocket/SDK dan tidak menggunakan pelayan HTTP webhook yang dikongsi.
|
||||
|
||||
| Saluran | Penyediaan |
|
||||
| ---------------- | ------------------------------------------ |
|
||||
| **Telegram** | Mudah (hanya token) |
|
||||
| **Discord** | Mudah (token bot + intents) |
|
||||
| **WhatsApp** | Mudah (asli: imbas QR; atau bridge URL) |
|
||||
| **QQ** | Mudah (AppID + AppSecret) |
|
||||
| **DingTalk** | Sederhana (kelayakan aplikasi) |
|
||||
| **LINE** | Sederhana (kelayakan + webhook URL) |
|
||||
| **WeCom AI Bot** | Sederhana (Token + kunci AES) |
|
||||
| **Feishu** | Sederhana (App ID + Secret, mod WebSocket) |
|
||||
| **OneBot** | Sederhana (QQ melalui protokol OneBot) |
|
||||
@@ -74,108 +70,6 @@ Anda boleh menetapkan `use_markdown_v2: true` untuk mengaktifkan pilihan pemform
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Discord</b></summary>
|
||||
|
||||
**1. Cipta bot**
|
||||
|
||||
* Pergi ke <https://discord.com/developers/applications>
|
||||
* Cipta aplikasi → Bot → Add Bot
|
||||
* Salin token bot
|
||||
|
||||
**2. Aktifkan intents**
|
||||
|
||||
* Dalam tetapan Bot, aktifkan **MESSAGE CONTENT INTENT**
|
||||
* (Pilihan) Aktifkan **SERVER MEMBERS INTENT** jika anda bercadang menggunakan allow list berasaskan data ahli
|
||||
|
||||
**3. Dapatkan User ID anda**
|
||||
* Discord Settings → Advanced → aktifkan **Developer Mode**
|
||||
* Klik kanan avatar anda → **Copy User ID**
|
||||
|
||||
**4. Konfigurasi**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"discord": {
|
||||
"enabled": true,
|
||||
"type": "discord",
|
||||
"token": "YOUR_BOT_TOKEN",
|
||||
"allow_from": ["YOUR_USER_ID"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**5. Jemput bot**
|
||||
|
||||
* OAuth2 → URL Generator
|
||||
* Scopes: `bot`
|
||||
* Bot Permissions: `Send Messages`, `Read Message History`
|
||||
* Buka URL jemputan yang dijana dan tambahkan bot ke pelayan anda
|
||||
|
||||
**Pilihan: Mod trigger kumpulan**
|
||||
|
||||
Secara lalai bot membalas semua mesej dalam saluran pelayan. Untuk mengehadkan balasan kepada @mention sahaja, tambah:
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"discord": {
|
||||
"group_trigger": { "mention_only": true }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Anda juga boleh mencetuskan dengan awalan kata kunci (contohnya `!bot`):
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"discord": {
|
||||
"group_trigger": { "prefixes": ["!bot"] }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**6. Jalankan**
|
||||
|
||||
```bash
|
||||
picoclaw gateway
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>WhatsApp</b> (asli melalui whatsmeow)</summary>
|
||||
|
||||
PicoClaw boleh menyambung ke WhatsApp dalam dua cara:
|
||||
|
||||
- **Asli (disyorkan):** Dalam proses menggunakan [whatsmeow](https://github.com/tulir/whatsmeow). Tiada bridge berasingan. Tetapkan `"use_native": true` dan biarkan `bridge_url` kosong. Pada larian pertama, imbas kod QR dengan WhatsApp (Linked Devices). Sesi disimpan di bawah workspace anda (contohnya `workspace/whatsapp/`). Saluran asli ini adalah **pilihan** untuk memastikan binari lalai kekal kecil; bina dengan `-tags whatsapp_native` (contohnya `make build-whatsapp-native` atau `go build -tags whatsapp_native ./cmd/...`).
|
||||
- **Bridge:** Sambung ke bridge WebSocket luaran. Tetapkan `bridge_url` (contohnya `ws://localhost:3001`) dan biarkan `use_native` sebagai false.
|
||||
|
||||
**Konfigurasi (asli)**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"whatsapp": {
|
||||
"enabled": true,
|
||||
"type": "whatsapp",
|
||||
"use_native": true,
|
||||
"session_store_path": "",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Jika `session_store_path` kosong, sesi akan disimpan dalam `<workspace>/whatsapp/`. Jalankan `picoclaw gateway`; pada larian pertama, imbas kod QR yang dipaparkan dalam terminal menggunakan WhatsApp → Linked Devices.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>QQ</b></summary>
|
||||
|
||||
@@ -244,55 +138,6 @@ picoclaw gateway
|
||||
```
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>LINE</b></summary>
|
||||
|
||||
**1. Cipta Akaun Rasmi LINE**
|
||||
|
||||
- Pergi ke [LINE Developers Console](https://developers.line.biz/)
|
||||
- Cipta provider → Cipta saluran Messaging API
|
||||
- Salin **Channel Secret** dan **Channel Access Token**
|
||||
|
||||
**2. Konfigurasi**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"line": {
|
||||
"enabled": true,
|
||||
"type": "line",
|
||||
"channel_secret": "YOUR_CHANNEL_SECRET",
|
||||
"channel_access_token": "YOUR_CHANNEL_ACCESS_TOKEN",
|
||||
"webhook_path": "/webhook/line",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> Webhook LINE diservis pada pelayan Gateway yang dikongsi (`gateway.host`:`gateway.port`, lalai `127.0.0.1:18790`).
|
||||
|
||||
**3. Tetapkan Webhook URL**
|
||||
|
||||
LINE memerlukan HTTPS untuk webhook. Gunakan reverse proxy atau tunnel:
|
||||
|
||||
```bash
|
||||
# Contoh dengan ngrok (port lalai gateway ialah 18790)
|
||||
ngrok http 18790
|
||||
```
|
||||
|
||||
Kemudian tetapkan Webhook URL dalam LINE Developers Console kepada `https://your-domain/webhook/line` dan aktifkan **Use webhook**.
|
||||
|
||||
**4. Jalankan**
|
||||
|
||||
```bash
|
||||
picoclaw gateway
|
||||
```
|
||||
|
||||
> Dalam sembang kumpulan, bot hanya membalas apabila @disebut. Balasan akan memetik mesej asal.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>WeCom (企业微信)</b></summary>
|
||||
|
||||
@@ -329,7 +174,6 @@ Lihat [Panduan Konfigurasi WeCom](../channels/wecom/README.zh.md) untuk arahan p
|
||||
}
|
||||
```
|
||||
|
||||
> Webhook WeCom diservis pada pelayan Gateway yang dikongsi (`gateway.host`:`gateway.port`, lalai `127.0.0.1:18790`).
|
||||
|
||||
**Quick Setup - WeCom App:**
|
||||
|
||||
|
||||
@@ -4,19 +4,15 @@
|
||||
|
||||
## 💬 Aplicativos de Chat
|
||||
|
||||
Converse com seu picoclaw através do Telegram, Discord, WhatsApp, QQ, DingTalk, LINE, WeCom, Feishu, OneBot, MQTT
|
||||
Converse com seu picoclaw através do Telegram, QQ, DingTalk, WeCom, Feishu, OneBot, MQTT
|
||||
|
||||
> **Nota**: Todos os canais baseados em webhook (LINE, WeCom, etc.) são servidos em um único servidor HTTP Gateway compartilhado (`gateway.host`:`gateway.port`, padrão `127.0.0.1:18790`). Não há portas por canal para configurar. Nota: Feishu usa o modo WebSocket/SDK e não utiliza o servidor HTTP webhook compartilhado.
|
||||
|
||||
| Canal | Dificuldade | Descrição | Documentação |
|
||||
| -------------------- | ------------------ | ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
|
||||
| **Telegram** | ⭐ Fácil | Recomendado, voz para texto, long polling (sem IP público) | [Documentação](../channels/telegram/README.pt-br.md) |
|
||||
| **Discord** | ⭐ Fácil | Socket Mode, suporte a grupos/DM, ecossistema bot rico | [Documentação](../channels/discord/README.pt-br.md) |
|
||||
| **WhatsApp** | ⭐ Fácil | Nativo (scan QR) ou Bridge URL | [Documentação](#whatsapp) |
|
||||
| **Weixin** | ⭐ Fácil | Scan QR nativo (API Tencent iLink) | [Documentação](#weixin) |
|
||||
| **QQ** | ⭐⭐ Médio | API bot oficial, comunidade chinesa | [Documentação](../channels/qq/README.pt-br.md) |
|
||||
| **DingTalk** | ⭐⭐ Médio | Modo Stream (sem IP público), empresarial | [Documentação](../channels/dingtalk/README.pt-br.md) |
|
||||
| **LINE** | ⭐⭐⭐ Avançado | HTTPS Webhook obrigatório | [Documentação](../channels/line/README.pt-br.md) |
|
||||
| **WeCom (企业微信)** | ⭐⭐⭐ Avançado | Bot de grupo (Webhook), app personalizado (API), AI Bot | [Guia](../channels/wecom/README.pt-br.md) |
|
||||
| **Feishu (飞书)** | ⭐⭐⭐ Avançado | Colaboração empresarial, rico em recursos | [Documentação](../channels/feishu/README.pt-br.md) |
|
||||
| **OneBot** | ⭐⭐ Médio | Compatível com NapCat/Go-CQHTTP, ecossistema comunitário | [Documentação](../channels/onebot/README.pt-br.md) |
|
||||
@@ -72,110 +68,6 @@ Voce tambem pode gerenciar skills instaladas diretamente pelo Telegram:
|
||||
|
||||
</details>
|
||||
|
||||
<a id="discord"></a>
|
||||
<details>
|
||||
<summary><b>Discord</b></summary>
|
||||
|
||||
**1. Criar um bot**
|
||||
|
||||
* Acesse <https://discord.com/developers/applications>
|
||||
* Crie um aplicativo → Bot → Add Bot
|
||||
* Copie o token do bot
|
||||
|
||||
**2. Habilitar intents**
|
||||
|
||||
* Nas configurações do Bot, habilite **MESSAGE CONTENT INTENT**
|
||||
* (Opcional) Habilite **SERVER MEMBERS INTENT** se planeja usar listas de permissão baseadas em dados de membros
|
||||
|
||||
**3. Obter seu User ID**
|
||||
* Configurações do Discord → Avançado → habilite **Developer Mode**
|
||||
* Clique com o botão direito no seu avatar → **Copy User ID**
|
||||
|
||||
**4. Configurar**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"discord": {
|
||||
"enabled": true,
|
||||
"type": "discord",
|
||||
"token": "YOUR_BOT_TOKEN",
|
||||
"allow_from": ["YOUR_USER_ID"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**5. Convidar o bot**
|
||||
|
||||
* OAuth2 → URL Generator
|
||||
* Scopes: `bot`
|
||||
* Bot Permissions: `Send Messages`, `Read Message History`
|
||||
* Abra a URL de convite gerada e adicione o bot ao seu servidor
|
||||
|
||||
**Opcional: Modo de ativação em grupo**
|
||||
|
||||
Por padrão, o bot responde a todas as mensagens em um canal do servidor. Para restringir respostas apenas a @menções, adicione:
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"discord": {
|
||||
"group_trigger": { "mention_only": true }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Você também pode ativar por prefixos de palavras-chave (ex.: `!bot`):
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"discord": {
|
||||
"group_trigger": { "prefixes": ["!bot"] }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**6. Executar**
|
||||
|
||||
```bash
|
||||
picoclaw gateway
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<a id="whatsapp"></a>
|
||||
<details>
|
||||
<summary><b>WhatsApp</b> (nativo via whatsmeow)</summary>
|
||||
|
||||
O PicoClaw pode se conectar ao WhatsApp de duas formas:
|
||||
|
||||
- **Nativo (recomendado):** In-process usando [whatsmeow](https://github.com/tulir/whatsmeow). Sem bridge separado. Defina `"use_native": true` e deixe `bridge_url` vazio. Na primeira execução, escaneie o QR code com o WhatsApp (Dispositivos Vinculados). A sessão é armazenada no seu workspace (ex.: `workspace/whatsapp/`). O canal nativo é **opcional** para manter o binário padrão pequeno; compile com `-tags whatsapp_native` (ex.: `make build-whatsapp-native` ou `go build -tags whatsapp_native ./cmd/...`).
|
||||
- **Bridge:** Conecte-se a um bridge WebSocket externo. Defina `bridge_url` (ex.: `ws://localhost:3001`) e mantenha `use_native` como false.
|
||||
|
||||
**Configurar (nativo)**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"whatsapp": {
|
||||
"enabled": true,
|
||||
"type": "whatsapp",
|
||||
"use_native": true,
|
||||
"session_store_path": "",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Se `session_store_path` estiver vazio, a sessão é armazenada em `<workspace>/whatsapp/`. Execute `picoclaw gateway`; na primeira execução, escaneie o QR code impresso no terminal com WhatsApp → Dispositivos Vinculados.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="weixin"></a>
|
||||
<details>
|
||||
<summary><b>Weixin</b> (WeChat Pessoal)</summary>
|
||||
@@ -292,56 +184,6 @@ picoclaw gateway
|
||||
|
||||
</details>
|
||||
|
||||
<a id="line"></a>
|
||||
<details>
|
||||
<summary><b>LINE</b></summary>
|
||||
|
||||
**1. Criar uma Conta Oficial LINE**
|
||||
|
||||
- Acesse o [LINE Developers Console](https://developers.line.biz/)
|
||||
- Crie um provider → Crie um canal Messaging API
|
||||
- Copie o **Channel Secret** e o **Channel Access Token**
|
||||
|
||||
**2. Configurar**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"line": {
|
||||
"enabled": true,
|
||||
"type": "line",
|
||||
"channel_secret": "YOUR_CHANNEL_SECRET",
|
||||
"channel_access_token": "YOUR_CHANNEL_ACCESS_TOKEN",
|
||||
"webhook_path": "/webhook/line",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> O webhook do LINE é servido no servidor Gateway compartilhado (`gateway.host`:`gateway.port`, padrão `127.0.0.1:18790`).
|
||||
|
||||
**3. Configurar URL do Webhook**
|
||||
|
||||
O LINE requer HTTPS para webhooks. Use um proxy reverso ou túnel:
|
||||
|
||||
```bash
|
||||
# Exemplo com ngrok (porta padrão do gateway é 18790)
|
||||
ngrok http 18790
|
||||
```
|
||||
|
||||
Em seguida, defina a URL do Webhook no LINE Developers Console como `https://your-domain/webhook/line` e habilite **Use webhook**.
|
||||
|
||||
**4. Executar**
|
||||
|
||||
```bash
|
||||
picoclaw gateway
|
||||
```
|
||||
|
||||
> Em chats de grupo, o bot responde apenas quando @mencionado. As respostas citam a mensagem original.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="wecom"></a>
|
||||
<details>
|
||||
<summary><b>WeCom (企业微信)</b></summary>
|
||||
@@ -379,7 +221,6 @@ Veja o [Guia de Configuração do WeCom](../channels/wecom/README.pt-br.md) para
|
||||
}
|
||||
```
|
||||
|
||||
> O webhook do WeCom é servido no servidor Gateway compartilhado (`gateway.host`:`gateway.port`, padrão `127.0.0.1:18790`).
|
||||
|
||||
**Configuração Rápida - WeCom App:**
|
||||
|
||||
|
||||
+1
-160
@@ -4,19 +4,15 @@
|
||||
|
||||
## 💬 Ứng Dụng Chat
|
||||
|
||||
Trò chuyện với picoclaw của bạn qua Telegram, Discord, WhatsApp, QQ, DingTalk, LINE, WeCom, Feishu, OneBot, MQTT
|
||||
Trò chuyện với picoclaw của bạn qua Telegram, QQ, DingTalk, WeCom, Feishu, OneBot, MQTT
|
||||
|
||||
> **Lưu ý**: Tất cả các kênh dựa trên webhook (LINE, WeCom, v.v.) được phục vụ trên một máy chủ HTTP Gateway chung (`gateway.host`:`gateway.port`, mặc định `127.0.0.1:18790`). Không có port riêng cho từng kênh. Lưu ý: Feishu sử dụng chế độ WebSocket/SDK và không sử dụng máy chủ HTTP webhook chung.
|
||||
|
||||
| Kênh | Độ khó | Mô tả | Tài liệu |
|
||||
| -------------------- | ------------------ | ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
|
||||
| **Telegram** | ⭐ Dễ | Khuyến nghị, chuyển giọng nói thành văn bản, long polling (không cần IP công khai) | [Tài liệu](../channels/telegram/README.vi.md) |
|
||||
| **Discord** | ⭐ Dễ | Socket Mode, hỗ trợ nhóm/DM, hệ sinh thái bot phong phú | [Tài liệu](../channels/discord/README.vi.md) |
|
||||
| **WhatsApp** | ⭐ Dễ | Bản địa (quét QR) hoặc Bridge URL | [Tài liệu](#whatsapp) |
|
||||
| **Weixin** | ⭐ Dễ | Quét QR gốc (API Tencent iLink) | [Tài liệu](#weixin) |
|
||||
| **QQ** | ⭐⭐ Trung bình | API bot chính thức, cộng đồng Trung Quốc | [Tài liệu](../channels/qq/README.vi.md) |
|
||||
| **DingTalk** | ⭐⭐ Trung bình | Chế độ Stream (không cần IP công khai), doanh nghiệp | [Tài liệu](../channels/dingtalk/README.vi.md) |
|
||||
| **LINE** | ⭐⭐⭐ Nâng cao | Yêu cầu HTTPS Webhook | [Tài liệu](../channels/line/README.vi.md) |
|
||||
| **WeCom (企业微信)** | ⭐⭐⭐ Nâng cao | Bot nhóm (Webhook), ứng dụng tùy chỉnh (API), AI Bot | [Hướng dẫn](../channels/wecom/README.vi.md) |
|
||||
| **Feishu (飞书)** | ⭐⭐⭐ Nâng cao | Cộng tác doanh nghiệp, nhiều tính năng | [Tài liệu](../channels/feishu/README.vi.md) |
|
||||
| **OneBot** | ⭐⭐ Trung bình | Tương thích NapCat/Go-CQHTTP, hệ sinh thái cộng đồng | [Tài liệu](../channels/onebot/README.vi.md) |
|
||||
@@ -72,110 +68,6 @@ Ban cung co the quan ly skill da cai dat truc tiep tu Telegram:
|
||||
|
||||
</details>
|
||||
|
||||
<a id="discord"></a>
|
||||
<details>
|
||||
<summary><b>Discord</b></summary>
|
||||
|
||||
**1. Tạo bot**
|
||||
|
||||
* Truy cập <https://discord.com/developers/applications>
|
||||
* Tạo ứng dụng → Bot → Add Bot
|
||||
* Sao chép bot token
|
||||
|
||||
**2. Bật intents**
|
||||
|
||||
* Trong cài đặt Bot, bật **MESSAGE CONTENT INTENT**
|
||||
* (Tùy chọn) Bật **SERVER MEMBERS INTENT** nếu bạn muốn sử dụng danh sách cho phép dựa trên dữ liệu thành viên
|
||||
|
||||
**3. Lấy User ID**
|
||||
* Cài đặt Discord → Nâng cao → bật **Developer Mode**
|
||||
* Nhấp chuột phải vào avatar → **Copy User ID**
|
||||
|
||||
**4. Cấu hình**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"discord": {
|
||||
"enabled": true,
|
||||
"type": "discord",
|
||||
"token": "YOUR_BOT_TOKEN",
|
||||
"allow_from": ["YOUR_USER_ID"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**5. Mời bot**
|
||||
|
||||
* OAuth2 → URL Generator
|
||||
* Scopes: `bot`
|
||||
* Bot Permissions: `Send Messages`, `Read Message History`
|
||||
* Mở URL mời được tạo và thêm bot vào server của bạn
|
||||
|
||||
**Tùy chọn: Chế độ kích hoạt nhóm**
|
||||
|
||||
Mặc định bot phản hồi tất cả tin nhắn trong kênh server. Để giới hạn phản hồi chỉ khi @mention, thêm:
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"discord": {
|
||||
"group_trigger": { "mention_only": true }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Bạn cũng có thể kích hoạt bằng tiền tố từ khóa (ví dụ: `!bot`):
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"discord": {
|
||||
"group_trigger": { "prefixes": ["!bot"] }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**6. Chạy**
|
||||
|
||||
```bash
|
||||
picoclaw gateway
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<a id="whatsapp"></a>
|
||||
<details>
|
||||
<summary><b>WhatsApp</b> (native qua whatsmeow)</summary>
|
||||
|
||||
PicoClaw có thể kết nối WhatsApp theo hai cách:
|
||||
|
||||
- **Native (khuyến nghị):** In-process sử dụng [whatsmeow](https://github.com/tulir/whatsmeow). Không cần bridge riêng. Đặt `"use_native": true` và để trống `bridge_url`. Lần chạy đầu tiên, quét mã QR bằng WhatsApp (Thiết bị liên kết). Phiên được lưu trong workspace (ví dụ: `workspace/whatsapp/`). Kênh native là **tùy chọn** để giữ binary mặc định nhỏ; build với `-tags whatsapp_native` (ví dụ: `make build-whatsapp-native` hoặc `go build -tags whatsapp_native ./cmd/...`).
|
||||
- **Bridge:** Kết nối đến bridge WebSocket bên ngoài. Đặt `bridge_url` (ví dụ: `ws://localhost:3001`) và giữ `use_native` là false.
|
||||
|
||||
**Cấu hình (native)**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"whatsapp": {
|
||||
"enabled": true,
|
||||
"type": "whatsapp",
|
||||
"use_native": true,
|
||||
"session_store_path": "",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Nếu `session_store_path` trống, phiên được lưu tại `<workspace>/whatsapp/`. Chạy `picoclaw gateway`; lần chạy đầu tiên, quét mã QR hiển thị trong terminal bằng WhatsApp → Thiết bị liên kết.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="weixin"></a>
|
||||
<details>
|
||||
<summary><b>Weixin</b> (WeChat Cá nhân)</summary>
|
||||
@@ -292,56 +184,6 @@ picoclaw gateway
|
||||
|
||||
</details>
|
||||
|
||||
<a id="line"></a>
|
||||
<details>
|
||||
<summary><b>LINE</b></summary>
|
||||
|
||||
**1. Tạo Tài Khoản LINE Official**
|
||||
|
||||
- Truy cập [LINE Developers Console](https://developers.line.biz/)
|
||||
- Tạo provider → Tạo kênh Messaging API
|
||||
- Sao chép **Channel Secret** và **Channel Access Token**
|
||||
|
||||
**2. Cấu hình**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"line": {
|
||||
"enabled": true,
|
||||
"type": "line",
|
||||
"channel_secret": "YOUR_CHANNEL_SECRET",
|
||||
"channel_access_token": "YOUR_CHANNEL_ACCESS_TOKEN",
|
||||
"webhook_path": "/webhook/line",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> Webhook LINE được phục vụ trên máy chủ Gateway chung (`gateway.host`:`gateway.port`, mặc định `127.0.0.1:18790`).
|
||||
|
||||
**3. Thiết lập Webhook URL**
|
||||
|
||||
LINE yêu cầu HTTPS cho webhook. Sử dụng reverse proxy hoặc tunnel:
|
||||
|
||||
```bash
|
||||
# Ví dụ với ngrok (port mặc định gateway là 18790)
|
||||
ngrok http 18790
|
||||
```
|
||||
|
||||
Sau đó đặt Webhook URL trong LINE Developers Console thành `https://your-domain/webhook/line` và bật **Use webhook**.
|
||||
|
||||
**4. Chạy**
|
||||
|
||||
```bash
|
||||
picoclaw gateway
|
||||
```
|
||||
|
||||
> Trong chat nhóm, bot chỉ phản hồi khi được @mention. Phản hồi trích dẫn tin nhắn gốc.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="wecom"></a>
|
||||
<details>
|
||||
<summary><b>WeCom (企业微信)</b></summary>
|
||||
@@ -379,7 +221,6 @@ Xem [Hướng Dẫn Cấu Hình WeCom](../channels/wecom/README.vi.md) để bi
|
||||
}
|
||||
```
|
||||
|
||||
> Webhook WeCom được phục vụ trên máy chủ Gateway chung (`gateway.host`:`gateway.port`, mặc định `127.0.0.1:18790`).
|
||||
|
||||
**Thiết Lập Nhanh - WeCom App:**
|
||||
|
||||
|
||||
+1
-159
@@ -4,7 +4,7 @@
|
||||
|
||||
## 💬 聊天应用集成 (Chat Apps)
|
||||
|
||||
PicoClaw 支持多种聊天平台,使您的 Agent 能够连接到任何地方,包括 Telegram、Discord、WhatsApp、微信、QQ、钉钉、LINE、企业微信、飞书、OneBot、MQTT 等。
|
||||
PicoClaw 支持多种聊天平台,使您的 Agent 能够连接到任何地方,包括 Telegram、微信、QQ、钉钉、企业微信、飞书、OneBot、MQTT 等。
|
||||
|
||||
> **注意**: 依赖 HTTP 回调的渠道共用同一个 Gateway HTTP 服务器(`gateway.host`:`gateway.port`,默认 `127.0.0.1:18790`),无需为每个渠道单独配置端口。飞书、钉钉、企业微信这类 Socket/Stream 模式渠道不依赖共享 webhook 服务器来接收入站消息。
|
||||
|
||||
@@ -13,12 +13,9 @@ PicoClaw 支持多种聊天平台,使您的 Agent 能够连接到任何地方
|
||||
| 渠道 | 设置难度 | 特性说明 | 文档链接 |
|
||||
| -------------------- | ----------- | ----------------------------------------- | --------------------------------------------------------------------------------------------------------------- |
|
||||
| **Telegram** | ⭐ 简单 | 推荐,支持语音转文字,长轮询无需公网 | [查看文档](../channels/telegram/README.zh.md) |
|
||||
| **Discord** | ⭐ 简单 | Socket Mode,支持群组/私信,Bot 生态成熟 | [查看文档](../channels/discord/README.zh.md) |
|
||||
| **WhatsApp** | ⭐ 简单 | 原生 (QR 扫码) 或 Bridge URL | [查看文档](#whatsapp) |
|
||||
| **微信 (Weixin)** | ⭐ 简单 | 原生扫码(腾讯 iLink API) | [查看文档](#weixin) |
|
||||
| **QQ** | ⭐⭐ 中等 | 官方机器人 API,适合国内社群 | [查看文档](../channels/qq/README.zh.md) |
|
||||
| **钉钉 (DingTalk)** | ⭐⭐ 中等 | Stream 模式无需公网,企业办公首选 | [查看文档](../channels/dingtalk/README.zh.md) |
|
||||
| **LINE** | ⭐⭐⭐ 较难 | 需要 HTTPS Webhook | [查看文档](../channels/line/README.zh.md) |
|
||||
| **企业微信 (WeCom)** | ⭐⭐⭐ 较难 | 官方 AI Bot WebSocket 接入,支持流式回复和媒体消息 | [查看文档](../channels/wecom/README.zh.md) |
|
||||
| **飞书 (Feishu)** | ⭐⭐⭐ 较难 | 企业级协作,功能丰富 | [查看文档](../channels/feishu/README.zh.md) |
|
||||
| **OneBot** | ⭐⭐ 中等 | 兼容 NapCat/Go-CQHTTP,社区生态丰富 | [查看文档](../channels/onebot/README.zh.md) |
|
||||
@@ -76,111 +73,6 @@ Telegram 侧保留的是命令菜单注册能力;通用命令的实际执行
|
||||
|
||||
</details>
|
||||
|
||||
<a id="discord"></a>
|
||||
<details>
|
||||
<summary><b>Discord</b></summary>
|
||||
|
||||
**1. 创建 Bot**
|
||||
|
||||
* 前往 <https://discord.com/developers/applications>
|
||||
* 创建应用 → Bot → 添加 Bot
|
||||
* 复制 Bot Token
|
||||
|
||||
**2. 启用 Intents**
|
||||
|
||||
* 在 Bot 设置中启用 **MESSAGE CONTENT INTENT**
|
||||
* (可选)启用 **SERVER MEMBERS INTENT**(如需基于成员数据的白名单)
|
||||
|
||||
**3. 获取 User ID**
|
||||
|
||||
* Discord 设置 → 高级 → 启用 **开发者模式**
|
||||
* 右键点击头像 → **复制用户 ID**
|
||||
|
||||
**4. 配置**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"discord": {
|
||||
"enabled": true,
|
||||
"type": "discord",
|
||||
"token": "YOUR_BOT_TOKEN",
|
||||
"allow_from": ["YOUR_USER_ID"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**5. 邀请 Bot**
|
||||
|
||||
* OAuth2 → URL Generator
|
||||
* Scopes: `bot`
|
||||
* Bot Permissions: `Send Messages`, `Read Message History`
|
||||
* 打开生成的邀请链接,将 Bot 添加到服务器
|
||||
|
||||
**可选:群组触发模式**
|
||||
|
||||
默认情况下 Bot 会回复服务器频道中的所有消息。如需仅在 @提及时回复:
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"discord": {
|
||||
"group_trigger": { "mention_only": true }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
也可通过关键词前缀触发(如 `!bot`):
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"discord": {
|
||||
"group_trigger": { "prefixes": ["!bot"] }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**6. 运行**
|
||||
|
||||
```bash
|
||||
picoclaw gateway
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<a id="whatsapp"></a>
|
||||
<details>
|
||||
<summary><b>WhatsApp</b>(原生 whatsmeow)</summary>
|
||||
|
||||
PicoClaw 支持两种 WhatsApp 连接方式:
|
||||
|
||||
- **原生(推荐):** 进程内使用 [whatsmeow](https://github.com/tulir/whatsmeow),无需独立 Bridge。设置 `"use_native": true` 并留空 `bridge_url`。首次运行时用 WhatsApp 扫描 QR 码(关联设备)。会话存储在工作区下(如 `workspace/whatsapp/`)。原生渠道为**可选**构建,使用 `-tags whatsapp_native` 编译(如 `make build-whatsapp-native` 或 `go build -tags whatsapp_native ./cmd/...`)。
|
||||
- **Bridge:** 连接外部 WebSocket Bridge。设置 `bridge_url`(如 `ws://localhost:3001`),保持 `use_native` 为 false。
|
||||
|
||||
**配置(原生)**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"whatsapp": {
|
||||
"enabled": true,
|
||||
"type": "whatsapp",
|
||||
"use_native": true,
|
||||
"session_store_path": "",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
如果 `session_store_path` 为空,会话存储在 `<workspace>/whatsapp/`。运行 `picoclaw gateway`;首次运行时在终端扫描 QR 码(WhatsApp → 关联设备)。
|
||||
|
||||
</details>
|
||||
|
||||
<a id="weixin"></a>
|
||||
<details>
|
||||
<summary><b>微信 (Weixin)</b></summary>
|
||||
@@ -297,56 +189,6 @@ picoclaw gateway
|
||||
|
||||
</details>
|
||||
|
||||
<a id="line"></a>
|
||||
<details>
|
||||
<summary><b>LINE</b></summary>
|
||||
|
||||
**1. 创建 LINE Official Account**
|
||||
|
||||
- 前往 [LINE Developers Console](https://developers.line.biz/)
|
||||
- 创建 Provider → 创建 Messaging API Channel
|
||||
- 复制 **Channel Secret** 和 **Channel Access Token**
|
||||
|
||||
**2. 配置**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"line": {
|
||||
"enabled": true,
|
||||
"type": "line",
|
||||
"channel_secret": "YOUR_CHANNEL_SECRET",
|
||||
"channel_access_token": "YOUR_CHANNEL_ACCESS_TOKEN",
|
||||
"webhook_path": "/webhook/line",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> LINE Webhook 挂载在共享 Gateway 服务器上(`gateway.host`:`gateway.port`,默认 `127.0.0.1:18790`)。
|
||||
|
||||
**3. 设置 Webhook URL**
|
||||
|
||||
LINE 要求 HTTPS Webhook。使用反向代理或隧道:
|
||||
|
||||
```bash
|
||||
# 示例:使用 ngrok(Gateway 默认端口 18790)
|
||||
ngrok http 18790
|
||||
```
|
||||
|
||||
然后在 LINE Developers Console 中将 Webhook URL 设置为 `https://your-domain/webhook/line` 并启用 **Use webhook**。
|
||||
|
||||
**4. 运行**
|
||||
|
||||
```bash
|
||||
picoclaw gateway
|
||||
```
|
||||
|
||||
> 在群聊中,Bot 仅在被 @提及时回复。回复会引用原始消息。
|
||||
|
||||
</details>
|
||||
|
||||
<a id="feishu"></a>
|
||||
<details>
|
||||
<summary><b>飞书 (Feishu)</b></summary>
|
||||
|
||||
@@ -149,7 +149,7 @@ dammi le ultime news
|
||||
- Les commandes slash génériques sont exécutées via un chemin unique dans `pkg/agent/loop.go` via `commands.Executor`.
|
||||
- Les adaptateurs de canaux ne consomment plus les commandes génériques localement ; ils transmettent le texte entrant au chemin bus/agent. Telegram enregistre toujours automatiquement au démarrage les commandes prises en charge, comme `/start`, `/help`, `/show`, `/list`, `/use` et `/btw`.
|
||||
- Une commande slash inconnue (par exemple `/foo`) passe au traitement LLM normal.
|
||||
- Une commande enregistrée mais non prise en charge sur le canal actuel (par exemple `/show` sur WhatsApp) renvoie une erreur explicite à l'utilisateur et arrête le traitement ultérieur.
|
||||
- Une commande enregistrée mais non prise en charge sur le canal actuel renvoie une erreur explicite à l'utilisateur et arrête le traitement ultérieur.
|
||||
|
||||
### 🔒 Sandbox de Sécurité
|
||||
|
||||
@@ -208,7 +208,7 @@ Même avec `restrict_to_workspace: false`, l'outil `exec` bloque ces commandes d
|
||||
|
||||
| Clé de configuration | Type | Par défaut | Description |
|
||||
|----------------------|------|------------|-------------|
|
||||
| `tools.exec.allow_remote` | bool | `false` | Autoriser l'outil exec depuis les canaux distants (Telegram/Discord etc.) |
|
||||
| `tools.exec.allow_remote` | bool | `false` | Autoriser l'outil exec depuis les canaux distants (Telegram/Feishu etc.) |
|
||||
| `tools.exec.enable_deny_patterns` | bool | `true` | Activer l'interception des commandes dangereuses |
|
||||
| `tools.exec.custom_deny_patterns` | string[] | `[]` | Patterns regex personnalisés à bloquer |
|
||||
| `tools.exec.custom_allow_patterns` | string[] | `[]` | Patterns regex personnalisés à autoriser |
|
||||
|
||||
@@ -116,7 +116,7 @@ export PICOCLAW_BUILTIN_SKILLS=/path/to/skills
|
||||
- I comandi slash generici vengono eseguiti tramite un unico percorso in `pkg/agent/loop.go` via `commands.Executor`.
|
||||
- Gli adattatori dei canali non consumano più localmente i comandi generici; inoltrano il testo in entrata al percorso bus/agent. Telegram registra ancora automaticamente i comandi supportati all'avvio.
|
||||
- Un comando slash sconosciuto (ad esempio `/foo`) viene passato all'elaborazione LLM come se fosse un messaggio dell'utente.
|
||||
- Un comando registrato ma non supportato sul canale corrente (ad esempio `/show` su WhatsApp) restituisce un errore esplicito all'utente e interrompe l'elaborazione.
|
||||
- Un comando registrato ma non supportato sul canale corrente restituisce un errore esplicito all'utente e interrompe l'elaborazione.
|
||||
|
||||
### Allowlist dei Tool per Agent
|
||||
|
||||
@@ -238,7 +238,7 @@ Anche con `restrict_to_workspace: false`, lo strumento `exec` blocca questi coma
|
||||
|
||||
| Chiave di configurazione | Tipo | Predefinito | Descrizione |
|
||||
|--------------------------|------|-------------|-------------|
|
||||
| `tools.exec.allow_remote` | bool | `false` | Consente lo strumento exec da canali remoti (Telegram/Discord ecc.) |
|
||||
| `tools.exec.allow_remote` | bool | `false` | Consente lo strumento exec da canali remoti (Telegram/Feishu ecc.) |
|
||||
| `tools.exec.enable_deny_patterns` | bool | `true` | Abilita l'intercettazione dei comandi pericolosi |
|
||||
| `tools.exec.custom_deny_patterns` | string[] | `[]` | Pattern regex personalizzati da bloccare |
|
||||
| `tools.exec.custom_allow_patterns` | string[] | `[]` | Pattern regex personalizzati da consentire |
|
||||
|
||||
@@ -150,7 +150,7 @@ dammi le ultime news
|
||||
- 汎用スラッシュコマンドは `pkg/agent/loop.go` 内の `commands.Executor` を通じて統一的に実行されます。
|
||||
- チャネルアダプターはローカルで汎用コマンドを消費しなくなりました。受信テキストを bus/agent パスに転送するだけです。Telegram は起動時に `/start`、`/help`、`/show`、`/list`、`/use`、`/btw` などのサポート済みコマンドを自動登録します。
|
||||
- 未登録のスラッシュコマンド(例: `/foo`)は通常の LLM 処理にパススルーされます。
|
||||
- 登録済みだが現在のチャネルでサポートされていないコマンド(例: WhatsApp での `/show`)は、明示的なユーザー向けエラーを返し、以降の処理を停止します。
|
||||
- 登録済みだが現在のチャネルでサポートされていないコマンドは、明示的なユーザー向けエラーを返し、以降の処理を停止します。
|
||||
|
||||
### 🔒 セキュリティサンドボックス
|
||||
|
||||
@@ -209,7 +209,7 @@ PicoClaw はデフォルトでサンドボックス環境で実行されます
|
||||
|
||||
| 設定キー | 型 | デフォルト値 | 説明 |
|
||||
|----------|------|-------------|------|
|
||||
| `tools.exec.allow_remote` | bool | `false` | リモートチャネル(Telegram/Discord など)からの exec ツール実行を許可 |
|
||||
| `tools.exec.allow_remote` | bool | `false` | リモートチャネル(Telegram/Feishu など)からの exec ツール実行を許可 |
|
||||
| `tools.exec.enable_deny_patterns` | bool | `true` | 危険なコマンドのインターセプトを有効化 |
|
||||
| `tools.exec.custom_deny_patterns` | string[] | `[]` | カスタムブロック正規表現パターン |
|
||||
| `tools.exec.custom_allow_patterns` | string[] | `[]` | カスタム許可正規表現パターン |
|
||||
|
||||
@@ -188,7 +188,7 @@ dammi le ultime news
|
||||
- Unknown slash command (for example `/foo`) passes through to normal LLM processing.
|
||||
- `/new` clears the current session's history and summary, like `/clear`. `/new <prompt>` clears them and immediately runs the supplied prompt; subsequent messages continue that fresh conversation. The model, workspace, and system instructions remain active. Spaces, tabs, and newlines can separate the command from its prompt.
|
||||
- If the same session already has a running or queued task, `/new` (with or without a prompt) replies with the current task's name and asks you to retry later. It does not interrupt the task or queue the new prompt. Other sessions can still use `/new`.
|
||||
- Registered but unsupported command on the current channel (for example `/show` on WhatsApp) returns an explicit user-facing error and stops further processing.
|
||||
- Registered but unsupported command on the current channel returns an explicit user-facing error and stops further processing.
|
||||
|
||||
### Session Isolation
|
||||
|
||||
@@ -455,7 +455,7 @@ Use `mode = lines` when:
|
||||
|
||||
| Config Key | Type | Default | Description |
|
||||
|------------|------|---------|-------------|
|
||||
| `tools.exec.allow_remote` | bool | `false` | Allow exec tool from remote channels (Telegram/Discord etc.) |
|
||||
| `tools.exec.allow_remote` | bool | `false` | Allow exec tool from remote channels (Telegram/Feishu etc.) |
|
||||
| `tools.exec.enable_deny_patterns` | bool | `true` | Enable dangerous command interception |
|
||||
| `tools.exec.custom_deny_patterns` | string[] | `[]` | Custom regex patterns to block |
|
||||
| `tools.exec.custom_allow_patterns` | string[] | `[]` | Custom regex patterns to allow |
|
||||
|
||||
@@ -135,7 +135,7 @@ dammi le ultime news
|
||||
- Generic slash command dilaksanakan melalui satu laluan dalam `pkg/agent/loop.go` melalui `commands.Executor`.
|
||||
- Adapter saluran tidak lagi menggunakan generic command secara setempat; ia memajukan teks masuk ke laluan bus/agent. Telegram masih auto-register arahan yang disokong semasa startup seperti `/start`, `/help`, `/show`, `/list`, `/use`, dan `/btw`.
|
||||
- Slash command yang tidak dikenali (contohnya `/foo`) akan diteruskan ke pemprosesan LLM biasa.
|
||||
- Arahan yang didaftarkan tetapi tidak disokong pada saluran semasa (contohnya `/show` di WhatsApp) akan memulangkan ralat yang jelas kepada pengguna dan menghentikan pemprosesan lanjut.
|
||||
- Arahan yang didaftarkan tetapi tidak disokong pada saluran semasa akan memulangkan ralat yang jelas kepada pengguna dan menghentikan pemprosesan lanjut.
|
||||
|
||||
### 🔒 Security Sandbox
|
||||
|
||||
@@ -194,7 +194,7 @@ Walaupun dengan `restrict_to_workspace: false`, tool `exec` menyekat arahan berb
|
||||
|
||||
| Kunci Config | Jenis | Lalai | Penerangan |
|
||||
| ---------------------------------- | -------- | ------- | ------------------------------------------------------------ |
|
||||
| `tools.exec.allow_remote` | bool | `false` | Benarkan tool exec dari saluran jauh (Telegram/Discord dll.) |
|
||||
| `tools.exec.allow_remote` | bool | `false` | Benarkan tool exec dari saluran jauh (Telegram/Feishu dll.) |
|
||||
| `tools.exec.enable_deny_patterns` | bool | `true` | Aktifkan pemintasan arahan berbahaya |
|
||||
| `tools.exec.custom_deny_patterns` | string[] | `[]` | Corak regex tersuai untuk disekat |
|
||||
| `tools.exec.custom_allow_patterns` | string[] | `[]` | Corak regex tersuai untuk dibenarkan |
|
||||
|
||||
@@ -150,7 +150,7 @@ dammi le ultime news
|
||||
- Comandos slash genéricos são executados através de um único caminho em `pkg/agent/loop.go` via `commands.Executor`.
|
||||
- Os adaptadores de canal não consomem mais comandos genéricos localmente; eles encaminham o texto de entrada para o caminho bus/agent. O Telegram ainda registra automaticamente na inicialização comandos suportados como `/start`, `/help`, `/show`, `/list`, `/use` e `/btw`.
|
||||
- Comando slash desconhecido (por exemplo `/foo`) passa para o processamento normal do LLM.
|
||||
- Comando registrado mas não suportado no canal atual (por exemplo `/show` no WhatsApp) retorna um erro explícito ao usuário e interrompe o processamento.
|
||||
- Comando registrado mas não suportado no canal atual retorna um erro explícito ao usuário e interrompe o processamento.
|
||||
|
||||
### 🔒 Sandbox de Segurança
|
||||
|
||||
@@ -209,7 +209,7 @@ Mesmo com `restrict_to_workspace: false`, a ferramenta `exec` bloqueia estes com
|
||||
|
||||
| Config Key | Type | Default | Description |
|
||||
|------------|------|---------|-------------|
|
||||
| `tools.exec.allow_remote` | bool | `false` | Allow exec tool from remote channels (Telegram/Discord etc.) |
|
||||
| `tools.exec.allow_remote` | bool | `false` | Allow exec tool from remote channels (Telegram/Feishu etc.) |
|
||||
| `tools.exec.enable_deny_patterns` | bool | `true` | Enable dangerous command interception |
|
||||
| `tools.exec.custom_deny_patterns` | string[] | `[]` | Custom regex patterns to block |
|
||||
| `tools.exec.custom_allow_patterns` | string[] | `[]` | Custom regex patterns to allow |
|
||||
|
||||
@@ -150,7 +150,7 @@ dammi le ultime news
|
||||
- Lệnh slash chung được thực thi qua một đường dẫn duy nhất trong `pkg/agent/loop.go` qua `commands.Executor`.
|
||||
- Adapter kênh không còn xử lý lệnh chung cục bộ; chúng chuyển tiếp văn bản đầu vào đến đường dẫn bus/agent. Telegram vẫn tự động đăng ký khi khởi động các lệnh được hỗ trợ như `/start`, `/help`, `/show`, `/list`, `/use`, va `/btw`.
|
||||
- Lệnh slash không xác định (ví dụ `/foo`) được chuyển sang xử lý LLM bình thường.
|
||||
- Lệnh đã đăng ký nhưng không được hỗ trợ trên kênh hiện tại (ví dụ `/show` trên WhatsApp) trả về lỗi rõ ràng cho người dùng và dừng xử lý tiếp.
|
||||
- Lệnh đã đăng ký nhưng không được hỗ trợ trên kênh hiện tại trả về lỗi rõ ràng cho người dùng và dừng xử lý tiếp.
|
||||
|
||||
### 🔒 Sandbox Bảo Mật
|
||||
|
||||
@@ -209,7 +209,7 @@ Ngay cả khi `restrict_to_workspace: false`, công cụ `exec` chặn các lệ
|
||||
|
||||
| Config Key | Type | Default | Description |
|
||||
|------------|------|---------|-------------|
|
||||
| `tools.exec.allow_remote` | bool | `false` | Allow exec tool from remote channels (Telegram/Discord etc.) |
|
||||
| `tools.exec.allow_remote` | bool | `false` | Allow exec tool from remote channels (Telegram/Feishu etc.) |
|
||||
| `tools.exec.enable_deny_patterns` | bool | `true` | Enable dangerous command interception |
|
||||
| `tools.exec.custom_deny_patterns` | string[] | `[]` | Custom regex patterns to block |
|
||||
| `tools.exec.custom_allow_patterns` | string[] | `[]` | Custom regex patterns to allow |
|
||||
|
||||
@@ -182,7 +182,7 @@ dammi le ultime news
|
||||
- 未注册的斜杠命令(例如 `/foo`)会透传给 LLM 按普通输入处理。
|
||||
- `/new` 与 `/clear` 一样,清除当前会话的历史和摘要。`/new <prompt>` 会先清除,再立即执行后面的新问题,后续消息继续这段新对话。当前模型、工作区和系统提示保持生效;命令与问题之间可以使用空格、制表符或换行分隔。
|
||||
- 如果同一会话已有正在执行或等待执行的任务,`/new`(包括带新问题的形式)会回复当前任务名称,提示稍后重试;不会打断旧任务,也不会将新问题加入队列。其他会话仍可使用 `/new`。
|
||||
- 已注册但当前 channel 不支持的命令(例如 WhatsApp 上的 `/show`)会返回明确的用户可见错误,并停止后续处理。
|
||||
- 已注册但当前 channel 不支持的命令会返回明确的用户可见错误,并停止后续处理。
|
||||
|
||||
### Session 隔离
|
||||
|
||||
@@ -321,7 +321,7 @@ PicoClaw 默认在沙箱环境中运行。Agent 只能访问配置的工作区
|
||||
|
||||
| 配置键 | 类型 | 默认值 | 描述 |
|
||||
|--------|------|--------|------|
|
||||
| `tools.exec.allow_remote` | bool | `false` | 允许从远程渠道(Telegram/Discord 等)执行 exec 工具 |
|
||||
| `tools.exec.allow_remote` | bool | `false` | 允许从远程渠道(Telegram/Feishu 等)执行 exec 工具 |
|
||||
| `tools.exec.enable_deny_patterns` | bool | `true` | 启用危险命令拦截 |
|
||||
| `tools.exec.custom_deny_patterns` | string[] | `[]` | 自定义阻止的正则表达式模式 |
|
||||
| `tools.exec.custom_allow_patterns` | string[] | `[]` | 自定义允许的正则表达式模式 |
|
||||
|
||||
@@ -373,20 +373,6 @@ picoclaw agent -m "Hello"
|
||||
"token": "123456:ABC...",
|
||||
"allow_from": ["123456789"]
|
||||
},
|
||||
"discord": {
|
||||
"enabled": true,
|
||||
"type": "discord",
|
||||
"token": "",
|
||||
"allow_from": [""]
|
||||
},
|
||||
"whatsapp": {
|
||||
"enabled": false,
|
||||
"type": "whatsapp",
|
||||
"bridge_url": "ws://localhost:3001",
|
||||
"use_native": false,
|
||||
"session_store_path": "",
|
||||
"allow_from": []
|
||||
},
|
||||
"feishu": {
|
||||
"enabled": false,
|
||||
"type": "feishu",
|
||||
|
||||
@@ -385,20 +385,6 @@ picoclaw agent -m "こんにちは"
|
||||
"token": "123456:ABC...",
|
||||
"allow_from": ["123456789"]
|
||||
},
|
||||
"discord": {
|
||||
"enabled": true,
|
||||
"type": "discord",
|
||||
"token": "",
|
||||
"allow_from": [""]
|
||||
},
|
||||
"whatsapp": {
|
||||
"enabled": false,
|
||||
"type": "whatsapp",
|
||||
"bridge_url": "ws://localhost:3001",
|
||||
"use_native": false,
|
||||
"session_store_path": "",
|
||||
"allow_from": []
|
||||
},
|
||||
"feishu": {
|
||||
"enabled": false,
|
||||
"type": "feishu",
|
||||
|
||||
@@ -609,20 +609,6 @@ picoclaw agent -m "Hello"
|
||||
"token": "123456:ABC...",
|
||||
"allow_from": ["123456789"]
|
||||
},
|
||||
"discord": {
|
||||
"enabled": true,
|
||||
"type": "discord",
|
||||
"token": "",
|
||||
"allow_from": [""]
|
||||
},
|
||||
"whatsapp": {
|
||||
"enabled": false,
|
||||
"type": "whatsapp",
|
||||
"bridge_url": "ws://localhost:3001",
|
||||
"use_native": false,
|
||||
"session_store_path": "",
|
||||
"allow_from": []
|
||||
},
|
||||
"feishu": {
|
||||
"enabled": false,
|
||||
"type": "feishu",
|
||||
|
||||
@@ -373,20 +373,6 @@ picoclaw agent -m "Hello"
|
||||
"token": "123456:ABC...",
|
||||
"allow_from": ["123456789"]
|
||||
},
|
||||
"discord": {
|
||||
"enabled": true,
|
||||
"type": "discord",
|
||||
"token": "",
|
||||
"allow_from": [""]
|
||||
},
|
||||
"whatsapp": {
|
||||
"enabled": false,
|
||||
"type": "whatsapp",
|
||||
"bridge_url": "ws://localhost:3001",
|
||||
"use_native": false,
|
||||
"session_store_path": "",
|
||||
"allow_from": []
|
||||
},
|
||||
"feishu": {
|
||||
"enabled": false,
|
||||
"type": "feishu",
|
||||
|
||||
@@ -373,20 +373,6 @@ picoclaw agent -m "Hello"
|
||||
"token": "123456:ABC...",
|
||||
"allow_from": ["123456789"]
|
||||
},
|
||||
"discord": {
|
||||
"enabled": true,
|
||||
"type": "discord",
|
||||
"token": "",
|
||||
"allow_from": [""]
|
||||
},
|
||||
"whatsapp": {
|
||||
"enabled": false,
|
||||
"type": "whatsapp",
|
||||
"bridge_url": "ws://localhost:3001",
|
||||
"use_native": false,
|
||||
"session_store_path": "",
|
||||
"allow_from": []
|
||||
},
|
||||
"feishu": {
|
||||
"enabled": false,
|
||||
"type": "feishu",
|
||||
|
||||
@@ -503,20 +503,6 @@ picoclaw agent -m "你好"
|
||||
"token": "123456:ABC...",
|
||||
"allow_from": ["123456789"]
|
||||
},
|
||||
"discord": {
|
||||
"enabled": true,
|
||||
"type": "discord",
|
||||
"token": "",
|
||||
"allow_from": [""]
|
||||
},
|
||||
"whatsapp": {
|
||||
"enabled": false,
|
||||
"type": "whatsapp",
|
||||
"bridge_url": "ws://localhost:3001",
|
||||
"use_native": false,
|
||||
"session_store_path": "",
|
||||
"allow_from": []
|
||||
},
|
||||
"feishu": {
|
||||
"enabled": false,
|
||||
"type": "feishu",
|
||||
|
||||
@@ -36,7 +36,7 @@ This guide explains how to configure both for real deployments.
|
||||
}
|
||||
```
|
||||
|
||||
### Route only Discord mentions in one workspace
|
||||
### Route only Feishu mentions in one workspace
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -48,11 +48,11 @@ This guide explains how to configure both for real deployments.
|
||||
"dispatch": {
|
||||
"rules": [
|
||||
{
|
||||
"name": "discord mentions",
|
||||
"name": "feishu mentions",
|
||||
"agent": "support",
|
||||
"when": {
|
||||
"channel": "discord",
|
||||
"space": "guild:t001",
|
||||
"channel": "feishu",
|
||||
"chat": "oc_group001",
|
||||
"mentioned": true
|
||||
}
|
||||
}
|
||||
@@ -109,7 +109,7 @@ If no rule matches, PicoClaw falls back to the default agent.
|
||||
|
||||
| Field | Meaning | Example |
|
||||
| --- | --- | --- |
|
||||
| `channel` | Channel name | `telegram`, `discord`, `feishu` |
|
||||
| `channel` | Channel name | `telegram`, `weixin`, `feishu` |
|
||||
| `account` | Normalized account ID | `default`, `bot2` |
|
||||
| `space` | Workspace, guild, or similar container | `guild:t001`, `guild:123456` |
|
||||
| `chat` | Direct chat, group, or channel | `direct:user123`, `group:-100123`, `channel:c123` |
|
||||
@@ -202,7 +202,7 @@ Example:
|
||||
{
|
||||
"session": {
|
||||
"identity_links": {
|
||||
"john": ["discord:u123", "legacy-user-42"]
|
||||
"john": ["feishu:u123", "legacy-user-42"]
|
||||
}
|
||||
},
|
||||
"agents": {
|
||||
|
||||
@@ -36,7 +36,7 @@ PicoClaw 里用户能直接感知到的“路由”主要有两部分:
|
||||
}
|
||||
```
|
||||
|
||||
### 只处理某个 Discord server 里的 @提及
|
||||
### 只处理某个 Feishu group 里的 @提及
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -48,11 +48,11 @@ PicoClaw 里用户能直接感知到的“路由”主要有两部分:
|
||||
"dispatch": {
|
||||
"rules": [
|
||||
{
|
||||
"name": "discord mentions",
|
||||
"name": "feishu mentions",
|
||||
"agent": "support",
|
||||
"when": {
|
||||
"channel": "discord",
|
||||
"space": "guild:t001",
|
||||
"channel": "feishu",
|
||||
"chat": "oc_group001",
|
||||
"mentioned": true
|
||||
}
|
||||
}
|
||||
@@ -109,7 +109,7 @@ agents.dispatch.rules
|
||||
|
||||
| 字段 | 含义 | 示例 |
|
||||
| --- | --- | --- |
|
||||
| `channel` | Channel 名称 | `telegram`、`discord`、`feishu` |
|
||||
| `channel` | Channel 名称 | `telegram`、`weixin`、`feishu` |
|
||||
| `account` | 归一化后的 account ID | `default`、`bot2` |
|
||||
| `space` | workspace、guild 等上层容器 | `guild:t001`、`guild:123456` |
|
||||
| `chat` | 私聊、群或频道 | `direct:user123`、`group:-100123`、`channel:c123` |
|
||||
@@ -202,7 +202,7 @@ agents.dispatch.rules
|
||||
{
|
||||
"session": {
|
||||
"identity_links": {
|
||||
"john": ["discord:u123", "legacy-user-42"]
|
||||
"john": ["feishu:u123", "legacy-user-42"]
|
||||
}
|
||||
},
|
||||
"agents": {
|
||||
|
||||
@@ -73,8 +73,8 @@ If your channel exposes a `space` value, you can route by workspace or guild ins
|
||||
|
||||
Use this when:
|
||||
|
||||
- a Discord server assistant should share context across channels
|
||||
- a Discord guild assistant should share context across channels
|
||||
- a Feishu group assistant should share context across channels
|
||||
- a Feishu group assistant should share context across channels
|
||||
|
||||
### Split by thread or forum topic
|
||||
|
||||
@@ -212,7 +212,7 @@ Example:
|
||||
"session": {
|
||||
"dimensions": ["chat", "sender"],
|
||||
"identity_links": {
|
||||
"john": ["discord:u123", "u123", "legacy-user-42"]
|
||||
"john": ["feishu:u123", "u123", "legacy-user-42"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -244,7 +244,7 @@ Switch to:
|
||||
}
|
||||
```
|
||||
|
||||
### The same user does not share memory across Discord and Telegram
|
||||
### The same user does not share memory across Feishu and Telegram
|
||||
|
||||
That is expected.
|
||||
PicoClaw still separates sessions by channel even if you use `sender`.
|
||||
|
||||
@@ -73,8 +73,8 @@ Session 数据保存在工作区目录下,通常是:
|
||||
|
||||
适用场景:
|
||||
|
||||
- Discord server 里的 assistant 想跨多个 channel 共享上下文
|
||||
- Discord guild 里的 assistant 想跨多个 channel 共享上下文
|
||||
- Feishu group 里的 assistant 想跨多个 channel 共享上下文
|
||||
- Feishu group 里的 assistant 想跨多个 channel 共享上下文
|
||||
|
||||
### 按线程或论坛 topic 隔离
|
||||
|
||||
@@ -212,7 +212,7 @@ Telegram forum 消息在默认 `chat` 模式下就会保留 topic 隔离。
|
||||
"session": {
|
||||
"dimensions": ["chat", "sender"],
|
||||
"identity_links": {
|
||||
"john": ["discord:u123", "u123", "legacy-user-42"]
|
||||
"john": ["feishu:u123", "u123", "legacy-user-42"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -244,7 +244,7 @@ Telegram forum 消息在默认 `chat` 模式下就会保留 topic 隔离。
|
||||
}
|
||||
```
|
||||
|
||||
### 同一个用户在 Discord 和 Telegram 之间没有共享记忆
|
||||
### 同一个用户在 Feishu 和 Telegram 之间没有共享记忆
|
||||
|
||||
这是当前实现下的预期行为。
|
||||
即使使用了 `sender`,PicoClaw 仍然会按 channel 做基础隔离。
|
||||
|
||||
@@ -365,13 +365,10 @@ Parlez à votre PicoClaw via plus de 17 plateformes de messagerie :
|
||||
| Channel | Configuration | Protocole | Docs |
|
||||
|---------|---------------|-----------|------|
|
||||
| **Telegram** | Facile (token bot) | Long polling | [Guide](../channels/telegram/README.fr.md) |
|
||||
| **Discord** | Facile (token bot + intents) | WebSocket | [Guide](../channels/discord/README.fr.md) |
|
||||
| **WhatsApp** | Facile (scan QR ou URL bridge) | Natif / Bridge | [Guide](../guides/chat-apps.fr.md#whatsapp) |
|
||||
| **Weixin** | Facile (scan QR natif) | iLink API | [Guide](../guides/chat-apps.fr.md#weixin) |
|
||||
| **QQ** | Facile (AppID + AppSecret) | WebSocket | [Guide](../channels/qq/README.fr.md) |
|
||||
| **DingTalk** | Moyen (identifiants client) | Stream | [Guide](../channels/dingtalk/README.fr.md) |
|
||||
| **Feishu / Lark** | Moyen (App ID + Secret) | WebSocket/SDK | [Guide](../channels/feishu/README.fr.md) |
|
||||
| **LINE** | Moyen (identifiants + webhook) | Webhook | [Guide](../channels/line/README.fr.md) |
|
||||
| **WeCom** | Facile (QR login ou manuel) | WebSocket | [Guide](../channels/wecom/README.fr.md) |
|
||||
| **OneBot** | Moyen (URL WebSocket) | OneBot v11 | [Guide](../channels/onebot/README.fr.md) |
|
||||
|
||||
|
||||
@@ -364,13 +364,10 @@ Bicara dengan PicoClaw Anda melalui 17+ platform pesan:
|
||||
| Channel | Pengaturan | Protocol | Dokumentasi |
|
||||
|---------|------------|----------|-------------|
|
||||
| **Telegram** | Mudah (bot token) | Long polling | [Panduan](../channels/telegram/README.md) |
|
||||
| **Discord** | Mudah (bot token + intents) | WebSocket | [Panduan](../channels/discord/README.md) |
|
||||
| **WhatsApp** | Mudah (scan QR atau bridge URL) | Native / Bridge | [Panduan](../guides/chat-apps.md#whatsapp) |
|
||||
| **Weixin** | Mudah (scan QR native) | iLink API | [Panduan](../guides/chat-apps.md#weixin) |
|
||||
| **QQ** | Mudah (AppID + AppSecret) | WebSocket | [Panduan](../channels/qq/README.md) |
|
||||
| **DingTalk** | Sedang (client credentials) | Stream | [Panduan](../channels/dingtalk/README.md) |
|
||||
| **Feishu / Lark** | Sedang (App ID + Secret) | WebSocket/SDK | [Panduan](../channels/feishu/README.md) |
|
||||
| **LINE** | Sedang (credentials + webhook) | Webhook | [Panduan](../channels/line/README.md) |
|
||||
| **WeCom** | Mudah (login QR atau manual) | WebSocket | [Panduan](../channels/wecom/README.md) |
|
||||
| **OneBot** | Sedang (WebSocket URL) | OneBot v11 | [Panduan](../channels/onebot/README.md) |
|
||||
|
||||
|
||||
@@ -364,13 +364,10 @@ Parla con il tuo PicoClaw attraverso 17+ piattaforme di messaggistica:
|
||||
| Channel | Configurazione | Protocollo | Docs |
|
||||
|---------|----------------|------------|------|
|
||||
| **Telegram** | Facile (bot token) | Long polling | [Guida](../channels/telegram/README.md) |
|
||||
| **Discord** | Facile (bot token + intents) | WebSocket | [Guida](../channels/discord/README.md) |
|
||||
| **WhatsApp** | Facile (QR scan o bridge URL) | Nativo / Bridge | [Guida](../guides/chat-apps.md#whatsapp) |
|
||||
| **Weixin** | Facile (scan QR nativo) | iLink API | [Guida](../guides/chat-apps.md#weixin) |
|
||||
| **QQ** | Facile (AppID + AppSecret) | WebSocket | [Guida](../channels/qq/README.md) |
|
||||
| **DingTalk** | Medio (credenziali client) | Stream | [Guida](../channels/dingtalk/README.md) |
|
||||
| **Feishu / Lark** | Medio (App ID + Secret) | WebSocket/SDK | [Guida](../channels/feishu/README.md) |
|
||||
| **LINE** | Medio (credenziali + webhook) | Webhook | [Guida](../channels/line/README.md) |
|
||||
| **WeCom** | Facile (login QR o manuale) | WebSocket | [Guida](../channels/wecom/README.md) |
|
||||
| **OneBot** | Medio (WebSocket URL) | OneBot v11 | [Guida](../channels/onebot/README.md) |
|
||||
|
||||
|
||||
@@ -365,13 +365,10 @@ Provider の完全な設定詳細は [Provider とモデル](../guides/providers
|
||||
| Channel | セットアップ | Protocol | ドキュメント |
|
||||
|---------|------------|----------|------------|
|
||||
| **Telegram** | 簡単(bot トークン) | Long polling | [ガイド](../channels/telegram/README.ja.md) |
|
||||
| **Discord** | 簡単(bot トークン + intents) | WebSocket | [ガイド](../channels/discord/README.ja.md) |
|
||||
| **WhatsApp** | 簡単(QR スキャンまたは bridge URL) | Native / Bridge | [ガイド](../guides/chat-apps.ja.md#whatsapp) |
|
||||
| **微信 (Weixin)** | 簡単(QR スキャン) | iLink API | [ガイド](../guides/chat-apps.ja.md#weixin) |
|
||||
| **QQ** | 簡単(AppID + AppSecret) | WebSocket | [ガイド](../channels/qq/README.ja.md) |
|
||||
| **DingTalk** | 中級(クライアント認証情報) | Stream | [ガイド](../channels/dingtalk/README.ja.md) |
|
||||
| **Feishu / Lark** | 中級(App ID + Secret) | WebSocket/SDK | [ガイド](../channels/feishu/README.ja.md) |
|
||||
| **LINE** | 中級(認証情報 + webhook) | Webhook | [ガイド](../channels/line/README.ja.md) |
|
||||
| **WeCom** | 簡単(QR ログインまたは手動) | WebSocket | [ガイド](../channels/wecom/README.ja.md) |
|
||||
| **OneBot** | 中級(WebSocket URL) | OneBot v11 | [ガイド](../channels/onebot/README.ja.md) |
|
||||
|
||||
|
||||
@@ -367,13 +367,10 @@ PicoClaw는 `model_list` 설정을 통해 30개 이상의 LLM 프로바이더를
|
||||
| 채널 | 설정 | 프로토콜 | 문서 |
|
||||
|---------|------|----------|------|
|
||||
| **Telegram** | 쉬움(봇 토큰) | Long polling | [가이드](../channels/telegram/README.md) |
|
||||
| **Discord** | 쉬움(봇 토큰 + intents) | WebSocket | [가이드](../channels/discord/README.md) |
|
||||
| **WhatsApp** | 쉬움(QR 스캔 또는 브리지 URL) | Native / Bridge | [가이드](../guides/chat-apps.md#whatsapp) |
|
||||
| **Weixin** | 쉬움(네이티브 QR 스캔) | iLink API | [가이드](../guides/chat-apps.md#weixin) |
|
||||
| **QQ** | 쉬움(AppID + AppSecret) | WebSocket | [가이드](../channels/qq/README.md) |
|
||||
| **DingTalk** | 중간(클라이언트 자격 증명) | Stream | [가이드](../channels/dingtalk/README.md) |
|
||||
| **Feishu / Lark** | 중간(App ID + Secret) | WebSocket/SDK | [가이드](../channels/feishu/README.md) |
|
||||
| **LINE** | 중간(인증 정보 + webhook) | Webhook | [가이드](../channels/line/README.md) |
|
||||
| **WeCom** | 쉬움(QR 로그인 또는 수동 설정) | WebSocket | [가이드](../channels/wecom/README.md) |
|
||||
| **OneBot** | 중간(WebSocket URL) | OneBot v11 | [가이드](../channels/onebot/README.md) |
|
||||
|
||||
|
||||
@@ -362,13 +362,10 @@ Bercakap dengan PicoClaw anda melalui 17+ platform pemesejan:
|
||||
| Saluran | Persediaan | Protokol | Dok |
|
||||
|---------|-----------|----------|-----|
|
||||
| **Telegram** | Mudah (token bot) | Long polling | [Panduan](../channels/telegram/README.md) |
|
||||
| **Discord** | Mudah (token bot + intents) | WebSocket | [Panduan](../channels/discord/README.md) |
|
||||
| **WhatsApp** | Mudah (imbas QR atau URL jambatan) | Natif / Jambatan | [Panduan](../guides/chat-apps.ms.md#whatsapp) |
|
||||
| **Weixin** | Mudah (imbas QR natif) | iLink API | [Panduan](../guides/chat-apps.ms.md#weixin) |
|
||||
| **QQ** | Mudah (AppID + AppSecret) | WebSocket | [Panduan](../channels/qq/README.md) |
|
||||
| **DingTalk** | Sederhana (kelayakan klien) | Stream | [Panduan](../channels/dingtalk/README.md) |
|
||||
| **Feishu / Lark** | Sederhana (App ID + Secret) | WebSocket/SDK | [Panduan](../channels/feishu/README.md) |
|
||||
| **LINE** | Sederhana (kelayakan + webhook) | Webhook | [Panduan](../channels/line/README.md) |
|
||||
| **WeCom** | Mudah (log masuk QR atau manual) | WebSocket | [Panduan](../channels/wecom/README.md) |
|
||||
| **OneBot** | Sederhana (URL WebSocket) | OneBot v11 | [Panduan](../channels/onebot/README.md) |
|
||||
|
||||
|
||||
@@ -365,13 +365,10 @@ Converse com seu PicoClaw por meio de mais de 17 plataformas de mensagens:
|
||||
| Channel | Configuração | Protocolo | Docs |
|
||||
|---------|--------------|-----------|------|
|
||||
| **Telegram** | Fácil (bot token) | Long polling | [Guia](../channels/telegram/README.pt-br.md) |
|
||||
| **Discord** | Fácil (bot token + intents) | WebSocket | [Guia](../channels/discord/README.pt-br.md) |
|
||||
| **WhatsApp** | Fácil (QR scan ou bridge URL) | Nativo / Bridge | [Guia](../guides/chat-apps.pt-br.md#whatsapp) |
|
||||
| **Weixin** | Fácil (scan QR nativo) | iLink API | [Guia](../guides/chat-apps.pt-br.md#weixin) |
|
||||
| **QQ** | Fácil (AppID + AppSecret) | WebSocket | [Guia](../channels/qq/README.pt-br.md) |
|
||||
| **DingTalk** | Médio (credenciais do cliente) | Stream | [Guia](../channels/dingtalk/README.pt-br.md) |
|
||||
| **Feishu / Lark** | Médio (App ID + Secret) | WebSocket/SDK | [Guia](../channels/feishu/README.pt-br.md) |
|
||||
| **LINE** | Médio (credenciais + webhook) | Webhook | [Guia](../channels/line/README.pt-br.md) |
|
||||
| **WeCom** | Fácil (login QR ou manual) | WebSocket | [Guia](../channels/wecom/README.pt-br.md) |
|
||||
| **OneBot** | Médio (WebSocket URL) | OneBot v11 | [Guia](../channels/onebot/README.pt-br.md) |
|
||||
|
||||
|
||||
@@ -365,13 +365,10 @@ Trò chuyện với PicoClaw của bạn qua 17+ nền tảng nhắn tin:
|
||||
| Channel | Thiết lập | Protocol | Tài liệu |
|
||||
|---------|-----------|----------|----------|
|
||||
| **Telegram** | Dễ (bot token) | Long polling | [Hướng dẫn](../channels/telegram/README.vi.md) |
|
||||
| **Discord** | Dễ (bot token + intents) | WebSocket | [Hướng dẫn](../channels/discord/README.vi.md) |
|
||||
| **WhatsApp** | Dễ (quét QR hoặc bridge URL) | Native / Bridge | [Hướng dẫn](../guides/chat-apps.vi.md#whatsapp) |
|
||||
| **Weixin** | Dễ (quét QR gốc) | iLink API | [Hướng dẫn](../guides/chat-apps.vi.md#weixin) |
|
||||
| **QQ** | Dễ (AppID + AppSecret) | WebSocket | [Hướng dẫn](../channels/qq/README.vi.md) |
|
||||
| **DingTalk** | Trung bình (client credentials) | Stream | [Hướng dẫn](../channels/dingtalk/README.vi.md) |
|
||||
| **Feishu / Lark** | Trung bình (App ID + Secret) | WebSocket/SDK | [Hướng dẫn](../channels/feishu/README.vi.md) |
|
||||
| **LINE** | Trung bình (credentials + webhook) | Webhook | [Hướng dẫn](../channels/line/README.vi.md) |
|
||||
| **WeCom** | Dễ (đăng nhập QR hoặc thủ công) | WebSocket | [Hướng dẫn](../channels/wecom/README.vi.md) |
|
||||
| **OneBot** | Trung bình (WebSocket URL) | OneBot v11 | [Hướng dẫn](../channels/onebot/README.vi.md) |
|
||||
|
||||
|
||||
@@ -365,13 +365,10 @@ PicoClaw 通过 `model_list` 配置支持 30+ LLM Provider,使用 `协议/模
|
||||
| Channel | 配置难度 | 协议 | 文档 |
|
||||
|---------|----------|------|------|
|
||||
| **Telegram** | 简单(bot token) | 长轮询 | [指南](../channels/telegram/README.zh.md) |
|
||||
| **Discord** | 简单(bot token + intents) | WebSocket | [指南](../channels/discord/README.zh.md) |
|
||||
| **WhatsApp** | 简单(扫码或 bridge URL) | 原生 / Bridge | [指南](../guides/chat-apps.zh.md#whatsapp) |
|
||||
| **微信 (Weixin)** | 简单(扫码登录) | iLink API | [指南](../guides/chat-apps.zh.md#weixin) |
|
||||
| **QQ** | 简单(AppID + AppSecret) | WebSocket | [指南](../channels/qq/README.zh.md) |
|
||||
| **钉钉** | 中等(client credentials) | Stream | [指南](../channels/dingtalk/README.zh.md) |
|
||||
| **飞书 / Lark** | 中等(App ID + Secret) | WebSocket/SDK | [指南](../channels/feishu/README.zh.md) |
|
||||
| **LINE** | 中等(credentials + webhook) | Webhook | [指南](../channels/line/README.zh.md) |
|
||||
| **企业微信** | 简单(扫码登录或手动配置) | WebSocket | [指南](../channels/wecom/README.zh.md) |
|
||||
| **OneBot** | 中等(WebSocket URL) | OneBot v11 | [指南](../channels/onebot/README.zh.md) |
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ PicoClaw uses a schema versioning system for `config.json` to ensure smooth upgr
|
||||
- **Changes**:
|
||||
- Added `enabled` field to `ModelConfig` — allows disabling individual model entries without removing them
|
||||
- During V1→V2 migration, `enabled` is auto-inferred: models with API keys or the reserved `local-model` name are enabled; others default to disabled
|
||||
- Migrated legacy channel fields: Discord `mention_only` → `group_trigger.mention_only`, OneBot `group_trigger_prefix` → `group_trigger.prefixes`
|
||||
- Migrated legacy channel fields: Channel `mention_only` → `group_trigger.mention_only`, OneBot `group_trigger_prefix` → `group_trigger.prefixes`
|
||||
- V0 configs now migrate directly to CurrentVersion (V2) instead of going through V1
|
||||
- `makeBackup()` now uses date-only suffix (e.g., `config.json.20260330.bak`) and also backs up `.security.yml`
|
||||
|
||||
|
||||
@@ -53,17 +53,12 @@ channels:
|
||||
app_secret: "your-feishu-app-secret"
|
||||
encrypt_key: "your-feishu-encrypt-key"
|
||||
verification_token: "your-feishu-verification-token"
|
||||
discord:
|
||||
token: "your-discord-bot-token"
|
||||
weixin:
|
||||
token: "your-weixin-token"
|
||||
qq:
|
||||
app_secret: "your-qq-app-secret"
|
||||
dingtalk:
|
||||
client_secret: "your-dingtalk-client-secret"
|
||||
line:
|
||||
channel_secret: "your-line-channel-secret"
|
||||
channel_access_token: "your-line-channel-access-token"
|
||||
onebot:
|
||||
access_token: "your-onebot-access-token"
|
||||
wecom:
|
||||
@@ -215,8 +210,6 @@ channels:
|
||||
app_secret: "value"
|
||||
encrypt_key: "value"
|
||||
verification_token: "value"
|
||||
discord:
|
||||
token: "value"
|
||||
```
|
||||
|
||||
**Mapping:**
|
||||
|
||||
@@ -11,7 +11,7 @@ When the LLM uses a tool that returns its own credentials (e.g., a tool that ech
|
||||
Sensitive values are collected from [`.security.yml`](./credential_encryption.md) — the centralized storage for all sensitive configuration (API keys, tokens, secrets stored alongside `config.json`). This includes:
|
||||
|
||||
- Model API keys
|
||||
- Channel tokens (Telegram, Discord, etc.)
|
||||
- Channel tokens (Telegram, etc.)
|
||||
- Web tool API keys (Brave, Tavily, Perplexity, etc.)
|
||||
- Skills tokens (GitHub, ClawHub)
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ PicoClaw 可以从工具调用结果中过滤敏感值(API 密钥、令牌、
|
||||
敏感值从 `.security.yml` 中收集 —— 这是所有敏感配置的集中存储,包括:
|
||||
|
||||
- 模型 API 密钥
|
||||
- 频道令牌(Telegram、Discord 等)
|
||||
- 频道令牌(Telegram 等)
|
||||
- Web 工具 API 密钥(Brave、Tavily、Perplexity 等)
|
||||
- 技能令牌(GitHub、ClawHub)
|
||||
|
||||
|
||||
@@ -10,7 +10,6 @@ require (
|
||||
github.com/aws/aws-sdk-go-v2 v1.42.0
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.25
|
||||
github.com/aws/aws-sdk-go-v2/service/bedrockruntime v1.53.3
|
||||
github.com/bwmarrin/discordgo v0.29.0
|
||||
github.com/caarlos0/env/v11 v11.4.1
|
||||
github.com/charmbracelet/lipgloss v1.1.0
|
||||
github.com/creack/pty v1.1.24
|
||||
@@ -22,7 +21,6 @@ require (
|
||||
github.com/h2non/filetype v1.1.3
|
||||
github.com/kagisearch/kagi-openapi-golang v0.0.0-20260526215348-96575e864d62
|
||||
github.com/larksuite/oapi-sdk-go/v3 v3.9.4
|
||||
github.com/line/line-bot-sdk-go/v8 v8.20.1
|
||||
github.com/mdp/qrterminal/v3 v3.2.1
|
||||
github.com/minio/selfupdate v0.6.0
|
||||
github.com/modelcontextprotocol/go-sdk v1.6.1
|
||||
@@ -39,18 +37,15 @@ require (
|
||||
github.com/stretchr/testify v1.11.1
|
||||
github.com/tencent-connect/botgo v0.2.1
|
||||
go.mau.fi/util v0.9.8
|
||||
go.mau.fi/whatsmeow v0.0.0-20260219150138-7ae702b1eed4
|
||||
golang.org/x/oauth2 v0.36.0
|
||||
golang.org/x/term v0.44.0
|
||||
golang.org/x/time v0.15.0
|
||||
google.golang.org/protobuf v1.36.11
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
modernc.org/sqlite v1.53.0
|
||||
)
|
||||
|
||||
require (
|
||||
aead.dev/minisign v0.2.0 // indirect
|
||||
filippo.io/edwards25519 v1.2.0 // indirect
|
||||
github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v1.7.2 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.12 // indirect
|
||||
@@ -68,17 +63,13 @@ require (
|
||||
github.com/aws/smithy-go v1.27.1 // indirect
|
||||
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
|
||||
github.com/bahlo/generic-list-go v0.2.0 // indirect
|
||||
github.com/beeper/argo-go v1.1.2 // indirect
|
||||
github.com/buger/jsonparser v1.1.2 // indirect
|
||||
github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect
|
||||
github.com/charmbracelet/x/ansi v0.8.0 // indirect
|
||||
github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd // indirect
|
||||
github.com/charmbracelet/x/term v0.2.1 // indirect
|
||||
github.com/cloudflare/circl v1.6.3 // indirect
|
||||
github.com/coder/websocket v1.8.14 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/elliotchance/orderedmap/v3 v3.1.0 // indirect
|
||||
github.com/go-logr/logr v1.4.3 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1 // indirect
|
||||
@@ -91,7 +82,6 @@ require (
|
||||
github.com/mattn/go-runewidth v0.0.16 // indirect
|
||||
github.com/ncruces/go-strftime v1.0.0 // indirect
|
||||
github.com/pb33f/ordered-map/v2 v2.3.1 // indirect
|
||||
github.com/petermattis/goid v0.0.0-20260330135022-df67b199bc81 // indirect
|
||||
github.com/pion/randutil v0.1.0 // indirect
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
@@ -99,15 +89,12 @@ require (
|
||||
github.com/segmentio/asm v1.1.3 // indirect
|
||||
github.com/segmentio/encoding v0.5.4 // indirect
|
||||
github.com/standard-webhooks/standard-webhooks/libraries v0.0.1 // indirect
|
||||
github.com/vektah/gqlparser/v2 v2.5.27 // indirect
|
||||
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
|
||||
go.mau.fi/libsignal v0.2.1 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.1.0 // indirect
|
||||
go.opentelemetry.io/otel v1.35.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.35.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.35.0 // indirect
|
||||
go.yaml.in/yaml/v4 v4.0.0-rc.2 // indirect
|
||||
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f // indirect
|
||||
golang.org/x/text v0.39.0 // indirect
|
||||
modernc.org/libc v1.73.4 // indirect
|
||||
modernc.org/mathutil v1.7.1 // indirect
|
||||
@@ -143,5 +130,3 @@ require (
|
||||
golang.org/x/sync v0.21.0 // indirect
|
||||
golang.org/x/sys v0.46.0
|
||||
)
|
||||
|
||||
replace github.com/bwmarrin/discordgo => github.com/yeongaori/discordgo-fork v0.0.0-20260319072544-e8e546f5d532
|
||||
@@ -1,8 +1,6 @@
|
||||
aead.dev/minisign v0.2.0 h1:kAWrq/hBRu4AARY6AlciO83xhNnW9UaC8YipS2uhLPk=
|
||||
aead.dev/minisign v0.2.0/go.mod h1:zdq6LdSd9TbuSxchxwhpA9zEb9YXcVGoE8JakuiGaIQ=
|
||||
cloud.google.com/go/compute/metadata v0.3.0/go.mod h1:zFmK7XCadkQkj6TtorcaGlCW1hT1fIilQDwofLpJ20k=
|
||||
filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo=
|
||||
filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.0 h1:CU4+EJeJi3TKYWEcYuSdWsjzw0nVsK/H0MSQOiPcymU=
|
||||
@@ -15,14 +13,8 @@ github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1 h1:WJ
|
||||
github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1/go.mod h1:tCcJZ0uHAmvjsVYzEFivsRTN00oz5BEsRgQHu5JZ9WE=
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v1.7.2 h1:RHK7bS+HQMslb1sZpAokUt+zTVmue0hKSs2C791hhzU=
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v1.7.2/go.mod h1:HKpQxkWaGLJ+D/5H8QRpyQXA1eKjxkFlOMwck5+33Jk=
|
||||
github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7OputlJIzU=
|
||||
github.com/DATA-DOG/go-sqlmock v1.5.2/go.mod h1:88MAG/4G7SMwSE3CeA0ZKzrT5CiOU3OJ+JlNzwDqpNU=
|
||||
github.com/adhocore/gronx v1.20.0 h1:PD13Mo0wekkZ7ZZR9yb1TqeqTfybs7/K3ez9DmjQwEs=
|
||||
github.com/adhocore/gronx v1.20.0/go.mod h1:7oUY1WAU8rEJWmAxXR2DN0JaO4gi9khSgKjiRypqteg=
|
||||
github.com/agnivade/levenshtein v1.2.1 h1:EHBY3UOn1gwdy/VbFwgo4cxecRznFk7fKWN1KOX7eoM=
|
||||
github.com/agnivade/levenshtein v1.2.1/go.mod h1:QVVI16kDrtSuwcpd0p1+xMC6Z/VfhtCyDIjcwga4/DU=
|
||||
github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883 h1:bvNMNQO63//z+xNgfBlViaCIJKLlCJ6/fmUseuG0wVQ=
|
||||
github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8=
|
||||
github.com/andybalholm/brotli v1.2.1 h1:R+f5xP285VArJDRgowrfb9DqL18yVK0gKAW/F+eTWro=
|
||||
github.com/andybalholm/brotli v1.2.1/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
|
||||
github.com/anthropics/anthropic-sdk-go v1.55.1 h1:GxukHUVou6AFIngxa/Aw1z79hmwg13Hmn++KE9werbM=
|
||||
@@ -63,8 +55,6 @@ github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiE
|
||||
github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
|
||||
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
|
||||
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
|
||||
github.com/beeper/argo-go v1.1.2 h1:UQI2G8F+NLfGTOmTUI0254pGKx/HUU/etbUGTJv91Fs=
|
||||
github.com/beeper/argo-go v1.1.2/go.mod h1:M+LJAnyowKVQ6Rdj6XYGEn+qcVFkb3R/MUpqkGR0hM4=
|
||||
github.com/buger/jsonparser v1.1.2 h1:frqHqw7otoVbk5M8LlE/L7HTnIq2v9RX6EJ48i9AxJk=
|
||||
github.com/buger/jsonparser v1.1.2/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
|
||||
github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M=
|
||||
@@ -87,12 +77,8 @@ github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd h1:vy0G
|
||||
github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs=
|
||||
github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ=
|
||||
github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg=
|
||||
github.com/cloudflare/circl v1.6.3 h1:9GPOhQGF9MCYUeXyMYlqTR6a5gTrgR/fBLXvUgtVcg8=
|
||||
github.com/cloudflare/circl v1.6.3/go.mod h1:2eXP6Qfat4O/Yhh8BznvKnJ+uzEoTQ6jVKJRn81BiS4=
|
||||
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
|
||||
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
|
||||
github.com/coder/websocket v1.8.14 h1:9L0p0iKiNOibykf283eHkKUHHrpG7f65OE3BhhO7v9g=
|
||||
github.com/coder/websocket v1.8.14/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
|
||||
@@ -107,8 +93,6 @@ github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkp
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/eclipse/paho.mqtt.golang v1.5.1 h1:/VSOv3oDLlpqR2Epjn1Q7b2bSTplJIeV2ISgCl2W7nE=
|
||||
github.com/eclipse/paho.mqtt.golang v1.5.1/go.mod h1:1/yJCneuyOoCOzKSsOTUc0AJfpsItBGWvYpBLimhArU=
|
||||
github.com/elliotchance/orderedmap/v3 v3.1.0 h1:j4DJ5ObEmMBt/lcwIecKcoRxIQUEnw0L804lXYDt/pg=
|
||||
github.com/elliotchance/orderedmap/v3 v3.1.0/go.mod h1:G+Hc2RwaZvJMcS4JpGCOyViCnGeKf0bTYCGTO4uhjSo=
|
||||
github.com/ergochat/readline v0.1.3 h1:/DytGTmwdUJcLAe3k3VJgowh5vNnsdifYT6uVaf4pSo=
|
||||
github.com/ergochat/readline v0.1.3/go.mod h1:o3ux9QLHLm77bq7hDB21UTm6HlV2++IPDMfIfKDuOgY=
|
||||
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
|
||||
@@ -193,8 +177,6 @@ github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0
|
||||
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
|
||||
github.com/larksuite/oapi-sdk-go/v3 v3.9.4 h1:oMgcY7NBjJv1QXJqFAfcoN/TbScCkCuRZfbb1mCwZmI=
|
||||
github.com/larksuite/oapi-sdk-go/v3 v3.9.4/go.mod h1:ZEplY+kwuIrj/nqw5uSCINNATcH3KdxSN7y+UxYY5fI=
|
||||
github.com/line/line-bot-sdk-go/v8 v8.20.1 h1:OE7qwJbuZPz9MGOHHNI0E6rQNtIU7ENHyFXpvbVLwII=
|
||||
github.com/line/line-bot-sdk-go/v8 v8.20.1/go.mod h1:QMXJwPka2ysSeVQKWXkBp8DzBFs+CFAXFNo75KJtWho=
|
||||
github.com/lucasb-eyer/go-colorful v1.3.0 h1:2/yBRLdWBZKrf7gB40FoiKfAWYQ0lqNcbuQwVHXptag=
|
||||
github.com/lucasb-eyer/go-colorful v1.3.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
|
||||
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
|
||||
@@ -203,8 +185,6 @@ github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWE
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
|
||||
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||
github.com/mattn/go-sqlite3 v1.14.42 h1:MigqEP4ZmHw3aIdIT7T+9TLa90Z6smwcthx+Azv4Cgo=
|
||||
github.com/mattn/go-sqlite3 v1.14.42/go.mod h1:pjEuOr8IwzLJP2MfGeTb0A35jauH+C2kbHKBr7yXKVQ=
|
||||
github.com/mdp/qrterminal/v3 v3.2.1 h1:6+yQjiiOsSuXT5n9/m60E54vdgFsw0zhADHhHLrFet4=
|
||||
github.com/mdp/qrterminal/v3 v3.2.1/go.mod h1:jOTmXvnBsMy5xqLniO0R++Jmjs2sTm9dFSuQ5kpz/SU=
|
||||
github.com/minio/selfupdate v0.6.0 h1:i76PgT0K5xO9+hjzKcacQtO7+MjJ4JKA8Ak8XQ9DDwU=
|
||||
@@ -231,8 +211,6 @@ github.com/openai/openai-go/v3 v3.22.0 h1:6MEoNoV8sbjOVmXdvhmuX3BjVbVdcExbVyGixi
|
||||
github.com/openai/openai-go/v3 v3.22.0/go.mod h1:cdufnVK14cWcT9qA1rRtrXx4FTRsgbDPW7Ia7SS5cZo=
|
||||
github.com/pb33f/ordered-map/v2 v2.3.1 h1:5319HDO0aw4DA4gzi+zv4FXU9UlSs3xGZ40wcP1nBjY=
|
||||
github.com/pb33f/ordered-map/v2 v2.3.1/go.mod h1:qxFQgd0PkVUtOMCkTapqotNgzRhMPL7VvaHKbd1HnmQ=
|
||||
github.com/petermattis/goid v0.0.0-20260330135022-df67b199bc81 h1:WDsQxOJDy0N1VRAjXLpi8sCEZRSGarLWQevDxpTBRrM=
|
||||
github.com/petermattis/goid v0.0.0-20260330135022-df67b199bc81/go.mod h1:pxMtw7cyUw6B2bRH0ZBANSPg+AoSud1I1iyJHI69jH4=
|
||||
github.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA=
|
||||
github.com/pion/randutil v0.1.0/go.mod h1:XcJrSMMbbMRhASFVOlj/5hQial/Y8oH/HVo7TBZq+j8=
|
||||
github.com/pion/rtp v1.10.2 h1:l+f6tTDcAH6xwepaAoW791ddhuYsJlqRATOzirO04Mo=
|
||||
@@ -260,8 +238,6 @@ github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
|
||||
github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=
|
||||
github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=
|
||||
github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=
|
||||
github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8=
|
||||
github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I=
|
||||
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
|
||||
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
|
||||
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
@@ -303,25 +279,17 @@ github.com/valyala/fasthttp v1.71.0 h1:tepR7H+Guh9VUqxxcPggYi8R3lGUu2Rsdh+z7/FCY
|
||||
github.com/valyala/fasthttp v1.71.0/go.mod h1:z1sDUvOShhXq/C9mwH/fSm1Vb71tUJwmQdgkBrBNwnA=
|
||||
github.com/valyala/fastjson v1.6.10 h1:/yjJg8jaVQdYR3arGxPE2X5z89xrlhS0eGXdv+ADTh4=
|
||||
github.com/valyala/fastjson v1.6.10/go.mod h1:e6FubmQouUNP73jtMLmcbxS6ydWIpOfhz34TSfO3JaE=
|
||||
github.com/vektah/gqlparser/v2 v2.5.27 h1:RHPD3JOplpk5mP5JGX8RKZkt2/Vwj/PZv0HxTdwFp0s=
|
||||
github.com/vektah/gqlparser/v2 v2.5.27/go.mod h1:D1/VCZtV3LPnQrcPBeR/q5jkSQIPti0uYCP/RI0gIeo=
|
||||
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
|
||||
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
|
||||
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
|
||||
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
|
||||
github.com/yeongaori/discordgo-fork v0.0.0-20260319072544-e8e546f5d532 h1:gxFHYeUDGziRb0zXYEqBFohC+NJbIW9L0tddaXMWr2o=
|
||||
github.com/yeongaori/discordgo-fork v0.0.0-20260319072544-e8e546f5d532/go.mod h1:A0FcMFJKJ9fRjgSuZ2o+pIQ6mPS81SVuiLN2vYTa7Ao=
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
|
||||
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
go.mau.fi/libsignal v0.2.1 h1:vRZG4EzTn70XY6Oh/pVKrQGuMHBkAWlGRC22/85m9L0=
|
||||
go.mau.fi/libsignal v0.2.1/go.mod h1:iVvjrHyfQqWajOUaMEsIfo3IqgVMrhWcPiiEzk7NgoU=
|
||||
go.mau.fi/util v0.9.8 h1:+/jf8eM2dAT2wx9UidmaneH28r/CSCKCniCyby1qWz8=
|
||||
go.mau.fi/util v0.9.8/go.mod h1:up/5mbzH2M1pSBNXqRxODn8dg/hEKbLJu92W4/SNAX0=
|
||||
go.mau.fi/whatsmeow v0.0.0-20260219150138-7ae702b1eed4 h1:hsmlwsM+VqfF70cpdZEeIUKer2XWCQmQPK0u0tHy3ZQ=
|
||||
go.mau.fi/whatsmeow v0.0.0-20260219150138-7ae702b1eed4/go.mod h1:mXCRFyPEPn4jqWz6Afirn8vY7DpHCPnlKq6I2cWwFHM=
|
||||
go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
|
||||
go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
|
||||
go.opentelemetry.io/otel v1.35.0 h1:xKWKPxrxB6OtMCbmMY021CqC45J+3Onta9MqjhnusiQ=
|
||||
@@ -445,8 +413,6 @@ google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzi
|
||||
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
|
||||
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
||||
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
|
||||
+22
-22
@@ -494,8 +494,8 @@ func TestProcessMessage_IncludesCurrentSenderInDynamicContext(t *testing.T) {
|
||||
al := NewAgentLoop(cfg, msgBus, provider)
|
||||
|
||||
response, err := al.processMessage(context.Background(), testInboundMessage(bus.InboundMessage{
|
||||
Channel: "discord",
|
||||
SenderID: "discord:123",
|
||||
Channel: "testchat",
|
||||
SenderID: "testchat:123",
|
||||
Sender: bus.SenderInfo{
|
||||
DisplayName: "Alice",
|
||||
},
|
||||
@@ -513,7 +513,7 @@ func TestProcessMessage_IncludesCurrentSenderInDynamicContext(t *testing.T) {
|
||||
}
|
||||
|
||||
systemPrompt := provider.lastMessages[0].Content
|
||||
wantSender := "## Current Sender\nCurrent sender: Alice (ID: discord:123)"
|
||||
wantSender := "## Current Sender\nCurrent sender: Alice (ID: testchat:123)"
|
||||
if !strings.Contains(systemPrompt, wantSender) {
|
||||
t.Fatalf("system prompt missing sender context %q:\n%s", wantSender, systemPrompt)
|
||||
}
|
||||
@@ -1178,8 +1178,8 @@ func TestProcessMessage_BtwCommandIncludesRequestContextAndMedia(t *testing.T) {
|
||||
useTestSideQuestionProvider(al, provider)
|
||||
|
||||
response, err := al.processMessage(context.Background(), testInboundMessage(bus.InboundMessage{
|
||||
Channel: "discord",
|
||||
SenderID: "discord:123",
|
||||
Channel: "testchat",
|
||||
SenderID: "testchat:123",
|
||||
Sender: bus.SenderInfo{
|
||||
DisplayName: "Alice",
|
||||
},
|
||||
@@ -1198,10 +1198,10 @@ func TestProcessMessage_BtwCommandIncludesRequestContextAndMedia(t *testing.T) {
|
||||
}
|
||||
|
||||
systemPrompt := provider.lastMessages[0].Content
|
||||
if !strings.Contains(systemPrompt, "## Current Session\nChannel: discord\nChat ID: group-1") {
|
||||
if !strings.Contains(systemPrompt, "## Current Session\nChannel: testchat\nChat ID: group-1") {
|
||||
t.Fatalf("system prompt missing current session context:\n%s", systemPrompt)
|
||||
}
|
||||
if !strings.Contains(systemPrompt, "## Current Sender\nCurrent sender: Alice (ID: discord:123)") {
|
||||
if !strings.Contains(systemPrompt, "## Current Sender\nCurrent sender: Alice (ID: testchat:123)") {
|
||||
t.Fatalf("system prompt missing current sender context:\n%s", systemPrompt)
|
||||
}
|
||||
|
||||
@@ -2006,7 +2006,7 @@ func TestAppendEventContextFields_IncludesInboundRouteAndScope(t *testing.T) {
|
||||
|
||||
appendEventContextFields(fields, &TurnContext{
|
||||
Inbound: &bus.InboundContext{
|
||||
Channel: "discord",
|
||||
Channel: "testchat",
|
||||
Account: "workspace-a",
|
||||
ChatID: "C123",
|
||||
ChatType: "channel",
|
||||
@@ -2018,20 +2018,20 @@ func TestAppendEventContextFields_IncludesInboundRouteAndScope(t *testing.T) {
|
||||
},
|
||||
Route: &routing.ResolvedRoute{
|
||||
AgentID: "support",
|
||||
Channel: "discord",
|
||||
Channel: "testchat",
|
||||
AccountID: "workspace-a",
|
||||
MatchedBy: "default",
|
||||
SessionPolicy: routing.SessionPolicy{
|
||||
Dimensions: []string{"chat", "sender"},
|
||||
IdentityLinks: map[string][]string{
|
||||
"canonical-user": {"discord:U123"},
|
||||
"canonical-user": {"testchat:U123"},
|
||||
},
|
||||
},
|
||||
},
|
||||
Scope: &session.SessionScope{
|
||||
Version: session.ScopeVersionV1,
|
||||
AgentID: "support",
|
||||
Channel: "discord",
|
||||
Channel: "testchat",
|
||||
Account: "workspace-a",
|
||||
Dimensions: []string{"chat", "sender"},
|
||||
Values: map[string]string{
|
||||
@@ -2041,8 +2041,8 @@ func TestAppendEventContextFields_IncludesInboundRouteAndScope(t *testing.T) {
|
||||
},
|
||||
})
|
||||
|
||||
if fields["inbound_channel"] != "discord" {
|
||||
t.Fatalf("inbound_channel = %v, want discord", fields["inbound_channel"])
|
||||
if fields["inbound_channel"] != "testchat" {
|
||||
t.Fatalf("inbound_channel = %v, want testchat", fields["inbound_channel"])
|
||||
}
|
||||
if fields["inbound_topic_id"] != "thread-42" {
|
||||
t.Fatalf("inbound_topic_id = %v, want thread-42", fields["inbound_topic_id"])
|
||||
@@ -2090,7 +2090,7 @@ func TestResolveMessageRoute_UsesInboundContextAccount(t *testing.T) {
|
||||
|
||||
route, _, err := al.resolveMessageRoute(testInboundMessage(bus.InboundMessage{
|
||||
Context: bus.InboundContext{
|
||||
Channel: "discord",
|
||||
Channel: "testchat",
|
||||
Account: "workspace-a",
|
||||
ChatID: "C123",
|
||||
ChatType: "channel",
|
||||
@@ -5532,7 +5532,7 @@ func TestTargetReasoningChannelID_AllChannels(t *testing.T) {
|
||||
"whatsapp": "rid-whatsapp",
|
||||
"telegram": "rid-telegram",
|
||||
"feishu": "rid-feishu",
|
||||
"discord": "rid-discord",
|
||||
"testchat": "rid-testchat",
|
||||
"mqtt": "rid-mqtt",
|
||||
"qq": "rid-qq",
|
||||
"dingtalk": "rid-dingtalk",
|
||||
@@ -5550,7 +5550,7 @@ func TestTargetReasoningChannelID_AllChannels(t *testing.T) {
|
||||
{channel: "whatsapp", wantID: "rid-whatsapp"},
|
||||
{channel: "telegram", wantID: "rid-telegram"},
|
||||
{channel: "feishu", wantID: "rid-feishu"},
|
||||
{channel: "discord", wantID: "rid-discord"},
|
||||
{channel: "testchat", wantID: "rid-testchat"},
|
||||
{channel: "mqtt", wantID: "rid-mqtt"},
|
||||
{channel: "qq", wantID: "rid-qq"},
|
||||
{channel: "dingtalk", wantID: "rid-dingtalk"},
|
||||
@@ -5620,13 +5620,13 @@ func TestHandleReasoning(t *testing.T) {
|
||||
|
||||
t.Run("publishes one message for non telegram", func(t *testing.T) {
|
||||
al, msgBus := newLoop(t)
|
||||
al.handleReasoning(context.Background(), "hello reasoning", "discord", "channel-1")
|
||||
al.handleReasoning(context.Background(), "hello reasoning", "testchat", "channel-1")
|
||||
|
||||
msg, ok := <-msgBus.OutboundChan()
|
||||
if !ok {
|
||||
t.Fatal("expected an outbound message")
|
||||
}
|
||||
if msg.Channel != "discord" || msg.ChatID != "channel-1" || msg.Content != "hello reasoning" {
|
||||
if msg.Channel != "testchat" || msg.ChatID != "channel-1" || msg.Content != "hello reasoning" {
|
||||
t.Fatalf("unexpected outbound message: %+v", msg)
|
||||
}
|
||||
})
|
||||
@@ -5709,7 +5709,7 @@ func TestHandleReasoning(t *testing.T) {
|
||||
defer cancel()
|
||||
|
||||
start := time.Now()
|
||||
al.handleReasoning(ctx, "should timeout", "discord", "channel-full")
|
||||
al.handleReasoning(ctx, "should timeout", "testchat", "channel-full")
|
||||
elapsed := time.Since(start)
|
||||
|
||||
// handleReasoning uses a 5s internal timeout, but the parent ctx
|
||||
@@ -6180,8 +6180,8 @@ func TestProcessMessage_DoesNotLeakReasoningContentInToolFeedback(t *testing.T)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessMessage_DoesNotPublishToolFeedbackForDiscordWhenDisabled(t *testing.T) {
|
||||
assertToolFeedbackNotPublishedWhenDisabled(t, "discord")
|
||||
func TestProcessMessage_DoesNotPublishToolFeedbackForTestChatWhenDisabled(t *testing.T) {
|
||||
assertToolFeedbackNotPublishedWhenDisabled(t, "testchat")
|
||||
}
|
||||
|
||||
func assertToolFeedbackNotPublishedWhenDisabled(t *testing.T, channel string) {
|
||||
@@ -6776,7 +6776,7 @@ func TestInjectPathTags_HandlesVariousChannelPlaceholders(t *testing.T) {
|
||||
{"image_photo", "[image: photo]", "[image:/tmp/p.png]", "[image:/tmp/p.png]"},
|
||||
// WeCom / WeChat / Line format
|
||||
{"bare_image", "[image]", "[image:/tmp/p.png]", "[image:/tmp/p.png]"},
|
||||
// QQ / Discord format with filename
|
||||
// QQ / TestChat format with filename
|
||||
{"image_filename", "[image: pic.jpg]", "[image:/tmp/p.png]", "[image:/tmp/p.png]"},
|
||||
{"audio_with_filename", "[audio: voice.m4a]", "[audio:/tmp/a.m4a]", "[audio:/tmp/a.m4a]"},
|
||||
{"bare_audio", "[audio]", "[audio:/tmp/a.m4a]", "[audio:/tmp/a.m4a]"},
|
||||
|
||||
@@ -156,8 +156,8 @@ func TestBuildMessages_CurrentSenderDynamicContext(t *testing.T) {
|
||||
},
|
||||
{
|
||||
name: "id only",
|
||||
senderID: "discord:123",
|
||||
wantLine: "Current sender: discord:123",
|
||||
senderID: "testchat:123",
|
||||
wantLine: "Current sender: testchat:123",
|
||||
wantSection: true,
|
||||
},
|
||||
{
|
||||
@@ -168,7 +168,7 @@ func TestBuildMessages_CurrentSenderDynamicContext(t *testing.T) {
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
msgs := cb.BuildMessages(nil, "", "hello", nil, "discord", "chat1", tt.senderID, tt.senderDisplayName)
|
||||
msgs := cb.BuildMessages(nil, "", "hello", nil, "testchat", "chat1", tt.senderID, tt.senderDisplayName)
|
||||
sys := msgs[0].Content
|
||||
|
||||
if tt.wantSection {
|
||||
|
||||
@@ -50,7 +50,7 @@ func TestNormalizeProcessOptions_PopulatesDispatchFromLegacyFields(t *testing.T)
|
||||
|
||||
func TestNormalizeProcessOptions_UsesDispatchAsSourceOfTruth(t *testing.T) {
|
||||
inbound := &bus.InboundContext{
|
||||
Channel: "discord",
|
||||
Channel: "testchat",
|
||||
ChatID: "C123",
|
||||
ChatType: "channel",
|
||||
SenderID: "U123",
|
||||
@@ -59,7 +59,7 @@ func TestNormalizeProcessOptions_UsesDispatchAsSourceOfTruth(t *testing.T) {
|
||||
}
|
||||
route := &routing.ResolvedRoute{
|
||||
AgentID: "support",
|
||||
Channel: "discord",
|
||||
Channel: "testchat",
|
||||
AccountID: "workspace-a",
|
||||
MatchedBy: "dispatch.rule:test",
|
||||
SessionPolicy: routing.SessionPolicy{
|
||||
@@ -69,7 +69,7 @@ func TestNormalizeProcessOptions_UsesDispatchAsSourceOfTruth(t *testing.T) {
|
||||
scope := &session.SessionScope{
|
||||
Version: session.ScopeVersionV1,
|
||||
AgentID: "support",
|
||||
Channel: "discord",
|
||||
Channel: "testchat",
|
||||
Account: "workspace-a",
|
||||
Dimensions: []string{"chat"},
|
||||
Values: map[string]string{
|
||||
@@ -80,7 +80,7 @@ func TestNormalizeProcessOptions_UsesDispatchAsSourceOfTruth(t *testing.T) {
|
||||
opts := normalizeProcessOptions(processOptions{
|
||||
Dispatch: DispatchRequest{
|
||||
SessionKey: "sk_v1_example",
|
||||
SessionAliases: []string{"agent:support:discord:channel:c123"},
|
||||
SessionAliases: []string{"agent:support:testchat:channel:c123"},
|
||||
InboundContext: inbound,
|
||||
RouteResult: route,
|
||||
SessionScope: scope,
|
||||
@@ -92,8 +92,8 @@ func TestNormalizeProcessOptions_UsesDispatchAsSourceOfTruth(t *testing.T) {
|
||||
if opts.SessionKey != "sk_v1_example" {
|
||||
t.Fatalf("SessionKey = %q, want sk_v1_example", opts.SessionKey)
|
||||
}
|
||||
if opts.Channel != "discord" || opts.ChatID != "C123" {
|
||||
t.Fatalf("legacy mirrors = (%q,%q), want (discord,C123)", opts.Channel, opts.ChatID)
|
||||
if opts.Channel != "testchat" || opts.ChatID != "C123" {
|
||||
t.Fatalf("legacy mirrors = (%q,%q), want (testchat,C123)", opts.Channel, opts.ChatID)
|
||||
}
|
||||
if opts.SenderID != "U123" || opts.MessageID != "m-1" {
|
||||
t.Fatalf("legacy sender/message = (%q,%q)", opts.SenderID, opts.MessageID)
|
||||
|
||||
@@ -1136,7 +1136,7 @@ func TestAgentLoop_HookRespond_MediaError(t *testing.T) {
|
||||
}
|
||||
|
||||
al.channelManager = newStartedTestChannelManager(t,
|
||||
al.bus.(*bus.MessageBus), al.mediaStore, "discord", &errorMediaChannel{
|
||||
al.bus.(*bus.MessageBus), al.mediaStore, "testchat", &errorMediaChannel{
|
||||
sendErr: errors.New("channel unavailable"),
|
||||
})
|
||||
|
||||
@@ -1150,7 +1150,7 @@ func TestAgentLoop_HookRespond_MediaError(t *testing.T) {
|
||||
|
||||
_, err := al.runAgentLoop(context.Background(), agent, processOptions{
|
||||
SessionKey: "session-media-err",
|
||||
Channel: "discord",
|
||||
Channel: "testchat",
|
||||
ChatID: "chat1",
|
||||
UserMessage: "send media",
|
||||
DefaultResponse: defaultResponse,
|
||||
|
||||
@@ -1267,12 +1267,12 @@ func TestAgentLoop_AgentForSession_UsesStoredScopeMetadata(t *testing.T) {
|
||||
t.Fatal("support session store does not support metadata")
|
||||
}
|
||||
|
||||
alias := "agent:support:discord:channel:c001"
|
||||
alias := "agent:support:testchat:channel:c001"
|
||||
key := session.BuildOpaqueSessionKey(alias)
|
||||
scope := &session.SessionScope{
|
||||
Version: session.ScopeVersionV1,
|
||||
AgentID: "support",
|
||||
Channel: "discord",
|
||||
Channel: "testchat",
|
||||
Account: "default",
|
||||
Dimensions: []string{"chat"},
|
||||
Values: map[string]string{
|
||||
|
||||
@@ -210,7 +210,8 @@ func (a *Agent) processUtterance(ctx context.Context, acc *speechAccumulator) {
|
||||
|
||||
channelType := acc.channel
|
||||
if channelType == "" {
|
||||
channelType = "discord" // fallback for legacy chunks
|
||||
logger.WarnC("voice-agent", "Ignoring transcription without a source channel")
|
||||
return
|
||||
}
|
||||
|
||||
text := strings.ToLower(strings.TrimSpace(res.Text))
|
||||
|
||||
@@ -56,7 +56,7 @@ func TestAgentHandleChunkCreatesSession(t *testing.T) {
|
||||
SessionID: "sess",
|
||||
SpeakerID: "speaker",
|
||||
ChatID: "chat",
|
||||
Channel: "discord",
|
||||
Channel: "testchat",
|
||||
Sequence: 1,
|
||||
Timestamp: 1,
|
||||
SampleRate: 48000,
|
||||
@@ -118,7 +118,7 @@ func TestAgentProcessUtteranceLeaveCommand(t *testing.T) {
|
||||
chatID: "chat",
|
||||
speakerID: "speaker",
|
||||
sessionID: "sess",
|
||||
channel: "discord",
|
||||
channel: "testchat",
|
||||
}
|
||||
|
||||
agent.processUtterance(context.Background(), acc)
|
||||
@@ -168,7 +168,7 @@ func TestAgentCheckSilencePublishesInboundAndCleansUp(t *testing.T) {
|
||||
chatID: "chat",
|
||||
speakerID: "speaker",
|
||||
sessionID: "sess",
|
||||
channel: "discord",
|
||||
channel: "testchat",
|
||||
}
|
||||
|
||||
agent.mu.Lock()
|
||||
@@ -179,7 +179,7 @@ func TestAgentCheckSilencePublishesInboundAndCleansUp(t *testing.T) {
|
||||
|
||||
select {
|
||||
case msg := <-mb.InboundChan():
|
||||
if msg.Channel != "discord" {
|
||||
if msg.Channel != "testchat" {
|
||||
t.Fatalf("unexpected inbound channel: %q", msg.Channel)
|
||||
}
|
||||
if !strings.Contains(msg.Content, "hello there") {
|
||||
|
||||
@@ -301,7 +301,7 @@ func TestSynthesizeAndStore_UsesOggMetadataByDefault(t *testing.T) {
|
||||
store,
|
||||
"hello",
|
||||
"",
|
||||
"discord",
|
||||
"testchat",
|
||||
"chat123",
|
||||
)
|
||||
if err != nil {
|
||||
@@ -333,7 +333,7 @@ func TestSynthesizeAndStore_UsesMp3MetadataForMimo(t *testing.T) {
|
||||
store,
|
||||
"hello",
|
||||
"",
|
||||
"discord",
|
||||
"testchat",
|
||||
"chat123",
|
||||
)
|
||||
if err != nil {
|
||||
|
||||
+14
-14
@@ -57,7 +57,7 @@ func TestPublishInbound_NormalizesContext(t *testing.T) {
|
||||
|
||||
msg := InboundMessage{
|
||||
Context: InboundContext{
|
||||
Channel: "discord",
|
||||
Channel: "testchat",
|
||||
Account: "workspace-a",
|
||||
ChatID: "C456/1712",
|
||||
ChatType: "group",
|
||||
@@ -77,8 +77,8 @@ func TestPublishInbound_NormalizesContext(t *testing.T) {
|
||||
}
|
||||
|
||||
got := <-mb.InboundChan()
|
||||
if got.Context.Channel != "discord" {
|
||||
t.Fatalf("expected context channel discord, got %q", got.Context.Channel)
|
||||
if got.Context.Channel != "testchat" {
|
||||
t.Fatalf("expected context channel testchat, got %q", got.Context.Channel)
|
||||
}
|
||||
if got.Context.Account != "workspace-a" {
|
||||
t.Fatalf("expected context account workspace-a, got %q", got.Context.Account)
|
||||
@@ -394,7 +394,7 @@ func TestPublishOutboundMedia_MirrorsContextToLegacyFields(t *testing.T) {
|
||||
|
||||
msg := OutboundMediaMessage{
|
||||
Context: InboundContext{
|
||||
Channel: "discord",
|
||||
Channel: "testchat",
|
||||
ChatID: "C001",
|
||||
},
|
||||
AgentID: "support",
|
||||
@@ -402,7 +402,7 @@ func TestPublishOutboundMedia_MirrorsContextToLegacyFields(t *testing.T) {
|
||||
Scope: &OutboundScope{
|
||||
Version: 1,
|
||||
AgentID: "support",
|
||||
Channel: "discord",
|
||||
Channel: "testchat",
|
||||
Dimensions: []string{"chat"},
|
||||
Values: map[string]string{
|
||||
"chat": "channel:c001",
|
||||
@@ -416,8 +416,8 @@ func TestPublishOutboundMedia_MirrorsContextToLegacyFields(t *testing.T) {
|
||||
}
|
||||
|
||||
got := <-mb.OutboundMediaChan()
|
||||
if got.Channel != "discord" {
|
||||
t.Fatalf("expected legacy channel discord, got %q", got.Channel)
|
||||
if got.Channel != "testchat" {
|
||||
t.Fatalf("expected legacy channel testchat, got %q", got.Channel)
|
||||
}
|
||||
if got.ChatID != "C001" {
|
||||
t.Fatalf("expected legacy chat ID C001, got %q", got.ChatID)
|
||||
@@ -428,7 +428,7 @@ func TestPublishOutboundMedia_MirrorsContextToLegacyFields(t *testing.T) {
|
||||
if got.Scope == nil || got.Scope.Values["chat"] != "channel:c001" {
|
||||
t.Fatalf("unexpected outbound media scope: %+v", got.Scope)
|
||||
}
|
||||
if got.Context.Channel != "discord" || got.Context.ChatID != "C001" {
|
||||
if got.Context.Channel != "testchat" || got.Context.ChatID != "C001" {
|
||||
t.Fatalf("unexpected outbound media context: %+v", got.Context)
|
||||
}
|
||||
}
|
||||
@@ -441,7 +441,7 @@ func TestPublishAudioChunkSubscribe(t *testing.T) {
|
||||
SessionID: "voice-1",
|
||||
SpeakerID: "speaker-1",
|
||||
ChatID: "chat-1",
|
||||
Channel: "discord",
|
||||
Channel: "testchat",
|
||||
Sequence: 7,
|
||||
Format: "opus",
|
||||
Data: []byte{0x01, 0x02},
|
||||
@@ -485,7 +485,7 @@ func TestPublishAudioChunk_BackpressureDropPublishesRuntimeEvent(t *testing.T) {
|
||||
SessionID: "voice-1",
|
||||
SpeakerID: "speaker-1",
|
||||
ChatID: "chat-1",
|
||||
Channel: "discord",
|
||||
Channel: "testchat",
|
||||
Sequence: uint64(i),
|
||||
Format: "opus",
|
||||
Data: []byte{0x01},
|
||||
@@ -498,7 +498,7 @@ func TestPublishAudioChunk_BackpressureDropPublishesRuntimeEvent(t *testing.T) {
|
||||
SessionID: "voice-1",
|
||||
SpeakerID: "speaker-1",
|
||||
ChatID: "chat-1",
|
||||
Channel: "discord",
|
||||
Channel: "testchat",
|
||||
Sequence: 999,
|
||||
Format: "opus",
|
||||
Data: []byte{0x01},
|
||||
@@ -513,7 +513,7 @@ func TestPublishAudioChunk_BackpressureDropPublishesRuntimeEvent(t *testing.T) {
|
||||
evt.Severity != runtimeevents.SeverityWarn {
|
||||
t.Fatalf("drop event = %+v", evt)
|
||||
}
|
||||
if evt.Scope.Channel != "discord" || evt.Scope.ChatID != "chat-1" {
|
||||
if evt.Scope.Channel != "testchat" || evt.Scope.ChatID != "chat-1" {
|
||||
t.Fatalf("drop event scope = %+v", evt.Scope)
|
||||
}
|
||||
if evt.Attrs["stream"] != "audio_chunk" ||
|
||||
@@ -851,7 +851,7 @@ func TestMessageBusHealthCheckIncludesQueueDepthAndDrops(t *testing.T) {
|
||||
|
||||
for i := range cap(mb.audioChunks) {
|
||||
if err := mb.PublishAudioChunk(context.Background(), AudioChunk{
|
||||
Channel: "discord",
|
||||
Channel: "testchat",
|
||||
ChatID: "voice-room",
|
||||
Sequence: uint64(i),
|
||||
Data: []byte("fill"),
|
||||
@@ -860,7 +860,7 @@ func TestMessageBusHealthCheckIncludesQueueDepthAndDrops(t *testing.T) {
|
||||
}
|
||||
}
|
||||
_ = mb.PublishAudioChunk(context.Background(), AudioChunk{
|
||||
Channel: "discord",
|
||||
Channel: "testchat",
|
||||
ChatID: "voice-room",
|
||||
Sequence: 999,
|
||||
Data: []byte("overflow"),
|
||||
|
||||
+2
-2
@@ -2,7 +2,7 @@ package bus
|
||||
|
||||
// SenderInfo provides structured sender identity information.
|
||||
type SenderInfo struct {
|
||||
Platform string `json:"platform,omitempty"` // "telegram", "discord", ...
|
||||
Platform string `json:"platform,omitempty"` // "telegram", ...
|
||||
PlatformID string `json:"platform_id,omitempty"` // raw platform ID, e.g. "123456"
|
||||
CanonicalID string `json:"canonical_id,omitempty"` // "platform:id" format
|
||||
Username string `json:"username,omitempty"` // username (e.g. @alice)
|
||||
@@ -109,7 +109,7 @@ type AudioChunk struct {
|
||||
SessionID string `json:"session_id"`
|
||||
SpeakerID string `json:"speaker_id"` // User ID or SSRC
|
||||
ChatID string `json:"chat_id"` // Where to respond
|
||||
Channel string `json:"channel"` // Source channel type (e.g. "discord")
|
||||
Channel string `json:"channel"` // Source channel type
|
||||
Sequence uint64 `json:"sequence"`
|
||||
Timestamp uint32 `json:"timestamp"`
|
||||
SampleRate int `json:"sample_rate"`
|
||||
|
||||
+8
-35
@@ -24,7 +24,6 @@
|
||||
```
|
||||
pkg/channels/
|
||||
├── telegram.go # Each channel directly in the channels package
|
||||
├── discord.go
|
||||
├── manager.go # Manager directly references each channel type
|
||||
├── ...
|
||||
```
|
||||
@@ -56,10 +55,7 @@ pkg/channels/
|
||||
│ ├── init.go # Factory registration
|
||||
│ ├── telegram.go # Implementation
|
||||
│ └── telegram_commands.go
|
||||
├── discord/
|
||||
│ ├── init.go
|
||||
│ └── discord.go
|
||||
├── line/ onebot/ dingtalk/ feishu/ wecom/ qq/ whatsapp/ whatsapp_native/ mqtt/
|
||||
├── onebot/ dingtalk/ feishu/ wecom/ qq/ mqtt/
|
||||
│ └── ...
|
||||
|
||||
pkg/bus/
|
||||
@@ -78,9 +74,9 @@ pkg/identity/
|
||||
```
|
||||
┌────────────┐ InboundMessage ┌───────────┐ LLM + Tools ┌────────────┐
|
||||
│ Telegram │──┐ │ │ │ │
|
||||
│ Discord │──┤ PublishInbound() │ │ PublishOutbound() │ │
|
||||
│ Weixin │──┤ PublishInbound() │ │ PublishOutbound() │ │
|
||||
│ Feishu │──┼──────────────────────▶ │ MessageBus │ ◀─────────────────── │ AgentLoop │
|
||||
│ LINE │──┤ (buffered chan, 64) │ │ (buffered chan, 64) │ │
|
||||
│ OneBot │──┤ (buffered chan, 64) │ │ (buffered chan, 64) │ │
|
||||
│ ... │──┘ │ │ │ │
|
||||
└────────────┘ └─────┬─────┘ └────────────┘
|
||||
│
|
||||
@@ -125,18 +121,15 @@ pkg/identity/
|
||||
|
||||
On the main branch, channel files were directly in `pkg/channels/` top level, e.g.:
|
||||
- `pkg/channels/telegram.go`
|
||||
- `pkg/channels/discord.go`
|
||||
|
||||
After refactoring, these files have been removed and code moved to corresponding sub-packages:
|
||||
- `pkg/channels/telegram/telegram.go`
|
||||
- `pkg/channels/discord/discord.go`
|
||||
|
||||
#### Step 2: Understand the structural change mapping
|
||||
|
||||
| main branch file | Refactored branch location | Changes |
|
||||
|---|---|---|
|
||||
| `pkg/channels/telegram.go` | `pkg/channels/telegram/telegram.go` + `init.go` | Package name changed from `channels` to `telegram` |
|
||||
| `pkg/channels/discord.go` | `pkg/channels/discord/discord.go` + `init.go` | Same as above |
|
||||
| `pkg/channels/manager.go` | `pkg/channels/manager.go` | Extensively rewritten |
|
||||
| _(did not exist)_ | `pkg/channels/base.go` | New shared abstraction layer |
|
||||
| _(did not exist)_ | `pkg/channels/registry.go` | New factory registry |
|
||||
@@ -144,7 +137,6 @@ After refactoring, these files have been removed and code moved to corresponding
|
||||
| _(did not exist)_ | `pkg/channels/interfaces.go` | New optional capability interfaces |
|
||||
| _(did not exist)_ | `pkg/channels/media.go` | New MediaSender interface |
|
||||
| _(did not exist)_ | `pkg/channels/webhook.go` | New WebhookHandler/HealthChecker |
|
||||
| _(did not exist)_ | `pkg/channels/whatsapp_native/` | New WhatsApp native mode (whatsmeow) |
|
||||
| _(did not exist)_ | `pkg/channels/split.go` | New message splitting (migrated from utils) |
|
||||
| _(did not exist)_ | `pkg/bus/types.go` | New structured message types |
|
||||
| _(did not exist)_ | `pkg/media/store.go` | New media file lifecycle management |
|
||||
@@ -343,7 +335,6 @@ func init() {
|
||||
// cmd/picoclaw/internal/gateway/helpers.go
|
||||
import (
|
||||
_ "github.com/sipeed/picoclaw/pkg/channels/telegram" // Triggers init() registration
|
||||
_ "github.com/sipeed/picoclaw/pkg/channels/discord"
|
||||
_ "github.com/sipeed/picoclaw/pkg/channels/your_new_channel" // New addition
|
||||
)
|
||||
```
|
||||
@@ -766,9 +757,9 @@ if c.owner != nil && c.placeholderRecorder != nil {
|
||||
```
|
||||
|
||||
**This means**:
|
||||
- Channels implementing `TypingCapable` (Telegram, Discord, LINE) do not need to manually call `StartTyping` + `RecordTypingStop` in `handleMessage`
|
||||
- Channels implementing `TypingCapable` (Telegram) do not need to manually call `StartTyping` + `RecordTypingStop` in `handleMessage`
|
||||
- Channels implementing `ReactionCapable` (OneBot) do not need to manually call `AddReaction` + `RecordTypingStop` in `handleMessage`
|
||||
- Channels implementing `PlaceholderCapable` (Telegram, Discord) do not need to manually send placeholder messages and call `RecordPlaceholder` in `handleMessage`
|
||||
- Channels implementing `PlaceholderCapable` (Telegram) do not need to manually send placeholder messages and call `RecordPlaceholder` in `handleMessage`
|
||||
- Channels only need to implement the corresponding interface; `HandleMessage` handles orchestration automatically
|
||||
- Channels that don't implement these interfaces are unaffected (type assertions will fail and be skipped)
|
||||
- `PlaceholderCapable`'s `SendPlaceholder` method internally decides whether to send based on the configured `PlaceholderConfig.Enabled`; returning `("", nil)` skips registration
|
||||
@@ -829,14 +820,6 @@ The Manager uses `InitChannelList()` to validate types and decode settings,
|
||||
then looks up factories by `bc.Type`. No per-channel entry needed in Manager —
|
||||
just register the factory and the config entry.
|
||||
|
||||
> **Note**: If your channel has multiple modes (like WhatsApp Bridge vs Native),
|
||||
> register both types in `channelSettingsFactory` and branch on config:
|
||||
> ```go
|
||||
> // In config_channel.go:
|
||||
> ChannelWhatsApp: (WhatsAppSettings{}),
|
||||
> ChannelWhatsAppNative: (WhatsAppSettings{}),
|
||||
> ```
|
||||
|
||||
#### Add blank import in Gateway
|
||||
|
||||
```go
|
||||
@@ -894,7 +877,7 @@ type Peer struct {
|
||||
|
||||
// Sender identity information
|
||||
type SenderInfo struct {
|
||||
Platform string `json:"platform,omitempty"` // "telegram", "discord", ...
|
||||
Platform string `json:"platform,omitempty"` // "telegram", "feishu", ...
|
||||
PlatformID string `json:"platform_id,omitempty"` // Platform-native ID
|
||||
CanonicalID string `json:"canonical_id,omitempty"` // "platform:id" canonical format
|
||||
Username string `json:"username,omitempty"`
|
||||
@@ -1070,8 +1053,6 @@ type channelWorker struct {
|
||||
```go
|
||||
var channelRateConfig = map[string]float64{
|
||||
"telegram": 20, // 20 msg/s
|
||||
"discord": 1, // 1 msg/s
|
||||
"line": 10, // 10 msg/s
|
||||
}
|
||||
// Default: 10 msg/s
|
||||
// burst = max(1, ceil(rate/2))
|
||||
@@ -1297,15 +1278,11 @@ make test # Full test suite
|
||||
| Sub-package | Registered Name | Optional Interfaces |
|
||||
|-------------|----------------|-------------------|
|
||||
| `pkg/channels/telegram/` | `"telegram"` | TypingCapable, PlaceholderCapable, MessageEditor, MediaSender |
|
||||
| `pkg/channels/discord/` | `"discord"` | TypingCapable, PlaceholderCapable, MessageEditor, MediaSender |
|
||||
| `pkg/channels/line/` | `"line"` | TypingCapable, MediaSender, WebhookHandler |
|
||||
| `pkg/channels/onebot/` | `"onebot"` | ReactionCapable, MediaSender |
|
||||
| `pkg/channels/dingtalk/` | `"dingtalk"` | — |
|
||||
| `pkg/channels/feishu/` | `"feishu"` | — (architecture-specific build tags: `feishu_32.go` / `feishu_64.go`) |
|
||||
| `pkg/channels/wecom/` | `"wecom"` | MediaSender |
|
||||
| `pkg/channels/qq/` | `"qq"` | — |
|
||||
| `pkg/channels/whatsapp/` | `"whatsapp"` | — (Bridge mode) |
|
||||
| `pkg/channels/whatsapp_native/` | `"whatsapp_native"` | — (Native whatsmeow mode) |
|
||||
| `pkg/channels/mqtt/` | `"mqtt"` | — |
|
||||
|
||||
### A.3 Interface Quick Reference
|
||||
@@ -1405,8 +1382,6 @@ agentLoop.Stop() // Stop Agent
|
||||
| Channel | Rate (msg/s) | Burst |
|
||||
|---------|-------------|-------|
|
||||
| telegram | 20 | 10 |
|
||||
| discord | 1 | 1 |
|
||||
| line | 10 | 5 |
|
||||
| _others_ | 10 (default) | 5 |
|
||||
|
||||
### A.6 Known Limitations and Caveats
|
||||
@@ -1417,10 +1392,8 @@ agentLoop.Stop() // Stop Agent
|
||||
|
||||
3. **WeCom is now a single channel**: `"wecom"` is implemented as a WebSocket-based AI Bot channel with route persistence. Access control uses the shared channel allowlist mechanism. It no longer exposes the legacy webhook/app split.
|
||||
|
||||
4. **WhatsApp has two modes**: `"whatsapp"` (Bridge mode, communicates via external bridge URL) and `"whatsapp_native"` (native whatsmeow mode, connects directly to WhatsApp). Manager selects which to initialize based on `WhatsAppConfig.UseNative`.
|
||||
|
||||
5. **DingTalk uses Stream mode**: DingTalk uses the SDK's Stream/WebSocket mode (not HTTP webhook), so it does not implement `WebhookHandler`.
|
||||
|
||||
6. **PlaceholderConfig vs implementation**: `PlaceholderConfig` appears in 4 channel configs (Telegram, Discord, LINE, OneBot), but only channels that implement both `PlaceholderCapable` + `MessageEditor` (Telegram, Discord) can actually use placeholder message editing. The rest are reserved fields.
|
||||
6. **PlaceholderConfig vs implementation**: `PlaceholderConfig` appears in 2 channel configs (Telegram, OneBot), but only channels that implement both `PlaceholderCapable` + `MessageEditor` (Telegram) can actually use placeholder message editing. The rest are reserved fields.
|
||||
|
||||
7. **ReasoningChannelID**: Most channel configs include a `reasoning_channel_id` field to route LLM reasoning/thinking output to a designated channel (WhatsApp, Telegram, Feishu, Discord, QQ, DingTalk, LINE, OneBot, WeCom). `BaseChannel` exposes this via the `WithReasoningChannelID` option and `ReasoningChannelID()` method.
|
||||
7. **ReasoningChannelID**: Most channel configs include a `reasoning_channel_id` field to route LLM reasoning/thinking output to a designated channel (Telegram, Feishu, QQ, DingTalk, OneBot, WeCom). `BaseChannel` exposes this via the `WithReasoningChannelID` option and `ReasoningChannelID()` method.
|
||||
@@ -24,7 +24,6 @@
|
||||
```
|
||||
pkg/channels/
|
||||
├── telegram.go # 每个 channel 直接放在 channels 包内
|
||||
├── discord.go
|
||||
├── manager.go # Manager 直接引用各 channel 类型
|
||||
├── ...
|
||||
```
|
||||
@@ -56,10 +55,7 @@ pkg/channels/
|
||||
│ ├── init.go # 工厂注册
|
||||
│ ├── telegram.go # 实现
|
||||
│ └── telegram_commands.go
|
||||
├── discord/
|
||||
│ ├── init.go
|
||||
│ └── discord.go
|
||||
├── line/ onebot/ dingtalk/ feishu/ wecom/ qq/ whatsapp/ whatsapp_native/ mqtt/
|
||||
├── onebot/ dingtalk/ feishu/ wecom/ qq/ mqtt/
|
||||
│ └── ...
|
||||
|
||||
pkg/bus/
|
||||
@@ -78,9 +74,9 @@ pkg/identity/
|
||||
```
|
||||
┌────────────┐ InboundMessage ┌───────────┐ LLM + Tools ┌────────────┐
|
||||
│ Telegram │──┐ │ │ │ │
|
||||
│ Discord │──┤ PublishInbound() │ │ PublishOutbound() │ │
|
||||
│ Weixin │──┤ PublishInbound() │ │ PublishOutbound() │ │
|
||||
│ Feishu │──┼──────────────────────▶ │ MessageBus │ ◀─────────────────── │ AgentLoop │
|
||||
│ LINE │──┤ (buffered chan, 64) │ │ (buffered chan, 64) │ │
|
||||
│ OneBot │──┤ (buffered chan, 64) │ │ (buffered chan, 64) │ │
|
||||
│ ... │──┘ │ │ │ │
|
||||
└────────────┘ └─────┬─────┘ └────────────┘
|
||||
│
|
||||
@@ -125,18 +121,15 @@ pkg/identity/
|
||||
|
||||
在 main 分支上,Channel 文件直接位于 `pkg/channels/` 顶层,例如:
|
||||
- `pkg/channels/telegram.go`
|
||||
- `pkg/channels/discord.go`
|
||||
|
||||
重构后,这些文件已被删除,代码移动到了对应子包:
|
||||
- `pkg/channels/telegram/telegram.go`
|
||||
- `pkg/channels/discord/discord.go`
|
||||
|
||||
#### 步骤 2:理解结构变化映射
|
||||
|
||||
| main 分支文件 | 重构分支位置 | 变化 |
|
||||
|---|---|---|
|
||||
| `pkg/channels/telegram.go` | `pkg/channels/telegram/telegram.go` + `init.go` | 包名从 `channels` 变为 `telegram` |
|
||||
| `pkg/channels/discord.go` | `pkg/channels/discord/discord.go` + `init.go` | 同上 |
|
||||
| `pkg/channels/manager.go` | `pkg/channels/manager.go` | 大幅重写 |
|
||||
| _(不存在)_ | `pkg/channels/base.go` | 新增共享抽象层 |
|
||||
| _(不存在)_ | `pkg/channels/registry.go` | 新增工厂注册表 |
|
||||
@@ -144,7 +137,6 @@ pkg/identity/
|
||||
| _(不存在)_ | `pkg/channels/interfaces.go` | 新增可选能力接口 |
|
||||
| _(不存在)_ | `pkg/channels/media.go` | 新增 MediaSender 接口 |
|
||||
| _(不存在)_ | `pkg/channels/webhook.go` | 新增 WebhookHandler/HealthChecker |
|
||||
| _(不存在)_ | `pkg/channels/whatsapp_native/` | 新增 WhatsApp 原生模式(whatsmeow) |
|
||||
| _(不存在)_ | `pkg/channels/split.go` | 新增消息分割(从 utils 迁入) |
|
||||
| _(不存在)_ | `pkg/bus/types.go` | 新增结构化消息类型 |
|
||||
| _(不存在)_ | `pkg/media/store.go` | 新增媒体文件生命周期管理 |
|
||||
@@ -343,7 +335,6 @@ func init() {
|
||||
// cmd/picoclaw/internal/gateway/helpers.go
|
||||
import (
|
||||
_ "github.com/sipeed/picoclaw/pkg/channels/telegram" // 触发 init() 注册
|
||||
_ "github.com/sipeed/picoclaw/pkg/channels/discord"
|
||||
_ "github.com/sipeed/picoclaw/pkg/channels/your_new_channel" // 新增
|
||||
)
|
||||
```
|
||||
@@ -765,9 +756,9 @@ if c.owner != nil && c.placeholderRecorder != nil {
|
||||
```
|
||||
|
||||
**这意味着**:
|
||||
- 实现 `TypingCapable` 的 channel(Telegram、Discord、LINE)无需在 `handleMessage` 中手动调用 `StartTyping` + `RecordTypingStop`
|
||||
- 实现 `TypingCapable` 的 channel(Telegram)无需在 `handleMessage` 中手动调用 `StartTyping` + `RecordTypingStop`
|
||||
- 实现 `ReactionCapable` 的 channel(OneBot)无需在 `handleMessage` 中手动调用 `AddReaction` + `RecordTypingStop`
|
||||
- 实现 `PlaceholderCapable` 的 channel(Telegram、Discord)无需在 `handleMessage` 中手动发送占位消息并调用 `RecordPlaceholder`
|
||||
- 实现 `PlaceholderCapable` 的 channel(Telegram)无需在 `handleMessage` 中手动发送占位消息并调用 `RecordPlaceholder`
|
||||
- Channel 只需实现对应接口,`HandleMessage` 会自动完成编排
|
||||
- 不实现这些接口的 channel 不受影响(类型断言会失败,跳过)
|
||||
- `PlaceholderCapable` 的 `SendPlaceholder` 方法内部根据配置的 `PlaceholderConfig.Enabled` 决定是否发送;返回 `("", nil)` 时跳过注册
|
||||
@@ -827,14 +818,6 @@ Manager 使用 `InitChannelList()` 来验证类型和解码设置,
|
||||
然后通过 `bc.Type` 查找工厂。不需要在 Manager 中添加每个 channel 的条目——
|
||||
只需注册工厂和配置条目即可。
|
||||
|
||||
> **注意**:如果你的 channel 有多种模式(如 WhatsApp Bridge vs Native),
|
||||
> 在 `channelSettingsFactory` 中注册两种类型,并根据配置分支:
|
||||
> ```go
|
||||
> // 在 config_channel.go 中:
|
||||
> ChannelWhatsApp: (WhatsAppSettings{}),
|
||||
> ChannelWhatsAppNative: (WhatsAppSettings{}),
|
||||
> ```
|
||||
|
||||
#### 在 Gateway 中添加 blank import
|
||||
|
||||
```go
|
||||
@@ -892,7 +875,7 @@ type Peer struct {
|
||||
|
||||
// 发送者身份信息
|
||||
type SenderInfo struct {
|
||||
Platform string `json:"platform,omitempty"` // "telegram", "discord", ...
|
||||
Platform string `json:"platform,omitempty"` // "telegram", "feishu", ...
|
||||
PlatformID string `json:"platform_id,omitempty"` // 平台原始 ID
|
||||
CanonicalID string `json:"canonical_id,omitempty"` // "platform:id" 规范格式
|
||||
Username string `json:"username,omitempty"`
|
||||
@@ -1068,8 +1051,6 @@ type channelWorker struct {
|
||||
```go
|
||||
var channelRateConfig = map[string]float64{
|
||||
"telegram": 20, // 20 msg/s
|
||||
"discord": 1, // 1 msg/s
|
||||
"line": 10, // 10 msg/s
|
||||
}
|
||||
// 默认: 10 msg/s
|
||||
// burst = max(1, ceil(rate/2))
|
||||
@@ -1295,15 +1276,11 @@ make test # 全量测试
|
||||
| 子包 | 注册名 | 可选接口 |
|
||||
|------|--------|----------|
|
||||
| `pkg/channels/telegram/` | `"telegram"` | TypingCapable, PlaceholderCapable, MessageEditor, MediaSender |
|
||||
| `pkg/channels/discord/` | `"discord"` | TypingCapable, PlaceholderCapable, MessageEditor, MediaSender |
|
||||
| `pkg/channels/line/` | `"line"` | TypingCapable, MediaSender, WebhookHandler |
|
||||
| `pkg/channels/onebot/` | `"onebot"` | ReactionCapable, MediaSender |
|
||||
| `pkg/channels/dingtalk/` | `"dingtalk"` | — |
|
||||
| `pkg/channels/feishu/` | `"feishu"` | — (架构特定 build tags: `feishu_32.go` / `feishu_64.go`) |
|
||||
| `pkg/channels/wecom/` | `"wecom"` | MediaSender |
|
||||
| `pkg/channels/qq/` | `"qq"` | — |
|
||||
| `pkg/channels/whatsapp/` | `"whatsapp"` | — (Bridge 模式) |
|
||||
| `pkg/channels/whatsapp_native/` | `"whatsapp_native"` | — (原生 whatsmeow 模式) |
|
||||
| `pkg/channels/mqtt/` | `"mqtt"` | — |
|
||||
|
||||
### A.3 接口速查表
|
||||
@@ -1403,8 +1380,6 @@ agentLoop.Stop() // 停止 Agent
|
||||
| Channel | 速率 (msg/s) | Burst |
|
||||
|---------|-------------|-------|
|
||||
| telegram | 20 | 10 |
|
||||
| discord | 1 | 1 |
|
||||
| line | 10 | 5 |
|
||||
| _其他_ | 10 (默认) | 5 |
|
||||
|
||||
### A.6 已知限制和注意事项
|
||||
@@ -1415,10 +1390,8 @@ agentLoop.Stop() // 停止 Agent
|
||||
|
||||
3. **WeCom 现在只有一个 channel**:`"wecom"` 采用 WebSocket AI Bot 实现,带路由持久化;访问控制走统一的 channel 白名单机制,不再保留旧的 webhook/app 双分支。
|
||||
|
||||
4. **WhatsApp 有两种模式**:`"whatsapp"`(Bridge 模式,通过外部 bridge URL 通信)和 `"whatsapp_native"`(原生 whatsmeow 模式,直接连接 WhatsApp)。Manager 根据 `WhatsAppConfig.UseNative` 决定初始化哪个。
|
||||
|
||||
5. **DingTalk 使用 Stream 模式**:DingTalk 使用 SDK 的 Stream/WebSocket 模式(非 HTTP webhook),因此不实现 `WebhookHandler`。
|
||||
|
||||
6. **PlaceholderConfig 的配置与实现**:`PlaceholderConfig` 出现在 4 个 channel config 中(Telegram、Discord、LINE、OneBot),但只有实现了 `PlaceholderCapable` + `MessageEditor` 的 channel(Telegram、Discord)能真正使用占位消息编辑功能。其余 channel 的 `PlaceholderConfig` 为预留字段。
|
||||
6. **PlaceholderConfig 的配置与实现**:`PlaceholderConfig` 出现在 2 个 channel config 中(Telegram、OneBot),但只有实现了 `PlaceholderCapable` + `MessageEditor` 的 channel(Telegram)能真正使用占位消息编辑功能。其余 channel 的 `PlaceholderConfig` 为预留字段。
|
||||
|
||||
7. **ReasoningChannelID**:大多数 channel config 都包含 `reasoning_channel_id` 字段,用于将 LLM 的思维链(reasoning/thinking)路由到指定 channel(WhatsApp、Telegram、Feishu、Discord、QQ、DingTalk、LINE、OneBot、WeCom)。`BaseChannel` 通过 `WithReasoningChannelID` 选项和 `ReasoningChannelID()` 方法暴露此配置。
|
||||
7. **ReasoningChannelID**:大多数 channel config 都包含 `reasoning_channel_id` 字段,用于将 LLM 的思维链(reasoning/thinking)路由到指定 channel(Telegram、Feishu、QQ、DingTalk、OneBot、WeCom)。`BaseChannel` 通过 `WithReasoningChannelID` 选项和 `ReasoningChannelID()` 方法暴露此配置。
|
||||
@@ -213,7 +213,7 @@ func TestIsAllowedSender(t *testing.T) {
|
||||
},
|
||||
{
|
||||
name: "canonical format wrong platform",
|
||||
allowList: []string{"discord:123456"},
|
||||
allowList: []string{"testchat:123456"},
|
||||
sender: bus.SenderInfo{
|
||||
Platform: "telegram",
|
||||
PlatformID: "123456",
|
||||
|
||||
@@ -1,993 +0,0 @@
|
||||
package discord
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/bwmarrin/discordgo"
|
||||
"github.com/gorilla/websocket"
|
||||
|
||||
"github.com/sipeed/picoclaw/pkg/audio"
|
||||
"github.com/sipeed/picoclaw/pkg/audio/tts"
|
||||
"github.com/sipeed/picoclaw/pkg/bus"
|
||||
"github.com/sipeed/picoclaw/pkg/channels"
|
||||
"github.com/sipeed/picoclaw/pkg/config"
|
||||
"github.com/sipeed/picoclaw/pkg/identity"
|
||||
"github.com/sipeed/picoclaw/pkg/logger"
|
||||
"github.com/sipeed/picoclaw/pkg/media"
|
||||
"github.com/sipeed/picoclaw/pkg/utils"
|
||||
)
|
||||
|
||||
const (
|
||||
sendTimeout = 10 * time.Second
|
||||
)
|
||||
|
||||
var (
|
||||
// Pre-compiled regexes for resolveDiscordRefs (avoid re-compiling per call)
|
||||
channelRefRe = regexp.MustCompile(`<#(\d+)>`)
|
||||
msgLinkRe = regexp.MustCompile(`https://(?:discord\.com|discordapp\.com)/channels/(\d+)/(\d+)/(\d+)`)
|
||||
)
|
||||
|
||||
type DiscordChannel struct {
|
||||
*channels.BaseChannel
|
||||
bc *config.Channel
|
||||
session *discordgo.Session
|
||||
config *config.DiscordSettings
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
typingMu sync.Mutex
|
||||
typingStop map[string]chan struct{} // chatID → stop signal
|
||||
progress *channels.ToolFeedbackAnimator
|
||||
botUserID string // stored for mention checking
|
||||
bus *bus.MessageBus
|
||||
tts tts.TTSProvider
|
||||
playTTSFn func(context.Context, *discordgo.VoiceConnection, string, uint64)
|
||||
ttsVoiceFn func(string) (*discordgo.VoiceConnection, bool)
|
||||
voiceMu sync.RWMutex
|
||||
voiceSSRC map[string]map[uint32]string // guildID -> ssrc -> userID
|
||||
|
||||
// TTS interruption: cancel active playback when user speaks
|
||||
ttsMu sync.Mutex
|
||||
cancelTTS context.CancelFunc
|
||||
ttsPlayID uint64
|
||||
}
|
||||
|
||||
func NewDiscordChannel(
|
||||
bc *config.Channel,
|
||||
cfg *config.DiscordSettings,
|
||||
bus *bus.MessageBus,
|
||||
) (*DiscordChannel, error) {
|
||||
discordgo.Logger = logger.NewLogger("discord").
|
||||
WithLevels(map[int]logger.LogLevel{
|
||||
discordgo.LogError: logger.ERROR,
|
||||
discordgo.LogWarning: logger.WARN,
|
||||
discordgo.LogInformational: logger.INFO,
|
||||
discordgo.LogDebug: logger.DEBUG,
|
||||
}).Log
|
||||
|
||||
session, err := discordgo.New("Bot " + cfg.Token.String())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create discord session: %w", err)
|
||||
}
|
||||
|
||||
if err := applyDiscordProxy(session, cfg.Proxy); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
base := channels.NewBaseChannel("discord", cfg, bus, bc.AllowFrom,
|
||||
channels.WithMaxMessageLength(2000),
|
||||
channels.WithGroupTrigger(bc.GroupTrigger),
|
||||
channels.WithReasoningChannelID(bc.ReasoningChannelID),
|
||||
)
|
||||
|
||||
ch := &DiscordChannel{
|
||||
BaseChannel: base,
|
||||
bc: bc,
|
||||
session: session,
|
||||
config: cfg,
|
||||
ctx: context.Background(),
|
||||
typingStop: make(map[string]chan struct{}),
|
||||
bus: bus,
|
||||
voiceSSRC: make(map[string]map[uint32]string),
|
||||
}
|
||||
ch.playTTSFn = ch.playTTS
|
||||
ch.ttsVoiceFn = ch.voiceConnectionForTTS
|
||||
ch.progress = channels.NewToolFeedbackAnimator(ch.EditMessage)
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
func (c *DiscordChannel) Start(ctx context.Context) error {
|
||||
logger.InfoC("discord", "Starting Discord bot")
|
||||
|
||||
c.ctx, c.cancel = context.WithCancel(ctx)
|
||||
|
||||
// Get bot user ID before opening session to avoid race condition
|
||||
botUser, err := c.session.User("@me")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get bot user: %w", err)
|
||||
}
|
||||
c.botUserID = botUser.ID
|
||||
|
||||
c.session.AddHandler(c.handleMessage)
|
||||
|
||||
go c.listenVoiceControl(c.ctx)
|
||||
|
||||
if err := c.session.Open(); err != nil {
|
||||
return fmt.Errorf("failed to open discord session: %w", err)
|
||||
}
|
||||
|
||||
c.SetRunning(true)
|
||||
|
||||
logger.InfoCF("discord", "Discord bot connected", map[string]any{
|
||||
"username": botUser.Username,
|
||||
"user_id": botUser.ID,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *DiscordChannel) Stop(ctx context.Context) error {
|
||||
logger.InfoC("discord", "Stopping Discord bot")
|
||||
c.SetRunning(false)
|
||||
|
||||
// Stop all typing goroutines before closing session
|
||||
c.typingMu.Lock()
|
||||
for chatID, stop := range c.typingStop {
|
||||
close(stop)
|
||||
delete(c.typingStop, chatID)
|
||||
}
|
||||
c.typingMu.Unlock()
|
||||
|
||||
// Cancel our context so typing goroutines using c.ctx.Done() exit
|
||||
if c.cancel != nil {
|
||||
c.cancel()
|
||||
}
|
||||
if c.progress != nil {
|
||||
c.progress.StopAll()
|
||||
}
|
||||
|
||||
if err := c.session.Close(); err != nil {
|
||||
return fmt.Errorf("failed to close discord session: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *DiscordChannel) Send(ctx context.Context, msg bus.OutboundMessage) ([]string, error) {
|
||||
if !c.IsRunning() {
|
||||
return nil, channels.ErrNotRunning
|
||||
}
|
||||
|
||||
channelID := msg.ChatID
|
||||
if channelID == "" {
|
||||
return nil, fmt.Errorf("channel ID is empty")
|
||||
}
|
||||
|
||||
if len([]rune(msg.Content)) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
isToolFeedback := outboundMessageIsToolFeedback(msg)
|
||||
if isToolFeedback {
|
||||
if msgID, handled, err := c.progress.Update(ctx, channelID, msg.Content); handled {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return []string{msgID}, nil
|
||||
}
|
||||
}
|
||||
trackedMsgID, hasTrackedMsg := c.currentToolFeedbackMessage(channelID)
|
||||
hasTrackedMsg = hasTrackedMsg && !channels.IsCommandReply(msg)
|
||||
if !channels.IsCommandReply(msg) {
|
||||
c.maybeStartTTS(channelID, msg.Content, isToolFeedback)
|
||||
}
|
||||
if !isToolFeedback {
|
||||
if msgIDs, handled := c.FinalizeToolFeedbackMessage(ctx, msg); handled {
|
||||
return msgIDs, nil
|
||||
}
|
||||
}
|
||||
|
||||
content := msg.Content
|
||||
if isToolFeedback {
|
||||
content = channels.InitialAnimatedToolFeedbackContent(msg.Content)
|
||||
}
|
||||
msgID, err := c.sendChunk(ctx, channelID, content, msg.ReplyToMessageID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if isToolFeedback {
|
||||
c.RecordToolFeedbackMessage(channelID, msgID, msg.Content)
|
||||
} else if hasTrackedMsg {
|
||||
c.dismissTrackedToolFeedbackMessage(ctx, channelID, trackedMsgID)
|
||||
}
|
||||
return []string{msgID}, nil
|
||||
}
|
||||
|
||||
func (c *DiscordChannel) maybeStartTTS(channelID, content string, isToolFeedback bool) {
|
||||
if c.tts == nil || isToolFeedback {
|
||||
return
|
||||
}
|
||||
|
||||
voiceFn := c.ttsVoiceFn
|
||||
if voiceFn == nil {
|
||||
voiceFn = c.voiceConnectionForTTS
|
||||
}
|
||||
vc, ok := voiceFn(channelID)
|
||||
if !ok || vc == nil {
|
||||
return
|
||||
}
|
||||
|
||||
// Cancel any previous TTS playback.
|
||||
c.ttsMu.Lock()
|
||||
if c.cancelTTS != nil {
|
||||
c.cancelTTS()
|
||||
}
|
||||
ttsCtx, ttsCancel := context.WithCancel(c.ctx)
|
||||
c.ttsPlayID++
|
||||
playID := c.ttsPlayID
|
||||
c.cancelTTS = ttsCancel
|
||||
playFn := c.playTTSFn
|
||||
c.ttsMu.Unlock()
|
||||
|
||||
if playFn == nil {
|
||||
playFn = c.playTTS
|
||||
}
|
||||
go playFn(ttsCtx, vc, content, playID)
|
||||
}
|
||||
|
||||
func (c *DiscordChannel) voiceConnectionForTTS(channelID string) (*discordgo.VoiceConnection, bool) {
|
||||
if c.session == nil || c.session.State == nil {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
ch, err := c.session.State.Channel(channelID)
|
||||
if err != nil || ch == nil || ch.GuildID == "" {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
vc, ok := c.session.VoiceConnections[ch.GuildID]
|
||||
if !ok || vc == nil {
|
||||
return nil, false
|
||||
}
|
||||
return vc, true
|
||||
}
|
||||
|
||||
// SendMedia implements the channels.MediaSender interface.
|
||||
func (c *DiscordChannel) SendMedia(ctx context.Context, msg bus.OutboundMediaMessage) ([]string, error) {
|
||||
if !c.IsRunning() {
|
||||
return nil, channels.ErrNotRunning
|
||||
}
|
||||
|
||||
channelID := msg.ChatID
|
||||
if channelID == "" {
|
||||
return nil, fmt.Errorf("channel ID is empty")
|
||||
}
|
||||
trackedMsgID, hasTrackedMsg := c.currentToolFeedbackMessage(channelID)
|
||||
|
||||
store := c.GetMediaStore()
|
||||
if store == nil {
|
||||
return nil, fmt.Errorf("no media store available: %w", channels.ErrSendFailed)
|
||||
}
|
||||
|
||||
// Collect all files into a single ChannelMessageSendComplex call
|
||||
files := make([]*discordgo.File, 0, len(msg.Parts))
|
||||
var caption string
|
||||
|
||||
for _, part := range msg.Parts {
|
||||
localPath, err := store.Resolve(part.Ref)
|
||||
if err != nil {
|
||||
logger.ErrorCF("discord", "Failed to resolve media ref", map[string]any{
|
||||
"ref": part.Ref,
|
||||
"error": err.Error(),
|
||||
})
|
||||
continue
|
||||
}
|
||||
|
||||
file, err := os.Open(localPath)
|
||||
if err != nil {
|
||||
logger.ErrorCF("discord", "Failed to open media file", map[string]any{
|
||||
"path": localPath,
|
||||
"error": err.Error(),
|
||||
})
|
||||
continue
|
||||
}
|
||||
// Note: discordgo reads from the Reader and we can't close it before send
|
||||
|
||||
filename := part.Filename
|
||||
if filename == "" {
|
||||
filename = "file"
|
||||
}
|
||||
|
||||
files = append(files, &discordgo.File{
|
||||
Name: filename,
|
||||
ContentType: part.ContentType,
|
||||
Reader: file,
|
||||
})
|
||||
|
||||
if part.Caption != "" && caption == "" {
|
||||
caption = part.Caption
|
||||
}
|
||||
}
|
||||
|
||||
if len(files) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
sendCtx, cancel := context.WithTimeout(ctx, sendTimeout)
|
||||
defer cancel()
|
||||
|
||||
type mediaResult struct {
|
||||
id string
|
||||
err error
|
||||
}
|
||||
done := make(chan mediaResult, 1)
|
||||
go func() {
|
||||
sentMsg, err := c.session.ChannelMessageSendComplex(channelID, &discordgo.MessageSend{
|
||||
Content: caption,
|
||||
Files: files,
|
||||
})
|
||||
if err != nil {
|
||||
done <- mediaResult{err: err}
|
||||
return
|
||||
}
|
||||
done <- mediaResult{id: sentMsg.ID}
|
||||
}()
|
||||
|
||||
select {
|
||||
case r := <-done:
|
||||
// Close all file readers
|
||||
for _, f := range files {
|
||||
if closer, ok := f.Reader.(*os.File); ok {
|
||||
closer.Close()
|
||||
}
|
||||
}
|
||||
if r.err != nil {
|
||||
return nil, fmt.Errorf("discord send media: %w", channels.ErrTemporary)
|
||||
}
|
||||
if hasTrackedMsg {
|
||||
c.dismissTrackedToolFeedbackMessage(ctx, channelID, trackedMsgID)
|
||||
}
|
||||
return []string{r.id}, nil
|
||||
case <-sendCtx.Done():
|
||||
// Close all file readers
|
||||
for _, f := range files {
|
||||
if closer, ok := f.Reader.(*os.File); ok {
|
||||
closer.Close()
|
||||
}
|
||||
}
|
||||
return nil, sendCtx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
// EditMessage implements channels.MessageEditor.
|
||||
func (c *DiscordChannel) EditMessage(ctx context.Context, chatID string, messageID string, content string) error {
|
||||
_, err := c.session.ChannelMessageEdit(chatID, messageID, content, discordgo.WithContext(ctx))
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteMessage implements channels.MessageDeleter.
|
||||
func (c *DiscordChannel) DeleteMessage(ctx context.Context, chatID string, messageID string) error {
|
||||
return c.session.ChannelMessageDelete(chatID, messageID, discordgo.WithContext(ctx))
|
||||
}
|
||||
|
||||
// SendPlaceholder implements channels.PlaceholderCapable.
|
||||
// It sends a placeholder message that will later be edited to the actual
|
||||
// response via EditMessage (channels.MessageEditor).
|
||||
func (c *DiscordChannel) SendPlaceholder(ctx context.Context, chatID string) (string, error) {
|
||||
if !c.bc.Placeholder.Enabled {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
text := c.bc.Placeholder.GetRandomText()
|
||||
|
||||
msg, err := c.session.ChannelMessageSend(chatID, text)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return msg.ID, nil
|
||||
}
|
||||
|
||||
func outboundMessageIsToolFeedback(msg bus.OutboundMessage) bool {
|
||||
if len(msg.Context.Raw) == 0 {
|
||||
return false
|
||||
}
|
||||
return strings.EqualFold(strings.TrimSpace(msg.Context.Raw["message_kind"]), "tool_feedback")
|
||||
}
|
||||
|
||||
func (c *DiscordChannel) currentToolFeedbackMessage(chatID string) (string, bool) {
|
||||
if c.progress == nil {
|
||||
return "", false
|
||||
}
|
||||
return c.progress.Current(chatID)
|
||||
}
|
||||
|
||||
func (c *DiscordChannel) takeToolFeedbackMessage(chatID string) (string, string, bool) {
|
||||
if c.progress == nil {
|
||||
return "", "", false
|
||||
}
|
||||
return c.progress.Take(chatID)
|
||||
}
|
||||
|
||||
func (c *DiscordChannel) RecordToolFeedbackMessage(chatID, messageID, content string) {
|
||||
if c.progress == nil {
|
||||
return
|
||||
}
|
||||
c.progress.Record(chatID, messageID, content)
|
||||
}
|
||||
|
||||
func (c *DiscordChannel) ClearToolFeedbackMessage(chatID string) {
|
||||
if c.progress == nil {
|
||||
return
|
||||
}
|
||||
c.progress.Clear(chatID)
|
||||
}
|
||||
|
||||
func (c *DiscordChannel) DismissToolFeedbackMessage(ctx context.Context, chatID string) {
|
||||
msgID, ok := c.currentToolFeedbackMessage(chatID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
c.dismissTrackedToolFeedbackMessage(ctx, chatID, msgID)
|
||||
}
|
||||
|
||||
func (c *DiscordChannel) dismissTrackedToolFeedbackMessage(ctx context.Context, chatID, messageID string) {
|
||||
if strings.TrimSpace(chatID) == "" || strings.TrimSpace(messageID) == "" {
|
||||
return
|
||||
}
|
||||
c.ClearToolFeedbackMessage(chatID)
|
||||
_ = c.DeleteMessage(ctx, chatID, messageID)
|
||||
}
|
||||
|
||||
func (c *DiscordChannel) finalizeTrackedToolFeedbackMessage(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
content string,
|
||||
editFn func(context.Context, string, string, string) error,
|
||||
) ([]string, bool) {
|
||||
msgID, baseContent, ok := c.takeToolFeedbackMessage(chatID)
|
||||
if !ok || editFn == nil {
|
||||
return nil, false
|
||||
}
|
||||
if err := editFn(ctx, chatID, msgID, content); err != nil {
|
||||
c.RecordToolFeedbackMessage(chatID, msgID, baseContent)
|
||||
return nil, false
|
||||
}
|
||||
return []string{msgID}, true
|
||||
}
|
||||
|
||||
func (c *DiscordChannel) FinalizeToolFeedbackMessage(ctx context.Context, msg bus.OutboundMessage) ([]string, bool) {
|
||||
if outboundMessageIsToolFeedback(msg) || channels.IsCommandReply(msg) {
|
||||
return nil, false
|
||||
}
|
||||
return c.finalizeTrackedToolFeedbackMessage(ctx, msg.ChatID, msg.Content, c.EditMessage)
|
||||
}
|
||||
|
||||
func (c *DiscordChannel) sendChunk(ctx context.Context, channelID, content, replyToID string) (string, error) {
|
||||
// Use the passed ctx for timeout control
|
||||
sendCtx, cancel := context.WithTimeout(ctx, sendTimeout)
|
||||
defer cancel()
|
||||
|
||||
type result struct {
|
||||
id string
|
||||
err error
|
||||
}
|
||||
done := make(chan result, 1)
|
||||
go func() {
|
||||
var (
|
||||
msg *discordgo.Message
|
||||
err error
|
||||
)
|
||||
|
||||
// If we have an ID, we send the message as "Reply"
|
||||
if replyToID != "" {
|
||||
msg, err = c.session.ChannelMessageSendComplex(channelID, &discordgo.MessageSend{
|
||||
Content: content,
|
||||
Reference: &discordgo.MessageReference{
|
||||
MessageID: replyToID,
|
||||
ChannelID: channelID,
|
||||
},
|
||||
})
|
||||
} else {
|
||||
// Otherwise, we send a normal message
|
||||
msg, err = c.session.ChannelMessageSend(channelID, content)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
done <- result{err: fmt.Errorf("discord send: %w", channels.ErrTemporary)}
|
||||
return
|
||||
}
|
||||
done <- result{id: msg.ID}
|
||||
}()
|
||||
|
||||
select {
|
||||
case r := <-done:
|
||||
return r.id, r.err
|
||||
case <-sendCtx.Done():
|
||||
return "", sendCtx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
// appendContent safely appends content to existing text
|
||||
func appendContent(content, suffix string) string {
|
||||
if content == "" {
|
||||
return suffix
|
||||
}
|
||||
return content + "\n" + suffix
|
||||
}
|
||||
|
||||
func (c *DiscordChannel) handleMessage(s *discordgo.Session, m *discordgo.MessageCreate) {
|
||||
if m == nil || m.Author == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if m.Author.ID == s.State.User.ID {
|
||||
return
|
||||
}
|
||||
|
||||
// Check allowlist first to avoid downloading attachments for rejected users
|
||||
sender := bus.SenderInfo{
|
||||
Platform: "discord",
|
||||
PlatformID: m.Author.ID,
|
||||
CanonicalID: identity.BuildCanonicalID("discord", m.Author.ID),
|
||||
Username: m.Author.Username,
|
||||
}
|
||||
// Build display name
|
||||
displayName := m.Author.Username
|
||||
if m.Author.Discriminator != "" && m.Author.Discriminator != "0" {
|
||||
displayName += "#" + m.Author.Discriminator
|
||||
}
|
||||
sender.DisplayName = displayName
|
||||
|
||||
if !c.IsAllowedSender(sender) {
|
||||
logger.DebugCF("discord", "Message rejected by allowlist", map[string]any{
|
||||
"user_id": m.Author.ID,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if c.handleVoiceCommand(s, m) {
|
||||
return
|
||||
}
|
||||
|
||||
content := m.Content
|
||||
|
||||
// In guild (group) channels, apply unified group trigger filtering
|
||||
// DMs (GuildID is empty) always get a response
|
||||
isMentioned := false
|
||||
if m.GuildID != "" {
|
||||
for _, mention := range m.Mentions {
|
||||
if mention.ID == c.botUserID {
|
||||
isMentioned = true
|
||||
break
|
||||
}
|
||||
}
|
||||
content = c.stripBotMention(content)
|
||||
respond, cleaned := c.ShouldRespondInGroup(isMentioned, content)
|
||||
if !respond {
|
||||
logger.DebugCF("discord", "Group message ignored by group trigger", map[string]any{
|
||||
"user_id": m.Author.ID,
|
||||
})
|
||||
return
|
||||
}
|
||||
content = cleaned
|
||||
} else {
|
||||
// DMs: just strip bot mention without filtering
|
||||
content = c.stripBotMention(content)
|
||||
}
|
||||
|
||||
// Resolve Discord refs in main content before concatenation to avoid
|
||||
// double-expanding links that appear in the referenced message.
|
||||
content = c.resolveDiscordRefs(s, content, m.GuildID)
|
||||
|
||||
// Prepend referenced (quoted) message content if this is a reply
|
||||
if m.MessageReference != nil && m.ReferencedMessage != nil {
|
||||
refContent := m.ReferencedMessage.Content
|
||||
if refContent != "" {
|
||||
refAuthor := "unknown"
|
||||
if m.ReferencedMessage.Author != nil {
|
||||
refAuthor = m.ReferencedMessage.Author.Username
|
||||
}
|
||||
refContent = c.resolveDiscordRefs(s, refContent, m.GuildID)
|
||||
content = fmt.Sprintf("[quoted message from %s]: %s\n\n%s",
|
||||
refAuthor, refContent, content)
|
||||
}
|
||||
}
|
||||
|
||||
senderID := m.Author.ID
|
||||
|
||||
mediaPaths := make([]string, 0, len(m.Attachments))
|
||||
|
||||
scope := channels.BuildMediaScope("discord", m.ChannelID, m.ID)
|
||||
|
||||
// Helper to register a local file with the media store
|
||||
storeMedia := func(localPath string, attachment *discordgo.MessageAttachment) string {
|
||||
if store := c.GetMediaStore(); store != nil {
|
||||
ref, err := store.Store(localPath, media.MediaMeta{
|
||||
Filename: attachment.Filename,
|
||||
ContentType: attachment.ContentType,
|
||||
Source: "discord",
|
||||
CleanupPolicy: media.CleanupPolicyDeleteOnCleanup,
|
||||
}, scope)
|
||||
if err == nil {
|
||||
return ref
|
||||
}
|
||||
}
|
||||
return localPath // fallback
|
||||
}
|
||||
|
||||
for _, attachment := range m.Attachments {
|
||||
localPath := c.downloadAttachment(attachment.URL, attachment.Filename)
|
||||
if localPath != "" {
|
||||
mediaPaths = append(mediaPaths, storeMedia(localPath, attachment))
|
||||
tag := attachmentMediaTag(attachment.Filename, attachment.ContentType)
|
||||
content = appendContent(content, fmt.Sprintf("[%s: %s]", tag, attachment.Filename))
|
||||
} else {
|
||||
logger.WarnCF("discord", "Failed to download attachment", map[string]any{
|
||||
"url": attachment.URL,
|
||||
"filename": attachment.Filename,
|
||||
})
|
||||
mediaPaths = append(mediaPaths, attachment.URL)
|
||||
content = appendContent(content, fmt.Sprintf("[attachment: %s]", attachment.URL))
|
||||
}
|
||||
}
|
||||
|
||||
if content == "" && len(mediaPaths) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
if content == "" {
|
||||
content = "[media only]"
|
||||
}
|
||||
|
||||
logger.DebugCF("discord", "Received message", map[string]any{
|
||||
"sender_name": sender.DisplayName,
|
||||
"sender_id": senderID,
|
||||
"preview": utils.Truncate(content, 50),
|
||||
})
|
||||
|
||||
peerKind := "channel"
|
||||
if m.GuildID == "" {
|
||||
peerKind = "direct"
|
||||
}
|
||||
|
||||
metadata := map[string]string{
|
||||
"user_id": senderID,
|
||||
"username": m.Author.Username,
|
||||
"display_name": sender.DisplayName,
|
||||
"guild_id": m.GuildID,
|
||||
"channel_id": m.ChannelID,
|
||||
"is_dm": fmt.Sprintf("%t", m.GuildID == ""),
|
||||
}
|
||||
inboundCtx := bus.InboundContext{
|
||||
Channel: c.Name(),
|
||||
ChatID: m.ChannelID,
|
||||
ChatType: peerKind,
|
||||
SenderID: senderID,
|
||||
MessageID: m.ID,
|
||||
Mentioned: isMentioned,
|
||||
Raw: metadata,
|
||||
}
|
||||
if m.GuildID != "" {
|
||||
inboundCtx.SpaceID = m.GuildID
|
||||
inboundCtx.SpaceType = "guild"
|
||||
}
|
||||
if m.MessageReference != nil {
|
||||
inboundCtx.ReplyToMessageID = m.MessageReference.MessageID
|
||||
}
|
||||
|
||||
c.HandleInboundContext(c.ctx, m.ChannelID, content, mediaPaths, inboundCtx, sender)
|
||||
}
|
||||
|
||||
// startTyping starts a continuous typing indicator loop for the given chatID.
|
||||
// It stops any existing typing loop for that chatID before starting a new one.
|
||||
func (c *DiscordChannel) startTyping(chatID string) {
|
||||
c.typingMu.Lock()
|
||||
// Stop existing loop for this chatID if any
|
||||
if stop, ok := c.typingStop[chatID]; ok {
|
||||
close(stop)
|
||||
}
|
||||
stop := make(chan struct{})
|
||||
c.typingStop[chatID] = stop
|
||||
c.typingMu.Unlock()
|
||||
|
||||
go func() {
|
||||
if err := c.session.ChannelTyping(chatID); err != nil {
|
||||
logger.DebugCF("discord", "ChannelTyping error", map[string]any{"chatID": chatID, "err": err})
|
||||
}
|
||||
ticker := time.NewTicker(8 * time.Second)
|
||||
defer ticker.Stop()
|
||||
timeout := time.After(5 * time.Minute)
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
case <-timeout:
|
||||
return
|
||||
case <-c.ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
if err := c.session.ChannelTyping(chatID); err != nil {
|
||||
logger.DebugCF("discord", "ChannelTyping error", map[string]any{"chatID": chatID, "err": err})
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// stopTyping stops the typing indicator loop for the given chatID.
|
||||
func (c *DiscordChannel) stopTyping(chatID string) {
|
||||
c.typingMu.Lock()
|
||||
defer c.typingMu.Unlock()
|
||||
if stop, ok := c.typingStop[chatID]; ok {
|
||||
close(stop)
|
||||
delete(c.typingStop, chatID)
|
||||
}
|
||||
}
|
||||
|
||||
// StartTyping implements channels.TypingCapable.
|
||||
// It starts a continuous typing indicator and returns an idempotent stop function.
|
||||
func (c *DiscordChannel) StartTyping(ctx context.Context, chatID string) (func(), error) {
|
||||
c.startTyping(chatID)
|
||||
return func() { c.stopTyping(chatID) }, nil
|
||||
}
|
||||
|
||||
func (c *DiscordChannel) downloadAttachment(url, filename string) string {
|
||||
return utils.DownloadFile(url, filename, utils.DownloadOptions{
|
||||
LoggerPrefix: "discord",
|
||||
ProxyURL: c.config.Proxy,
|
||||
})
|
||||
}
|
||||
|
||||
func attachmentMediaTag(filename, contentType string) string {
|
||||
ct := strings.ToLower(contentType)
|
||||
switch {
|
||||
case strings.HasPrefix(ct, "image/"):
|
||||
return "image"
|
||||
case strings.HasPrefix(ct, "audio/"), ct == "application/ogg", ct == "application/x-ogg":
|
||||
return "audio"
|
||||
case strings.HasPrefix(ct, "video/"):
|
||||
return "video"
|
||||
}
|
||||
|
||||
ext := strings.ToLower(filepath.Ext(filename))
|
||||
switch ext {
|
||||
case ".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp":
|
||||
return "image"
|
||||
case ".mp3", ".wav", ".ogg", ".m4a", ".flac", ".aac", ".wma":
|
||||
return "audio"
|
||||
case ".mp4", ".avi", ".mov", ".webm", ".mkv":
|
||||
return "video"
|
||||
}
|
||||
|
||||
return "file"
|
||||
}
|
||||
|
||||
func applyDiscordProxy(session *discordgo.Session, proxyAddr string) error {
|
||||
var proxyFunc func(*http.Request) (*url.URL, error)
|
||||
if proxyAddr != "" {
|
||||
proxyURL, err := url.Parse(proxyAddr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid discord proxy URL %q: %w", proxyAddr, err)
|
||||
}
|
||||
proxyFunc = http.ProxyURL(proxyURL)
|
||||
} else if os.Getenv("HTTP_PROXY") != "" || os.Getenv("HTTPS_PROXY") != "" {
|
||||
proxyFunc = http.ProxyFromEnvironment
|
||||
}
|
||||
|
||||
if proxyFunc == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
transport := &http.Transport{Proxy: proxyFunc}
|
||||
session.Client = &http.Client{
|
||||
Timeout: sendTimeout,
|
||||
Transport: transport,
|
||||
}
|
||||
|
||||
if session.Dialer != nil {
|
||||
dialerCopy := *session.Dialer
|
||||
dialerCopy.Proxy = proxyFunc
|
||||
session.Dialer = &dialerCopy
|
||||
} else {
|
||||
session.Dialer = &websocket.Dialer{Proxy: proxyFunc}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// resolveDiscordRefs resolves channel references (<#id> → #channel-name) and
|
||||
// expands Discord message links to show the linked message content.
|
||||
// Only links pointing to the same guild are expanded to prevent cross-guild leakage.
|
||||
func (c *DiscordChannel) resolveDiscordRefs(s *discordgo.Session, text string, guildID string) string {
|
||||
// 1. Resolve channel references: <#id> → #channel-name
|
||||
text = channelRefRe.ReplaceAllStringFunc(text, func(match string) string {
|
||||
parts := channelRefRe.FindStringSubmatch(match)
|
||||
if len(parts) < 2 {
|
||||
return match
|
||||
}
|
||||
// Prefer session state cache to avoid API calls
|
||||
if ch, err := s.State.Channel(parts[1]); err == nil {
|
||||
return "#" + ch.Name
|
||||
}
|
||||
if ch, err := s.Channel(parts[1]); err == nil {
|
||||
return "#" + ch.Name
|
||||
}
|
||||
return match
|
||||
})
|
||||
|
||||
// 2. Expand Discord message links (max 3, same guild only)
|
||||
matches := msgLinkRe.FindAllStringSubmatch(text, 3)
|
||||
for _, m := range matches {
|
||||
if len(m) < 4 {
|
||||
continue
|
||||
}
|
||||
linkGuildID, channelID, messageID := m[1], m[2], m[3]
|
||||
// Security: only expand links from the same guild
|
||||
if linkGuildID != guildID {
|
||||
continue
|
||||
}
|
||||
msg, err := s.ChannelMessage(channelID, messageID)
|
||||
if err != nil || msg == nil || msg.Content == "" {
|
||||
continue
|
||||
}
|
||||
author := "unknown"
|
||||
if msg.Author != nil {
|
||||
author = msg.Author.Username
|
||||
}
|
||||
text += fmt.Sprintf("\n[linked message from %s]: %s", author, msg.Content)
|
||||
}
|
||||
|
||||
return text
|
||||
}
|
||||
|
||||
// stripBotMention removes the bot mention from the message content.
|
||||
// Discord mentions have the format <@USER_ID> or <@!USER_ID> (with nickname).
|
||||
func (c *DiscordChannel) stripBotMention(text string) string {
|
||||
if c.botUserID == "" {
|
||||
return text
|
||||
}
|
||||
// Remove both regular mention <@USER_ID> and nickname mention <@!USER_ID>
|
||||
text = strings.ReplaceAll(text, fmt.Sprintf("<@%s>", c.botUserID), "")
|
||||
text = strings.ReplaceAll(text, fmt.Sprintf("<@!%s>", c.botUserID), "")
|
||||
return strings.TrimSpace(text)
|
||||
}
|
||||
|
||||
func (c *DiscordChannel) listenVoiceControl(ctx context.Context) {
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case ctrl, ok := <-c.bus.VoiceControlsChan():
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if ctrl.Type == "command" && ctrl.Action == "leave" {
|
||||
if strings.HasPrefix(ctrl.SessionID, "discord_vc_") {
|
||||
guildID := strings.TrimPrefix(ctrl.SessionID, "discord_vc_")
|
||||
vc, exists := c.session.VoiceConnections[guildID]
|
||||
if exists && vc != nil {
|
||||
vc.Disconnect(ctx)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *DiscordChannel) playTTS(ctx context.Context, vc *discordgo.VoiceConnection, text string, playID uint64) {
|
||||
// Capture the cancel func associated with this playback (if any).
|
||||
// Clear cancelTTS when playback finishes (normal or interrupted),
|
||||
// but only if it still refers to this playback's cancel func.
|
||||
defer func() {
|
||||
c.ttsMu.Lock()
|
||||
if c.ttsPlayID == playID {
|
||||
c.cancelTTS = nil
|
||||
}
|
||||
c.ttsMu.Unlock()
|
||||
}()
|
||||
|
||||
sentences := audio.SplitSentences(text)
|
||||
if len(sentences) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
logger.InfoCF("discord", "Starting streamed TTS", map[string]any{"sentences": len(sentences)})
|
||||
|
||||
// Pipeline: prefetch next sentence's audio while playing current
|
||||
type ttResult struct {
|
||||
stream io.ReadCloser
|
||||
err error
|
||||
}
|
||||
|
||||
var prefetch chan ttResult
|
||||
|
||||
// Ensure any in-flight prefetch is drained on exit to prevent stream leaks,
|
||||
// but avoid blocking indefinitely if the prefetch goroutine is stuck or never sends.
|
||||
defer func() {
|
||||
if prefetch != nil {
|
||||
select {
|
||||
case result := <-prefetch:
|
||||
if result.stream != nil {
|
||||
result.stream.Close()
|
||||
}
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
// Timed out waiting for a prefetched result; avoid blocking on exit.
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
for i, sentence := range sentences {
|
||||
// Check for cancellation (interruption)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
logger.InfoCF("discord", "TTS interrupted", map[string]any{"at_sentence": i})
|
||||
return
|
||||
default:
|
||||
}
|
||||
|
||||
// Start prefetching the NEXT sentence while we process the current one
|
||||
var nextPrefetch chan ttResult
|
||||
if i+1 < len(sentences) {
|
||||
nextPrefetch = make(chan ttResult, 1)
|
||||
nextSentence := sentences[i+1]
|
||||
go func() {
|
||||
s, e := c.tts.Synthesize(ctx, nextSentence)
|
||||
nextPrefetch <- ttResult{s, e}
|
||||
}()
|
||||
}
|
||||
|
||||
// Get the current sentence's audio
|
||||
var stream io.ReadCloser
|
||||
var err error
|
||||
|
||||
if prefetch != nil {
|
||||
// Use prefetched result from previous iteration, but be responsive to cancellation.
|
||||
var result ttResult
|
||||
select {
|
||||
case result = <-prefetch:
|
||||
stream, err = result.stream, result.err
|
||||
case <-ctx.Done():
|
||||
// Context canceled while waiting for prefetched audio; abort playback.
|
||||
logger.InfoCF(
|
||||
"discord",
|
||||
"TTS interrupted while waiting for prefetched audio",
|
||||
map[string]any{"at_sentence": i},
|
||||
)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
// First sentence: synthesize directly
|
||||
stream, err = c.tts.Synthesize(ctx, sentence)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
if stream != nil {
|
||||
stream.Close()
|
||||
}
|
||||
logger.ErrorCF("discord", "TTS synthesize failed", map[string]any{"error": err.Error(), "sentence": i})
|
||||
prefetch = nextPrefetch
|
||||
continue
|
||||
}
|
||||
|
||||
if err := streamOggOpusToDiscord(ctx, vc, stream); err != nil {
|
||||
logger.ErrorCF("discord", "TTS playback failed", map[string]any{"error": err.Error(), "sentence": i})
|
||||
}
|
||||
stream.Close()
|
||||
|
||||
prefetch = nextPrefetch
|
||||
}
|
||||
}
|
||||
|
||||
// VoiceCapabilities returns the voice capabilities of the channel.
|
||||
func (c *DiscordChannel) VoiceCapabilities() channels.VoiceCapabilities {
|
||||
return channels.VoiceCapabilities{ASR: true, TTS: true}
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
package discord
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestChannelRefRegex(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
wantID string
|
||||
wantOK bool
|
||||
}{
|
||||
{"basic channel ref", "<#123456789>", "123456789", true},
|
||||
{"long id", "<#9876543210123456>", "9876543210123456", true},
|
||||
{"no match plain text", "hello world", "", false},
|
||||
{"no match partial", "<#>", "", false},
|
||||
{"no match letters", "<#abc>", "", false},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
matches := channelRefRe.FindStringSubmatch(tt.input)
|
||||
if tt.wantOK {
|
||||
if len(matches) < 2 || matches[1] != tt.wantID {
|
||||
t.Errorf("channelRefRe(%q) = %v, want ID %q", tt.input, matches, tt.wantID)
|
||||
}
|
||||
} else {
|
||||
if len(matches) >= 2 {
|
||||
t.Errorf("channelRefRe(%q) should not match, got %v", tt.input, matches)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMsgLinkRegex(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
wantGuild string
|
||||
wantChan string
|
||||
wantMsg string
|
||||
wantOK bool
|
||||
}{
|
||||
{
|
||||
"discord.com link",
|
||||
"https://discord.com/channels/111/222/333",
|
||||
"111", "222", "333", true,
|
||||
},
|
||||
{
|
||||
"discordapp.com link",
|
||||
"https://discordapp.com/channels/111/222/333",
|
||||
"111", "222", "333", true,
|
||||
},
|
||||
{
|
||||
"real world ids",
|
||||
"check this https://discord.com/channels/9000000000000001/9000000000000002/9000000000000003 please",
|
||||
"9000000000000001", "9000000000000002", "9000000000000003", true,
|
||||
},
|
||||
{"no match http", "http://discord.com/channels/1/2/3", "", "", "", false},
|
||||
{"no match missing segment", "https://discord.com/channels/1/2", "", "", "", false},
|
||||
{"no match plain text", "hello world", "", "", "", false},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
matches := msgLinkRe.FindStringSubmatch(tt.input)
|
||||
if tt.wantOK {
|
||||
if len(matches) < 4 {
|
||||
t.Fatalf("msgLinkRe(%q) didn't match, want guild=%s chan=%s msg=%s",
|
||||
tt.input, tt.wantGuild, tt.wantChan, tt.wantMsg)
|
||||
}
|
||||
if matches[1] != tt.wantGuild || matches[2] != tt.wantChan || matches[3] != tt.wantMsg {
|
||||
t.Errorf("msgLinkRe(%q) = guild=%s chan=%s msg=%s, want %s/%s/%s",
|
||||
tt.input, matches[1], matches[2], matches[3],
|
||||
tt.wantGuild, tt.wantChan, tt.wantMsg)
|
||||
}
|
||||
} else {
|
||||
if len(matches) >= 4 {
|
||||
t.Errorf("msgLinkRe(%q) should not match, got %v", tt.input, matches)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMsgLinkRegex_MultipleMatches(t *testing.T) {
|
||||
input := "see https://discord.com/channels/1/2/3 and https://discord.com/channels/4/5/6 and https://discord.com/channels/7/8/9 and https://discord.com/channels/10/11/12"
|
||||
matches := msgLinkRe.FindAllStringSubmatch(input, 3)
|
||||
if len(matches) != 3 {
|
||||
t.Fatalf("expected 3 matches (capped), got %d", len(matches))
|
||||
}
|
||||
// Verify the 3rd match is 7/8/9 (not 10/11/12)
|
||||
if matches[2][1] != "7" || matches[2][2] != "8" || matches[2][3] != "9" {
|
||||
t.Errorf("3rd match = %v, want guild=7 chan=8 msg=9", matches[2])
|
||||
}
|
||||
}
|
||||
@@ -1,351 +0,0 @@
|
||||
package discord
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"reflect"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/bwmarrin/discordgo"
|
||||
|
||||
"github.com/sipeed/picoclaw/pkg/audio/tts"
|
||||
"github.com/sipeed/picoclaw/pkg/bus"
|
||||
"github.com/sipeed/picoclaw/pkg/channels"
|
||||
)
|
||||
|
||||
type stubTTSProvider struct{}
|
||||
|
||||
func (stubTTSProvider) Name() string { return "stub-tts" }
|
||||
|
||||
func (stubTTSProvider) Synthesize(context.Context, string) (io.ReadCloser, error) {
|
||||
return io.NopCloser(&noopReader{}), nil
|
||||
}
|
||||
|
||||
type noopReader struct{}
|
||||
|
||||
func (*noopReader) Read(p []byte) (int, error) {
|
||||
return 0, io.EOF
|
||||
}
|
||||
|
||||
func TestApplyDiscordProxy_CustomProxy(t *testing.T) {
|
||||
session, err := discordgo.New("Bot test-token")
|
||||
if err != nil {
|
||||
t.Fatalf("discordgo.New() error: %v", err)
|
||||
}
|
||||
|
||||
if err = applyDiscordProxy(session, "http://127.0.0.1:7890"); err != nil {
|
||||
t.Fatalf("applyDiscordProxy() error: %v", err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequest("GET", "https://discord.com/api/v10/gateway", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("http.NewRequest() error: %v", err)
|
||||
}
|
||||
|
||||
restProxy := session.Client.Transport.(*http.Transport).Proxy
|
||||
restProxyURL, err := restProxy(req)
|
||||
if err != nil {
|
||||
t.Fatalf("rest proxy func error: %v", err)
|
||||
}
|
||||
if got, want := restProxyURL.String(), "http://127.0.0.1:7890"; got != want {
|
||||
t.Fatalf("REST proxy = %q, want %q", got, want)
|
||||
}
|
||||
|
||||
wsProxyURL, err := session.Dialer.Proxy(req)
|
||||
if err != nil {
|
||||
t.Fatalf("ws proxy func error: %v", err)
|
||||
}
|
||||
if got, want := wsProxyURL.String(), "http://127.0.0.1:7890"; got != want {
|
||||
t.Fatalf("WS proxy = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyDiscordProxy_FromEnvironment(t *testing.T) {
|
||||
t.Setenv("HTTP_PROXY", "http://127.0.0.1:8888")
|
||||
t.Setenv("http_proxy", "http://127.0.0.1:8888")
|
||||
t.Setenv("HTTPS_PROXY", "http://127.0.0.1:8888")
|
||||
t.Setenv("https_proxy", "http://127.0.0.1:8888")
|
||||
t.Setenv("ALL_PROXY", "")
|
||||
t.Setenv("all_proxy", "")
|
||||
t.Setenv("NO_PROXY", "")
|
||||
t.Setenv("no_proxy", "")
|
||||
|
||||
session, err := discordgo.New("Bot test-token")
|
||||
if err != nil {
|
||||
t.Fatalf("discordgo.New() error: %v", err)
|
||||
}
|
||||
|
||||
if err = applyDiscordProxy(session, ""); err != nil {
|
||||
t.Fatalf("applyDiscordProxy() error: %v", err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequest("GET", "https://discord.com/api/v10/gateway", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("http.NewRequest() error: %v", err)
|
||||
}
|
||||
|
||||
gotURL, err := session.Dialer.Proxy(req)
|
||||
if err != nil {
|
||||
t.Fatalf("ws proxy func error: %v", err)
|
||||
}
|
||||
|
||||
wantURL, err := url.Parse("http://127.0.0.1:8888")
|
||||
if err != nil {
|
||||
t.Fatalf("url.Parse() error: %v", err)
|
||||
}
|
||||
if gotURL.String() != wantURL.String() {
|
||||
t.Fatalf("WS proxy = %q, want %q", gotURL.String(), wantURL.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyDiscordProxy_InvalidProxyURL(t *testing.T) {
|
||||
session, err := discordgo.New("Bot test-token")
|
||||
if err != nil {
|
||||
t.Fatalf("discordgo.New() error: %v", err)
|
||||
}
|
||||
|
||||
if err = applyDiscordProxy(session, "://bad-proxy"); err == nil {
|
||||
t.Fatal("applyDiscordProxy() expected error for invalid proxy URL, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSend_NonToolFeedbackDeletesTrackedProgressMessage(t *testing.T) {
|
||||
var (
|
||||
mu sync.Mutex
|
||||
requests []string
|
||||
)
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
mu.Lock()
|
||||
requests = append(requests, r.Method+" "+r.URL.Path)
|
||||
mu.Unlock()
|
||||
|
||||
switch {
|
||||
case r.Method == http.MethodPatch && r.URL.Path == "/channels/chat-1/messages/prog-1":
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = io.WriteString(w, `{"id":"prog-1"}`)
|
||||
default:
|
||||
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
origChannels := discordgo.EndpointChannels
|
||||
discordgo.EndpointChannels = server.URL + "/channels/"
|
||||
defer func() {
|
||||
discordgo.EndpointChannels = origChannels
|
||||
}()
|
||||
|
||||
session, err := discordgo.New("Bot test-token")
|
||||
if err != nil {
|
||||
t.Fatalf("discordgo.New() error: %v", err)
|
||||
}
|
||||
session.Client = server.Client()
|
||||
|
||||
ch := &DiscordChannel{
|
||||
BaseChannel: channels.NewBaseChannel("discord", nil, bus.NewMessageBus(), nil),
|
||||
session: session,
|
||||
ctx: context.Background(),
|
||||
typingStop: make(map[string]chan struct{}),
|
||||
voiceSSRC: make(map[string]map[uint32]string),
|
||||
}
|
||||
ch.progress = channels.NewToolFeedbackAnimator(ch.EditMessage)
|
||||
ch.SetRunning(true)
|
||||
ch.RecordToolFeedbackMessage("chat-1", "prog-1", "🔧 `read_file`")
|
||||
|
||||
ids, err := ch.Send(context.Background(), bus.OutboundMessage{
|
||||
ChatID: "chat-1",
|
||||
Content: "final reply",
|
||||
Context: bus.InboundContext{
|
||||
Channel: "discord",
|
||||
ChatID: "chat-1",
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Send() error = %v", err)
|
||||
}
|
||||
if got, want := ids, []string{"prog-1"}; !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("Send() ids = %v, want %v", got, want)
|
||||
}
|
||||
if _, ok := ch.currentToolFeedbackMessage("chat-1"); ok {
|
||||
t.Fatal("expected tracked tool feedback message to be cleared")
|
||||
}
|
||||
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
wantRequests := []string{
|
||||
"PATCH /channels/chat-1/messages/prog-1",
|
||||
}
|
||||
if !reflect.DeepEqual(requests, wantRequests) {
|
||||
t.Fatalf("requests = %v, want %v", requests, wantRequests)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEditMessage_UsesContextCancellation(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
select {
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
case <-time.After(time.Second):
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = io.WriteString(w, `{"id":"msg-1"}`)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
origChannels := discordgo.EndpointChannels
|
||||
discordgo.EndpointChannels = server.URL + "/channels/"
|
||||
defer func() {
|
||||
discordgo.EndpointChannels = origChannels
|
||||
}()
|
||||
|
||||
session, err := discordgo.New("Bot test-token")
|
||||
if err != nil {
|
||||
t.Fatalf("discordgo.New() error: %v", err)
|
||||
}
|
||||
session.Client = server.Client()
|
||||
|
||||
ch := &DiscordChannel{
|
||||
BaseChannel: channels.NewBaseChannel("discord", nil, bus.NewMessageBus(), nil),
|
||||
session: session,
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
|
||||
defer cancel()
|
||||
|
||||
start := time.Now()
|
||||
err = ch.EditMessage(ctx, "chat-1", "msg-1", "still running")
|
||||
elapsed := time.Since(start)
|
||||
|
||||
if err == nil {
|
||||
t.Fatal("expected EditMessage() to fail when context times out")
|
||||
}
|
||||
if elapsed >= 500*time.Millisecond {
|
||||
t.Fatalf("EditMessage() ignored context timeout, elapsed=%v", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFinalizeTrackedToolFeedbackMessage_StopsTrackingBeforeEdit(t *testing.T) {
|
||||
ch := &DiscordChannel{
|
||||
progress: channels.NewToolFeedbackAnimator(nil),
|
||||
}
|
||||
ch.RecordToolFeedbackMessage("chat-1", "msg-1", "🔧 `read_file`")
|
||||
|
||||
msgIDs, handled := ch.finalizeTrackedToolFeedbackMessage(
|
||||
context.Background(),
|
||||
"chat-1",
|
||||
"final reply",
|
||||
func(_ context.Context, chatID, messageID, content string) error {
|
||||
if _, ok := ch.currentToolFeedbackMessage(chatID); ok {
|
||||
t.Fatal("expected tracked tool feedback to be stopped before edit")
|
||||
}
|
||||
if chatID != "chat-1" || messageID != "msg-1" || content != "final reply" {
|
||||
t.Fatalf("unexpected edit args: %s %s %s", chatID, messageID, content)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
)
|
||||
if !handled {
|
||||
t.Fatal("expected finalizeTrackedToolFeedbackMessage to handle tracked message")
|
||||
}
|
||||
if got, want := msgIDs, []string{"msg-1"}; !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("finalizeTrackedToolFeedbackMessage() ids = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFinalizeToolFeedbackMessage_CommandReplyPreservesProgress(t *testing.T) {
|
||||
ch := &DiscordChannel{progress: channels.NewToolFeedbackAnimator(nil)}
|
||||
ch.RecordToolFeedbackMessage("chat-1", "progress-1", "Working")
|
||||
_, handled := ch.FinalizeToolFeedbackMessage(t.Context(), bus.OutboundMessage{
|
||||
ChatID: "chat-1", Content: "请待会再试",
|
||||
Context: bus.InboundContext{Raw: map[string]string{"outbound_kind": "command_reply"}},
|
||||
})
|
||||
if handled {
|
||||
t.Fatal("command reply finalized task progress")
|
||||
}
|
||||
if id, ok := ch.currentToolFeedbackMessage("chat-1"); !ok || id != "progress-1" {
|
||||
t.Fatal("task progress was removed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSend_NonToolFeedbackFinalizerStillStartsTTS(t *testing.T) {
|
||||
var (
|
||||
mu sync.Mutex
|
||||
requests []string
|
||||
)
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
mu.Lock()
|
||||
requests = append(requests, r.Method+" "+r.URL.Path)
|
||||
mu.Unlock()
|
||||
|
||||
switch {
|
||||
case r.Method == http.MethodPatch && r.URL.Path == "/channels/chat-1/messages/prog-1":
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = io.WriteString(w, `{"id":"prog-1"}`)
|
||||
default:
|
||||
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
origChannels := discordgo.EndpointChannels
|
||||
discordgo.EndpointChannels = server.URL + "/channels/"
|
||||
defer func() {
|
||||
discordgo.EndpointChannels = origChannels
|
||||
}()
|
||||
|
||||
session, err := discordgo.New("Bot test-token")
|
||||
if err != nil {
|
||||
t.Fatalf("discordgo.New() error: %v", err)
|
||||
}
|
||||
session.Client = server.Client()
|
||||
|
||||
ttsStarted := make(chan string, 1)
|
||||
ch := &DiscordChannel{
|
||||
BaseChannel: channels.NewBaseChannel("discord", nil, bus.NewMessageBus(), nil),
|
||||
session: session,
|
||||
ctx: context.Background(),
|
||||
typingStop: make(map[string]chan struct{}),
|
||||
voiceSSRC: make(map[string]map[uint32]string),
|
||||
tts: tts.TTSProvider(stubTTSProvider{}),
|
||||
}
|
||||
ch.ttsVoiceFn = func(string) (*discordgo.VoiceConnection, bool) {
|
||||
return &discordgo.VoiceConnection{}, true
|
||||
}
|
||||
ch.playTTSFn = func(_ context.Context, _ *discordgo.VoiceConnection, text string, _ uint64) {
|
||||
ttsStarted <- text
|
||||
}
|
||||
ch.progress = channels.NewToolFeedbackAnimator(ch.EditMessage)
|
||||
ch.SetRunning(true)
|
||||
ch.RecordToolFeedbackMessage("chat-1", "prog-1", "🔧 `read_file`")
|
||||
|
||||
ids, err := ch.Send(context.Background(), bus.OutboundMessage{
|
||||
ChatID: "chat-1",
|
||||
Content: "final reply",
|
||||
Context: bus.InboundContext{
|
||||
Channel: "discord",
|
||||
ChatID: "chat-1",
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Send() error = %v", err)
|
||||
}
|
||||
if got, want := ids, []string{"prog-1"}; !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("Send() ids = %v, want %v", got, want)
|
||||
}
|
||||
|
||||
select {
|
||||
case got := <-ttsStarted:
|
||||
if got != "final reply" {
|
||||
t.Fatalf("TTS content = %q, want final reply", got)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("expected TTS to start for finalized tracked tool feedback reply")
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
package discord
|
||||
|
||||
import (
|
||||
"github.com/sipeed/picoclaw/pkg/audio/tts"
|
||||
"github.com/sipeed/picoclaw/pkg/bus"
|
||||
"github.com/sipeed/picoclaw/pkg/channels"
|
||||
"github.com/sipeed/picoclaw/pkg/config"
|
||||
)
|
||||
|
||||
func init() {
|
||||
channels.RegisterFactory(
|
||||
config.ChannelDiscord,
|
||||
func(channelName, channelType string, cfg *config.Config, b *bus.MessageBus) (channels.Channel, error) {
|
||||
bc := cfg.Channels[channelName]
|
||||
decoded, err := bc.GetDecoded()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c, ok := decoded.(*config.DiscordSettings)
|
||||
if !ok {
|
||||
return nil, channels.ErrSendFailed
|
||||
}
|
||||
ch, err := NewDiscordChannel(bc, c, b)
|
||||
if err == nil {
|
||||
ch.tts = tts.DetectTTS(cfg)
|
||||
}
|
||||
return ch, err
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -1,316 +0,0 @@
|
||||
package discord
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/bwmarrin/discordgo"
|
||||
|
||||
"github.com/sipeed/picoclaw/pkg/audio"
|
||||
"github.com/sipeed/picoclaw/pkg/bus"
|
||||
"github.com/sipeed/picoclaw/pkg/identity"
|
||||
"github.com/sipeed/picoclaw/pkg/logger"
|
||||
)
|
||||
|
||||
func (c *DiscordChannel) setVoiceUserID(guildID string, ssrc uint32, userID string) {
|
||||
if userID == "" {
|
||||
return
|
||||
}
|
||||
|
||||
c.voiceMu.Lock()
|
||||
defer c.voiceMu.Unlock()
|
||||
|
||||
ssrcMap, ok := c.voiceSSRC[guildID]
|
||||
if !ok {
|
||||
ssrcMap = make(map[uint32]string)
|
||||
c.voiceSSRC[guildID] = ssrcMap
|
||||
}
|
||||
ssrcMap[ssrc] = userID
|
||||
}
|
||||
|
||||
func (c *DiscordChannel) voiceUserID(guildID string, ssrc uint32) string {
|
||||
c.voiceMu.RLock()
|
||||
defer c.voiceMu.RUnlock()
|
||||
|
||||
ssrcMap, ok := c.voiceSSRC[guildID]
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
return ssrcMap[ssrc]
|
||||
}
|
||||
|
||||
func (c *DiscordChannel) handleVoiceCommand(s *discordgo.Session, m *discordgo.MessageCreate) bool {
|
||||
if m.Content == "!vc join" {
|
||||
vs, err := s.State.VoiceState(m.GuildID, m.Author.ID)
|
||||
if err != nil || vs == nil {
|
||||
if _, sendErr := s.ChannelMessageSend(
|
||||
m.ChannelID,
|
||||
"You need to be in a voice channel first!",
|
||||
); sendErr != nil {
|
||||
logger.InfoCF("discord", "Failed to send voice channel requirement message", map[string]any{
|
||||
"channel": m.ChannelID,
|
||||
"error": sendErr,
|
||||
})
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
logger.InfoCF("discord", "Joining voice channel", map[string]any{"channel": vs.ChannelID})
|
||||
vc, err := s.ChannelVoiceJoin(c.ctx, m.GuildID, vs.ChannelID, false, false)
|
||||
if err != nil {
|
||||
if _, sendErr := s.ChannelMessageSend(
|
||||
m.ChannelID,
|
||||
fmt.Sprintf("Failed to join voice channel: %v", err),
|
||||
); sendErr != nil {
|
||||
logger.InfoCF("discord", "Failed to send voice join error message", map[string]any{
|
||||
"channel": m.ChannelID,
|
||||
"error": sendErr,
|
||||
})
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
go c.receiveVoice(vc, m.GuildID, m.ChannelID)
|
||||
if _, sendErr := s.ChannelMessageSend(
|
||||
m.ChannelID,
|
||||
"Joined Voice Channel! Listening for audio...",
|
||||
); sendErr != nil {
|
||||
logger.InfoCF("discord", "Failed to send voice join success message", map[string]any{
|
||||
"channel": m.ChannelID,
|
||||
"error": sendErr,
|
||||
})
|
||||
}
|
||||
return true
|
||||
} else if m.Content == "!vc leave" {
|
||||
vc, exists := s.VoiceConnections[m.GuildID]
|
||||
if exists && vc != nil {
|
||||
if err := vc.Disconnect(c.ctx); err != nil {
|
||||
logger.InfoCF("discord", "Failed to disconnect from voice channel", map[string]any{
|
||||
"guild": m.GuildID,
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
if _, sendErr := s.ChannelMessageSend(m.ChannelID, "Left Voice Channel."); sendErr != nil {
|
||||
logger.InfoCF("discord", "Failed to send voice leave success message", map[string]any{
|
||||
"channel": m.ChannelID,
|
||||
"error": sendErr,
|
||||
})
|
||||
}
|
||||
} else {
|
||||
if _, sendErr := s.ChannelMessageSend(m.ChannelID, "Not in a voice channel."); sendErr != nil {
|
||||
logger.InfoCF("discord", "Failed to send voice not-in-channel message", map[string]any{
|
||||
"channel": m.ChannelID,
|
||||
"error": sendErr,
|
||||
})
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func VoiceReceiveActive(vc *discordgo.VoiceConnection) bool {
|
||||
return vc != nil && vc.OpusRecv != nil
|
||||
}
|
||||
|
||||
func streamOggOpusToDiscord(ctx context.Context, vc *discordgo.VoiceConnection, r io.Reader) (retErr error) {
|
||||
// Recover from panic if vc.OpusSend is closed mid-send (e.g. on disconnect)
|
||||
defer func() {
|
||||
if rec := recover(); rec != nil {
|
||||
retErr = fmt.Errorf("voice connection closed during playback")
|
||||
logger.RecoverPanicNoExit(rec)
|
||||
}
|
||||
}()
|
||||
|
||||
// Wait for the speaking transition to register
|
||||
vc.Speaking(true)
|
||||
defer vc.Speaking(false)
|
||||
|
||||
return audio.DecodeOggOpus(r, func(frame []byte) error {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case vc.OpusSend <- frame:
|
||||
return nil
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (c *DiscordChannel) receiveVoice(vc *discordgo.VoiceConnection, guildID string, chatID string) {
|
||||
logger.InfoCF("discord", "Started listening for voice", map[string]any{"guild": guildID})
|
||||
|
||||
vc.AddHandler(func(_ *discordgo.VoiceConnection, vs *discordgo.VoiceSpeakingUpdate) {
|
||||
if vs == nil {
|
||||
return
|
||||
}
|
||||
c.setVoiceUserID(guildID, uint32(vs.SSRC), vs.UserID)
|
||||
})
|
||||
|
||||
defer func() {
|
||||
c.voiceMu.Lock()
|
||||
delete(c.voiceSSRC, guildID)
|
||||
c.voiceMu.Unlock()
|
||||
}()
|
||||
|
||||
go func(ctx context.Context, vc *discordgo.VoiceConnection) {
|
||||
// Recover from potential panics if OpusSend is closed mid-send.
|
||||
defer func() {
|
||||
if rec := recover(); rec != nil {
|
||||
logger.WarnCF("discord", "Recovered from panic while sending wake-up frames", map[string]any{
|
||||
"error": rec,
|
||||
"guild": guildID,
|
||||
})
|
||||
}
|
||||
}()
|
||||
|
||||
// If the voice connection or OpusSend are not available, nothing to do.
|
||||
if vc == nil || vc.OpusSend == nil {
|
||||
return
|
||||
}
|
||||
|
||||
time.Sleep(250 * time.Millisecond) // Wait a bit for connection to settle
|
||||
|
||||
// Abort if the context has already been canceled.
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
default:
|
||||
}
|
||||
|
||||
vc.Speaking(true)
|
||||
defer vc.Speaking(false)
|
||||
|
||||
silenceFrame := []byte{0xF8, 0xFF, 0xFE}
|
||||
for i := 0; i < 5; i++ {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case vc.OpusSend <- silenceFrame:
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
|
||||
logger.DebugCF("discord", "Sent wake-up silence frames", map[string]any{"guild": guildID})
|
||||
}(c.ctx, vc)
|
||||
sessionID := fmt.Sprintf("discord_vc_%s", guildID)
|
||||
|
||||
c.bus.PublishVoiceControl(c.ctx, bus.VoiceControl{
|
||||
SessionID: sessionID,
|
||||
Type: "state",
|
||||
Action: "listening",
|
||||
})
|
||||
|
||||
var sequence uint64 = 0
|
||||
var interruptCount int
|
||||
var lastInterruptAt time.Time
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-c.ctx.Done():
|
||||
return
|
||||
case p, ok := <-vc.OpusRecv:
|
||||
if !ok {
|
||||
logger.InfoCF("discord", "Voice channel closed", map[string]any{"guild": guildID})
|
||||
// Cancel any TTS that may still be playing
|
||||
c.ttsMu.Lock()
|
||||
if c.cancelTTS != nil {
|
||||
c.cancelTTS()
|
||||
c.cancelTTS = nil
|
||||
}
|
||||
c.ttsMu.Unlock()
|
||||
return
|
||||
}
|
||||
|
||||
if p == nil {
|
||||
logger.DebugCF("discord", "Received nil Opus packet", nil)
|
||||
continue
|
||||
}
|
||||
|
||||
if len(p.Opus) == 0 {
|
||||
logger.DebugCF("discord", "Received empty Opus packet", map[string]any{
|
||||
"seq": p.Sequence,
|
||||
"ssrc": p.SSRC,
|
||||
})
|
||||
continue
|
||||
}
|
||||
|
||||
logger.DebugCF("discord", "Received Opus packet", map[string]any{
|
||||
"seq": p.Sequence,
|
||||
"len": len(p.Opus),
|
||||
"ssrc": p.SSRC,
|
||||
})
|
||||
// Interruption detection: if user sends voice while TTS is playing,
|
||||
// cancel TTS after a short debounce (3 packets in 200ms)
|
||||
now := time.Now()
|
||||
if now.Sub(lastInterruptAt) > 500*time.Millisecond {
|
||||
interruptCount = 0
|
||||
}
|
||||
interruptCount++
|
||||
lastInterruptAt = now
|
||||
|
||||
if interruptCount >= 3 {
|
||||
c.ttsMu.Lock()
|
||||
if c.cancelTTS != nil {
|
||||
c.cancelTTS()
|
||||
c.cancelTTS = nil
|
||||
logger.InfoCF("discord", "TTS interrupted by user voice", nil)
|
||||
}
|
||||
c.ttsMu.Unlock()
|
||||
interruptCount = 0
|
||||
}
|
||||
|
||||
userID := c.voiceUserID(guildID, p.SSRC)
|
||||
if userID == "" {
|
||||
logger.DebugCF("discord", "Dropping voice packet without user mapping", map[string]any{
|
||||
"ssrc": p.SSRC,
|
||||
"guild": guildID,
|
||||
})
|
||||
continue
|
||||
}
|
||||
|
||||
sender := bus.SenderInfo{
|
||||
Platform: "discord",
|
||||
PlatformID: userID,
|
||||
CanonicalID: identity.BuildCanonicalID("discord", userID),
|
||||
}
|
||||
if !c.IsAllowedSender(sender) {
|
||||
logger.DebugCF("discord", "Voice packet rejected by allowlist", map[string]any{
|
||||
"user_id": userID,
|
||||
"guild": guildID,
|
||||
})
|
||||
continue
|
||||
}
|
||||
|
||||
sequence++
|
||||
|
||||
chunk := bus.AudioChunk{
|
||||
SessionID: sessionID,
|
||||
SpeakerID: userID,
|
||||
ChatID: chatID,
|
||||
Channel: "discord",
|
||||
Sequence: sequence,
|
||||
Timestamp: p.Timestamp,
|
||||
SampleRate: 48000,
|
||||
Channels: 2,
|
||||
Format: "opus",
|
||||
Data: p.Opus,
|
||||
}
|
||||
|
||||
// Pass the parent context directly; the bus applies its own
|
||||
// audio drop budget internally.
|
||||
// A 100ms caller-level timeout would fire before the bus's
|
||||
// backpressure handling, masking drop counters and events.
|
||||
err := c.bus.PublishAudioChunk(c.ctx, chunk)
|
||||
if err != nil {
|
||||
logger.ErrorCF("discord", "Failed to publish audio chunk", map[string]any{
|
||||
"guild": guildID,
|
||||
"sessionID": sessionID,
|
||||
"sequence": sequence,
|
||||
"error": err.Error(),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
package line
|
||||
|
||||
import (
|
||||
"github.com/sipeed/picoclaw/pkg/bus"
|
||||
"github.com/sipeed/picoclaw/pkg/channels"
|
||||
"github.com/sipeed/picoclaw/pkg/config"
|
||||
)
|
||||
|
||||
func init() {
|
||||
channels.RegisterFactory(
|
||||
config.ChannelLINE,
|
||||
func(channelName, channelType string, cfg *config.Config, b *bus.MessageBus) (channels.Channel, error) {
|
||||
bc := cfg.Channels[channelName]
|
||||
decoded, err := bc.GetDecoded()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c, ok := decoded.(*config.LINESettings)
|
||||
if !ok {
|
||||
return nil, channels.ErrSendFailed
|
||||
}
|
||||
return NewLINEChannel(bc, c, b)
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -1,627 +0,0 @@
|
||||
package line
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/line/line-bot-sdk-go/v8/linebot/messaging_api"
|
||||
"github.com/line/line-bot-sdk-go/v8/linebot/webhook"
|
||||
|
||||
"github.com/sipeed/picoclaw/pkg/bus"
|
||||
"github.com/sipeed/picoclaw/pkg/channels"
|
||||
"github.com/sipeed/picoclaw/pkg/config"
|
||||
"github.com/sipeed/picoclaw/pkg/identity"
|
||||
"github.com/sipeed/picoclaw/pkg/logger"
|
||||
"github.com/sipeed/picoclaw/pkg/media"
|
||||
"github.com/sipeed/picoclaw/pkg/utils"
|
||||
)
|
||||
|
||||
const (
|
||||
lineContentEndpoint = "https://api-data.line.me/v2/bot/message/%s/content"
|
||||
lineReplyTokenMaxAge = 25 * time.Second
|
||||
|
||||
// Limit request body to prevent memory exhaustion (DoS).
|
||||
// LINE webhook payloads are typically a few KB; 1 MiB is generous.
|
||||
maxWebhookBodySize = 1 << 20 // 1 MiB
|
||||
)
|
||||
|
||||
type replyTokenEntry struct {
|
||||
token string
|
||||
timestamp time.Time
|
||||
}
|
||||
|
||||
// LINEChannel implements the Channel interface for LINE Official Account
|
||||
// using the LINE Messaging API with HTTP webhook for receiving messages
|
||||
// and the official LINE Bot SDK for sending messages.
|
||||
type LINEChannel struct {
|
||||
*channels.BaseChannel
|
||||
config *config.LINESettings
|
||||
client *messaging_api.MessagingApiAPI
|
||||
botUserID string // Bot's user ID
|
||||
botBasicID string // Bot's basic ID (e.g. @216ru...)
|
||||
botDisplayName string // Bot's display name for text-based mention detection
|
||||
replyTokens sync.Map // chatID -> replyTokenEntry
|
||||
quoteTokens sync.Map // chatID -> quoteToken (string)
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
// NewLINEChannel creates a new LINE channel instance.
|
||||
func NewLINEChannel(
|
||||
bc *config.Channel,
|
||||
cfg *config.LINESettings,
|
||||
messageBus *bus.MessageBus,
|
||||
) (*LINEChannel, error) {
|
||||
if cfg.ChannelSecret.String() == "" || cfg.ChannelAccessToken.String() == "" {
|
||||
return nil, fmt.Errorf("line channel_secret and channel_access_token are required")
|
||||
}
|
||||
|
||||
client, err := messaging_api.NewMessagingApiAPI(
|
||||
cfg.ChannelAccessToken.String(),
|
||||
messaging_api.WithHTTPClient(&http.Client{Timeout: 30 * time.Second}),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create LINE messaging client: %w", err)
|
||||
}
|
||||
|
||||
base := channels.NewBaseChannel(
|
||||
"line", cfg, messageBus, bc.AllowFrom,
|
||||
channels.WithMaxMessageLength(5000),
|
||||
channels.WithGroupTrigger(bc.GroupTrigger),
|
||||
channels.WithReasoningChannelID(bc.ReasoningChannelID),
|
||||
)
|
||||
|
||||
return &LINEChannel{
|
||||
BaseChannel: base,
|
||||
config: cfg,
|
||||
client: client,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Start initializes the LINE channel.
|
||||
func (c *LINEChannel) Start(ctx context.Context) error {
|
||||
logger.InfoC("line", "Starting LINE channel (Webhook Mode)")
|
||||
|
||||
c.ctx, c.cancel = context.WithCancel(ctx)
|
||||
|
||||
// Fetch bot profile to get bot's userId for mention detection
|
||||
info, err := c.client.WithContext(ctx).GetBotInfo()
|
||||
if err != nil {
|
||||
logger.WarnCF("line", "Failed to fetch bot info (mention detection disabled)", map[string]any{
|
||||
"error": err.Error(),
|
||||
})
|
||||
} else {
|
||||
c.botUserID = info.UserId
|
||||
c.botBasicID = info.BasicId
|
||||
c.botDisplayName = info.DisplayName
|
||||
logger.InfoCF("line", "Bot info fetched", map[string]any{
|
||||
"bot_user_id": c.botUserID,
|
||||
"basic_id": c.botBasicID,
|
||||
"display_name": c.botDisplayName,
|
||||
})
|
||||
}
|
||||
|
||||
c.SetRunning(true)
|
||||
logger.InfoC("line", "LINE channel started (Webhook Mode)")
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stop gracefully stops the LINE channel.
|
||||
func (c *LINEChannel) Stop(ctx context.Context) error {
|
||||
logger.InfoC("line", "Stopping LINE channel")
|
||||
|
||||
if c.cancel != nil {
|
||||
c.cancel()
|
||||
}
|
||||
|
||||
c.SetRunning(false)
|
||||
logger.InfoC("line", "LINE channel stopped")
|
||||
return nil
|
||||
}
|
||||
|
||||
// WebhookPath returns the path for registering on the shared HTTP server.
|
||||
func (c *LINEChannel) WebhookPath() string {
|
||||
if c.config.WebhookPath != "" {
|
||||
return c.config.WebhookPath
|
||||
}
|
||||
return "/webhook/line"
|
||||
}
|
||||
|
||||
// ServeHTTP implements http.Handler for the shared HTTP server.
|
||||
func (c *LINEChannel) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
c.webhookHandler(w, r)
|
||||
}
|
||||
|
||||
// webhookHandler handles incoming LINE webhook requests.
|
||||
func (c *LINEChannel) webhookHandler(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
// Limit body size to prevent memory exhaustion (DoS).
|
||||
// ParseRequest reads r.Body internally via io.ReadAll; wrapping with
|
||||
// MaxBytesReader ensures oversized payloads are rejected before full
|
||||
// allocation.
|
||||
r.Body = http.MaxBytesReader(w, r.Body, maxWebhookBodySize)
|
||||
|
||||
cb, err := webhook.ParseRequest(c.config.ChannelSecret.String(), r)
|
||||
if err != nil {
|
||||
var maxBytesErr *http.MaxBytesError
|
||||
if errors.As(err, &maxBytesErr) {
|
||||
logger.WarnC("line", "Webhook request body too large, rejected")
|
||||
http.Error(w, "Request entity too large", http.StatusRequestEntityTooLarge)
|
||||
} else if errors.Is(err, webhook.ErrInvalidSignature) {
|
||||
logger.WarnC("line", "Invalid webhook signature")
|
||||
http.Error(w, "Forbidden", http.StatusForbidden)
|
||||
} else {
|
||||
logger.ErrorCF("line", "Failed to parse webhook request", map[string]any{
|
||||
"error": err.Error(),
|
||||
})
|
||||
http.Error(w, "Bad request", http.StatusBadRequest)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Return 200 immediately, process events asynchronously
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
||||
for _, event := range cb.Events {
|
||||
go c.processEvent(event)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *LINEChannel) processEvent(event webhook.EventInterface) {
|
||||
msgEvent, ok := event.(webhook.MessageEvent)
|
||||
if !ok {
|
||||
logger.DebugCF("line", "Ignoring non-message event", map[string]any{
|
||||
"type": event.GetType(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
senderID, chatID, sourceType := c.resolveSource(msgEvent.Source)
|
||||
isGroup := sourceType == "group" || sourceType == "room"
|
||||
|
||||
// Store reply token for later use
|
||||
if msgEvent.ReplyToken != "" {
|
||||
c.replyTokens.Store(chatID, replyTokenEntry{
|
||||
token: msgEvent.ReplyToken,
|
||||
timestamp: time.Now(),
|
||||
})
|
||||
}
|
||||
|
||||
var content string
|
||||
var mediaPaths []string
|
||||
var messageID string
|
||||
var quoteToken string
|
||||
var isMentioned bool
|
||||
|
||||
// Helper to register a local file with the media store
|
||||
storeMedia := func(localPath, filename, scope string) string {
|
||||
if store := c.GetMediaStore(); store != nil {
|
||||
ref, err := store.Store(localPath, media.MediaMeta{
|
||||
Filename: filename,
|
||||
Source: "line",
|
||||
}, scope)
|
||||
if err == nil {
|
||||
return ref
|
||||
}
|
||||
}
|
||||
return localPath // fallback
|
||||
}
|
||||
|
||||
switch msg := msgEvent.Message.(type) {
|
||||
case webhook.TextMessageContent:
|
||||
messageID = msg.Id
|
||||
content = msg.Text
|
||||
isMentioned = c.isBotMentioned(msg)
|
||||
// Store quote token for quoting the original message in reply
|
||||
if msg.QuoteToken != "" {
|
||||
quoteToken = msg.QuoteToken
|
||||
c.quoteTokens.Store(chatID, msg.QuoteToken)
|
||||
}
|
||||
// Strip bot mention from text in group chats
|
||||
if isGroup {
|
||||
content = c.stripBotMention(content, msg)
|
||||
}
|
||||
case webhook.ImageMessageContent:
|
||||
messageID = msg.Id
|
||||
if msg.QuoteToken != "" {
|
||||
quoteToken = msg.QuoteToken
|
||||
c.quoteTokens.Store(chatID, msg.QuoteToken)
|
||||
}
|
||||
if localPath := c.downloadContent(msg.Id, "image.jpg"); localPath != "" {
|
||||
scope := channels.BuildMediaScope("line", chatID, msg.Id)
|
||||
mediaPaths = append(mediaPaths, storeMedia(localPath, "image.jpg", scope))
|
||||
content = "[image]"
|
||||
}
|
||||
case webhook.AudioMessageContent:
|
||||
messageID = msg.Id
|
||||
if localPath := c.downloadContent(msg.Id, "audio.m4a"); localPath != "" {
|
||||
scope := channels.BuildMediaScope("line", chatID, msg.Id)
|
||||
mediaPaths = append(mediaPaths, storeMedia(localPath, "audio.m4a", scope))
|
||||
content = "[audio]"
|
||||
}
|
||||
case webhook.VideoMessageContent:
|
||||
messageID = msg.Id
|
||||
if msg.QuoteToken != "" {
|
||||
quoteToken = msg.QuoteToken
|
||||
c.quoteTokens.Store(chatID, msg.QuoteToken)
|
||||
}
|
||||
if localPath := c.downloadContent(msg.Id, "video.mp4"); localPath != "" {
|
||||
scope := channels.BuildMediaScope("line", chatID, msg.Id)
|
||||
mediaPaths = append(mediaPaths, storeMedia(localPath, "video.mp4", scope))
|
||||
content = "[video]"
|
||||
}
|
||||
case webhook.FileMessageContent:
|
||||
messageID = msg.Id
|
||||
content = "[file]"
|
||||
case webhook.LocationMessageContent:
|
||||
messageID = msg.Id
|
||||
content = "[location]"
|
||||
if msg.Title != "" {
|
||||
content = fmt.Sprintf("[location: %s]", msg.Title)
|
||||
}
|
||||
case webhook.StickerMessageContent:
|
||||
messageID = msg.Id
|
||||
if msg.QuoteToken != "" {
|
||||
quoteToken = msg.QuoteToken
|
||||
c.quoteTokens.Store(chatID, msg.QuoteToken)
|
||||
}
|
||||
content = "[sticker]"
|
||||
default:
|
||||
logger.DebugCF("line", "Ignoring unsupported message type", map[string]any{
|
||||
"type": msgEvent.Message.GetType(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if strings.TrimSpace(content) == "" {
|
||||
return
|
||||
}
|
||||
|
||||
// In group chats, apply unified group trigger filtering
|
||||
if isGroup {
|
||||
respond, cleaned := c.ShouldRespondInGroup(isMentioned, content)
|
||||
if !respond {
|
||||
logger.DebugCF("line", "Ignoring group message by group trigger", map[string]any{
|
||||
"chat_id": chatID,
|
||||
})
|
||||
return
|
||||
}
|
||||
content = cleaned
|
||||
}
|
||||
|
||||
metadata := map[string]string{
|
||||
"platform": "line",
|
||||
"source_type": sourceType,
|
||||
}
|
||||
|
||||
logger.DebugCF("line", "Received message", map[string]any{
|
||||
"sender_id": senderID,
|
||||
"chat_id": chatID,
|
||||
"message_type": msgEvent.Message.GetType(),
|
||||
"is_group": isGroup,
|
||||
"preview": utils.Truncate(content, 50),
|
||||
})
|
||||
|
||||
sender := bus.SenderInfo{
|
||||
Platform: "line",
|
||||
PlatformID: senderID,
|
||||
CanonicalID: identity.BuildCanonicalID("line", senderID),
|
||||
}
|
||||
|
||||
if !c.IsAllowedSender(sender) {
|
||||
return
|
||||
}
|
||||
|
||||
inboundCtx := bus.InboundContext{
|
||||
Channel: c.Name(),
|
||||
ChatID: chatID,
|
||||
ChatType: map[bool]string{true: "group", false: "direct"}[isGroup],
|
||||
SenderID: senderID,
|
||||
MessageID: messageID,
|
||||
Mentioned: isMentioned,
|
||||
Raw: metadata,
|
||||
}
|
||||
if msgEvent.ReplyToken != "" {
|
||||
inboundCtx.ReplyHandles = map[string]string{
|
||||
"reply_token": msgEvent.ReplyToken,
|
||||
}
|
||||
if quoteToken != "" {
|
||||
inboundCtx.ReplyHandles["quote_token"] = quoteToken
|
||||
}
|
||||
}
|
||||
|
||||
c.HandleInboundContext(c.ctx, chatID, content, mediaPaths, inboundCtx, sender)
|
||||
}
|
||||
|
||||
// isBotMentioned checks if the bot is mentioned in the message.
|
||||
// It first checks the mention metadata (userId match or IsSelf), then falls back
|
||||
// to text-based detection using the bot's display name, since LINE may
|
||||
// not include userId in mentionees for Official Accounts.
|
||||
func (c *LINEChannel) isBotMentioned(msg webhook.TextMessageContent) bool {
|
||||
if msg.Mention != nil {
|
||||
for _, m := range msg.Mention.Mentionees {
|
||||
switch mentionee := m.(type) {
|
||||
case webhook.AllMentionee:
|
||||
return true
|
||||
case webhook.UserMentionee:
|
||||
if mentionee.IsSelf {
|
||||
return true
|
||||
}
|
||||
if c.botUserID != "" && mentionee.UserId == c.botUserID {
|
||||
return true
|
||||
}
|
||||
// Check if mentionee text overlaps with bot display name
|
||||
if c.botDisplayName != "" && mentionee.Index >= 0 && mentionee.Length > 0 {
|
||||
runes := []rune(msg.Text)
|
||||
end := int(mentionee.Index) + int(mentionee.Length)
|
||||
if end <= len(runes) {
|
||||
mentionText := string(runes[mentionee.Index:end])
|
||||
if strings.Contains(mentionText, c.botDisplayName) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: text-based detection with display name
|
||||
if c.botDisplayName != "" && strings.Contains(msg.Text, "@"+c.botDisplayName) {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// stripBotMention removes the @BotName mention text from the message.
|
||||
func (c *LINEChannel) stripBotMention(text string, msg webhook.TextMessageContent) string {
|
||||
stripped := false
|
||||
|
||||
if msg.Mention != nil {
|
||||
runes := []rune(text)
|
||||
for i := len(msg.Mention.Mentionees) - 1; i >= 0; i-- {
|
||||
m := msg.Mention.Mentionees[i]
|
||||
shouldStrip := false
|
||||
var index, length int32
|
||||
|
||||
switch mentionee := m.(type) {
|
||||
case webhook.UserMentionee:
|
||||
index = mentionee.Index
|
||||
length = mentionee.Length
|
||||
if mentionee.IsSelf {
|
||||
shouldStrip = true
|
||||
} else if c.botUserID != "" && mentionee.UserId == c.botUserID {
|
||||
shouldStrip = true
|
||||
} else if c.botDisplayName != "" && index >= 0 && length > 0 {
|
||||
end := int(index) + int(length)
|
||||
if end <= len(runes) {
|
||||
mentionText := string(runes[index:end])
|
||||
if strings.Contains(mentionText, c.botDisplayName) {
|
||||
shouldStrip = true
|
||||
}
|
||||
}
|
||||
}
|
||||
case webhook.AllMentionee:
|
||||
// Don't strip @All mentions
|
||||
continue
|
||||
default:
|
||||
continue
|
||||
}
|
||||
|
||||
if shouldStrip {
|
||||
start := int(index)
|
||||
end := int(index) + int(length)
|
||||
if start >= 0 && end <= len(runes) {
|
||||
runes = append(runes[:start], runes[end:]...)
|
||||
stripped = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if stripped {
|
||||
return strings.TrimSpace(string(runes))
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: strip @DisplayName from text
|
||||
if c.botDisplayName != "" {
|
||||
text = strings.ReplaceAll(text, "@"+c.botDisplayName, "")
|
||||
}
|
||||
|
||||
return strings.TrimSpace(text)
|
||||
}
|
||||
|
||||
// resolveSource extracts senderID, chatID, and source type from the event source.
|
||||
func (c *LINEChannel) resolveSource(source webhook.SourceInterface) (senderID, chatID, sourceType string) {
|
||||
switch src := source.(type) {
|
||||
case webhook.GroupSource:
|
||||
return src.UserId, src.GroupId, "group"
|
||||
case webhook.RoomSource:
|
||||
return src.UserId, src.RoomId, "room"
|
||||
case webhook.UserSource:
|
||||
return src.UserId, src.UserId, "user"
|
||||
default:
|
||||
logger.WarnCF("line", "Unknown source type", map[string]any{
|
||||
"type": fmt.Sprintf("%T", source),
|
||||
})
|
||||
return "", "", "unknown"
|
||||
}
|
||||
}
|
||||
|
||||
// Send sends a message to LINE. It first tries the Reply API (free)
|
||||
// using a cached reply token, then falls back to the Push API.
|
||||
func (c *LINEChannel) Send(ctx context.Context, msg bus.OutboundMessage) ([]string, error) {
|
||||
if !c.IsRunning() {
|
||||
return nil, channels.ErrNotRunning
|
||||
}
|
||||
|
||||
// Load and consume quote token for this chat
|
||||
var quoteToken string
|
||||
if qt, ok := c.quoteTokens.LoadAndDelete(msg.ChatID); ok {
|
||||
quoteToken = qt.(string)
|
||||
}
|
||||
|
||||
textMsg := messaging_api.TextMessage{
|
||||
Text: msg.Content,
|
||||
QuoteToken: quoteToken,
|
||||
}
|
||||
|
||||
// Try reply token first (free, valid for ~25 seconds)
|
||||
if entry, ok := c.replyTokens.LoadAndDelete(msg.ChatID); ok {
|
||||
tokenEntry := entry.(replyTokenEntry)
|
||||
if time.Since(tokenEntry.timestamp) < lineReplyTokenMaxAge {
|
||||
resp, _, err := c.client.WithContext(ctx).ReplyMessageWithHttpInfo(&messaging_api.ReplyMessageRequest{
|
||||
ReplyToken: tokenEntry.token,
|
||||
Messages: []messaging_api.MessageInterface{&textMsg},
|
||||
})
|
||||
if resp != nil && resp.Body != nil {
|
||||
_ = resp.Body.Close()
|
||||
}
|
||||
if err == nil {
|
||||
logger.DebugCF("line", "Message sent via Reply API", map[string]any{
|
||||
"chat_id": msg.ChatID,
|
||||
"quoted": quoteToken != "",
|
||||
})
|
||||
return nil, nil
|
||||
}
|
||||
logger.DebugCF("line", "Reply API failed, falling back to Push API", map[string]any{
|
||||
"error": err.Error(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Fall back to Push API
|
||||
resp, _, err := c.client.WithContext(ctx).PushMessageWithHttpInfo(&messaging_api.PushMessageRequest{
|
||||
To: msg.ChatID,
|
||||
Messages: []messaging_api.MessageInterface{&textMsg},
|
||||
}, "")
|
||||
return nil, classifySDKError(resp, err)
|
||||
}
|
||||
|
||||
// SendMedia implements the channels.MediaSender interface.
|
||||
// LINE requires media to be accessible via public URL; since we only have local files,
|
||||
// we fall back to sending a text message with the filename/caption.
|
||||
// For full support, an external file hosting service would be needed.
|
||||
func (c *LINEChannel) SendMedia(ctx context.Context, msg bus.OutboundMediaMessage) ([]string, error) {
|
||||
if !c.IsRunning() {
|
||||
return nil, channels.ErrNotRunning
|
||||
}
|
||||
|
||||
store := c.GetMediaStore()
|
||||
if store == nil {
|
||||
return nil, fmt.Errorf("no media store available: %w", channels.ErrSendFailed)
|
||||
}
|
||||
|
||||
// LINE Messaging API requires publicly accessible URLs for media messages.
|
||||
// Since we only have local file paths, send caption text as fallback.
|
||||
for _, part := range msg.Parts {
|
||||
caption := part.Caption
|
||||
if caption == "" {
|
||||
caption = fmt.Sprintf("[%s: %s]", part.Type, part.Filename)
|
||||
}
|
||||
|
||||
textMsg := messaging_api.TextMessage{Text: caption}
|
||||
resp, _, err := c.client.WithContext(ctx).PushMessageWithHttpInfo(&messaging_api.PushMessageRequest{
|
||||
To: msg.ChatID,
|
||||
Messages: []messaging_api.MessageInterface{&textMsg},
|
||||
}, "")
|
||||
if sdkErr := classifySDKError(resp, err); sdkErr != nil {
|
||||
return nil, sdkErr
|
||||
}
|
||||
}
|
||||
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// StartTyping implements channels.TypingCapable using LINE's loading animation.
|
||||
//
|
||||
// NOTE: The LINE loading animation API only works for 1:1 chats.
|
||||
// Group/room chat IDs (starting with "C" or "R") are detected automatically;
|
||||
// for these, a no-op stop function is returned without calling the API.
|
||||
func (c *LINEChannel) StartTyping(ctx context.Context, chatID string) (func(), error) {
|
||||
if chatID == "" {
|
||||
return func() {}, nil
|
||||
}
|
||||
|
||||
// Group/room chats: LINE loading animation is 1:1 only.
|
||||
if strings.HasPrefix(chatID, "C") || strings.HasPrefix(chatID, "R") {
|
||||
return func() {}, nil
|
||||
}
|
||||
|
||||
typingCtx, cancel := context.WithCancel(ctx)
|
||||
var once sync.Once
|
||||
stop := func() { once.Do(cancel) }
|
||||
|
||||
// Send immediately, then refresh periodically for long-running tasks.
|
||||
if err := c.sendLoading(typingCtx, chatID); err != nil {
|
||||
stop()
|
||||
return stop, err
|
||||
}
|
||||
|
||||
ticker := time.NewTicker(50 * time.Second)
|
||||
go func() {
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-typingCtx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
if err := c.sendLoading(typingCtx, chatID); err != nil {
|
||||
logger.DebugCF("line", "Failed to refresh loading indicator", map[string]any{
|
||||
"error": err.Error(),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
return stop, nil
|
||||
}
|
||||
|
||||
// classifySDKError maps an SDK HTTP response to the project's sentinel errors.
|
||||
func classifySDKError(resp *http.Response, err error) error {
|
||||
if resp != nil && resp.Body != nil {
|
||||
_ = resp.Body.Close()
|
||||
}
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if resp != nil {
|
||||
return channels.ClassifySendError(resp.StatusCode, err)
|
||||
}
|
||||
return channels.ClassifyNetError(err)
|
||||
}
|
||||
|
||||
// sendLoading sends a loading animation indicator to the chat.
|
||||
func (c *LINEChannel) sendLoading(ctx context.Context, chatID string) error {
|
||||
req := &messaging_api.ShowLoadingAnimationRequest{
|
||||
ChatId: chatID,
|
||||
LoadingSeconds: 60,
|
||||
}
|
||||
resp, _, err := c.client.WithContext(ctx).ShowLoadingAnimationWithHttpInfo(req)
|
||||
return classifySDKError(resp, err)
|
||||
}
|
||||
|
||||
// downloadContent downloads media content from the LINE content API.
|
||||
func (c *LINEChannel) downloadContent(messageID, filename string) string {
|
||||
url := fmt.Sprintf(lineContentEndpoint, messageID)
|
||||
return utils.DownloadFile(url, filename, utils.DownloadOptions{
|
||||
LoggerPrefix: "line",
|
||||
ExtraHeaders: map[string]string{
|
||||
"Authorization": "Bearer " + c.config.ChannelAccessToken.String(),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// VoiceCapabilities returns the voice capabilities of the channel.
|
||||
func (c *LINEChannel) VoiceCapabilities() channels.VoiceCapabilities {
|
||||
return channels.VoiceCapabilities{ASR: true, TTS: true}
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
package line
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/sipeed/picoclaw/pkg/config"
|
||||
)
|
||||
|
||||
func TestWebhookRejectsOversizedBody(t *testing.T) {
|
||||
ch := &LINEChannel{config: &config.LINESettings{}}
|
||||
|
||||
oversized := bytes.Repeat([]byte("A"), maxWebhookBodySize+1)
|
||||
req := httptest.NewRequest(http.MethodPost, "/webhook", bytes.NewReader(oversized))
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
ch.webhookHandler(rec, req)
|
||||
|
||||
if rec.Code != http.StatusRequestEntityTooLarge {
|
||||
t.Errorf("expected status %d, got %d", http.StatusRequestEntityTooLarge, rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebhookAcceptsMaxBodySize(t *testing.T) {
|
||||
ch := &LINEChannel{config: &config.LINESettings{}}
|
||||
|
||||
body := bytes.Repeat([]byte("A"), maxWebhookBodySize)
|
||||
req := httptest.NewRequest(http.MethodPost, "/webhook", bytes.NewReader(body))
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
ch.webhookHandler(rec, req)
|
||||
|
||||
// Missing signature should be rejected, but the body size should not trigger 413.
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Errorf("expected status %d, got %d", http.StatusForbidden, rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebhookRejectsOversizedBodyBeforeSignatureCheck(t *testing.T) {
|
||||
ch := &LINEChannel{config: &config.LINESettings{}}
|
||||
|
||||
oversized := bytes.Repeat([]byte("A"), maxWebhookBodySize+1)
|
||||
req := httptest.NewRequest(http.MethodPost, "/webhook", bytes.NewReader(oversized))
|
||||
req.Header.Set("X-Line-Signature", "invalidsignature")
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
ch.webhookHandler(rec, req)
|
||||
|
||||
if rec.Code != http.StatusRequestEntityTooLarge {
|
||||
t.Errorf("expected status %d, got %d", http.StatusRequestEntityTooLarge, rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebhookRejectsNonPostMethod(t *testing.T) {
|
||||
ch := &LINEChannel{config: &config.LINESettings{}}
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/webhook", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
ch.webhookHandler(rec, req)
|
||||
|
||||
if rec.Code != http.StatusMethodNotAllowed {
|
||||
t.Errorf("expected status %d, got %d", http.StatusMethodNotAllowed, rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebhookRejectsInvalidSignature(t *testing.T) {
|
||||
ch := &LINEChannel{
|
||||
config: &config.LINESettings{},
|
||||
}
|
||||
|
||||
body := `{"events":[]}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/webhook", strings.NewReader(body))
|
||||
req.Header.Set("X-Line-Signature", "invalidsignature")
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
ch.webhookHandler(rec, req)
|
||||
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Errorf("expected status %d, got %d", http.StatusForbidden, rec.Code)
|
||||
}
|
||||
}
|
||||
@@ -67,8 +67,6 @@ type placeholderEntry struct {
|
||||
// channelRateConfig maps channel name to per-second rate limit.
|
||||
var channelRateConfig = map[string]float64{
|
||||
"telegram": 20,
|
||||
"discord": 1,
|
||||
"line": 10,
|
||||
"qq": 5,
|
||||
}
|
||||
|
||||
@@ -1033,13 +1031,6 @@ func (m *Manager) getChannelConfigAndEnabled(channelName string) (*config.Channe
|
||||
return bc, false
|
||||
}
|
||||
|
||||
// Use Type to determine the config struct for validation.
|
||||
// The map key (channelName) is the config key, which may differ from the type.
|
||||
channelType := bc.Type
|
||||
if channelType == "" {
|
||||
channelType = channelName
|
||||
}
|
||||
|
||||
// Settings have already been decoded by InitChannelList, so we just need to
|
||||
// type-assert and check the relevant fields.
|
||||
decoded, err := bc.GetDecoded()
|
||||
@@ -1048,19 +1039,12 @@ func (m *Manager) getChannelConfigAndEnabled(channelName string) (*config.Channe
|
||||
}
|
||||
//nolint:revive
|
||||
switch settings := decoded.(type) {
|
||||
case *config.WhatsAppSettings:
|
||||
if channelType == config.ChannelWhatsApp {
|
||||
return bc, settings.BridgeURL != ""
|
||||
}
|
||||
return bc, channelType == config.ChannelWhatsAppNative && settings.UseNative
|
||||
case *config.WeComSettings:
|
||||
return bc, settings.BotID != "" && settings.Secret.String() != ""
|
||||
case *config.DingTalkSettings:
|
||||
return bc, settings.ClientID != ""
|
||||
case *config.WeixinSettings:
|
||||
return bc, settings.Token.String() != ""
|
||||
case *config.LINESettings:
|
||||
return bc, settings.ChannelAccessToken.String() != ""
|
||||
case *config.OneBotSettings:
|
||||
return bc, settings.WSUrl != ""
|
||||
case *config.QQSettings:
|
||||
@@ -1069,8 +1053,6 @@ func (m *Manager) getChannelConfigAndEnabled(channelName string) (*config.Channe
|
||||
return bc, settings.Token.String() != ""
|
||||
case *config.FeishuSettings:
|
||||
return bc, settings.AppSecret.String() != ""
|
||||
case *config.DiscordSettings:
|
||||
return bc, settings.Token.String() != ""
|
||||
case *config.MQTTSettings:
|
||||
return bc, settings.Broker != "" && settings.AgentID != ""
|
||||
}
|
||||
|
||||
@@ -50,19 +50,10 @@ func hiddenValues(key string, value map[string]any, ch *config.Channel) {
|
||||
if settings, ok := v.(*config.TelegramSettings); ok {
|
||||
value["token"] = settings.Token.String()
|
||||
}
|
||||
case "discord":
|
||||
if settings, ok := v.(*config.DiscordSettings); ok {
|
||||
value["token"] = settings.Token.String()
|
||||
}
|
||||
case "onebot":
|
||||
if settings, ok := v.(*config.OneBotSettings); ok {
|
||||
value["token"] = settings.AccessToken.String()
|
||||
}
|
||||
case "line":
|
||||
if settings, ok := v.(*config.LINESettings); ok {
|
||||
value["token"] = settings.ChannelAccessToken.String()
|
||||
value["secret"] = settings.ChannelSecret.String()
|
||||
}
|
||||
case "wecom":
|
||||
if settings, ok := v.(*config.WeComSettings); ok {
|
||||
value["secret"] = settings.Secret.String()
|
||||
|
||||
@@ -3017,8 +3017,8 @@ func TestBuildMediaScope_FastIDUniqueness(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestBuildMediaScope_WithMessageID(t *testing.T) {
|
||||
scope := BuildMediaScope("discord", "chat99", "msg123")
|
||||
expected := "discord:chat99:msg123"
|
||||
scope := BuildMediaScope("testchat", "chat99", "msg123")
|
||||
expected := "testchat:chat99:msg123"
|
||||
if scope != expected {
|
||||
t.Fatalf("expected %s, got %s", expected, scope)
|
||||
}
|
||||
|
||||
@@ -16,11 +16,9 @@ type VoiceCapabilityProvider interface {
|
||||
// Deprecated: Channels should implement VoiceCapabilityProvider instead.
|
||||
// To be removed once all existing capable channels conform to the interface.
|
||||
var asrCapableChannels = map[string]bool{
|
||||
"discord": true,
|
||||
"telegram": true,
|
||||
"qq": true,
|
||||
"weixin": true,
|
||||
"line": true,
|
||||
"feishu": true,
|
||||
"onebot": true,
|
||||
}
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
package whatsapp
|
||||
|
||||
import (
|
||||
"github.com/sipeed/picoclaw/pkg/bus"
|
||||
"github.com/sipeed/picoclaw/pkg/channels"
|
||||
"github.com/sipeed/picoclaw/pkg/config"
|
||||
)
|
||||
|
||||
func init() {
|
||||
channels.RegisterFactory(
|
||||
config.ChannelWhatsApp,
|
||||
func(channelName, channelType string, cfg *config.Config, b *bus.MessageBus) (channels.Channel, error) {
|
||||
bc := cfg.Channels[channelName]
|
||||
decoded, err := bc.GetDecoded()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c, ok := decoded.(*config.WhatsAppSettings)
|
||||
if !ok {
|
||||
return nil, channels.ErrSendFailed
|
||||
}
|
||||
return NewWhatsAppChannel(bc, c, b)
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -1,262 +0,0 @@
|
||||
package whatsapp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
|
||||
"github.com/sipeed/picoclaw/pkg/bus"
|
||||
"github.com/sipeed/picoclaw/pkg/channels"
|
||||
"github.com/sipeed/picoclaw/pkg/config"
|
||||
"github.com/sipeed/picoclaw/pkg/identity"
|
||||
"github.com/sipeed/picoclaw/pkg/logger"
|
||||
"github.com/sipeed/picoclaw/pkg/utils"
|
||||
)
|
||||
|
||||
type WhatsAppChannel struct {
|
||||
*channels.BaseChannel
|
||||
conn *websocket.Conn
|
||||
config *config.WhatsAppSettings
|
||||
url string
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
mu sync.Mutex
|
||||
connected bool
|
||||
}
|
||||
|
||||
func NewWhatsAppChannel(
|
||||
bc *config.Channel,
|
||||
cfg *config.WhatsAppSettings,
|
||||
bus *bus.MessageBus,
|
||||
) (*WhatsAppChannel, error) {
|
||||
base := channels.NewBaseChannel(
|
||||
"whatsapp",
|
||||
cfg,
|
||||
bus,
|
||||
bc.AllowFrom,
|
||||
channels.WithMaxMessageLength(65536),
|
||||
channels.WithReasoningChannelID(bc.ReasoningChannelID),
|
||||
)
|
||||
|
||||
return &WhatsAppChannel{
|
||||
BaseChannel: base,
|
||||
config: cfg,
|
||||
url: cfg.BridgeURL,
|
||||
connected: false,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *WhatsAppChannel) Start(ctx context.Context) error {
|
||||
logger.InfoCF("whatsapp", "Starting WhatsApp channel", map[string]any{
|
||||
"bridge_url": c.url,
|
||||
})
|
||||
|
||||
c.ctx, c.cancel = context.WithCancel(ctx)
|
||||
|
||||
dialer := websocket.DefaultDialer
|
||||
dialer.HandshakeTimeout = 10 * time.Second
|
||||
|
||||
conn, resp, err := dialer.Dial(c.url, nil)
|
||||
if resp != nil {
|
||||
_ = resp.Body.Close()
|
||||
}
|
||||
if err != nil {
|
||||
c.cancel()
|
||||
return fmt.Errorf("failed to connect to WhatsApp bridge: %w", err)
|
||||
}
|
||||
|
||||
c.mu.Lock()
|
||||
c.conn = conn
|
||||
c.connected = true
|
||||
c.mu.Unlock()
|
||||
|
||||
c.SetRunning(true)
|
||||
logger.InfoC("whatsapp", "WhatsApp channel connected")
|
||||
|
||||
go c.listen()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *WhatsAppChannel) Stop(ctx context.Context) error {
|
||||
logger.InfoC("whatsapp", "Stopping WhatsApp channel...")
|
||||
|
||||
// Cancel context first to signal listen goroutine to exit
|
||||
if c.cancel != nil {
|
||||
c.cancel()
|
||||
}
|
||||
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
if c.conn != nil {
|
||||
if err := c.conn.Close(); err != nil {
|
||||
logger.ErrorCF("whatsapp", "Error closing WhatsApp connection", map[string]any{
|
||||
"error": err.Error(),
|
||||
})
|
||||
}
|
||||
c.conn = nil
|
||||
}
|
||||
|
||||
c.connected = false
|
||||
c.SetRunning(false)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *WhatsAppChannel) Send(ctx context.Context, msg bus.OutboundMessage) ([]string, error) {
|
||||
if !c.IsRunning() {
|
||||
return nil, channels.ErrNotRunning
|
||||
}
|
||||
|
||||
// Check ctx before acquiring lock
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
default:
|
||||
}
|
||||
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
if c.conn == nil {
|
||||
return nil, fmt.Errorf("whatsapp connection not established: %w", channels.ErrTemporary)
|
||||
}
|
||||
|
||||
payload := map[string]any{
|
||||
"type": "message",
|
||||
"to": msg.ChatID,
|
||||
"content": msg.Content,
|
||||
}
|
||||
|
||||
data, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to marshal message: %w", err)
|
||||
}
|
||||
|
||||
_ = c.conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
|
||||
if err := c.conn.WriteMessage(websocket.TextMessage, data); err != nil {
|
||||
_ = c.conn.SetWriteDeadline(time.Time{})
|
||||
return nil, fmt.Errorf("whatsapp send: %w", channels.ErrTemporary)
|
||||
}
|
||||
_ = c.conn.SetWriteDeadline(time.Time{})
|
||||
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (c *WhatsAppChannel) listen() {
|
||||
for {
|
||||
select {
|
||||
case <-c.ctx.Done():
|
||||
return
|
||||
default:
|
||||
c.mu.Lock()
|
||||
conn := c.conn
|
||||
c.mu.Unlock()
|
||||
|
||||
if conn == nil {
|
||||
time.Sleep(1 * time.Second)
|
||||
continue
|
||||
}
|
||||
|
||||
_, message, err := conn.ReadMessage()
|
||||
if err != nil {
|
||||
logger.ErrorCF("whatsapp", "WhatsApp read error", map[string]any{
|
||||
"error": err.Error(),
|
||||
})
|
||||
time.Sleep(2 * time.Second)
|
||||
continue
|
||||
}
|
||||
|
||||
var msg map[string]any
|
||||
if err := json.Unmarshal(message, &msg); err != nil {
|
||||
logger.ErrorCF("whatsapp", "Failed to unmarshal WhatsApp message", map[string]any{
|
||||
"error": err.Error(),
|
||||
})
|
||||
continue
|
||||
}
|
||||
|
||||
msgType, ok := msg["type"].(string)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
if msgType == "message" {
|
||||
c.handleIncomingMessage(msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *WhatsAppChannel) handleIncomingMessage(msg map[string]any) {
|
||||
senderID, ok := msg["from"].(string)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
chatID, ok := msg["chat"].(string)
|
||||
if !ok {
|
||||
chatID = senderID
|
||||
}
|
||||
|
||||
content, ok := msg["content"].(string)
|
||||
if !ok {
|
||||
content = ""
|
||||
}
|
||||
|
||||
var mediaPaths []string
|
||||
if mediaData, ok := msg["media"].([]any); ok {
|
||||
mediaPaths = make([]string, 0, len(mediaData))
|
||||
for _, m := range mediaData {
|
||||
if path, ok := m.(string); ok {
|
||||
mediaPaths = append(mediaPaths, path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
metadata := make(map[string]string)
|
||||
var messageID string
|
||||
if mid, ok := msg["id"].(string); ok {
|
||||
messageID = mid
|
||||
}
|
||||
if userName, ok := msg["from_name"].(string); ok {
|
||||
metadata["user_name"] = userName
|
||||
}
|
||||
|
||||
logger.InfoCF("whatsapp", "WhatsApp message received", map[string]any{
|
||||
"sender": senderID,
|
||||
"preview": utils.Truncate(content, 50),
|
||||
})
|
||||
|
||||
sender := bus.SenderInfo{
|
||||
Platform: "whatsapp",
|
||||
PlatformID: senderID,
|
||||
CanonicalID: identity.BuildCanonicalID("whatsapp", senderID),
|
||||
}
|
||||
if display, ok := metadata["user_name"]; ok {
|
||||
sender.DisplayName = display
|
||||
}
|
||||
|
||||
if !c.IsAllowedSender(sender) {
|
||||
return
|
||||
}
|
||||
|
||||
inboundCtx := bus.InboundContext{
|
||||
Channel: "whatsapp",
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
MessageID: messageID,
|
||||
Raw: metadata,
|
||||
}
|
||||
if chatID == senderID {
|
||||
inboundCtx.ChatType = "direct"
|
||||
} else {
|
||||
inboundCtx.ChatType = "group"
|
||||
}
|
||||
|
||||
c.HandleInboundContext(c.ctx, chatID, content, mediaPaths, inboundCtx, sender)
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
package whatsapp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/sipeed/picoclaw/pkg/bus"
|
||||
"github.com/sipeed/picoclaw/pkg/channels"
|
||||
"github.com/sipeed/picoclaw/pkg/config"
|
||||
)
|
||||
|
||||
func TestHandleIncomingMessage_DoesNotConsumeGenericCommandsLocally(t *testing.T) {
|
||||
messageBus := bus.NewMessageBus()
|
||||
ch := &WhatsAppChannel{
|
||||
BaseChannel: channels.NewBaseChannel("whatsapp", config.WhatsAppSettings{}, messageBus, nil),
|
||||
ctx: context.Background(),
|
||||
}
|
||||
|
||||
ch.handleIncomingMessage(map[string]any{
|
||||
"type": "message",
|
||||
"id": "mid1",
|
||||
"from": "user1",
|
||||
"chat": "chat1",
|
||||
"content": "/help",
|
||||
})
|
||||
|
||||
inbound, ok := <-messageBus.InboundChan()
|
||||
if !ok {
|
||||
t.Fatal("expected inbound message to be forwarded")
|
||||
}
|
||||
if inbound.Channel != "whatsapp" {
|
||||
t.Fatalf("channel=%q", inbound.Channel)
|
||||
}
|
||||
if inbound.Content != "/help" {
|
||||
t.Fatalf("content=%q", inbound.Content)
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
package whatsapp
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
|
||||
"github.com/sipeed/picoclaw/pkg/bus"
|
||||
"github.com/sipeed/picoclaw/pkg/channels"
|
||||
"github.com/sipeed/picoclaw/pkg/config"
|
||||
)
|
||||
|
||||
func init() {
|
||||
channels.RegisterFactory(
|
||||
config.ChannelWhatsAppNative,
|
||||
func(channelName, channelType string, cfg *config.Config, b *bus.MessageBus) (channels.Channel, error) {
|
||||
bc := cfg.Channels[channelName]
|
||||
decoded, err := bc.GetDecoded()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c, ok := decoded.(*config.WhatsAppSettings)
|
||||
if !ok {
|
||||
return nil, channels.ErrSendFailed
|
||||
}
|
||||
storePath := c.SessionStorePath
|
||||
if storePath == "" {
|
||||
storePath = filepath.Join(cfg.WorkspacePath(), "whatsapp")
|
||||
}
|
||||
ch, err := NewWhatsAppNativeChannel(bc, channelName, c, b, storePath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ch, nil
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
//go:build whatsapp_native
|
||||
|
||||
package whatsapp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"go.mau.fi/whatsmeow/proto/waE2E"
|
||||
"go.mau.fi/whatsmeow/types"
|
||||
"go.mau.fi/whatsmeow/types/events"
|
||||
"google.golang.org/protobuf/proto"
|
||||
|
||||
"github.com/sipeed/picoclaw/pkg/bus"
|
||||
"github.com/sipeed/picoclaw/pkg/channels"
|
||||
"github.com/sipeed/picoclaw/pkg/config"
|
||||
)
|
||||
|
||||
func TestHandleIncoming_DoesNotConsumeGenericCommandsLocally(t *testing.T) {
|
||||
messageBus := bus.NewMessageBus()
|
||||
ch := &WhatsAppNativeChannel{
|
||||
BaseChannel: channels.NewBaseChannel("whatsapp_native", config.WhatsAppSettings{}, messageBus, nil),
|
||||
runCtx: context.Background(),
|
||||
}
|
||||
|
||||
evt := &events.Message{
|
||||
Info: types.MessageInfo{
|
||||
MessageSource: types.MessageSource{
|
||||
Sender: types.NewJID("1001", types.DefaultUserServer),
|
||||
Chat: types.NewJID("1001", types.DefaultUserServer),
|
||||
},
|
||||
ID: "mid1",
|
||||
PushName: "Alice",
|
||||
},
|
||||
Message: &waE2E.Message{
|
||||
Conversation: proto.String("/new"),
|
||||
},
|
||||
}
|
||||
|
||||
ch.handleIncoming(evt)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
t.Fatal("timeout waiting for message to be forwarded")
|
||||
return
|
||||
case inbound, ok := <-messageBus.InboundChan():
|
||||
if !ok {
|
||||
t.Fatal("expected inbound message to be forwarded")
|
||||
}
|
||||
if inbound.Channel != "whatsapp_native" {
|
||||
t.Fatalf("channel=%q", inbound.Channel)
|
||||
}
|
||||
if inbound.Content != "/new" {
|
||||
t.Fatalf("content=%q", inbound.Content)
|
||||
}
|
||||
}
|
||||
}
|
||||
Loaded 100 of 128 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user