refactor: trim unused IM channels and dependencies
Remove Slack, Slack Webhook, Teams Webhook, Matrix, Delta Chat, IRC and VK. Clean up channel configuration, migration support, examples and documentation. Drop unused SDKs and Matrix build tags while preserving the remaining channels. Validated with full Go tests, static checks, docs lint and a Linux amd64 build.
This commit is contained in:
1 parent
996dfefffe
commit
e7d4293052
112 files changed
+243
-12067
No files matched your search
@@ -23,13 +23,13 @@ jobs:
|
||||
uses: golangci/golangci-lint-action@v9
|
||||
with:
|
||||
version: v2.10.1
|
||||
args: --build-tags=goolm,stdjson
|
||||
args: --build-tags=stdjson
|
||||
|
||||
vuln_check:
|
||||
name: Security Check
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
GOFLAGS: -tags=goolm,stdjson
|
||||
GOFLAGS: -tags=stdjson
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v7
|
||||
@@ -63,7 +63,7 @@ jobs:
|
||||
run: go generate ./...
|
||||
|
||||
- name: Run go test
|
||||
run: go test -tags goolm,stdjson ./...
|
||||
run: go test -tags stdjson ./...
|
||||
|
||||
integration:
|
||||
name: Integration Tests
|
||||
|
||||
@@ -16,7 +16,6 @@ builds:
|
||||
env:
|
||||
- CGO_ENABLED=0
|
||||
tags:
|
||||
- goolm
|
||||
- stdjson
|
||||
ldflags:
|
||||
- -s -w
|
||||
|
||||
@@ -34,7 +34,7 @@ LDFLAGS=-X $(CONFIG_PKG).Version=$(VERSION) -X $(CONFIG_PKG).GitCommit=$(GIT_COM
|
||||
# Go variables
|
||||
GO?=go
|
||||
CGO_ENABLED?=0
|
||||
GO_BUILD_TAGS?=goolm,stdjson
|
||||
GO_BUILD_TAGS?=stdjson
|
||||
GOFLAGS?=-v -tags $(GO_BUILD_TAGS)
|
||||
GOCACHE?=$(CURDIR)/.cache/go-build
|
||||
GOMODCACHE?=$(CURDIR)/.cache/go-mod
|
||||
@@ -43,11 +43,6 @@ export CGO_ENABLED
|
||||
export GOCACHE
|
||||
export GOMODCACHE
|
||||
export GOTOOLCHAIN
|
||||
comma:=,
|
||||
empty:=
|
||||
space:=$(empty) $(empty)
|
||||
GO_BUILD_TAGS_NO_GOOLM:=$(subst $(space),$(comma),$(strip $(filter-out goolm,$(subst $(comma),$(space),$(GO_BUILD_TAGS)))))
|
||||
GOFLAGS_NO_GOOLM?=-v -tags $(GO_BUILD_TAGS_NO_GOOLM)
|
||||
|
||||
# Patch MIPS LE ELF e_flags (offset 36) for NaN2008-only kernels (e.g. Ingenic X2600).
|
||||
#
|
||||
@@ -223,7 +218,7 @@ build-whatsapp-native: generate
|
||||
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_NO_GOOLM),whatsapp_native -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-linux-mipsle ./$(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)
|
||||
@@ -249,7 +244,7 @@ build-linux-arm64: generate
|
||||
build-linux-mipsle: generate
|
||||
@echo "Building for linux/mipsle (softfloat)..."
|
||||
@mkdir -p $(BUILD_DIR)
|
||||
GOOS=linux GOARCH=mipsle GOMIPS=softfloat $(GO) build $(GOFLAGS_NO_GOOLM) -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-linux-mipsle ./$(CMD_DIR)
|
||||
GOOS=linux GOARCH=mipsle GOMIPS=softfloat $(GO) build $(GOFLAGS) -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-linux-mipsle ./$(CMD_DIR)
|
||||
$(call PATCH_MIPS_FLAGS,$(BUILD_DIR)/$(BINARY_NAME)-linux-mipsle)
|
||||
@echo "Build complete: $(BUILD_DIR)/$(BINARY_NAME)-linux-mipsle"
|
||||
|
||||
@@ -274,7 +269,7 @@ build-all: generate
|
||||
@$(PTY_PATCH_LOONG64)
|
||||
GOOS=linux GOARCH=loong64 $(GO) build $(GOFLAGS) -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-linux-loong64 ./$(CMD_DIR)
|
||||
GOOS=linux GOARCH=riscv64 $(GO) build $(GOFLAGS) -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-linux-riscv64 ./$(CMD_DIR)
|
||||
GOOS=linux GOARCH=mipsle GOMIPS=softfloat $(GO) build $(GOFLAGS_NO_GOOLM) -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-linux-mipsle ./$(CMD_DIR)
|
||||
GOOS=linux GOARCH=mipsle GOMIPS=softfloat $(GO) build $(GOFLAGS) -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-linux-mipsle ./$(CMD_DIR)
|
||||
$(call PATCH_MIPS_FLAGS,$(BUILD_DIR)/$(BINARY_NAME)-linux-mipsle)
|
||||
GOOS=linux GOARCH=arm GOARM=7 $(GO) build $(GOFLAGS) -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-linux-armv7 ./$(CMD_DIR)
|
||||
GOOS=darwin GOARCH=arm64 $(GO) build $(GOFLAGS) -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-darwin-arm64 ./$(CMD_DIR)
|
||||
|
||||
@@ -385,15 +385,10 @@ Talk to your PicoClaw through 19+ messaging platforms:
|
||||
| **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) |
|
||||
| **Slack** | Easy (bot + app token) | Socket Mode | [Guide](docs/channels/slack/README.md) |
|
||||
| **Matrix** | Medium (homeserver + token) | Sync API | [Guide](docs/channels/matrix/README.md) |
|
||||
| **Delta Chat** | Easy (account script or email/password) | JSON-RPC (email/E2EE) | [Guide](docs/channels/deltachat/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) |
|
||||
| **VK** | Easy (group token) | Long Poll | [Guide](docs/channels/vk/README.md) |
|
||||
| **IRC** | Medium (server + nick) | IRC protocol | [Guide](docs/guides/chat-apps.md#irc) |
|
||||
| **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, Slack, Email, KOOK, Signal, ...
|
||||
* **IM Matrix**: QQ, WeChat (Work), DingTalk, Feishu (Lark), Telegram, Discord, WhatsApp, LINE, 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.
|
||||
|
||||
|
||||
@@ -184,38 +184,6 @@
|
||||
"client_secret": "YOUR_CLIENT_SECRET"
|
||||
}
|
||||
},
|
||||
"slack": {
|
||||
"enabled": false,
|
||||
"type": "slack",
|
||||
"allow_from": [],
|
||||
"reasoning_channel_id": "",
|
||||
"settings": {
|
||||
"bot_token": "xoxb-YOUR-BOT-TOKEN",
|
||||
"app_token": "xapp-YOUR-APP-TOKEN"
|
||||
}
|
||||
},
|
||||
"matrix": {
|
||||
"enabled": false,
|
||||
"type": "matrix",
|
||||
"allow_from": [],
|
||||
"group_trigger": {
|
||||
"mention_only": true
|
||||
},
|
||||
"placeholder": {
|
||||
"enabled": true,
|
||||
"text": ["Thinking...", "Processing...", "Typing..."]
|
||||
},
|
||||
"reasoning_channel_id": "",
|
||||
"settings": {
|
||||
"homeserver": "https://matrix.org",
|
||||
"user_id": "@your-bot:matrix.org",
|
||||
"access_token": "YOUR_MATRIX_ACCESS_TOKEN",
|
||||
"device_id": "",
|
||||
"join_on_invite": true,
|
||||
"crypto_database_path": "",
|
||||
"crypto_passphrase": "YOUR_MATRIX_CRYPTO_PICKLE_KEY"
|
||||
}
|
||||
},
|
||||
"line": {
|
||||
"enabled": false,
|
||||
"type": "line",
|
||||
@@ -253,31 +221,6 @@
|
||||
"websocket_url": "wss://openws.work.weixin.qq.com",
|
||||
"send_thinking_message": true
|
||||
}
|
||||
},
|
||||
"irc": {
|
||||
"enabled": false,
|
||||
"type": "irc",
|
||||
"allow_from": [],
|
||||
"group_trigger": {
|
||||
"mention_only": true
|
||||
},
|
||||
"typing": {
|
||||
"enabled": false
|
||||
},
|
||||
"reasoning_channel_id": "",
|
||||
"settings": {
|
||||
"server": "irc.libera.chat:6697",
|
||||
"tls": true,
|
||||
"nick": "mybot",
|
||||
"user": "",
|
||||
"real_name": "",
|
||||
"password": "",
|
||||
"nickserv_password": "",
|
||||
"sasl_user": "",
|
||||
"sasl_password": "",
|
||||
"channels": ["#mychannel"],
|
||||
"request_caps": ["server-time", "message-tags"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"tools": {
|
||||
|
||||
@@ -89,11 +89,11 @@ This means dispatch rules must match the normalized shape, for example:
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "slack-mentions",
|
||||
"name": "discord-mentions",
|
||||
"agent": "support",
|
||||
"when": {
|
||||
"channel": "slack",
|
||||
"space": "workspace:t001",
|
||||
"channel": "discord",
|
||||
"space": "guild:t001",
|
||||
"mentioned": true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,11 +88,11 @@ type ResolvedRoute struct {
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "slack-mentions",
|
||||
"name": "discord-mentions",
|
||||
"agent": "support",
|
||||
"when": {
|
||||
"channel": "slack",
|
||||
"space": "workspace:t001",
|
||||
"channel": "discord",
|
||||
"space": "guild:t001",
|
||||
"mentioned": true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,7 +77,7 @@ For compatibility, the allocator also emits legacy aliases such as:
|
||||
|
||||
```text
|
||||
agent:main:direct:user123
|
||||
agent:main:slack:channel:c001
|
||||
agent:main:discord:channel:c001
|
||||
agent:main:pico:direct:pico:session-123
|
||||
```
|
||||
|
||||
|
||||
@@ -77,7 +77,7 @@ sk_v1_<sha256>
|
||||
|
||||
```text
|
||||
agent:main:direct:user123
|
||||
agent:main:slack:channel:c001
|
||||
agent:main:discord:channel:c001
|
||||
agent:main:pico:direct:pico:session-123
|
||||
```
|
||||
|
||||
|
||||
@@ -1,148 +0,0 @@
|
||||
> Back to [README](../../../README.md)
|
||||
|
||||
# Delta Chat Channel
|
||||
|
||||
PicoClaw can run as a Delta Chat bot by launching a local
|
||||
`deltachat-rpc-server` process and talking to it over JSON-RPC. The RPC server
|
||||
handles the email account, IMAP/SMTP connection, message store, and encryption
|
||||
keys.
|
||||
|
||||
## Install
|
||||
|
||||
Install the Delta Chat RPC server. If `deltachat-rpc-server` is on `PATH`,
|
||||
PicoClaw can find it automatically; otherwise set `rpc_server_path` to the
|
||||
exact binary path.
|
||||
|
||||
```bash
|
||||
pip install deltachat-rpc-server
|
||||
which deltachat-rpc-server
|
||||
```
|
||||
|
||||
Prebuilt binaries are also available from the
|
||||
[Delta Chat core releases](https://github.com/deltachat/deltachat-core-rust/releases).
|
||||
|
||||
## Configure
|
||||
|
||||
The easiest setup is to let PicoClaw create a chatmail account in Delta
|
||||
Chat's local account store. Put a relay marker in `email` using an empty local
|
||||
part, for example `@nine.testrun.org`:
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"deltachat": {
|
||||
"enabled": true,
|
||||
"type": "deltachat",
|
||||
"allow_from": ["friend@example.org"],
|
||||
"group_trigger": {
|
||||
"mention_only": true
|
||||
},
|
||||
"settings": {
|
||||
"email": "@nine.testrun.org",
|
||||
"display_name": "PicoClaw Bot",
|
||||
"avatar_image": "/home/me/bot-avatar.png"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
On startup, PicoClaw creates the account through `deltachat-rpc-server`, then
|
||||
stops with an error that contains the generated address. Replace the relay
|
||||
marker with that full email address and run PicoClaw again:
|
||||
|
||||
```json
|
||||
{
|
||||
"email": "bot123@nine.testrun.org",
|
||||
"display_name": "PicoClaw Bot",
|
||||
"avatar_image": "/home/me/bot-avatar.png"
|
||||
}
|
||||
```
|
||||
|
||||
If `email` is missing, the startup error lists the built-in relay choices copied
|
||||
from Parla. You can use one of those relay markers, or a custom chatmail relay
|
||||
with the same `@server.name` form.
|
||||
|
||||
`password` is not needed for PicoClaw-created chatmail accounts. Omit it when
|
||||
`email` points to an already configured account in `data_dir`; the JSON-RPC
|
||||
server owns the mailbox password. The legacy password-based path remains only
|
||||
for classic email accounts that PicoClaw must configure itself. In that mode,
|
||||
`password` is a secure field; on first config load it is moved to
|
||||
`~/.picoclaw/.security.yml`, and it can also be set with
|
||||
`PICOCLAW_CHANNELS_DELTACHAT_PASSWORD`.
|
||||
|
||||
`display_name` and `avatar_image` are optional profile settings. When present,
|
||||
PicoClaw applies them on every startup, so changing the avatar path in config is
|
||||
enough to update the bot profile.
|
||||
|
||||
| Field | Required | Description |
|
||||
|-------|----------|-------------|
|
||||
| `email` | Yes | Full bot mailbox address, or first-run relay marker such as `@nine.testrun.org` |
|
||||
| `rpc_server_path` | No | Path to `deltachat-rpc-server`; only needed when it is not on `PATH` |
|
||||
| `password` | No | Legacy only; required when PicoClaw must configure/reconfigure a classic mailbox itself |
|
||||
| `display_name` | No | Startup-applied profile name shown to contacts and used for group mention detection |
|
||||
| `avatar_image` | No | Startup-applied profile avatar image path; `~` is expanded. Missing files are warned and ignored |
|
||||
| `data_dir` | No | Account database directory. Default: `~/.picoclaw/deltachat/<channel-name>` |
|
||||
| `invite_link` | No | Delta Chat invite link to join on startup |
|
||||
| `allow_crosspost` | No | Default `false`. When `true`, senders allowed by `allow_from` may use `message` tool targets outside the current chat, or resolve recipients by email/contact/chat name |
|
||||
| `imap_server`, `imap_port` | No | Manual IMAP override for password-based configuration |
|
||||
| `smtp_server`, `smtp_port` | No | Manual SMTP override for password-based configuration |
|
||||
|
||||
Standard channel fields such as `allow_from`, `group_trigger`, and
|
||||
`reasoning_channel_id` also apply.
|
||||
|
||||
## First Run
|
||||
|
||||
With `email` set to `@server`, PicoClaw creates the chatmail account, prints
|
||||
the generated full email in the startup error, and exits. Update `email` to that
|
||||
full address and run PicoClaw again. On later runs, PicoClaw selects the
|
||||
configured account by `email`, applies optional profile settings, marks it as a
|
||||
bot, and starts IO.
|
||||
|
||||
With a new `data_dir` plus legacy `password`, PicoClaw can still configure a
|
||||
classic email account and validate the mailbox credentials; after that, the
|
||||
account is reused from the local data directory.
|
||||
|
||||
Delta Chat requires peers to learn the bot's encryption key before messaging
|
||||
it. On startup PicoClaw prints the bot invite link and QR code. Add the bot from
|
||||
Delta Chat with that invite, not by typing the bare email address.
|
||||
|
||||
## Behavior
|
||||
|
||||
- Direct chats always respond after `allow_from` passes.
|
||||
- Group chats follow `group_trigger`; without one, every group message is
|
||||
handled.
|
||||
- Messages from the bot itself, device chats, and info/system messages are
|
||||
ignored.
|
||||
- Accepted inbound messages are marked seen after the allow-list check.
|
||||
- Incoming attachments (images, audio, video, documents) are registered with
|
||||
the media store and handed to the agent, so it can view images or operate on
|
||||
the files directly. If no media store is available, the path is appended
|
||||
inline as `[attachment: /path]` instead.
|
||||
- Outbound attachments are supported: when the agent emits media, each file is
|
||||
sent as a Delta Chat message (with the caption as text). Delta Chat infers the
|
||||
view type from the file, so images, GIFs, and videos render natively.
|
||||
- Crosspost recipient lookup is disabled by default. The agent can always reply
|
||||
to the current numeric chat ID, but sending to another numeric chat ID or
|
||||
resolving an email/contact/chat name requires `allow_crosspost: true`
|
||||
and the current sender must pass `allow_from`; `allow_from: ["*"]` allows this
|
||||
for any sender.
|
||||
- Voice is supported in both directions when voice providers are configured:
|
||||
incoming voice notes are transcribed by the agent's ASR and the transcript is
|
||||
passed to the model; the agent can reply with synthesized speech, which is
|
||||
delivered as a native Delta Chat voice message (`send_tts`). This requires an
|
||||
ASR and/or TTS provider under `voice` — it is not Delta Chat-specific config.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Symptom | Fix |
|
||||
|---------|-----|
|
||||
| `deltachat-rpc-server not found on PATH` or `rpc_server_path ... not found` | Install the RPC server on PATH, or set `rpc_server_path` to an absolute path |
|
||||
| `email is required` | Choose one listed chatmail server, set `email` to a first-run marker such as `@nine.testrun.org`, run `picoclaw g`, then replace it with the generated full email |
|
||||
| `created chatmail account ...` | Replace the `@server` marker in `email` with the generated full email and run PicoClaw again |
|
||||
| `account ... is not configured in data_dir` | Point `data_dir` at the existing JSON-RPC account store, or use `email="@server"` to create one |
|
||||
| `configure (check email/password/server)` | Check credentials, app password requirements, or IMAP/SMTP overrides |
|
||||
| Bot does not answer in a group | Check `group_trigger`; mention `display_name` or use a configured prefix |
|
||||
| Bot ignores a sender | Add the sender email to `allow_from`, or use `["*"]` for open access |
|
||||
| Sender cannot message the bot | Re-add the bot with the startup QR/invite so Delta Chat can establish encryption |
|
||||
| Agent cannot send to an email/name/other chat ID | Enable `settings.allow_crosspost` and allow the controlling sender in `allow_from`; this capability is disabled by default for privacy |
|
||||
@@ -1,65 +0,0 @@
|
||||
> Retour au [README](../../project/README.fr.md)
|
||||
|
||||
# Guide de configuration du canal Matrix
|
||||
|
||||
## 1. Exemple de configuration
|
||||
|
||||
Ajoutez ceci à `config.json` :
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"matrix": {
|
||||
"enabled": true,
|
||||
"type": "matrix",
|
||||
"homeserver": "https://matrix.org",
|
||||
"user_id": "@your-bot:matrix.org",
|
||||
"access_token": "YOUR_MATRIX_ACCESS_TOKEN",
|
||||
"device_id": "",
|
||||
"join_on_invite": true,
|
||||
"allow_from": [],
|
||||
"group_trigger": {
|
||||
"mention_only": true
|
||||
},
|
||||
"placeholder": {
|
||||
"enabled": true,
|
||||
"text": "Thinking..."
|
||||
},
|
||||
"reasoning_channel_id": "",
|
||||
"message_format": "richtext"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 2. Référence des champs
|
||||
|
||||
| Champ | Type | Requis | Description |
|
||||
|----------------------|----------|--------|-------------|
|
||||
| enabled | bool | Oui | Activer ou désactiver le canal Matrix |
|
||||
| homeserver | string | Oui | URL du homeserver Matrix (par exemple `https://matrix.org`) |
|
||||
| user_id | string | Oui | ID utilisateur Matrix du bot (par exemple `@bot:matrix.org`) |
|
||||
| access_token | string | Oui | Jeton d'accès du bot |
|
||||
| device_id | string | Non | ID d'appareil Matrix optionnel |
|
||||
| join_on_invite | bool | Non | Rejoindre automatiquement les salons invités |
|
||||
| allow_from | []string | Non | Liste blanche d'utilisateurs (IDs Matrix) |
|
||||
| group_trigger | object | Non | Stratégie de déclenchement de groupe (`mention_only` / `prefixes`) |
|
||||
| placeholder | object | Non | Configuration du message de remplacement |
|
||||
| reasoning_channel_id | string | Non | Canal cible pour la sortie de raisonnement |
|
||||
| message_format | string | Non | Format de sortie : `"richtext"` (défaut) rend le markdown en HTML ; `"plain"` envoie du texte brut uniquement |
|
||||
|
||||
## 3. Fonctionnalités actuellement supportées
|
||||
|
||||
- Envoi/réception de messages texte avec rendu markdown (gras, italique, titres, blocs de code, etc.)
|
||||
- Format de message configurable (`richtext` / `plain`)
|
||||
- Téléchargement d'images/audio/vidéo/fichiers entrants (MediaStore en priorité, chemin local en secours)
|
||||
- Normalisation de l'audio entrant dans le flux de transcription existant (`[audio: ...]`)
|
||||
- Upload et envoi d'images/audio/vidéo/fichiers sortants
|
||||
- Règles de déclenchement de groupe (y compris le mode mention uniquement)
|
||||
- État de frappe (`m.typing`)
|
||||
- Message de remplacement + remplacement de la réponse finale
|
||||
- Rejoindre automatiquement les salons invités (peut être désactivé)
|
||||
|
||||
## 4. TODO
|
||||
|
||||
- Améliorations des métadonnées des médias riches (par exemple taille et miniatures des images/vidéos)
|
||||
@@ -1,65 +0,0 @@
|
||||
> [README](../../project/README.ja.md) に戻る
|
||||
|
||||
# Matrix チャンネル設定ガイド
|
||||
|
||||
## 1. 設定例
|
||||
|
||||
`config.json` に以下を追加してください:
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"matrix": {
|
||||
"enabled": true,
|
||||
"type": "matrix",
|
||||
"homeserver": "https://matrix.org",
|
||||
"user_id": "@your-bot:matrix.org",
|
||||
"access_token": "YOUR_MATRIX_ACCESS_TOKEN",
|
||||
"device_id": "",
|
||||
"join_on_invite": true,
|
||||
"allow_from": [],
|
||||
"group_trigger": {
|
||||
"mention_only": true
|
||||
},
|
||||
"placeholder": {
|
||||
"enabled": true,
|
||||
"text": "Thinking..."
|
||||
},
|
||||
"reasoning_channel_id": "",
|
||||
"message_format": "richtext"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 2. フィールドリファレンス
|
||||
|
||||
| フィールド | 型 | 必須 | 説明 |
|
||||
|----------------------|----------|------|------|
|
||||
| enabled | bool | はい | Matrix チャンネルの有効/無効 |
|
||||
| homeserver | string | はい | Matrix ホームサーバー URL(例:`https://matrix.org`) |
|
||||
| user_id | string | はい | ボットの Matrix ユーザー ID(例:`@bot:matrix.org`) |
|
||||
| access_token | string | はい | ボットのアクセストークン |
|
||||
| device_id | string | いいえ | オプションの Matrix デバイス ID |
|
||||
| join_on_invite | bool | いいえ | 招待されたルームに自動参加 |
|
||||
| allow_from | []string | いいえ | ユーザーホワイトリスト(Matrix ユーザー ID) |
|
||||
| group_trigger | object | いいえ | グループトリガー戦略(`mention_only` / `prefixes`) |
|
||||
| placeholder | object | いいえ | プレースホルダーメッセージ設定 |
|
||||
| reasoning_channel_id | string | いいえ | 推論出力のターゲットチャンネル |
|
||||
| message_format | string | いいえ | 出力形式:`"richtext"`(デフォルト)は markdown を HTML としてレンダリング;`"plain"` はプレーンテキストのみ送信 |
|
||||
|
||||
## 3. 現在サポートされている機能
|
||||
|
||||
- markdown レンダリング付きテキストメッセージ送受信(太字、斜体、見出し、コードブロックなど)
|
||||
- 設定可能なメッセージ形式(`richtext` / `plain`)
|
||||
- 受信画像/音声/動画/ファイルのダウンロード(MediaStore 優先、ローカルパスフォールバック)
|
||||
- 受信音声の既存文字起こしフローへの正規化(`[audio: ...]`)
|
||||
- 送信画像/音声/動画/ファイルのアップロードと送信
|
||||
- グループトリガールール(メンションのみモードを含む)
|
||||
- タイピング状態(`m.typing`)
|
||||
- プレースホルダーメッセージ + 最終返信の置き換え
|
||||
- 招待されたルームへの自動参加(無効化可能)
|
||||
|
||||
## 4. TODO
|
||||
|
||||
- リッチメディアメタデータの改善(例:画像/動画のサイズとサムネイル)
|
||||
@@ -1,77 +0,0 @@
|
||||
> Back to [README](../../../README.md)
|
||||
|
||||
# Matrix Channel Configuration Guide
|
||||
|
||||
## 1. Example Configuration
|
||||
|
||||
Add this to `config.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"matrix": {
|
||||
"enabled": true,
|
||||
"type": "matrix",
|
||||
"homeserver": "https://matrix.org",
|
||||
"user_id": "@your-bot:matrix.org",
|
||||
"access_token": "YOUR_MATRIX_ACCESS_TOKEN",
|
||||
"device_id": "",
|
||||
"join_on_invite": true,
|
||||
"allow_from": [],
|
||||
"group_trigger": {
|
||||
"mention_only": true
|
||||
},
|
||||
"placeholder": {
|
||||
"enabled": true,
|
||||
"text": ["Thinking...", "Processing...", "Typing..."]
|
||||
},
|
||||
"reasoning_channel_id": "",
|
||||
"message_format": "richtext",
|
||||
"crypto_database_path": "",
|
||||
"crypto_passphrase": "YOUR_MATRIX_CRYPTO_PICKLE_KEY"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 2. Field Reference
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|----------------------|----------|----------|-------------|
|
||||
| enabled | bool | Yes | Enable or disable the Matrix channel |
|
||||
| homeserver | string | Yes | Matrix homeserver URL (for example `https://matrix.org`) |
|
||||
| user_id | string | Yes | Bot Matrix user ID (for example `@bot:matrix.org`) |
|
||||
| access_token | string | Yes | Bot access token |
|
||||
| device_id | string | No | Optional Matrix device ID |
|
||||
| join_on_invite | bool | No | Auto-join invited rooms |
|
||||
| allow_from | []string | No | User whitelist (Matrix user IDs) |
|
||||
| group_trigger | object | No | Group trigger strategy (`mention_only` / `prefixes`) |
|
||||
| placeholder | object | No | Placeholder message config (see below) |
|
||||
| reasoning_channel_id | string | No | Target channel for reasoning output |
|
||||
| message_format | string | No | Output format: `"richtext"` (default) renders markdown as HTML; `"plain"` sends plain text only |
|
||||
| crypto_database_path | string | No | Path to store the crypto database (uses workspace path `~/.picoclaw/workspace` if empty) |
|
||||
| crypto_passphrase | string | No | Serialization key for encrypting session keys in the database; must remain unchanged once set |
|
||||
|
||||
### Placeholder Config
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|---------|----------------|----------|-------------|
|
||||
| enabled | bool | No | Enable placeholder messages (default: false) |
|
||||
| text | string/[]string | No | Placeholder text(s). Can be a single string or array of strings. If multiple texts are provided, one is randomly selected at runtime. Default: "Thinking..." |
|
||||
|
||||
## 3. Currently Supported
|
||||
|
||||
- Text message send/receive with markdown rendering (bold, italic, headers, code blocks, etc.)
|
||||
- Configurable message format (`richtext` / `plain`)
|
||||
- Incoming image/audio/video/file download (MediaStore first, local path fallback)
|
||||
- Incoming audio normalization into existing transcription flow (`[audio: ...]`)
|
||||
- Outgoing image/audio/video/file upload and send
|
||||
- Group trigger rules (including mention-only mode)
|
||||
- Typing state (`m.typing`)
|
||||
- Placeholder message + final reply replacement
|
||||
- Auto-join invited rooms (can be disabled)
|
||||
- End-to-end encryption (E2EE) support for encrypted messages
|
||||
|
||||
## 4. TODO
|
||||
|
||||
- Rich media metadata improvements (for example image/video size and thumbnails)
|
||||
@@ -1,65 +0,0 @@
|
||||
> Voltar ao [README](../../project/README.pt-br.md)
|
||||
|
||||
# Guia de Configuração do Canal Matrix
|
||||
|
||||
## 1. Exemplo de Configuração
|
||||
|
||||
Adicione isto ao `config.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"matrix": {
|
||||
"enabled": true,
|
||||
"type": "matrix",
|
||||
"homeserver": "https://matrix.org",
|
||||
"user_id": "@your-bot:matrix.org",
|
||||
"access_token": "YOUR_MATRIX_ACCESS_TOKEN",
|
||||
"device_id": "",
|
||||
"join_on_invite": true,
|
||||
"allow_from": [],
|
||||
"group_trigger": {
|
||||
"mention_only": true
|
||||
},
|
||||
"placeholder": {
|
||||
"enabled": true,
|
||||
"text": "Thinking..."
|
||||
},
|
||||
"reasoning_channel_id": "",
|
||||
"message_format": "richtext"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 2. Referência de Campos
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
|----------------------|----------|-------------|-----------|
|
||||
| enabled | bool | Sim | Habilitar ou desabilitar o canal Matrix |
|
||||
| homeserver | string | Sim | URL do homeserver Matrix (por exemplo `https://matrix.org`) |
|
||||
| user_id | string | Sim | ID de usuário Matrix do bot (por exemplo `@bot:matrix.org`) |
|
||||
| access_token | string | Sim | Token de acesso do bot |
|
||||
| device_id | string | Não | ID de dispositivo Matrix opcional |
|
||||
| join_on_invite | bool | Não | Entrar automaticamente em salas convidadas |
|
||||
| allow_from | []string | Não | Lista branca de usuários (IDs Matrix) |
|
||||
| group_trigger | object | Não | Estratégia de gatilho de grupo (`mention_only` / `prefixes`) |
|
||||
| placeholder | object | Não | Configuração de mensagem de espaço reservado |
|
||||
| reasoning_channel_id | string | Não | Canal alvo para saída de raciocínio |
|
||||
| message_format | string | Não | Formato de saída: `"richtext"` (padrão) renderiza markdown como HTML; `"plain"` envia apenas texto simples |
|
||||
|
||||
## 3. Suporte Atual
|
||||
|
||||
- Envio/recebimento de mensagens de texto com renderização markdown (negrito, itálico, cabeçalhos, blocos de código, etc.)
|
||||
- Formato de mensagem configurável (`richtext` / `plain`)
|
||||
- Download de imagens/áudio/vídeo/arquivos recebidos (MediaStore primeiro, fallback para caminho local)
|
||||
- Normalização de áudio recebido no fluxo de transcrição existente (`[audio: ...]`)
|
||||
- Upload e envio de imagens/áudio/vídeo/arquivos de saída
|
||||
- Regras de gatilho de grupo (incluindo modo somente menção)
|
||||
- Estado de digitação (`m.typing`)
|
||||
- Mensagem de espaço reservado + substituição de resposta final
|
||||
- Entrada automática em salas convidadas (pode ser desabilitado)
|
||||
|
||||
## 4. TODO
|
||||
|
||||
- Melhorias nos metadados de mídia rica (por exemplo tamanho e miniaturas de imagens/vídeos)
|
||||
@@ -1,65 +0,0 @@
|
||||
> Quay lại [README](../../project/README.vi.md)
|
||||
|
||||
# Hướng dẫn Cấu hình Kênh Matrix
|
||||
|
||||
## 1. Cấu hình Mẫu
|
||||
|
||||
Thêm vào `config.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"matrix": {
|
||||
"enabled": true,
|
||||
"type": "matrix",
|
||||
"homeserver": "https://matrix.org",
|
||||
"user_id": "@your-bot:matrix.org",
|
||||
"access_token": "YOUR_MATRIX_ACCESS_TOKEN",
|
||||
"device_id": "",
|
||||
"join_on_invite": true,
|
||||
"allow_from": [],
|
||||
"group_trigger": {
|
||||
"mention_only": true
|
||||
},
|
||||
"placeholder": {
|
||||
"enabled": true,
|
||||
"text": "Thinking..."
|
||||
},
|
||||
"reasoning_channel_id": "",
|
||||
"message_format": "richtext"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 2. Tham chiếu Trường
|
||||
|
||||
| Trường | Kiểu | Bắt buộc | Mô tả |
|
||||
|----------------------|----------|----------|-------|
|
||||
| enabled | bool | Có | Bật hoặc tắt kênh Matrix |
|
||||
| homeserver | string | Có | URL homeserver Matrix (ví dụ `https://matrix.org`) |
|
||||
| user_id | string | Có | ID người dùng Matrix của bot (ví dụ `@bot:matrix.org`) |
|
||||
| access_token | string | Có | Token truy cập của bot |
|
||||
| device_id | string | Không | ID thiết bị Matrix tùy chọn |
|
||||
| join_on_invite | bool | Không | Tự động tham gia phòng được mời |
|
||||
| allow_from | []string | Không | Danh sách trắng người dùng (ID Matrix) |
|
||||
| group_trigger | object | Không | Chiến lược kích hoạt nhóm (`mention_only` / `prefixes`) |
|
||||
| placeholder | object | Không | Cấu hình tin nhắn giữ chỗ |
|
||||
| reasoning_channel_id | string | Không | Kênh đích cho đầu ra suy luận |
|
||||
| message_format | string | Không | Định dạng đầu ra: `"richtext"` (mặc định) render markdown thành HTML; `"plain"` chỉ gửi văn bản thuần |
|
||||
|
||||
## 3. Tính năng Hiện tại
|
||||
|
||||
- Gửi/nhận tin nhắn văn bản với render markdown (đậm, nghiêng, tiêu đề, khối code, v.v.)
|
||||
- Định dạng tin nhắn có thể cấu hình (`richtext` / `plain`)
|
||||
- Tải xuống hình ảnh/âm thanh/video/tệp đến (MediaStore trước, fallback đường dẫn cục bộ)
|
||||
- Chuẩn hóa âm thanh đến vào luồng phiên âm hiện có (`[audio: ...]`)
|
||||
- Tải lên và gửi hình ảnh/âm thanh/video/tệp đi
|
||||
- Quy tắc kích hoạt nhóm (bao gồm chế độ chỉ đề cập)
|
||||
- Trạng thái đang gõ (`m.typing`)
|
||||
- Tin nhắn giữ chỗ + thay thế phản hồi cuối cùng
|
||||
- Tự động tham gia phòng được mời (có thể tắt)
|
||||
|
||||
## 4. TODO
|
||||
|
||||
- Cải thiện metadata phương tiện phong phú (ví dụ kích thước và hình thu nhỏ hình ảnh/video)
|
||||
@@ -1,76 +0,0 @@
|
||||
> 返回 [README](../../project/README.zh.md)
|
||||
|
||||
# Matrix 通道配置指南
|
||||
|
||||
## 1. 配置示例
|
||||
|
||||
在 `config.json` 中添加:
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"matrix": {
|
||||
"enabled": true,
|
||||
"type": "matrix",
|
||||
"homeserver": "https://matrix.org",
|
||||
"user_id": "@your-bot:matrix.org",
|
||||
"access_token": "YOUR_MATRIX_ACCESS_TOKEN",
|
||||
"device_id": "",
|
||||
"join_on_invite": true,
|
||||
"allow_from": [],
|
||||
"group_trigger": {
|
||||
"mention_only": true
|
||||
},
|
||||
"placeholder": {
|
||||
"enabled": true,
|
||||
"text": ["Thinking...", "Processing...", "Typing..."]
|
||||
},
|
||||
"reasoning_channel_id": "",
|
||||
"message_format": "richtext",
|
||||
"crypto_database_path": "",
|
||||
"crypto_passphrase": "YOUR_MATRIX_CRYPTO_PICKLE_KEY"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 2. 参数说明
|
||||
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
|----------------------|----------|------|------|
|
||||
| enabled | bool | 是 | 是否启用 Matrix 通道 |
|
||||
| homeserver | string | 是 | Matrix 服务器地址(例如 `https://matrix.org`) |
|
||||
| user_id | string | 是 | 机器人 Matrix 用户 ID(例如 `@bot:matrix.org`) |
|
||||
| access_token | string | 是 | 机器人 access token |
|
||||
| device_id | string | 否 | 设备 ID(可选) |
|
||||
| join_on_invite | bool | 否 | 是否自动加入邀请房间 |
|
||||
| allow_from | []string | 否 | 白名单用户(Matrix 用户 ID) |
|
||||
| group_trigger | object | 否 | 群聊触发策略(支持 `mention_only` / `prefixes`) |
|
||||
| placeholder | object | 否 | 占位消息配置 |
|
||||
| reasoning_channel_id | string | 否 | 思维链输出目标通道 |
|
||||
| message_format | string | 否 | 消息格式:`richtext`(富文本)或 `plain`(纯文本) |
|
||||
| crypto_database_path | string | 否 | 加密数据库存储路径(为空时使用工作空间路径 `~/.picoclaw/workspace`) |
|
||||
| crypto_passphrase | string | 否 | 加密数据库中 session key 的序列化密钥;设置后不能更改 |
|
||||
|
||||
### 占位消息配置 (Placeholder)
|
||||
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
|---------|-----------------|------|------|
|
||||
| enabled | bool | 否 | 是否启用占位消息(默认:false) |
|
||||
| text | string/[]string | 否 | 占位文本。可以是单个字符串或字符串数组。如果提供多个文本,运行时会随机选择一个。默认:"Thinking..." |
|
||||
|
||||
## 3. 当前支持
|
||||
|
||||
- 文本消息收发
|
||||
- 图片/音频/视频/文件消息入站下载(写入 MediaStore / 本地路径回退)
|
||||
- 音频消息按统一标记进入现有转写流程(`[audio: ...]`)
|
||||
- 图片/音频/视频/文件消息出站发送(上传到 Matrix 媒体库后发送)
|
||||
- 群聊触发规则(支持仅 @ 提及时响应)
|
||||
- Typing 状态(`m.typing`)
|
||||
- 占位消息(`Thinking... 💭`)+ 最终回复替换
|
||||
- 自动加入邀请房间(可关闭)
|
||||
- 端对端加密(E2EE)消息支持
|
||||
|
||||
## 4. TODO
|
||||
|
||||
- 富媒体细节增强(如 image/video 的尺寸、缩略图等 metadata)
|
||||
@@ -1,36 +0,0 @@
|
||||
> Retour au [README](../../project/README.fr.md)
|
||||
|
||||
# Slack
|
||||
|
||||
Slack est l'une des principales plateformes de messagerie instantanée pour les entreprises. PicoClaw utilise le Socket Mode de Slack pour une communication bidirectionnelle en temps réel, sans nécessiter la configuration d'un endpoint webhook public.
|
||||
|
||||
## Configuration
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"slack": {
|
||||
"enabled": true,
|
||||
"type": "slack",
|
||||
"bot_token": "xoxb-...",
|
||||
"app_token": "xapp-...",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Champ | Type | Requis | Description |
|
||||
| ---------- | ------ | ------ | ---------------------------------------------------------------------------- |
|
||||
| enabled | bool | Oui | Activer ou non le canal Slack |
|
||||
| bot_token | string | Oui | Bot User OAuth Token du bot Slack (commence par xoxb-) |
|
||||
| app_token | string | Oui | App Level Token Socket Mode de l'application Slack (commence par xapp-) |
|
||||
| allow_from | array | Non | Liste blanche d'ID utilisateurs ; vide signifie tous les utilisateurs |
|
||||
|
||||
## Procédure de configuration
|
||||
|
||||
1. Rendez-vous sur [Slack API](https://api.slack.com/) et créez une nouvelle application Slack
|
||||
2. Activez le Socket Mode et obtenez l'App Level Token
|
||||
3. Ajoutez des Bot Token Scopes (par exemple `chat:write`, `im:history`, etc.)
|
||||
4. Installez l'application dans votre espace de travail et obtenez le Bot User OAuth Token
|
||||
5. Renseignez le Bot Token et l'App Token dans le fichier de configuration
|
||||
@@ -1,36 +0,0 @@
|
||||
> [README](../../project/README.ja.md) に戻る
|
||||
|
||||
# Slack
|
||||
|
||||
Slack は世界をリードする企業向けインスタントメッセージングプラットフォームです。PicoClaw は Slack の Socket Mode を使用してリアルタイムの双方向通信を実現しており、公開 Webhook エンドポイントの設定は不要です。
|
||||
|
||||
## 設定
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"slack": {
|
||||
"enabled": true,
|
||||
"type": "slack",
|
||||
"bot_token": "xoxb-...",
|
||||
"app_token": "xapp-...",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| フィールド | 型 | 必須 | 説明 |
|
||||
| ---------- | ------ | ------ | ------------------------------------------------------------------------ |
|
||||
| enabled | bool | はい | Slack チャンネルを有効にするかどうか |
|
||||
| bot_token | string | はい | Slack ボットの Bot User OAuth Token(xoxb- で始まる) |
|
||||
| app_token | string | はい | Slack アプリの Socket Mode App Level Token(xapp- で始まる) |
|
||||
| allow_from | array | いいえ | ユーザーIDのホワイトリスト。空の場合は全ユーザーを許可 |
|
||||
|
||||
## セットアップ手順
|
||||
|
||||
1. [Slack API](https://api.slack.com/) にアクセスして新しい Slack アプリを作成する
|
||||
2. Socket Mode を有効にして App Level Token を取得する
|
||||
3. Bot Token Scopes を追加する(例: `chat:write`、`im:history` など)
|
||||
4. アプリをワークスペースにインストールして Bot User OAuth Token を取得する
|
||||
5. Bot Token と App Token を設定ファイルに入力する
|
||||
@@ -1,36 +0,0 @@
|
||||
> Back to [README](../../../README.md)
|
||||
|
||||
# Slack
|
||||
|
||||
Slack is a leading enterprise instant messaging platform. PicoClaw uses Slack's Socket Mode for real-time bidirectional communication, with no need to configure a public webhook endpoint.
|
||||
|
||||
## Configuration
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"slack": {
|
||||
"enabled": true,
|
||||
"type": "slack",
|
||||
"bot_token": "xoxb-...",
|
||||
"app_token": "xapp-...",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
| ---------- | ------ | -------- | ------------------------------------------------------------------------ |
|
||||
| enabled | bool | Yes | Whether to enable the Slack channel |
|
||||
| bot_token | string | Yes | Bot User OAuth Token for the Slack bot (starts with xoxb-) |
|
||||
| app_token | string | Yes | Socket Mode App Level Token for the Slack app (starts with xapp-) |
|
||||
| allow_from | array | No | User ID whitelist; empty means all users are allowed |
|
||||
|
||||
## Setup
|
||||
|
||||
1. Go to [Slack API](https://api.slack.com/) and create a new Slack app
|
||||
2. Enable Socket Mode and obtain the App Level Token
|
||||
3. Add Bot Token Scopes (e.g. `chat:write`, `im:history`, etc.)
|
||||
4. Install the app to your workspace and obtain the Bot User OAuth Token
|
||||
5. Fill in the Bot Token and App Token in the configuration file
|
||||
@@ -1,36 +0,0 @@
|
||||
> Voltar ao [README](../../project/README.pt-br.md)
|
||||
|
||||
# Slack
|
||||
|
||||
O Slack é uma das principais plataformas de mensagens instantâneas para empresas. O PicoClaw usa o Socket Mode do Slack para comunicação bidirecional em tempo real, sem necessidade de configurar um endpoint de webhook público.
|
||||
|
||||
## Configuração
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"slack": {
|
||||
"enabled": true,
|
||||
"type": "slack",
|
||||
"bot_token": "xoxb-...",
|
||||
"app_token": "xapp-...",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Campo | Tipo | Obrigatório | Descrição |
|
||||
| ---------- | ------ | ----------- | ---------------------------------------------------------------------------- |
|
||||
| enabled | bool | Sim | Se o canal Slack deve ser habilitado |
|
||||
| bot_token | string | Sim | Bot User OAuth Token do bot Slack (começa com xoxb-) |
|
||||
| app_token | string | Sim | App Level Token do Socket Mode do aplicativo Slack (começa com xapp-) |
|
||||
| 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 [Slack API](https://api.slack.com/) e crie um novo aplicativo Slack
|
||||
2. Ative o Socket Mode e obtenha o App Level Token
|
||||
3. Adicione Bot Token Scopes (ex.: `chat:write`, `im:history`, etc.)
|
||||
4. Instale o aplicativo no seu workspace e obtenha o Bot User OAuth Token
|
||||
5. Preencha o Bot Token e o App Token no arquivo de configuração
|
||||
@@ -1,36 +0,0 @@
|
||||
> Quay lại [README](../../project/README.vi.md)
|
||||
|
||||
# Slack
|
||||
|
||||
Slack là nền tảng nhắn tin tức thì hàng đầu dành cho doanh nghiệp. PicoClaw sử dụng Socket Mode của Slack để giao tiếp hai chiều theo thời gian thực, không cần cấu hình endpoint webhook công khai.
|
||||
|
||||
## Cấu hình
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"slack": {
|
||||
"enabled": true,
|
||||
"type": "slack",
|
||||
"bot_token": "xoxb-...",
|
||||
"app_token": "xapp-...",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Trường | Kiểu | Bắt buộc | Mô tả |
|
||||
| ---------- | ------ | -------- | ---------------------------------------------------------------------------- |
|
||||
| enabled | bool | Có | Có bật kênh Slack hay không |
|
||||
| bot_token | string | Có | Bot User OAuth Token của Slack bot (bắt đầu bằng xoxb-) |
|
||||
| app_token | string | Có | App Level Token Socket Mode của ứng dụng Slack (bắt đầu bằng xapp-) |
|
||||
| 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 [Slack API](https://api.slack.com/) và tạo một ứng dụng Slack mới
|
||||
2. Bật Socket Mode và lấy App Level Token
|
||||
3. Thêm Bot Token Scopes (ví dụ: `chat:write`, `im:history`, v.v.)
|
||||
4. Cài đặt ứng dụng vào workspace và lấy Bot User OAuth Token
|
||||
5. Điền Bot Token và App Token vào file cấu hình
|
||||
@@ -1,36 +0,0 @@
|
||||
> 返回 [README](../../project/README.zh.md)
|
||||
|
||||
# Slack
|
||||
|
||||
Slack 是全球领先的企业级即时通讯平台。PicoClaw 采用 Slack 的 Socket Mode 实现实时双向通信,无需配置公开的 Webhook 端点。
|
||||
|
||||
## 配置
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"slack": {
|
||||
"enabled": true,
|
||||
"type": "slack",
|
||||
"bot_token": "xoxb-...",
|
||||
"app_token": "xapp-...",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| 字段 | 类型 | 必填 | 描述 |
|
||||
| ---------- | ------ | ---- | -------------------------------------------------------- |
|
||||
| enabled | bool | 是 | 是否启用 Slack 频道 |
|
||||
| bot_token | string | 是 | Slack 机器人的 Bot User OAuth Token (以 xoxb- 开头) |
|
||||
| app_token | string | 是 | Slack 应用的 Socket Mode App Level Token (以 xapp- 开头) |
|
||||
| allow_from | array | 否 | 用户ID白名单,空表示允许所有用户 |
|
||||
|
||||
## 设置流程
|
||||
|
||||
1. 前往 [Slack API](https://api.slack.com/) 创建一个新的 Slack 应用
|
||||
2. 启用 Socket Mode 并获取 App Level Token
|
||||
3. 添加 Bot Token Scopes(例如`chat:write`、`im:history`等)
|
||||
4. 安装应用到工作区并获取 Bot User OAuth Token
|
||||
5. 将 Bot Token 和 App Token 填入配置文件中
|
||||
@@ -1,198 +0,0 @@
|
||||
# VK (VKontakte)
|
||||
|
||||
The VK channel uses Bots Long Poll API for bot-based communication with VK social network. It supports text messages, media attachments (photos, videos, audio, documents, stickers), and group chat interactions.
|
||||
|
||||
## Configuration
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"vk": {
|
||||
"enabled": true,
|
||||
"type": "vk",
|
||||
"token": "NOT_HERE",
|
||||
"group_id": 123456789,
|
||||
"allow_from": ["123456789"],
|
||||
"group_trigger": {
|
||||
"mention_only": false,
|
||||
"prefixes": ["/bot", "!bot"]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
| ---------------- | ------ | -------- | ------------------------------------------------------------------ |
|
||||
| enabled | bool | Yes | Whether to enable the VK channel |
|
||||
| token | string | Yes | Set to `NOT_HERE` - token is stored securely (see Token Storage) |
|
||||
| group_id | int | Yes | VK Community ID (Group ID) |
|
||||
| allow_from | array | No | Allowlist of user IDs; empty means all users are allowed |
|
||||
| group_trigger | object | No | Configuration for group chat triggers |
|
||||
|
||||
### Token Storage
|
||||
|
||||
For security reasons, the VK access token should not be stored directly in the configuration file. Instead:
|
||||
|
||||
1. Set `token` to `"NOT_HERE"` in the configuration
|
||||
2. Store the actual token using one of these methods:
|
||||
- **Environment variable**: Set `PICOCLAW_CHANNELS_VK_TOKEN` environment variable
|
||||
- **Secure storage**: Use PicoClaw's secure token storage mechanism
|
||||
|
||||
Example using environment variable:
|
||||
```bash
|
||||
export PICOCLAW_CHANNELS_VK_TOKEN="vk1.a.abc123..."
|
||||
```
|
||||
|
||||
### Group Trigger Configuration
|
||||
|
||||
| Field | Type | Description |
|
||||
| ------------ | -------- | ------------------------------------------------------------------ |
|
||||
| mention_only | bool | Only respond when bot is mentioned in group chats |
|
||||
| prefixes | []string | List of prefixes that trigger bot response in group chats |
|
||||
|
||||
## Setup
|
||||
|
||||
### 1. Create a VK Community
|
||||
|
||||
1. Go to [VK](https://vk.com) and log in
|
||||
2. Create a new community or use an existing one
|
||||
3. Note your Community ID (found in the community URL, e.g., `public123456789`)
|
||||
|
||||
### 2. Enable Messages
|
||||
|
||||
1. Go to your community page
|
||||
2. Click "Manage" → "Messages" → "Community Messages"
|
||||
3. Enable community messages
|
||||
|
||||
### 3. Create Access Token
|
||||
|
||||
1. Go to "Manage" → "API usage" → "Access tokens"
|
||||
2. Click "Create token"
|
||||
3. Select the following permissions:
|
||||
- `messages` - Access to messages
|
||||
- `photos` - Access to photos (optional)
|
||||
- `docs` - Access to documents (optional)
|
||||
4. Copy the generated access token
|
||||
5. Store the token securely (see Token Storage section below)
|
||||
|
||||
### 4. Configure PicoClaw
|
||||
|
||||
1. Add the token to your PicoClaw configuration
|
||||
2. Set the `group_id` to your community ID (numeric value)
|
||||
3. (Optional) Configure `allow_from` to restrict which user IDs can interact
|
||||
|
||||
## Features
|
||||
|
||||
### Supported Message Types
|
||||
|
||||
- **Text messages**: Full support for text messages
|
||||
- **Photos**: Photos are displayed as `[photo]` placeholder
|
||||
- **Videos**: Videos are displayed as `[video]` placeholder
|
||||
- **Audio**: Audio files are displayed as `[audio]` placeholder
|
||||
- **Voice messages**: Voice messages are displayed as `[voice]` placeholder and support transcription
|
||||
- **Documents**: Documents are displayed as `[document: filename]`
|
||||
- **Stickers**: Stickers are displayed as `[sticker]` placeholder
|
||||
|
||||
### Voice Support
|
||||
|
||||
The VK channel supports both voice message reception and text-to-speech capabilities:
|
||||
|
||||
- **ASR (Automatic Speech Recognition)**: Voice messages can be transcribed to text using configured voice models
|
||||
- **TTS (Text-to-Speech)**: Text responses can be converted to voice messages
|
||||
|
||||
To enable voice transcription, configure a voice model in your providers setup. See [Voice Transcription](../../guides/providers.md#voice-transcription) for details.
|
||||
|
||||
### Group Chat Support
|
||||
|
||||
The VK channel supports group chats with configurable triggers:
|
||||
|
||||
- **Mention-only mode**: Bot only responds when mentioned
|
||||
- **Prefix mode**: Bot responds to messages starting with specified prefixes
|
||||
- **Permissive mode**: Bot responds to all messages (default)
|
||||
|
||||
### Message Length
|
||||
|
||||
VK has a maximum message length of 4000 characters. PicoClaw automatically splits longer messages into multiple parts.
|
||||
|
||||
## Example Configuration
|
||||
|
||||
### Basic Configuration
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"vk": {
|
||||
"enabled": true,
|
||||
"type": "vk",
|
||||
"token": "NOT_HERE",
|
||||
"group_id": 123456789
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### With User Whitelist
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"vk": {
|
||||
"enabled": true,
|
||||
"type": "vk",
|
||||
"token": "NOT_HERE",
|
||||
"group_id": 123456789,
|
||||
"allow_from": ["123456789", "987654321"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### With Group Chat Triggers
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"vk": {
|
||||
"enabled": true,
|
||||
"type": "vk",
|
||||
"token": "NOT_HERE",
|
||||
"group_id": 123456789,
|
||||
"group_trigger": {
|
||||
"prefixes": ["/bot", "!bot"]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Bot Not Responding
|
||||
|
||||
1. Check that the access token is valid
|
||||
2. Verify that the `group_id` is correct
|
||||
3. Ensure the user ID is in `allow_from` if configured
|
||||
4. Check PicoClaw logs for error messages
|
||||
|
||||
### Permission Errors
|
||||
|
||||
Make sure the access token has the necessary permissions:
|
||||
- `messages` - Required for sending and receiving messages
|
||||
- `photos` - Optional, for handling photo attachments
|
||||
- `docs` - Optional, for handling document attachments
|
||||
|
||||
### Group Chat Issues
|
||||
|
||||
If the bot doesn't respond in group chats:
|
||||
1. Check `group_trigger` configuration
|
||||
2. Try using a prefix to trigger the bot
|
||||
3. Check if the bot has permission to read group messages
|
||||
|
||||
## API Reference
|
||||
|
||||
The VK channel uses the [VK SDK for Go](https://github.com/SevereCloud/vksdk) library, which supports VK API version 5.199.
|
||||
|
||||
For more information about VK API, see:
|
||||
- [VK API Documentation](https://dev.vk.com/en)
|
||||
- [VK Bots Long Poll API](https://dev.vk.com/en/api/bots-long-poll/getting-started)
|
||||
@@ -21,7 +21,7 @@ graph TD
|
||||
subgraph External Callers
|
||||
TG[Telegram]
|
||||
DC[Discord]
|
||||
SL[Slack]
|
||||
SL[Discord]
|
||||
end
|
||||
|
||||
subgraph AgentLoop
|
||||
|
||||
+1
-110
@@ -4,7 +4,7 @@
|
||||
|
||||
## 💬 Applications de Chat
|
||||
|
||||
Communiquez avec votre PicoClaw via Telegram, Discord, WhatsApp, Matrix, QQ, DingTalk, LINE, WeCom, Feishu, Slack, IRC, OneBot, MQTT.
|
||||
Communiquez avec votre PicoClaw via Telegram, Discord, WhatsApp, QQ, DingTalk, LINE, 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é.
|
||||
|
||||
@@ -14,14 +14,11 @@ Communiquez avec votre PicoClaw via Telegram, Discord, WhatsApp, Matrix, QQ, Din
|
||||
| **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) |
|
||||
| **Slack** | ⭐ Facile | **Socket Mode** (pas d'IP publique requise), entreprise | [Documentation](../channels/slack/README.fr.md) |
|
||||
| **Matrix** | ⭐⭐ Moyen | Protocole fédéré, auto-hébergement possible | [Documentation](../channels/matrix/README.fr.md) |
|
||||
| **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) |
|
||||
| **IRC** | ⭐⭐ Moyen | Serveur + configuration TLS | [Documentation](#irc) |
|
||||
| **OneBot** | ⭐⭐ Moyen | Compatible NapCat/Go-CQHTTP, écosystème communautaire | [Documentation](../channels/onebot/README.fr.md) |
|
||||
| **MQTT** | ⭐ Facile | N'importe quel client MQTT via broker pub/sub | [Documentation](../channels/mqtt/README.fr.md) |
|
||||
|
||||
@@ -294,42 +291,6 @@ picoclaw gateway
|
||||
```
|
||||
</details>
|
||||
|
||||
<a id="matrix"></a>
|
||||
<details>
|
||||
<summary><b>Matrix</b></summary>
|
||||
|
||||
**1. Préparer le compte bot**
|
||||
|
||||
* Utilisez votre homeserver préféré (par ex. `https://matrix.org` ou auto-hébergé)
|
||||
* Créez un utilisateur bot et obtenez son access token
|
||||
|
||||
**2. Configurer**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"matrix": {
|
||||
"enabled": true,
|
||||
"type": "matrix",
|
||||
"homeserver": "https://matrix.org",
|
||||
"user_id": "@your-bot:matrix.org",
|
||||
"access_token": "YOUR_MATRIX_ACCESS_TOKEN",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**3. Lancer**
|
||||
|
||||
```bash
|
||||
picoclaw gateway
|
||||
```
|
||||
|
||||
Pour toutes les options (`device_id`, `join_on_invite`, `group_trigger`, `placeholder`, `reasoning_channel_id`), voir le [Guide de Configuration du Canal Matrix](../channels/matrix/README.md).
|
||||
|
||||
</details>
|
||||
|
||||
<a id="line"></a>
|
||||
<details>
|
||||
<summary><b>LINE</b></summary>
|
||||
@@ -539,76 +500,6 @@ Pour toutes les options, voir le [Guide de Configuration du Canal Feishu](../cha
|
||||
|
||||
</details>
|
||||
|
||||
<a id="slack"></a>
|
||||
<details>
|
||||
<summary><b>Slack</b></summary>
|
||||
|
||||
**1. Créer une application Slack**
|
||||
|
||||
* Allez sur [Slack API](https://api.slack.com/apps) et créez une nouvelle application
|
||||
* Sous **OAuth & Permissions**, ajoutez les scopes bot : `chat:write`, `app_mentions:read`, `im:history`, `im:read`, `im:write`
|
||||
* Installez l'application dans votre workspace
|
||||
* Copiez le **Bot Token** (`xoxb-...`) et l'**App-Level Token** (`xapp-...`, activez Socket Mode pour l'obtenir)
|
||||
|
||||
**2. Configurer**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"slack": {
|
||||
"enabled": true,
|
||||
"type": "slack",
|
||||
"bot_token": "xoxb-YOUR-BOT-TOKEN",
|
||||
"app_token": "xapp-YOUR-APP-TOKEN",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**3. Lancer**
|
||||
|
||||
```bash
|
||||
picoclaw gateway
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<a id="irc"></a>
|
||||
<details>
|
||||
<summary><b>IRC</b></summary>
|
||||
|
||||
**1. Configurer**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"irc": {
|
||||
"enabled": true,
|
||||
"type": "irc",
|
||||
"server": "irc.libera.chat:6697",
|
||||
"tls": true,
|
||||
"nick": "picoclaw-bot",
|
||||
"channels": ["#your-channel"],
|
||||
"password": "",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Optionnel : `nickserv_password` pour l'authentification NickServ, `sasl_user`/`sasl_password` pour l'authentification SASL.
|
||||
|
||||
**2. Lancer**
|
||||
|
||||
```bash
|
||||
picoclaw gateway
|
||||
```
|
||||
|
||||
Le bot se connectera au serveur IRC et rejoindra les canaux spécifiés.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="onebot"></a>
|
||||
<details>
|
||||
<summary><b>OneBot (QQ via protocole OneBot)</b></summary>
|
||||
|
||||
@@ -16,14 +16,11 @@ PicoClaw は複数のチャットプラットフォームをサポートして
|
||||
| **Discord** | ⭐ 簡単 | Socket Mode、グループ/DM 対応、Bot エコシステム充実 | [ドキュメント](../channels/discord/README.ja.md) |
|
||||
| **WhatsApp** | ⭐ 簡単 | ネイティブ (QR スキャン) または Bridge URL | [ドキュメント](#whatsapp) |
|
||||
| **微信 (Weixin)** | ⭐ 簡単 | ネイティブ QR スキャン(Tencent iLink API)| [ドキュメント](#weixin) |
|
||||
| **Slack** | ⭐ 簡単 | **Socket Mode** (公開 IP 不要)、エンタープライズ対応 | [ドキュメント](../channels/slack/README.ja.md) |
|
||||
| **Matrix** | ⭐⭐ 中程度 | フェデレーションプロトコル、セルフホスト対応 | [ドキュメント](../channels/matrix/README.ja.md) |
|
||||
| **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) |
|
||||
| **IRC** | ⭐⭐ 中程度 | サーバー + TLS 設定 | [ドキュメント](#irc) |
|
||||
| **OneBot** | ⭐⭐ 中程度 | NapCat/Go-CQHTTP 互換、コミュニティエコシステム充実 | [ドキュメント](../channels/onebot/README.ja.md) |
|
||||
| **MQTT** | ⭐ 簡単 | ブローカー経由で任意の MQTT クライアントと通信 | [ドキュメント](../channels/mqtt/README.ja.md) |
|
||||
|
||||
@@ -213,42 +210,6 @@ picoclaw gateway
|
||||
|
||||
</details>
|
||||
|
||||
<a id="matrix"></a>
|
||||
<details>
|
||||
<summary><b>Matrix</b></summary>
|
||||
|
||||
**1. Bot アカウントを準備**
|
||||
|
||||
* お好みの homeserver(例: `https://matrix.org` またはセルフホスト)を使用
|
||||
* Bot ユーザーを作成し、access token を取得
|
||||
|
||||
**2. 設定**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"matrix": {
|
||||
"enabled": true,
|
||||
"type": "matrix",
|
||||
"homeserver": "https://matrix.org",
|
||||
"user_id": "@your-bot:matrix.org",
|
||||
"access_token": "YOUR_MATRIX_ACCESS_TOKEN",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**3. 実行**
|
||||
|
||||
```bash
|
||||
picoclaw gateway
|
||||
```
|
||||
|
||||
すべてのオプション(`device_id`、`join_on_invite`、`group_trigger`、`placeholder`、`reasoning_channel_id`)については [Matrix チャネル設定ガイド](../channels/matrix/README.md) を参照してください。
|
||||
|
||||
</details>
|
||||
|
||||
<a id="qq"></a>
|
||||
<details>
|
||||
<summary><b>QQ</b></summary>
|
||||
@@ -292,76 +253,6 @@ QQ 開放プラットフォームでは、OpenClaw 互換ボットのワンク
|
||||
|
||||
</details>
|
||||
|
||||
<a id="slack"></a>
|
||||
<details>
|
||||
<summary><b>Slack</b></summary>
|
||||
|
||||
**1. Slack App を作成**
|
||||
|
||||
* [Slack API](https://api.slack.com/apps) にアクセスして新しいアプリを作成
|
||||
* **OAuth & Permissions** で Bot スコープを追加:`chat:write`、`app_mentions:read`、`im:history`、`im:read`、`im:write`
|
||||
* アプリをワークスペースにインストール
|
||||
* **Bot Token**(`xoxb-...`)と **App-Level Token**(`xapp-...`、Socket Mode を有効にして取得)をコピー
|
||||
|
||||
**2. 設定**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"slack": {
|
||||
"enabled": true,
|
||||
"type": "slack",
|
||||
"bot_token": "xoxb-YOUR-BOT-TOKEN",
|
||||
"app_token": "xapp-YOUR-APP-TOKEN",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**3. 実行**
|
||||
|
||||
```bash
|
||||
picoclaw gateway
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<a id="irc"></a>
|
||||
<details>
|
||||
<summary><b>IRC</b></summary>
|
||||
|
||||
**1. 設定**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"irc": {
|
||||
"enabled": true,
|
||||
"type": "irc",
|
||||
"server": "irc.libera.chat:6697",
|
||||
"tls": true,
|
||||
"nick": "picoclaw-bot",
|
||||
"channels": ["#your-channel"],
|
||||
"password": "",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
オプション:NickServ 認証用の `nickserv_password`、SASL 認証用の `sasl_user`/`sasl_password`。
|
||||
|
||||
**2. 実行**
|
||||
|
||||
```bash
|
||||
picoclaw gateway
|
||||
```
|
||||
|
||||
ボットは IRC サーバーに接続し、指定されたチャネルに参加します。
|
||||
|
||||
</details>
|
||||
|
||||
<a id="dingtalk"></a>
|
||||
<details>
|
||||
<summary><b>DingTalk</b></summary>
|
||||
|
||||
+1
-110
@@ -4,7 +4,7 @@
|
||||
|
||||
## 💬 Chat Apps
|
||||
|
||||
Talk to your picoclaw through Telegram, Discord, WhatsApp, Matrix, QQ, DingTalk, LINE, WeCom, Feishu, Slack, IRC, OneBot, MQTT
|
||||
Talk to your picoclaw through Telegram, Discord, WhatsApp, QQ, DingTalk, LINE, 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.
|
||||
|
||||
@@ -14,14 +14,11 @@ Talk to your picoclaw through Telegram, Discord, WhatsApp, Matrix, QQ, DingTalk,
|
||||
| **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) |
|
||||
| **Slack** | ⭐ Easy | **Socket Mode** (no public IP needed), enterprise | [Docs](../channels/slack/README.md) |
|
||||
| **Matrix** | ⭐⭐ Medium | Federated protocol, self-hosting supported | [Docs](../channels/matrix/README.md) |
|
||||
| **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) |
|
||||
| **IRC** | ⭐⭐ Medium | Server + TLS configuration | [Docs](#irc) |
|
||||
| **OneBot** | ⭐⭐ Medium | NapCat/Go-CQHTTP compatible, community ecosystem | [Docs](../channels/onebot/README.md) |
|
||||
| **MQTT** | ⭐ Easy | Any MQTT client via broker pub/sub | [Docs](../channels/mqtt/README.md) |
|
||||
|
||||
@@ -300,42 +297,6 @@ picoclaw gateway
|
||||
```
|
||||
</details>
|
||||
|
||||
<a id="matrix"></a>
|
||||
<details>
|
||||
<summary><b>Matrix</b></summary>
|
||||
|
||||
**1. Prepare bot account**
|
||||
|
||||
* Use your preferred homeserver (e.g. `https://matrix.org` or self-hosted)
|
||||
* Create a bot user and obtain its access token
|
||||
|
||||
**2. Configure**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"matrix": {
|
||||
"enabled": true,
|
||||
"type": "matrix",
|
||||
"homeserver": "https://matrix.org",
|
||||
"user_id": "@your-bot:matrix.org",
|
||||
"access_token": "YOUR_MATRIX_ACCESS_TOKEN",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**3. Run**
|
||||
|
||||
```bash
|
||||
picoclaw gateway
|
||||
```
|
||||
|
||||
For full options (`device_id`, `join_on_invite`, `group_trigger`, `placeholder`, `reasoning_channel_id`), see [Matrix Channel Configuration Guide](../channels/matrix/README.md).
|
||||
|
||||
</details>
|
||||
|
||||
<a id="line"></a>
|
||||
<details>
|
||||
<summary><b>LINE</b></summary>
|
||||
@@ -477,76 +438,6 @@ For full options, see [Feishu Channel Configuration Guide](../channels/feishu/RE
|
||||
|
||||
</details>
|
||||
|
||||
<a id="slack"></a>
|
||||
<details>
|
||||
<summary><b>Slack</b></summary>
|
||||
|
||||
**1. Create a Slack app**
|
||||
|
||||
* Go to [Slack API](https://api.slack.com/apps) and create a new app
|
||||
* Under **OAuth & Permissions**, add bot scopes: `chat:write`, `app_mentions:read`, `im:history`, `im:read`, `im:write`
|
||||
* Install the app to your workspace
|
||||
* Copy the **Bot Token** (`xoxb-...`) and **App-Level Token** (`xapp-...`, enable Socket Mode to get this)
|
||||
|
||||
**2. Configure**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"slack": {
|
||||
"enabled": true,
|
||||
"type": "slack",
|
||||
"bot_token": "xoxb-YOUR-BOT-TOKEN",
|
||||
"app_token": "xapp-YOUR-APP-TOKEN",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**3. Run**
|
||||
|
||||
```bash
|
||||
picoclaw gateway
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<a id="irc"></a>
|
||||
<details>
|
||||
<summary><b>IRC</b></summary>
|
||||
|
||||
**1. Configure**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"irc": {
|
||||
"enabled": true,
|
||||
"type": "irc",
|
||||
"server": "irc.libera.chat:6697",
|
||||
"tls": true,
|
||||
"nick": "picoclaw-bot",
|
||||
"channels": ["#your-channel"],
|
||||
"password": "",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Optional: `nickserv_password` for NickServ authentication, `sasl_user`/`sasl_password` for SASL auth.
|
||||
|
||||
**2. Run**
|
||||
|
||||
```bash
|
||||
picoclaw gateway
|
||||
```
|
||||
|
||||
The bot will connect to the IRC server and join the specified channels.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="onebot"></a>
|
||||
<details>
|
||||
<summary><b>OneBot (QQ via OneBot protocol)</b></summary>
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## 💬 Aplikasi Sembang
|
||||
|
||||
Berbual dengan picoclaw anda melalui Telegram, Discord, WhatsApp, Matrix, QQ, DingTalk, LINE, WeCom, Feishu, Slack, IRC, OneBot, MQTT
|
||||
Berbual dengan picoclaw anda melalui Telegram, Discord, WhatsApp, QQ, DingTalk, LINE, 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.
|
||||
|
||||
@@ -13,14 +13,11 @@ Berbual dengan picoclaw anda melalui Telegram, Discord, WhatsApp, Matrix, QQ, Di
|
||||
| **Telegram** | Mudah (hanya token) |
|
||||
| **Discord** | Mudah (token bot + intents) |
|
||||
| **WhatsApp** | Mudah (asli: imbas QR; atau bridge URL) |
|
||||
| **Matrix** | Sederhana (homeserver + access token bot) |
|
||||
| **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) |
|
||||
| **Slack** | Sederhana (Bot token + App token) |
|
||||
| **IRC** | Sederhana (pelayan + konfigurasi TLS) |
|
||||
| **OneBot** | Sederhana (QQ melalui protokol OneBot) |
|
||||
| **MQTT** | Mudah (broker + agent_id) |
|
||||
|
||||
@@ -247,41 +244,6 @@ picoclaw gateway
|
||||
```
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Matrix</b></summary>
|
||||
|
||||
**1. Sediakan akaun bot**
|
||||
|
||||
* Gunakan homeserver pilihan anda (contohnya `https://matrix.org` atau self-hosted)
|
||||
* Cipta pengguna bot dan dapatkan access tokennya
|
||||
|
||||
**2. Konfigurasi**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"matrix": {
|
||||
"enabled": true,
|
||||
"type": "matrix",
|
||||
"homeserver": "https://matrix.org",
|
||||
"user_id": "@your-bot:matrix.org",
|
||||
"access_token": "YOUR_MATRIX_ACCESS_TOKEN",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**3. Jalankan**
|
||||
|
||||
```bash
|
||||
picoclaw gateway
|
||||
```
|
||||
|
||||
Untuk pilihan penuh (`device_id`, `join_on_invite`, `group_trigger`, `placeholder`, `reasoning_channel_id`), lihat [Panduan Konfigurasi Saluran Matrix](../channels/matrix/README.md).
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>LINE</b></summary>
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## 💬 Aplicativos de Chat
|
||||
|
||||
Converse com seu picoclaw através do Telegram, Discord, WhatsApp, Matrix, QQ, DingTalk, LINE, WeCom, Feishu, Slack, IRC, OneBot, MQTT
|
||||
Converse com seu picoclaw através do Telegram, Discord, WhatsApp, QQ, DingTalk, LINE, 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.
|
||||
|
||||
@@ -14,14 +14,11 @@ Converse com seu picoclaw através do Telegram, Discord, WhatsApp, Matrix, QQ, D
|
||||
| **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) |
|
||||
| **Slack** | ⭐ Fácil | **Socket Mode** (sem IP público), empresarial | [Documentação](../channels/slack/README.pt-br.md) |
|
||||
| **Matrix** | ⭐⭐ Médio | Protocolo federado, suporte a auto-hospedagem | [Documentação](../channels/matrix/README.pt-br.md) |
|
||||
| **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) |
|
||||
| **IRC** | ⭐⭐ Médio | Servidor + configuração TLS | [Documentação](#irc) |
|
||||
| **OneBot** | ⭐⭐ Médio | Compatível com NapCat/Go-CQHTTP, ecossistema comunitário | [Documentação](../channels/onebot/README.pt-br.md) |
|
||||
| **MQTT** | ⭐ Fácil | Qualquer cliente MQTT via broker pub/sub | [Documentação](../channels/mqtt/README.pt-br.md) |
|
||||
|
||||
@@ -295,42 +292,6 @@ picoclaw gateway
|
||||
|
||||
</details>
|
||||
|
||||
<a id="matrix"></a>
|
||||
<details>
|
||||
<summary><b>Matrix</b></summary>
|
||||
|
||||
**1. Preparar conta do bot**
|
||||
|
||||
* Use seu homeserver preferido (ex.: `https://matrix.org` ou auto-hospedado)
|
||||
* Crie um usuário bot e obtenha seu access token
|
||||
|
||||
**2. Configurar**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"matrix": {
|
||||
"enabled": true,
|
||||
"type": "matrix",
|
||||
"homeserver": "https://matrix.org",
|
||||
"user_id": "@your-bot:matrix.org",
|
||||
"access_token": "YOUR_MATRIX_ACCESS_TOKEN",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**3. Executar**
|
||||
|
||||
```bash
|
||||
picoclaw gateway
|
||||
```
|
||||
|
||||
Para opções completas (`device_id`, `join_on_invite`, `group_trigger`, `placeholder`, `reasoning_channel_id`), veja o [Guia de Configuração do Canal Matrix](../channels/matrix/README.md).
|
||||
|
||||
</details>
|
||||
|
||||
<a id="line"></a>
|
||||
<details>
|
||||
<summary><b>LINE</b></summary>
|
||||
@@ -539,76 +500,6 @@ Para opções completas, veja o [Guia de Configuração do Canal Feishu](../chan
|
||||
|
||||
</details>
|
||||
|
||||
<a id="slack"></a>
|
||||
<details>
|
||||
<summary><b>Slack</b></summary>
|
||||
|
||||
**1. Criar um aplicativo Slack**
|
||||
|
||||
* Acesse a [Slack API](https://api.slack.com/apps) e crie um novo aplicativo
|
||||
* Em **OAuth & Permissions**, adicione os escopos do bot: `chat:write`, `app_mentions:read`, `im:history`, `im:read`, `im:write`
|
||||
* Instale o aplicativo no seu workspace
|
||||
* Copie o **Bot Token** (`xoxb-...`) e o **App-Level Token** (`xapp-...`, habilite Socket Mode para obtê-lo)
|
||||
|
||||
**2. Configurar**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"slack": {
|
||||
"enabled": true,
|
||||
"type": "slack",
|
||||
"bot_token": "xoxb-YOUR-BOT-TOKEN",
|
||||
"app_token": "xapp-YOUR-APP-TOKEN",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**3. Executar**
|
||||
|
||||
```bash
|
||||
picoclaw gateway
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<a id="irc"></a>
|
||||
<details>
|
||||
<summary><b>IRC</b></summary>
|
||||
|
||||
**1. Configurar**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"irc": {
|
||||
"enabled": true,
|
||||
"type": "irc",
|
||||
"server": "irc.libera.chat:6697",
|
||||
"tls": true,
|
||||
"nick": "picoclaw-bot",
|
||||
"channels": ["#your-channel"],
|
||||
"password": "",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Opcional: `nickserv_password` para autenticação NickServ, `sasl_user`/`sasl_password` para autenticação SASL.
|
||||
|
||||
**2. Executar**
|
||||
|
||||
```bash
|
||||
picoclaw gateway
|
||||
```
|
||||
|
||||
O bot se conectará ao servidor IRC e entrará nos canais especificados.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="onebot"></a>
|
||||
<details>
|
||||
<summary><b>OneBot (QQ via protocolo OneBot)</b></summary>
|
||||
|
||||
+1
-110
@@ -4,7 +4,7 @@
|
||||
|
||||
## 💬 Ứng Dụng Chat
|
||||
|
||||
Trò chuyện với picoclaw của bạn qua Telegram, Discord, WhatsApp, Matrix, QQ, DingTalk, LINE, WeCom, Feishu, Slack, IRC, OneBot, MQTT
|
||||
Trò chuyện với picoclaw của bạn qua Telegram, Discord, WhatsApp, QQ, DingTalk, LINE, 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.
|
||||
|
||||
@@ -14,14 +14,11 @@ Trò chuyện với picoclaw của bạn qua Telegram, Discord, WhatsApp, Matrix
|
||||
| **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) |
|
||||
| **Slack** | ⭐ Dễ | **Socket Mode** (không cần IP công khai), doanh nghiệp | [Tài liệu](../channels/slack/README.vi.md) |
|
||||
| **Matrix** | ⭐⭐ Trung bình | Giao thức liên kết, hỗ trợ tự lưu trữ | [Tài liệu](../channels/matrix/README.vi.md) |
|
||||
| **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) |
|
||||
| **IRC** | ⭐⭐ Trung bình | Máy chủ + cấu hình TLS | [Tài liệu](#irc) |
|
||||
| **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) |
|
||||
| **MQTT** | ⭐ Dễ | Bất kỳ client MQTT nào qua broker pub/sub | [Tài liệu](../channels/mqtt/README.vi.md) |
|
||||
|
||||
@@ -295,42 +292,6 @@ picoclaw gateway
|
||||
|
||||
</details>
|
||||
|
||||
<a id="matrix"></a>
|
||||
<details>
|
||||
<summary><b>Matrix</b></summary>
|
||||
|
||||
**1. Chuẩn bị tài khoản bot**
|
||||
|
||||
* Sử dụng homeserver ưa thích (ví dụ: `https://matrix.org` hoặc tự host)
|
||||
* Tạo user bot và lấy access token
|
||||
|
||||
**2. Cấu hình**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"matrix": {
|
||||
"enabled": true,
|
||||
"type": "matrix",
|
||||
"homeserver": "https://matrix.org",
|
||||
"user_id": "@your-bot:matrix.org",
|
||||
"access_token": "YOUR_MATRIX_ACCESS_TOKEN",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**3. Chạy**
|
||||
|
||||
```bash
|
||||
picoclaw gateway
|
||||
```
|
||||
|
||||
Để xem đầy đủ các tùy chọn (`device_id`, `join_on_invite`, `group_trigger`, `placeholder`, `reasoning_channel_id`), xem [Hướng Dẫn Cấu Hình Kênh Matrix](../channels/matrix/README.md).
|
||||
|
||||
</details>
|
||||
|
||||
<a id="line"></a>
|
||||
<details>
|
||||
<summary><b>LINE</b></summary>
|
||||
@@ -540,76 +501,6 @@ Mở Feishu, tìm tên bot của bạn và bắt đầu trò chuyện. Bạn cũ
|
||||
|
||||
</details>
|
||||
|
||||
<a id="slack"></a>
|
||||
<details>
|
||||
<summary><b>Slack</b></summary>
|
||||
|
||||
**1. Tạo ứng dụng Slack**
|
||||
|
||||
* Truy cập [Slack API](https://api.slack.com/apps) và tạo ứng dụng mới
|
||||
* Trong **OAuth & Permissions**, thêm các scope bot: `chat:write`, `app_mentions:read`, `im:history`, `im:read`, `im:write`
|
||||
* Cài đặt ứng dụng vào workspace của bạn
|
||||
* Sao chép **Bot Token** (`xoxb-...`) và **App-Level Token** (`xapp-...`, bật Socket Mode để lấy token này)
|
||||
|
||||
**2. Cấu hình**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"slack": {
|
||||
"enabled": true,
|
||||
"type": "slack",
|
||||
"bot_token": "xoxb-YOUR-BOT-TOKEN",
|
||||
"app_token": "xapp-YOUR-APP-TOKEN",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**3. Chạy**
|
||||
|
||||
```bash
|
||||
picoclaw gateway
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<a id="irc"></a>
|
||||
<details>
|
||||
<summary><b>IRC</b></summary>
|
||||
|
||||
**1. Cấu hình**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"irc": {
|
||||
"enabled": true,
|
||||
"type": "irc",
|
||||
"server": "irc.libera.chat:6697",
|
||||
"tls": true,
|
||||
"nick": "picoclaw-bot",
|
||||
"channels": ["#your-channel"],
|
||||
"password": "",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Tùy chọn: `nickserv_password` để xác thực NickServ, `sasl_user`/`sasl_password` để xác thực SASL.
|
||||
|
||||
**2. Chạy**
|
||||
|
||||
```bash
|
||||
picoclaw gateway
|
||||
```
|
||||
|
||||
Bot sẽ kết nối đến máy chủ IRC và tham gia các kênh đã chỉ định.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="onebot"></a>
|
||||
<details>
|
||||
<summary><b>OneBot (QQ qua giao thức OneBot)</b></summary>
|
||||
|
||||
+1
-110
@@ -4,7 +4,7 @@
|
||||
|
||||
## 💬 聊天应用集成 (Chat Apps)
|
||||
|
||||
PicoClaw 支持多种聊天平台,使您的 Agent 能够连接到任何地方,包括 Telegram、Discord、WhatsApp、微信、QQ、钉钉、LINE、企业微信、飞书、Slack、IRC、OneBot、MQTT 等。
|
||||
PicoClaw 支持多种聊天平台,使您的 Agent 能够连接到任何地方,包括 Telegram、Discord、WhatsApp、微信、QQ、钉钉、LINE、企业微信、飞书、OneBot、MQTT 等。
|
||||
|
||||
> **注意**: 依赖 HTTP 回调的渠道共用同一个 Gateway HTTP 服务器(`gateway.host`:`gateway.port`,默认 `127.0.0.1:18790`),无需为每个渠道单独配置端口。飞书、钉钉、企业微信这类 Socket/Stream 模式渠道不依赖共享 webhook 服务器来接收入站消息。
|
||||
|
||||
@@ -16,14 +16,11 @@ PicoClaw 支持多种聊天平台,使您的 Agent 能够连接到任何地方
|
||||
| **Discord** | ⭐ 简单 | Socket Mode,支持群组/私信,Bot 生态成熟 | [查看文档](../channels/discord/README.zh.md) |
|
||||
| **WhatsApp** | ⭐ 简单 | 原生 (QR 扫码) 或 Bridge URL | [查看文档](#whatsapp) |
|
||||
| **微信 (Weixin)** | ⭐ 简单 | 原生扫码(腾讯 iLink API) | [查看文档](#weixin) |
|
||||
| **Slack** | ⭐ 简单 | **Socket Mode** (无需公网 IP),企业级支持 | [查看文档](../channels/slack/README.zh.md) |
|
||||
| **Matrix** | ⭐⭐ 中等 | 联邦协议,支持自建 homeserver 与公开服务器 | [查看文档](../channels/matrix/README.zh.md) |
|
||||
| **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) |
|
||||
| **IRC** | ⭐⭐ 中等 | 服务器 + TLS 配置 | [查看文档](#irc) |
|
||||
| **OneBot** | ⭐⭐ 中等 | 兼容 NapCat/Go-CQHTTP,社区生态丰富 | [查看文档](../channels/onebot/README.zh.md) |
|
||||
| **MQTT** | ⭐ 简单 | 任意 MQTT 客户端通过 Broker 收发消息 | [查看文档](../channels/mqtt/README.zh.md) |
|
||||
|
||||
@@ -221,42 +218,6 @@ picoclaw gateway
|
||||
|
||||
</details>
|
||||
|
||||
<a id="matrix"></a>
|
||||
<details>
|
||||
<summary><b>Matrix</b></summary>
|
||||
|
||||
**1. 准备 Bot 账号**
|
||||
|
||||
* 使用你的 homeserver(如 `https://matrix.org` 或自建)
|
||||
* 创建 Bot 用户并获取 access token
|
||||
|
||||
**2. 配置**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"matrix": {
|
||||
"enabled": true,
|
||||
"type": "matrix",
|
||||
"homeserver": "https://matrix.org",
|
||||
"user_id": "@your-bot:matrix.org",
|
||||
"access_token": "YOUR_MATRIX_ACCESS_TOKEN",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**3. 运行**
|
||||
|
||||
```bash
|
||||
picoclaw gateway
|
||||
```
|
||||
|
||||
完整选项(`device_id`、`join_on_invite`、`group_trigger`、`placeholder`、`reasoning_channel_id`)请参考 [Matrix 渠道配置指南](../channels/matrix/README.md)。
|
||||
|
||||
</details>
|
||||
|
||||
<a id="qq"></a>
|
||||
<details>
|
||||
<summary><b>QQ</b></summary>
|
||||
@@ -300,76 +261,6 @@ QQ 开放平台提供了一键创建 OpenClaw 兼容机器人的页面:
|
||||
|
||||
</details>
|
||||
|
||||
<a id="slack"></a>
|
||||
<details>
|
||||
<summary><b>Slack</b></summary>
|
||||
|
||||
**1. 创建 Slack App**
|
||||
|
||||
* 前往 [Slack API](https://api.slack.com/apps) 创建新应用
|
||||
* 在 **OAuth & Permissions** 中添加 Bot 权限范围:`chat:write`、`app_mentions:read`、`im:history`、`im:read`、`im:write`
|
||||
* 将应用安装到你的工作区
|
||||
* 复制 **Bot Token**(`xoxb-...`)和 **App-Level Token**(`xapp-...`,启用 Socket Mode 后获取)
|
||||
|
||||
**2. 配置**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"slack": {
|
||||
"enabled": true,
|
||||
"type": "slack",
|
||||
"bot_token": "xoxb-YOUR-BOT-TOKEN",
|
||||
"app_token": "xapp-YOUR-APP-TOKEN",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**3. 运行**
|
||||
|
||||
```bash
|
||||
picoclaw gateway
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<a id="irc"></a>
|
||||
<details>
|
||||
<summary><b>IRC</b></summary>
|
||||
|
||||
**1. 配置**
|
||||
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"irc": {
|
||||
"enabled": true,
|
||||
"type": "irc",
|
||||
"server": "irc.libera.chat:6697",
|
||||
"tls": true,
|
||||
"nick": "picoclaw-bot",
|
||||
"channels": ["#your-channel"],
|
||||
"password": "",
|
||||
"allow_from": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
可选:`nickserv_password` 用于 NickServ 认证,`sasl_user`/`sasl_password` 用于 SASL 认证。
|
||||
|
||||
**2. 运行**
|
||||
|
||||
```bash
|
||||
picoclaw gateway
|
||||
```
|
||||
|
||||
Bot 将连接到 IRC 服务器并加入指定的频道。
|
||||
|
||||
</details>
|
||||
|
||||
<a id="dingtalk"></a>
|
||||
<details>
|
||||
<summary><b>钉钉 (DingTalk)</b></summary>
|
||||
|
||||
@@ -36,7 +36,7 @@ This guide explains how to configure both for real deployments.
|
||||
}
|
||||
```
|
||||
|
||||
### Route only Slack mentions in one workspace
|
||||
### Route only Discord mentions in one workspace
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -48,11 +48,11 @@ This guide explains how to configure both for real deployments.
|
||||
"dispatch": {
|
||||
"rules": [
|
||||
{
|
||||
"name": "slack mentions",
|
||||
"name": "discord mentions",
|
||||
"agent": "support",
|
||||
"when": {
|
||||
"channel": "slack",
|
||||
"space": "workspace:t001",
|
||||
"channel": "discord",
|
||||
"space": "guild:t001",
|
||||
"mentioned": true
|
||||
}
|
||||
}
|
||||
@@ -109,9 +109,9 @@ If no rule matches, PicoClaw falls back to the default agent.
|
||||
|
||||
| Field | Meaning | Example |
|
||||
| --- | --- | --- |
|
||||
| `channel` | Channel name | `telegram`, `slack`, `discord` |
|
||||
| `channel` | Channel name | `telegram`, `discord`, `feishu` |
|
||||
| `account` | Normalized account ID | `default`, `bot2` |
|
||||
| `space` | Workspace, guild, or similar container | `workspace:t001`, `guild:123456` |
|
||||
| `space` | Workspace, guild, or similar container | `guild:t001`, `guild:123456` |
|
||||
| `chat` | Direct chat, group, or channel | `direct:user123`, `group:-100123`, `channel:c123` |
|
||||
| `topic` | Thread or topic | `topic:42` |
|
||||
| `sender` | Normalized sender identity | `12345`, `john` |
|
||||
@@ -202,7 +202,7 @@ Example:
|
||||
{
|
||||
"session": {
|
||||
"identity_links": {
|
||||
"john": ["slack:u123", "legacy-user-42"]
|
||||
"john": ["discord:u123", "legacy-user-42"]
|
||||
}
|
||||
},
|
||||
"agents": {
|
||||
|
||||
@@ -36,7 +36,7 @@ PicoClaw 里用户能直接感知到的“路由”主要有两部分:
|
||||
}
|
||||
```
|
||||
|
||||
### 只处理某个 Slack workspace 里的 @提及
|
||||
### 只处理某个 Discord server 里的 @提及
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -48,11 +48,11 @@ PicoClaw 里用户能直接感知到的“路由”主要有两部分:
|
||||
"dispatch": {
|
||||
"rules": [
|
||||
{
|
||||
"name": "slack mentions",
|
||||
"name": "discord mentions",
|
||||
"agent": "support",
|
||||
"when": {
|
||||
"channel": "slack",
|
||||
"space": "workspace:t001",
|
||||
"channel": "discord",
|
||||
"space": "guild:t001",
|
||||
"mentioned": true
|
||||
}
|
||||
}
|
||||
@@ -109,9 +109,9 @@ agents.dispatch.rules
|
||||
|
||||
| 字段 | 含义 | 示例 |
|
||||
| --- | --- | --- |
|
||||
| `channel` | Channel 名称 | `telegram`、`slack`、`discord` |
|
||||
| `channel` | Channel 名称 | `telegram`、`discord`、`feishu` |
|
||||
| `account` | 归一化后的 account ID | `default`、`bot2` |
|
||||
| `space` | workspace、guild 等上层容器 | `workspace:t001`、`guild:123456` |
|
||||
| `space` | workspace、guild 等上层容器 | `guild:t001`、`guild:123456` |
|
||||
| `chat` | 私聊、群或频道 | `direct:user123`、`group:-100123`、`channel:c123` |
|
||||
| `topic` | 线程或话题 | `topic:42` |
|
||||
| `sender` | 归一化后的发送者身份 | `12345`、`john` |
|
||||
@@ -202,7 +202,7 @@ agents.dispatch.rules
|
||||
{
|
||||
"session": {
|
||||
"identity_links": {
|
||||
"john": ["slack:u123", "legacy-user-42"]
|
||||
"john": ["discord:u123", "legacy-user-42"]
|
||||
}
|
||||
},
|
||||
"agents": {
|
||||
|
||||
@@ -73,7 +73,7 @@ If your channel exposes a `space` value, you can route by workspace or guild ins
|
||||
|
||||
Use this when:
|
||||
|
||||
- a Slack workspace assistant should share context across channels
|
||||
- a Discord server assistant should share context across channels
|
||||
- a Discord guild assistant should share context across channels
|
||||
|
||||
### Split by thread or forum topic
|
||||
@@ -212,7 +212,7 @@ Example:
|
||||
"session": {
|
||||
"dimensions": ["chat", "sender"],
|
||||
"identity_links": {
|
||||
"john": ["slack:u123", "u123", "legacy-user-42"]
|
||||
"john": ["discord:u123", "u123", "legacy-user-42"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -244,7 +244,7 @@ Switch to:
|
||||
}
|
||||
```
|
||||
|
||||
### The same user does not share memory across Slack and Telegram
|
||||
### The same user does not share memory across Discord and Telegram
|
||||
|
||||
That is expected.
|
||||
PicoClaw still separates sessions by channel even if you use `sender`.
|
||||
|
||||
@@ -73,7 +73,7 @@ Session 数据保存在工作区目录下,通常是:
|
||||
|
||||
适用场景:
|
||||
|
||||
- Slack workspace 里的 assistant 想跨多个 channel 共享上下文
|
||||
- Discord server 里的 assistant 想跨多个 channel 共享上下文
|
||||
- Discord guild 里的 assistant 想跨多个 channel 共享上下文
|
||||
|
||||
### 按线程或论坛 topic 隔离
|
||||
@@ -212,7 +212,7 @@ Telegram forum 消息在默认 `chat` 模式下就会保留 topic 隔离。
|
||||
"session": {
|
||||
"dimensions": ["chat", "sender"],
|
||||
"identity_links": {
|
||||
"john": ["slack:u123", "u123", "legacy-user-42"]
|
||||
"john": ["discord:u123", "u123", "legacy-user-42"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -244,7 +244,7 @@ Telegram forum 消息在默认 `chat` 模式下就会保留 topic 隔离。
|
||||
}
|
||||
```
|
||||
|
||||
### 同一个用户在 Slack 和 Telegram 之间没有共享记忆
|
||||
### 同一个用户在 Discord 和 Telegram 之间没有共享记忆
|
||||
|
||||
这是当前实现下的预期行为。
|
||||
即使使用了 `sender`,PicoClaw 仍然会按 channel 做基础隔离。
|
||||
|
||||
@@ -30,7 +30,6 @@
|
||||
|
||||
**Fonctionne sur du matériel à $10 avec <10 Mo de RAM** — c'est 99% de mémoire en moins qu'OpenClaw et 98% moins cher qu'un Mac mini !
|
||||
|
||||
|
||||
<table align="center">
|
||||
<tr align="center">
|
||||
<td align="center" valign="top">
|
||||
@@ -84,7 +83,6 @@
|
||||
|
||||
</details>
|
||||
|
||||
|
||||
## ✨ Fonctionnalités
|
||||
|
||||
🪶 **Ultra-léger** : Empreinte mémoire du cœur <10 Mo — 99% plus petit qu'OpenClaw.*
|
||||
@@ -157,7 +155,6 @@ PicoClaw peut être déployé sur pratiquement n'importe quel appareil Linux !
|
||||
|
||||
🌟 D'autres cas de déploiement vous attendent !
|
||||
|
||||
|
||||
## 📦 Installation
|
||||
|
||||
### Télécharger depuis picoclaw.io (Recommandé)
|
||||
@@ -372,13 +369,10 @@ Parlez à votre PicoClaw via plus de 17 plateformes de messagerie :
|
||||
| **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) |
|
||||
| **Slack** | Facile (token bot + app) | Socket Mode | [Guide](../channels/slack/README.fr.md) |
|
||||
| **Matrix** | Moyen (homeserver + token) | Sync API | [Guide](../channels/matrix/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) |
|
||||
| **IRC** | Moyen (serveur + pseudo) | Protocole IRC | [Guide](../guides/chat-apps.fr.md#irc) |
|
||||
| **OneBot** | Moyen (URL WebSocket) | OneBot v11 | [Guide](../channels/onebot/README.fr.md) |
|
||||
|
||||
> Tous les channels basés sur webhook partagent un seul serveur HTTP Gateway (`gateway.host`:`gateway.port`, par défaut `127.0.0.1:18790`). Feishu utilise le mode WebSocket/SDK et n'utilise pas le serveur HTTP partagé.
|
||||
|
||||
@@ -368,13 +368,10 @@ Bicara dengan PicoClaw Anda melalui 17+ platform pesan:
|
||||
| **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) |
|
||||
| **Slack** | Mudah (bot + app token) | Socket Mode | [Panduan](../channels/slack/README.md) |
|
||||
| **Matrix** | Sedang (homeserver + token) | Sync API | [Panduan](../channels/matrix/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) |
|
||||
| **IRC** | Sedang (server + nick) | IRC protocol | [Panduan](../guides/chat-apps.md#irc) |
|
||||
| **OneBot** | Sedang (WebSocket URL) | OneBot v11 | [Panduan](../channels/onebot/README.md) |
|
||||
|
||||
> Semua channel berbasis webhook berbagi satu server HTTP Gateway (`gateway.host`:`gateway.port`, default `127.0.0.1:18790`). Feishu menggunakan mode WebSocket/SDK dan tidak menggunakan server HTTP bersama.
|
||||
|
||||
@@ -368,13 +368,10 @@ Parla con il tuo PicoClaw attraverso 17+ piattaforme di messaggistica:
|
||||
| **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) |
|
||||
| **Slack** | Facile (bot + app token) | Socket Mode | [Guida](../channels/slack/README.md) |
|
||||
| **Matrix** | Medio (homeserver + token) | Sync API | [Guida](../channels/matrix/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) |
|
||||
| **IRC** | Medio (server + nick) | Protocollo IRC | [Guida](../guides/chat-apps.md#irc) |
|
||||
| **OneBot** | Medio (WebSocket URL) | OneBot v11 | [Guida](../channels/onebot/README.md) |
|
||||
|
||||
> Tutti i channel basati su webhook condividono un singolo server HTTP Gateway (`gateway.host`:`gateway.port`, default `127.0.0.1:18790`). Feishu usa la modalità WebSocket/SDK e non usa il server HTTP condiviso.
|
||||
|
||||
@@ -369,13 +369,10 @@ Provider の完全な設定詳細は [Provider とモデル](../guides/providers
|
||||
| **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) |
|
||||
| **Slack** | 簡単(bot + app トークン) | Socket Mode | [ガイド](../channels/slack/README.ja.md) |
|
||||
| **Matrix** | 中級(homeserver + トークン) | Sync API | [ガイド](../channels/matrix/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) |
|
||||
| **IRC** | 中級(サーバー + nick) | IRC protocol | [ガイド](../guides/chat-apps.ja.md#irc) |
|
||||
| **OneBot** | 中級(WebSocket URL) | OneBot v11 | [ガイド](../channels/onebot/README.ja.md) |
|
||||
|
||||
> webhook ベースのすべての Channel は単一の Gateway HTTP サーバー(`gateway.host`:`gateway.port`、デフォルト `127.0.0.1:18790`)を共有します。Feishu は WebSocket/SDK モードを使用し、共有 HTTP サーバーを使用しません。
|
||||
|
||||
@@ -371,14 +371,10 @@ PicoClaw는 `model_list` 설정을 통해 30개 이상의 LLM 프로바이더를
|
||||
| **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) |
|
||||
| **Slack** | 쉬움(봇 + 앱 토큰) | Socket Mode | [가이드](../channels/slack/README.md) |
|
||||
| **Matrix** | 중간(homeserver + 토큰) | Sync API | [가이드](../channels/matrix/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) |
|
||||
| **VK** | 쉬움(그룹 토큰) | Long Poll | [가이드](../channels/vk/README.md) |
|
||||
| **IRC** | 중간(서버 + 닉네임) | IRC protocol | [가이드](../guides/chat-apps.md#irc) |
|
||||
| **OneBot** | 중간(WebSocket URL) | OneBot v11 | [가이드](../channels/onebot/README.md) |
|
||||
|
||||
> webhook 기반 채널은 모두 하나의 게이트웨이 HTTP 서버(`gateway.host`:`gateway.port`, 기본값 `127.0.0.1:18790`)를 공유합니다. Feishu는 WebSocket/SDK 모드를 사용하며 이 공용 HTTP 서버를 사용하지 않습니다.
|
||||
|
||||
@@ -53,7 +53,6 @@
|
||||
> * **BERHATI-HATI:** Banyak domain `.ai/.org/.com/.net/...` telah didaftarkan oleh pihak ketiga. Jangan percayai mereka.
|
||||
> * **NOTA:** PicoClaw dalam pembangunan pesat awal. Mungkin terdapat isu keselamatan yang belum diselesaikan. Jangan deploy ke pengeluaran sebelum v1.0.
|
||||
|
||||
|
||||
## 📢 Berita
|
||||
|
||||
2026-05-11 🛒 **LicheeRV-Claw tersedia di AliExpress!** Anda kini boleh membeli LicheeRV-Claw di [AliExpress](https://www.aliexpress.com/item/1005006519668532.html), menjadikannya lebih mudah untuk mencuba PicoClaw pada perkakasan RISC-V yang kompak.
|
||||
@@ -155,7 +154,6 @@ PicoClaw boleh digunakan pada hampir mana-mana peranti Linux!
|
||||
|
||||
🌟 Lebih Banyak Kes Deployment Menanti!
|
||||
|
||||
|
||||
## 📦 Pemasangan
|
||||
|
||||
### Muat turun dari picoclaw.io (Disyorkan)
|
||||
@@ -357,7 +355,6 @@ Untuk butiran konfigurasi penyedia penuh, lihat [Penyedia & Model](../guides/pro
|
||||
|
||||
</details>
|
||||
|
||||
|
||||
## 💬 Saluran (Aplikasi Sembang)
|
||||
|
||||
Bercakap dengan PicoClaw anda melalui 17+ platform pemesejan:
|
||||
@@ -369,13 +366,10 @@ Bercakap dengan PicoClaw anda melalui 17+ platform pemesejan:
|
||||
| **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) |
|
||||
| **Slack** | Mudah (token bot + app) | Socket Mode | [Panduan](../channels/slack/README.md) |
|
||||
| **Matrix** | Sederhana (homeserver + token) | Sync API | [Panduan](../channels/matrix/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) |
|
||||
| **IRC** | Sederhana (pelayan + nick) | Protokol IRC | [Panduan](../guides/chat-apps.ms.md#irc) |
|
||||
| **OneBot** | Sederhana (URL WebSocket) | OneBot v11 | [Panduan](../channels/onebot/README.md) |
|
||||
|
||||
> Semua saluran berasaskan webhook berkongsi satu pelayan HTTP Gateway (`gateway.host`:`gateway.port`, lalai `127.0.0.1:18790`). Feishu menggunakan mod WebSocket/SDK dan tidak menggunakan pelayan HTTP yang dikongsi.
|
||||
|
||||
@@ -369,13 +369,10 @@ Converse com seu PicoClaw por meio de mais de 17 plataformas de mensagens:
|
||||
| **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) |
|
||||
| **Slack** | Fácil (bot + app token) | Socket Mode | [Guia](../channels/slack/README.pt-br.md) |
|
||||
| **Matrix** | Médio (homeserver + token) | Sync API | [Guia](../channels/matrix/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) |
|
||||
| **IRC** | Médio (servidor + nick) | Protocolo IRC | [Guia](../guides/chat-apps.pt-br.md#irc) |
|
||||
| **OneBot** | Médio (WebSocket URL) | OneBot v11 | [Guia](../channels/onebot/README.pt-br.md) |
|
||||
|
||||
> Todos os channels baseados em webhook compartilham um único servidor HTTP do Gateway (`gateway.host`:`gateway.port`, padrão `127.0.0.1:18790`). O Feishu usa modo WebSocket/SDK e não utiliza o servidor HTTP compartilhado.
|
||||
|
||||
@@ -369,13 +369,10 @@ Trò chuyện với PicoClaw của bạn qua 17+ nền tảng nhắn tin:
|
||||
| **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) |
|
||||
| **Slack** | Dễ (bot + app token) | Socket Mode | [Hướng dẫn](../channels/slack/README.vi.md) |
|
||||
| **Matrix** | Trung bình (homeserver + token) | Sync API | [Hướng dẫn](../channels/matrix/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) |
|
||||
| **IRC** | Trung bình (server + nick) | IRC protocol | [Hướng dẫn](../guides/chat-apps.vi.md#irc) |
|
||||
| **OneBot** | Trung bình (WebSocket URL) | OneBot v11 | [Hướng dẫn](../channels/onebot/README.vi.md) |
|
||||
|
||||
> Tất cả các Channel dựa trên webhook dùng chung một Gateway HTTP server (`gateway.host`:`gateway.port`, mặc định `127.0.0.1:18790`). Feishu sử dụng chế độ WebSocket/SDK và không dùng HTTP server chung.
|
||||
|
||||
@@ -369,14 +369,10 @@ PicoClaw 通过 `model_list` 配置支持 30+ LLM Provider,使用 `协议/模
|
||||
| **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) |
|
||||
| **Slack** | 简单(bot + app token) | Socket Mode | [指南](../channels/slack/README.zh.md) |
|
||||
| **Matrix** | 中等(homeserver + token) | Sync API | [指南](../channels/matrix/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) |
|
||||
| **VK** | 简单(群组 token) | Long Poll | [指南](../channels/vk/README.md) |
|
||||
| **IRC** | 中等(server + nick) | IRC 协议 | [指南](../guides/chat-apps.zh.md#irc) |
|
||||
| **OneBot** | 中等(WebSocket URL) | OneBot v11 | [指南](../channels/onebot/README.zh.md) |
|
||||
|
||||
> 所有基于 Webhook 的 Channel 共用同一个 Gateway HTTP 服务器(`gateway.host`:`gateway.port`,默认 `127.0.0.1:18790`)。飞书使用 WebSocket/SDK 模式,不使用共享 HTTP 服务器。
|
||||
|
||||
@@ -61,11 +61,6 @@ channels:
|
||||
app_secret: "your-qq-app-secret"
|
||||
dingtalk:
|
||||
client_secret: "your-dingtalk-client-secret"
|
||||
slack:
|
||||
bot_token: "your-slack-bot-token"
|
||||
app_token: "your-slack-app-token"
|
||||
matrix:
|
||||
access_token: "your-matrix-access-token"
|
||||
line:
|
||||
channel_secret: "your-line-channel-secret"
|
||||
channel_access_token: "your-line-channel-access-token"
|
||||
@@ -84,10 +79,6 @@ channels:
|
||||
encoding_aes_key: "your-wecom-aibot-encoding-aes-key"
|
||||
pico:
|
||||
token: "your-pico-token"
|
||||
irc:
|
||||
password: "your-irc-password"
|
||||
nickserv_password: "your-irc-nickserv-password"
|
||||
sasl_password: "your-irc-sasl-password"
|
||||
|
||||
# Channel Settings (nested format for channels that use settings block)
|
||||
channel_list:
|
||||
|
||||
@@ -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, Slack, Matrix, etc.)
|
||||
- Channel tokens (Telegram, Discord, etc.)
|
||||
- Web tool API keys (Brave, Tavily, Perplexity, etc.)
|
||||
- Skills tokens (GitHub, ClawHub)
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ PicoClaw 可以从工具调用结果中过滤敏感值(API 密钥、令牌、
|
||||
敏感值从 `.security.yml` 中收集 —— 这是所有敏感配置的集中存储,包括:
|
||||
|
||||
- 模型 API 密钥
|
||||
- 频道令牌(Telegram、Discord、Slack、Matrix 等)
|
||||
- 频道令牌(Telegram、Discord 等)
|
||||
- Web 工具 API 密钥(Brave、Tavily、Perplexity 等)
|
||||
- 技能令牌(GitHub、ClawHub)
|
||||
|
||||
|
||||
@@ -5,10 +5,8 @@ go 1.25.13
|
||||
require (
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.0
|
||||
github.com/SevereCloud/vksdk/v3 v3.3.1
|
||||
github.com/adhocore/gronx v1.20.0
|
||||
github.com/anthropics/anthropic-sdk-go v1.55.1
|
||||
github.com/atc0005/go-teams-notify/v2 v2.14.0
|
||||
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
|
||||
@@ -17,7 +15,6 @@ require (
|
||||
github.com/charmbracelet/lipgloss v1.1.0
|
||||
github.com/creack/pty v1.1.24
|
||||
github.com/eclipse/paho.mqtt.golang v1.5.1
|
||||
github.com/ergochat/irc-go v0.6.0
|
||||
github.com/ergochat/readline v0.1.3
|
||||
github.com/gomarkdown/markdown v0.0.0-20260411013819-759bbc3e3207
|
||||
github.com/google/uuid v1.6.0
|
||||
@@ -37,7 +34,6 @@ require (
|
||||
github.com/pion/webrtc/v3 v3.3.6
|
||||
github.com/pmezard/go-difflib v1.0.0
|
||||
github.com/rs/zerolog v1.35.1
|
||||
github.com/slack-go/slack v0.23.1
|
||||
github.com/spf13/cobra v1.10.2
|
||||
github.com/spf13/pflag v1.0.10
|
||||
github.com/stretchr/testify v1.11.1
|
||||
@@ -49,7 +45,6 @@ require (
|
||||
golang.org/x/time v0.15.0
|
||||
google.golang.org/protobuf v1.36.11
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
maunium.net/go/mautrix v0.27.0
|
||||
modernc.org/sqlite v1.53.0
|
||||
)
|
||||
|
||||
@@ -94,7 +89,6 @@ require (
|
||||
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.16 // indirect
|
||||
github.com/mattn/go-sqlite3 v1.14.42 // 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
|
||||
@@ -106,8 +100,6 @@ require (
|
||||
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/vmihailenco/msgpack/v5 v5.4.1 // indirect
|
||||
github.com/vmihailenco/tagparser/v2 v2.0.0 // 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
|
||||
|
||||
@@ -17,8 +17,6 @@ github.com/AzureAD/microsoft-authentication-library-for-go v1.7.2 h1:RHK7bS+HQMs
|
||||
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/SevereCloud/vksdk/v3 v3.3.1 h1:O86zsp5LQnHE+O5acvuXM/s6S1LyxzVTkF6+Lup0Jyg=
|
||||
github.com/SevereCloud/vksdk/v3 v3.3.1/go.mod h1:c6WaA5aocUYsXfkcUbg2qy45V9M1VDcqHHmHIN14NAw=
|
||||
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=
|
||||
@@ -29,8 +27,6 @@ github.com/andybalholm/brotli v1.2.1 h1:R+f5xP285VArJDRgowrfb9DqL18yVK0gKAW/F+eT
|
||||
github.com/andybalholm/brotli v1.2.1/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
|
||||
github.com/anthropics/anthropic-sdk-go v1.55.1 h1:GxukHUVou6AFIngxa/Aw1z79hmwg13Hmn++KE9werbM=
|
||||
github.com/anthropics/anthropic-sdk-go v1.55.1/go.mod h1:3EfIfmFqxH6rbiLcIP4tPFyXL/IHakx2wDG4OU+TIEI=
|
||||
github.com/atc0005/go-teams-notify/v2 v2.14.0 h1:7N+xw+COnYANLREaAveQ65rsNQ12nIZJED9nMLyscCo=
|
||||
github.com/atc0005/go-teams-notify/v2 v2.14.0/go.mod h1:EECsWM2b0Hvoz7O+QdlsvyN2KCUOFQCGj8bUBXv3A3Q=
|
||||
github.com/aws/aws-sdk-go-v2 v1.42.0 h1:XvXMJTkFQtpBKIWZnmr9ZEOc2InWM2yldjXEJ/bymhA=
|
||||
github.com/aws/aws-sdk-go-v2 v1.42.0/go.mod h1:27+ACypSLljLAEKsCYOmrjKh83vuTRkuAe9Uv/3A4bg=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.12 h1:oRtsqWgxbpeXrOlxOoQStx2M9WNbIkPq4C4Xn1or6bc=
|
||||
@@ -113,8 +109,6 @@ github.com/eclipse/paho.mqtt.golang v1.5.1 h1:/VSOv3oDLlpqR2Epjn1Q7b2bSTplJIeV2I
|
||||
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/irc-go v0.6.0 h1:Y0AGV76aeihJfCtLaQh+OyJKFiKGrYC0VTkeMZ6XW28=
|
||||
github.com/ergochat/irc-go v0.6.0/go.mod h1:2vi7KNpIPWnReB5hmLpl92eMywQvuIeIIGdt/FQCph0=
|
||||
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=
|
||||
@@ -131,8 +125,6 @@ github.com/go-resty/resty/v2 v2.6.0/go.mod h1:PwvJS6hvaPkjtjNg9ph+VrSD92bi5Zq73w
|
||||
github.com/go-resty/resty/v2 v2.17.1 h1:x3aMpHK1YM9e4va/TMDRlusDDoZiQ+ViDu/WpA6xTM4=
|
||||
github.com/go-resty/resty/v2 v2.17.1/go.mod h1:kCKZ3wWmwJaNc7S29BRtUhJwy7iqmn+2mLtQrOyQlVA=
|
||||
github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE=
|
||||
github.com/go-test/deep v1.1.1 h1:0r/53hagsehfO4bzD2Pgr/+RgHqhmf+k1Bpse2cTu1U=
|
||||
github.com/go-test/deep v1.1.1/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE=
|
||||
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
|
||||
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
|
||||
@@ -270,8 +262,6 @@ github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfv
|
||||
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/slack-go/slack v0.23.1 h1:ZS5B96wxxYQRwvJ3/vJFtqtUZi3tXhsZCyT44Nv7M80=
|
||||
github.com/slack-go/slack v0.23.1/go.mod h1:H0yR/YBuRJ39RkE+JpV/d/oEsbanzTRowR82bCN0cEs=
|
||||
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=
|
||||
@@ -315,10 +305,6 @@ github.com/valyala/fastjson v1.6.10 h1:/yjJg8jaVQdYR3arGxPE2X5z89xrlhS0eGXdv+ADT
|
||||
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/vmihailenco/msgpack/v5 v5.4.1 h1:cQriyiUvjTwOHg8QZaPihLWeRAAVoCpE00IUPn0Bjt8=
|
||||
github.com/vmihailenco/msgpack/v5 v5.4.1/go.mod h1:GaZTsDaehaPpQVyxrf5mtQlH+pc21PIudVV/E3rRQok=
|
||||
github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g=
|
||||
github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds=
|
||||
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=
|
||||
@@ -476,8 +462,6 @@ gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
maunium.net/go/mautrix v0.27.0 h1:yfEYwoIluVWkofUgbZl9gP4i5nQTF+QNsxtb+r5bKlM=
|
||||
maunium.net/go/mautrix v0.27.0/go.mod h1:7QpEQiTy6p4LHkXXaZI+N46tGYy8HMhD0JjzZAFoFWs=
|
||||
modernc.org/cc/v4 v4.28.4 h1:Hd/4Es+MBj+/7hSdZaisNyu6bv3V0Dp2MdllyfqaH+c=
|
||||
modernc.org/cc/v4 v4.28.4/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
|
||||
modernc.org/ccgo/v4 v4.34.4 h1:OVnSOWQjVKOYkFxoHYB+qQmSHK5gqMqARM+K9DpR/Ws=
|
||||
|
||||
@@ -41,7 +41,7 @@ The runner auto-discovers every suite under `integration/suites/`, so adding a s
|
||||
- The shared runner is defined in [`integration/docker-compose.runner.yml`](docker-compose.runner.yml).
|
||||
- Each suite lives in `integration/suites/<suite-name>/`.
|
||||
- The runner script loads `suite.env`, merges the shared compose file with the suite-specific compose files, starts dependency services, runs the suite command, and then tears everything down.
|
||||
- The shared runner container sets `GOFLAGS=-tags=goolm,stdjson,integration`, so tests run with the same build tags used by CI.
|
||||
- The shared runner container sets `GOFLAGS=-tags=stdjson,integration`, so tests run with the same build tags used by CI.
|
||||
|
||||
In practice, each suite gives us:
|
||||
|
||||
@@ -125,7 +125,7 @@ This is the fastest way to reproduce exactly what the CI integration job does fo
|
||||
For faster iteration while writing the test, you can run the Go test itself without Docker:
|
||||
|
||||
```bash
|
||||
go test -tags=goolm,stdjson,integration ./pkg/mcp -run TestIntegration_StreamableHTTPCompatibility -v
|
||||
go test -tags=stdjson,integration ./pkg/mcp -run TestIntegration_StreamableHTTPCompatibility -v
|
||||
```
|
||||
|
||||
You can also run the real-server smoke test directly if you provide the same environment variables that the Docker suite would inject:
|
||||
@@ -135,7 +135,7 @@ PICOCLAW_MCP_REAL_SERVER_JSON='{"enabled":true,"type":"http","url":"http://127.0
|
||||
PICOCLAW_MCP_REAL_TOOL_NAME=echo \
|
||||
PICOCLAW_MCP_REAL_TOOL_ARGS_JSON='{"message":"hello"}' \
|
||||
PICOCLAW_MCP_REAL_EXPECT_SUBSTRING=hello \
|
||||
go test -tags=goolm,stdjson,integration ./pkg/mcp -run TestIntegration_RealConfiguredServer -v
|
||||
go test -tags=stdjson,integration ./pkg/mcp -run TestIntegration_RealConfiguredServer -v
|
||||
```
|
||||
|
||||
Notes:
|
||||
@@ -235,7 +235,7 @@ Practical advice:
|
||||
At minimum:
|
||||
|
||||
```bash
|
||||
go test -tags=goolm,stdjson,integration ./path/to/package -run TestIntegration_Name -v
|
||||
go test -tags=stdjson,integration ./path/to/package -run TestIntegration_Name -v
|
||||
bash ./scripts/run-integration-tests.sh <suite-name>
|
||||
```
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ services:
|
||||
GOMODCACHE: /go-mod-cache
|
||||
GOTOOLCHAIN: local
|
||||
CGO_ENABLED: "0"
|
||||
GOFLAGS: -tags=goolm,stdjson,integration
|
||||
GOFLAGS: -tags=stdjson,integration
|
||||
|
||||
volumes:
|
||||
picoclaw-integration-gocache:
|
||||
|
||||
+10
-12
@@ -2006,7 +2006,7 @@ func TestAppendEventContextFields_IncludesInboundRouteAndScope(t *testing.T) {
|
||||
|
||||
appendEventContextFields(fields, &TurnContext{
|
||||
Inbound: &bus.InboundContext{
|
||||
Channel: "slack",
|
||||
Channel: "discord",
|
||||
Account: "workspace-a",
|
||||
ChatID: "C123",
|
||||
ChatType: "channel",
|
||||
@@ -2018,20 +2018,20 @@ func TestAppendEventContextFields_IncludesInboundRouteAndScope(t *testing.T) {
|
||||
},
|
||||
Route: &routing.ResolvedRoute{
|
||||
AgentID: "support",
|
||||
Channel: "slack",
|
||||
Channel: "discord",
|
||||
AccountID: "workspace-a",
|
||||
MatchedBy: "default",
|
||||
SessionPolicy: routing.SessionPolicy{
|
||||
Dimensions: []string{"chat", "sender"},
|
||||
IdentityLinks: map[string][]string{
|
||||
"canonical-user": {"slack:U123"},
|
||||
"canonical-user": {"discord:U123"},
|
||||
},
|
||||
},
|
||||
},
|
||||
Scope: &session.SessionScope{
|
||||
Version: session.ScopeVersionV1,
|
||||
AgentID: "support",
|
||||
Channel: "slack",
|
||||
Channel: "discord",
|
||||
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"] != "slack" {
|
||||
t.Fatalf("inbound_channel = %v, want slack", fields["inbound_channel"])
|
||||
if fields["inbound_channel"] != "discord" {
|
||||
t.Fatalf("inbound_channel = %v, want discord", 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: "slack",
|
||||
Channel: "discord",
|
||||
Account: "workspace-a",
|
||||
ChatID: "C123",
|
||||
ChatType: "channel",
|
||||
@@ -5536,7 +5536,6 @@ func TestTargetReasoningChannelID_AllChannels(t *testing.T) {
|
||||
"mqtt": "rid-mqtt",
|
||||
"qq": "rid-qq",
|
||||
"dingtalk": "rid-dingtalk",
|
||||
"slack": "rid-slack",
|
||||
"line": "rid-line",
|
||||
"onebot": "rid-onebot",
|
||||
"wecom": "rid-wecom",
|
||||
@@ -5555,7 +5554,6 @@ func TestTargetReasoningChannelID_AllChannels(t *testing.T) {
|
||||
{channel: "mqtt", wantID: "rid-mqtt"},
|
||||
{channel: "qq", wantID: "rid-qq"},
|
||||
{channel: "dingtalk", wantID: "rid-dingtalk"},
|
||||
{channel: "slack", wantID: "rid-slack"},
|
||||
{channel: "line", wantID: "rid-line"},
|
||||
{channel: "onebot", wantID: "rid-onebot"},
|
||||
{channel: "wecom", wantID: "rid-wecom"},
|
||||
@@ -5622,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", "slack", "channel-1")
|
||||
al.handleReasoning(context.Background(), "hello reasoning", "discord", "channel-1")
|
||||
|
||||
msg, ok := <-msgBus.OutboundChan()
|
||||
if !ok {
|
||||
t.Fatal("expected an outbound message")
|
||||
}
|
||||
if msg.Channel != "slack" || msg.ChatID != "channel-1" || msg.Content != "hello reasoning" {
|
||||
if msg.Channel != "discord" || msg.ChatID != "channel-1" || msg.Content != "hello reasoning" {
|
||||
t.Fatalf("unexpected outbound message: %+v", msg)
|
||||
}
|
||||
})
|
||||
@@ -5711,7 +5709,7 @@ func TestHandleReasoning(t *testing.T) {
|
||||
defer cancel()
|
||||
|
||||
start := time.Now()
|
||||
al.handleReasoning(ctx, "should timeout", "slack", "channel-full")
|
||||
al.handleReasoning(ctx, "should timeout", "discord", "channel-full")
|
||||
elapsed := time.Since(start)
|
||||
|
||||
// handleReasoning uses a 5s internal timeout, but the parent ctx
|
||||
|
||||
@@ -50,7 +50,7 @@ func TestNormalizeProcessOptions_PopulatesDispatchFromLegacyFields(t *testing.T)
|
||||
|
||||
func TestNormalizeProcessOptions_UsesDispatchAsSourceOfTruth(t *testing.T) {
|
||||
inbound := &bus.InboundContext{
|
||||
Channel: "slack",
|
||||
Channel: "discord",
|
||||
ChatID: "C123",
|
||||
ChatType: "channel",
|
||||
SenderID: "U123",
|
||||
@@ -59,7 +59,7 @@ func TestNormalizeProcessOptions_UsesDispatchAsSourceOfTruth(t *testing.T) {
|
||||
}
|
||||
route := &routing.ResolvedRoute{
|
||||
AgentID: "support",
|
||||
Channel: "slack",
|
||||
Channel: "discord",
|
||||
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: "slack",
|
||||
Channel: "discord",
|
||||
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:slack:channel:c123"},
|
||||
SessionAliases: []string{"agent:support:discord: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 != "slack" || opts.ChatID != "C123" {
|
||||
t.Fatalf("legacy mirrors = (%q,%q), want (slack,C123)", opts.Channel, opts.ChatID)
|
||||
if opts.Channel != "discord" || opts.ChatID != "C123" {
|
||||
t.Fatalf("legacy mirrors = (%q,%q), want (discord,C123)", opts.Channel, opts.ChatID)
|
||||
}
|
||||
if opts.SenderID != "U123" || opts.MessageID != "m-1" {
|
||||
t.Fatalf("legacy sender/message = (%q,%q)", opts.SenderID, opts.MessageID)
|
||||
|
||||
@@ -1267,12 +1267,12 @@ func TestAgentLoop_AgentForSession_UsesStoredScopeMetadata(t *testing.T) {
|
||||
t.Fatal("support session store does not support metadata")
|
||||
}
|
||||
|
||||
alias := "agent:support:slack:channel:c001"
|
||||
alias := "agent:support:discord:channel:c001"
|
||||
key := session.BuildOpaqueSessionKey(alias)
|
||||
scope := &session.SessionScope{
|
||||
Version: session.ScopeVersionV1,
|
||||
AgentID: "support",
|
||||
Channel: "slack",
|
||||
Channel: "discord",
|
||||
Account: "default",
|
||||
Dimensions: []string{"chat"},
|
||||
Values: map[string]string{
|
||||
|
||||
@@ -168,7 +168,7 @@ func TestAgentCheckSilencePublishesInboundAndCleansUp(t *testing.T) {
|
||||
chatID: "chat",
|
||||
speakerID: "speaker",
|
||||
sessionID: "sess",
|
||||
channel: "slack",
|
||||
channel: "discord",
|
||||
}
|
||||
|
||||
agent.mu.Lock()
|
||||
@@ -179,7 +179,7 @@ func TestAgentCheckSilencePublishesInboundAndCleansUp(t *testing.T) {
|
||||
|
||||
select {
|
||||
case msg := <-mb.InboundChan():
|
||||
if msg.Channel != "slack" {
|
||||
if msg.Channel != "discord" {
|
||||
t.Fatalf("unexpected inbound channel: %q", msg.Channel)
|
||||
}
|
||||
if !strings.Contains(msg.Content, "hello there") {
|
||||
|
||||
+8
-8
@@ -57,7 +57,7 @@ func TestPublishInbound_NormalizesContext(t *testing.T) {
|
||||
|
||||
msg := InboundMessage{
|
||||
Context: InboundContext{
|
||||
Channel: "slack",
|
||||
Channel: "discord",
|
||||
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 != "slack" {
|
||||
t.Fatalf("expected context channel slack, got %q", got.Context.Channel)
|
||||
if got.Context.Channel != "discord" {
|
||||
t.Fatalf("expected context channel discord, 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: "slack",
|
||||
Channel: "discord",
|
||||
ChatID: "C001",
|
||||
},
|
||||
AgentID: "support",
|
||||
@@ -402,7 +402,7 @@ func TestPublishOutboundMedia_MirrorsContextToLegacyFields(t *testing.T) {
|
||||
Scope: &OutboundScope{
|
||||
Version: 1,
|
||||
AgentID: "support",
|
||||
Channel: "slack",
|
||||
Channel: "discord",
|
||||
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 != "slack" {
|
||||
t.Fatalf("expected legacy channel slack, got %q", got.Channel)
|
||||
if got.Channel != "discord" {
|
||||
t.Fatalf("expected legacy channel discord, 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 != "slack" || got.Context.ChatID != "C001" {
|
||||
if got.Context.Channel != "discord" || got.Context.ChatID != "C001" {
|
||||
t.Fatalf("unexpected outbound media context: %+v", got.Context)
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@ package bus
|
||||
|
||||
// SenderInfo provides structured sender identity information.
|
||||
type SenderInfo struct {
|
||||
Platform string `json:"platform,omitempty"` // "telegram", "discord", "slack", ...
|
||||
Platform string `json:"platform,omitempty"` // "telegram", "discord", ...
|
||||
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)
|
||||
|
||||
+69
-73
@@ -25,7 +25,6 @@
|
||||
pkg/channels/
|
||||
├── telegram.go # Each channel directly in the channels package
|
||||
├── discord.go
|
||||
├── slack.go
|
||||
├── manager.go # Manager directly references each channel type
|
||||
├── ...
|
||||
```
|
||||
@@ -60,7 +59,7 @@ pkg/channels/
|
||||
├── discord/
|
||||
│ ├── init.go
|
||||
│ └── discord.go
|
||||
├── slack/ line/ onebot/ dingtalk/ feishu/ wecom/ qq/ whatsapp/ whatsapp_native/ mqtt/
|
||||
├── line/ onebot/ dingtalk/ feishu/ wecom/ qq/ whatsapp/ whatsapp_native/ mqtt/
|
||||
│ └── ...
|
||||
|
||||
pkg/bus/
|
||||
@@ -80,7 +79,7 @@ pkg/identity/
|
||||
┌────────────┐ InboundMessage ┌───────────┐ LLM + Tools ┌────────────┐
|
||||
│ Telegram │──┐ │ │ │ │
|
||||
│ Discord │──┤ PublishInbound() │ │ PublishOutbound() │ │
|
||||
│ Slack │──┼──────────────────────▶ │ MessageBus │ ◀─────────────────── │ AgentLoop │
|
||||
│ Feishu │──┼──────────────────────▶ │ MessageBus │ ◀─────────────────── │ AgentLoop │
|
||||
│ LINE │──┤ (buffered chan, 64) │ │ (buffered chan, 64) │ │
|
||||
│ ... │──┘ │ │ │ │
|
||||
└────────────┘ └─────┬─────┘ └────────────┘
|
||||
@@ -409,21 +408,21 @@ Main changes to the Agent Loop:
|
||||
|
||||
### 3.1 Minimum Implementation Checklist
|
||||
|
||||
To add a new chat platform (e.g., `matrix`), you need to:
|
||||
To add a new chat platform (e.g., `examplechat`), you need to:
|
||||
|
||||
1. ✅ Create sub-package directory `pkg/channels/matrix/`
|
||||
1. ✅ Create sub-package directory `pkg/channels/examplechat/`
|
||||
2. ✅ Create `init.go` — factory registration
|
||||
3. ✅ Create `matrix.go` — channel implementation
|
||||
3. ✅ Create `examplechat.go` — channel implementation
|
||||
4. ✅ Add blank import in Gateway helpers
|
||||
5. ✅ Add config check in Manager.initChannels()
|
||||
6. ✅ Add config struct in `pkg/config/`
|
||||
|
||||
### 3.2 Complete Template
|
||||
|
||||
#### `pkg/channels/matrix/init.go`
|
||||
#### `pkg/channels/examplechat/init.go`
|
||||
|
||||
```go
|
||||
package matrix
|
||||
package examplechat
|
||||
|
||||
import (
|
||||
"github.com/sipeed/picoclaw/pkg/bus"
|
||||
@@ -432,21 +431,21 @@ import (
|
||||
)
|
||||
|
||||
func init() {
|
||||
channels.RegisterFactory(config.ChannelMatrix, func(channelName, channelType string, cfg *config.Config, b *bus.MessageBus) (channels.Channel, error) {
|
||||
channels.RegisterFactory(config.ChannelExampleChat, 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.MatrixSettings)
|
||||
c, ok := decoded.(*config.ExampleChatSettings)
|
||||
if !ok { return nil, channels.ErrSendFailed }
|
||||
return NewMatrixChannel(bc, c, b)
|
||||
return NewExampleChatChannel(bc, c, b)
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
#### `pkg/channels/matrix/matrix.go`
|
||||
#### `pkg/channels/examplechat/examplechat.go`
|
||||
|
||||
```go
|
||||
package matrix
|
||||
package examplechat
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -459,29 +458,29 @@ import (
|
||||
"github.com/sipeed/picoclaw/pkg/logger"
|
||||
)
|
||||
|
||||
// MatrixChannel implements channels.Channel for the Matrix protocol.
|
||||
type MatrixChannel struct {
|
||||
// ExampleChatChannel implements channels.Channel for the ExampleChat protocol.
|
||||
type ExampleChatChannel struct {
|
||||
*channels.BaseChannel // Must embed
|
||||
config *config.Config
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
// ... Matrix SDK client, etc.
|
||||
// ... ExampleChat SDK client, etc.
|
||||
}
|
||||
|
||||
func NewMatrixChannel(cfg *config.Config, msgBus *bus.MessageBus) (*MatrixChannel, error) {
|
||||
matrixCfg := cfg.Channels.Matrix // Assumes this field exists in config
|
||||
func NewExampleChatChannel(cfg *config.Config, msgBus *bus.MessageBus) (*ExampleChatChannel, error) {
|
||||
examplechatCfg := cfg.Channels.ExampleChat // Assumes this field exists in config
|
||||
|
||||
base := channels.NewBaseChannel(
|
||||
"matrix", // Channel name (globally unique)
|
||||
matrixCfg, // Raw config
|
||||
"examplechat", // Channel name (globally unique)
|
||||
examplechatCfg, // Raw config
|
||||
msgBus, // Message bus
|
||||
matrixCfg.AllowFrom, // Allow list
|
||||
channels.WithMaxMessageLength(65536), // Matrix message length limit
|
||||
channels.WithGroupTrigger(matrixCfg.GroupTrigger),
|
||||
channels.WithReasoningChannelID(matrixCfg.ReasoningChannelID), // Reasoning chain routing (optional)
|
||||
examplechatCfg.AllowFrom, // Allow list
|
||||
channels.WithMaxMessageLength(65536), // ExampleChat message length limit
|
||||
channels.WithGroupTrigger(examplechatCfg.GroupTrigger),
|
||||
channels.WithReasoningChannelID(examplechatCfg.ReasoningChannelID), // Reasoning chain routing (optional)
|
||||
)
|
||||
|
||||
return &MatrixChannel{
|
||||
return &ExampleChatChannel{
|
||||
BaseChannel: base,
|
||||
config: cfg,
|
||||
}, nil
|
||||
@@ -489,37 +488,37 @@ func NewMatrixChannel(cfg *config.Config, msgBus *bus.MessageBus) (*MatrixChanne
|
||||
|
||||
// ========== Required Channel Interface Methods ==========
|
||||
|
||||
func (c *MatrixChannel) Start(ctx context.Context) error {
|
||||
func (c *ExampleChatChannel) Start(ctx context.Context) error {
|
||||
c.ctx, c.cancel = context.WithCancel(ctx)
|
||||
|
||||
// 1. Initialize Matrix client
|
||||
// 1. Initialize ExampleChat client
|
||||
// 2. Start listening for messages
|
||||
// 3. Mark as running
|
||||
c.SetRunning(true)
|
||||
|
||||
logger.InfoC("matrix", "Matrix channel started")
|
||||
logger.InfoC("examplechat", "ExampleChat channel started")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *MatrixChannel) Stop(ctx context.Context) error {
|
||||
func (c *ExampleChatChannel) Stop(ctx context.Context) error {
|
||||
c.SetRunning(false)
|
||||
|
||||
if c.cancel != nil {
|
||||
c.cancel()
|
||||
}
|
||||
|
||||
logger.InfoC("matrix", "Matrix channel stopped")
|
||||
logger.InfoC("examplechat", "ExampleChat channel stopped")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *MatrixChannel) Send(ctx context.Context, msg bus.OutboundMessage) ([]string, error) {
|
||||
func (c *ExampleChatChannel) Send(ctx context.Context, msg bus.OutboundMessage) ([]string, error) {
|
||||
// 1. Check running state
|
||||
if !c.IsRunning() {
|
||||
return nil, channels.ErrNotRunning
|
||||
}
|
||||
|
||||
// 2. Send message to Matrix
|
||||
eventID, err := c.sendToMatrix(ctx, msg.ChatID, msg.Content)
|
||||
// 2. Send message to ExampleChat
|
||||
eventID, err := c.sendToExampleChat(ctx, msg.ChatID, msg.Content)
|
||||
if err != nil {
|
||||
// 3. Must use error classification wrapping
|
||||
// If you have an HTTP status code:
|
||||
@@ -535,12 +534,12 @@ func (c *MatrixChannel) Send(ctx context.Context, msg bus.OutboundMessage) ([]st
|
||||
|
||||
// ========== Incoming Message Handling ==========
|
||||
|
||||
func (c *MatrixChannel) handleIncoming(roomID, senderID, displayName, content string, msgID string) {
|
||||
func (c *ExampleChatChannel) handleIncoming(roomID, senderID, displayName, content string, msgID string) {
|
||||
// 1. Construct structured sender identity
|
||||
sender := bus.SenderInfo{
|
||||
Platform: "matrix",
|
||||
Platform: "examplechat",
|
||||
PlatformID: senderID,
|
||||
CanonicalID: identity.BuildCanonicalID("matrix", senderID),
|
||||
CanonicalID: identity.BuildCanonicalID("examplechat", senderID),
|
||||
Username: senderID,
|
||||
DisplayName: displayName,
|
||||
}
|
||||
@@ -590,8 +589,8 @@ func (c *MatrixChannel) handleIncoming(roomID, senderID, displayName, content st
|
||||
|
||||
// ========== Internal Methods ==========
|
||||
|
||||
func (c *MatrixChannel) sendToMatrix(ctx context.Context, roomID, content string) (string, error) {
|
||||
// Actual Matrix SDK call
|
||||
func (c *ExampleChatChannel) sendToExampleChat(ctx context.Context, roomID, content string) (string, error) {
|
||||
// Actual ExampleChat SDK call
|
||||
return "event-id", nil
|
||||
}
|
||||
```
|
||||
@@ -604,7 +603,7 @@ Depending on platform capabilities, your channel can optionally implement the fo
|
||||
|
||||
```go
|
||||
// If the platform supports sending images/files/audio/video
|
||||
func (c *MatrixChannel) SendMedia(ctx context.Context, msg bus.OutboundMediaMessage) ([]string, error) {
|
||||
func (c *ExampleChatChannel) SendMedia(ctx context.Context, msg bus.OutboundMediaMessage) ([]string, error) {
|
||||
if !c.IsRunning() {
|
||||
return nil, channels.ErrNotRunning
|
||||
}
|
||||
@@ -618,7 +617,7 @@ func (c *MatrixChannel) SendMedia(ctx context.Context, msg bus.OutboundMediaMess
|
||||
for _, part := range msg.Parts {
|
||||
localPath, err := store.Resolve(part.Ref)
|
||||
if err != nil {
|
||||
logger.ErrorCF("matrix", "Failed to resolve media", map[string]any{
|
||||
logger.ErrorCF("examplechat", "Failed to resolve media", map[string]any{
|
||||
"ref": part.Ref, "error": err.Error(),
|
||||
})
|
||||
continue
|
||||
@@ -627,9 +626,9 @@ func (c *MatrixChannel) SendMedia(ctx context.Context, msg bus.OutboundMediaMess
|
||||
// Call the appropriate API based on part.Type ("image"|"audio"|"video"|"file")
|
||||
switch part.Type {
|
||||
case "image":
|
||||
// Upload image to Matrix
|
||||
// Upload image to ExampleChat
|
||||
default:
|
||||
// Upload file to Matrix
|
||||
// Upload file to ExampleChat
|
||||
}
|
||||
// Append platform IDs here when the API returns them.
|
||||
// messageIDs = append(messageIDs, uploadedMessageID)
|
||||
@@ -642,14 +641,14 @@ func (c *MatrixChannel) SendMedia(ctx context.Context, msg bus.OutboundMediaMess
|
||||
|
||||
```go
|
||||
// If the platform supports "typing..." indicators
|
||||
func (c *MatrixChannel) StartTyping(ctx context.Context, chatID string) (stop func(), err error) {
|
||||
// Call Matrix API to send typing indicator
|
||||
func (c *ExampleChatChannel) StartTyping(ctx context.Context, chatID string) (stop func(), err error) {
|
||||
// Call ExampleChat API to send typing indicator
|
||||
// The returned stop function must be idempotent
|
||||
stopped := false
|
||||
return func() {
|
||||
if !stopped {
|
||||
stopped = true
|
||||
// Call Matrix API to stop typing
|
||||
// Call ExampleChat API to stop typing
|
||||
}
|
||||
}, nil
|
||||
}
|
||||
@@ -658,9 +657,9 @@ func (c *MatrixChannel) StartTyping(ctx context.Context, chatID string) (stop fu
|
||||
#### ReactionCapable — Message Reaction Indicator
|
||||
|
||||
```go
|
||||
// If the platform supports adding emoji reactions to inbound messages (e.g., Slack's 👀, OneBot's emoji 289)
|
||||
func (c *MatrixChannel) ReactToMessage(ctx context.Context, chatID, messageID string) (undo func(), err error) {
|
||||
// Call Matrix API to add reaction to message
|
||||
// If the platform supports adding emoji reactions to inbound messages (e.g., OneBot's emoji 289)
|
||||
func (c *ExampleChatChannel) ReactToMessage(ctx context.Context, chatID, messageID string) (undo func(), err error) {
|
||||
// Call ExampleChat API to add reaction to message
|
||||
// The returned undo function removes the reaction, must be idempotent
|
||||
err = c.addReaction(chatID, messageID, "eyes")
|
||||
if err != nil {
|
||||
@@ -676,8 +675,8 @@ func (c *MatrixChannel) ReactToMessage(ctx context.Context, chatID, messageID st
|
||||
|
||||
```go
|
||||
// If the platform supports editing sent messages (used for Placeholder replacement)
|
||||
func (c *MatrixChannel) EditMessage(ctx context.Context, chatID, messageID, content string) error {
|
||||
// Call Matrix API to edit message
|
||||
func (c *ExampleChatChannel) EditMessage(ctx context.Context, chatID, messageID, content string) error {
|
||||
// Call ExampleChat API to edit message
|
||||
return nil
|
||||
}
|
||||
```
|
||||
@@ -690,8 +689,8 @@ func (c *MatrixChannel) EditMessage(ctx context.Context, chatID, messageID, cont
|
||||
// automatically edit the placeholder into the final response on outbound.
|
||||
// SendPlaceholder checks PlaceholderConfig.Enabled internally;
|
||||
// returning ("", nil) means skip.
|
||||
func (c *MatrixChannel) SendPlaceholder(ctx context.Context, chatID string) (string, error) {
|
||||
cfg := c.config.Channels.Matrix.Placeholder
|
||||
func (c *ExampleChatChannel) SendPlaceholder(ctx context.Context, chatID string) (string, error) {
|
||||
cfg := c.config.Channels.ExampleChat.Placeholder
|
||||
if !cfg.Enabled {
|
||||
return "", nil
|
||||
}
|
||||
@@ -699,7 +698,7 @@ func (c *MatrixChannel) SendPlaceholder(ctx context.Context, chatID string) (str
|
||||
if text == "" {
|
||||
text = "Thinking... 💭"
|
||||
}
|
||||
// Call Matrix API to send placeholder message
|
||||
// Call ExampleChat API to send placeholder message
|
||||
msg, err := c.sendText(ctx, chatID, text)
|
||||
if err != nil {
|
||||
return "", err
|
||||
@@ -712,11 +711,11 @@ func (c *MatrixChannel) SendPlaceholder(ctx context.Context, chatID string) (str
|
||||
|
||||
```go
|
||||
// If the channel receives messages via webhook (rather than long-polling/WebSocket)
|
||||
func (c *MatrixChannel) WebhookPath() string {
|
||||
return "/webhook/matrix" // Path will be registered on the shared HTTP server
|
||||
func (c *ExampleChatChannel) WebhookPath() string {
|
||||
return "/webhook/examplechat" // Path will be registered on the shared HTTP server
|
||||
}
|
||||
|
||||
func (c *MatrixChannel) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
func (c *ExampleChatChannel) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
// Handle webhook request
|
||||
}
|
||||
```
|
||||
@@ -724,11 +723,11 @@ func (c *MatrixChannel) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
#### HealthChecker — Health Check Endpoint
|
||||
|
||||
```go
|
||||
func (c *MatrixChannel) HealthPath() string {
|
||||
return "/health/matrix"
|
||||
func (c *ExampleChatChannel) HealthPath() string {
|
||||
return "/health/examplechat"
|
||||
}
|
||||
|
||||
func (c *MatrixChannel) HealthHandler(w http.ResponseWriter, r *http.Request) {
|
||||
func (c *ExampleChatChannel) HealthHandler(w http.ResponseWriter, r *http.Request) {
|
||||
if c.IsRunning() {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte("OK"))
|
||||
@@ -768,7 +767,7 @@ 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 `ReactionCapable` (Slack, OneBot) do not need to manually call `AddReaction` + `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 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)
|
||||
@@ -792,12 +791,12 @@ the top level, with channel-specific settings in the `settings` sub-key:
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"matrix": {
|
||||
"examplechat": {
|
||||
"enabled": true,
|
||||
"type": "matrix",
|
||||
"type": "examplechat",
|
||||
"allow_from": ["@user:example.com"],
|
||||
"settings": {
|
||||
"home_server": "https://matrix.org",
|
||||
"home_server": "https://examplechat.org",
|
||||
"user_id": "@bot:example.com",
|
||||
"access_token": "enc://..."
|
||||
}
|
||||
@@ -810,8 +809,8 @@ Secure fields (tokens, passwords, API keys) go into `.security.yml`:
|
||||
|
||||
```yaml
|
||||
channels:
|
||||
matrix:
|
||||
access_token: "your-matrix-access-token"
|
||||
examplechat:
|
||||
access_token: "your-examplechat-access-token"
|
||||
```
|
||||
|
||||
Channel types must be registered in `channelSettingsFactory` in
|
||||
@@ -820,7 +819,7 @@ Channel types must be registered in `channelSettingsFactory` in
|
||||
```go
|
||||
var channelSettingsFactory = map[string]any{
|
||||
// ... existing channels
|
||||
ChannelMatrix: (MatrixSettings{}),
|
||||
ChannelExampleChat: (ExampleChatSettings{}),
|
||||
}
|
||||
```
|
||||
|
||||
@@ -843,7 +842,7 @@ just register the factory and the config entry.
|
||||
```go
|
||||
// cmd/picoclaw/internal/gateway/helpers.go
|
||||
import (
|
||||
_ "github.com/sipeed/picoclaw/pkg/channels/matrix"
|
||||
_ "github.com/sipeed/picoclaw/pkg/channels/examplechat"
|
||||
)
|
||||
```
|
||||
|
||||
@@ -1072,7 +1071,6 @@ type channelWorker struct {
|
||||
var channelRateConfig = map[string]float64{
|
||||
"telegram": 20, // 20 msg/s
|
||||
"discord": 1, // 1 msg/s
|
||||
"slack": 1, // 1 msg/s
|
||||
"line": 10, // 10 msg/s
|
||||
}
|
||||
// Default: 10 msg/s
|
||||
@@ -1267,7 +1265,7 @@ Existing test files:
|
||||
|
||||
To add tests for a new channel:
|
||||
```bash
|
||||
go test ./pkg/channels/matrix/ -v # Sub-package tests
|
||||
go test ./pkg/channels/examplechat/ -v # Sub-package tests
|
||||
go test ./pkg/channels/ -run TestSpecific -v # Framework tests
|
||||
make test # Full test suite
|
||||
```
|
||||
@@ -1300,7 +1298,6 @@ make test # Full test suite
|
||||
|-------------|----------------|-------------------|
|
||||
| `pkg/channels/telegram/` | `"telegram"` | TypingCapable, PlaceholderCapable, MessageEditor, MediaSender |
|
||||
| `pkg/channels/discord/` | `"discord"` | TypingCapable, PlaceholderCapable, MessageEditor, MediaSender |
|
||||
| `pkg/channels/slack/` | `"slack"` | ReactionCapable, MediaSender |
|
||||
| `pkg/channels/line/` | `"line"` | TypingCapable, MediaSender, WebhookHandler |
|
||||
| `pkg/channels/onebot/` | `"onebot"` | ReactionCapable, MediaSender |
|
||||
| `pkg/channels/dingtalk/` | `"dingtalk"` | — |
|
||||
@@ -1409,7 +1406,6 @@ agentLoop.Stop() // Stop Agent
|
||||
|---------|-------------|-------|
|
||||
| telegram | 20 | 10 |
|
||||
| discord | 1 | 1 |
|
||||
| slack | 1 | 1 |
|
||||
| line | 10 | 5 |
|
||||
| _others_ | 10 (default) | 5 |
|
||||
|
||||
@@ -1425,6 +1421,6 @@ agentLoop.Stop() // Stop Agent
|
||||
|
||||
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 5 channel configs (Telegram, Discord, Slack, 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 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.
|
||||
|
||||
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, Slack, 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 (WhatsApp, Telegram, Feishu, Discord, QQ, DingTalk, LINE, OneBot, WeCom). `BaseChannel` exposes this via the `WithReasoningChannelID` option and `ReasoningChannelID()` method.
|
||||
+69
-73
@@ -25,7 +25,6 @@
|
||||
pkg/channels/
|
||||
├── telegram.go # 每个 channel 直接放在 channels 包内
|
||||
├── discord.go
|
||||
├── slack.go
|
||||
├── manager.go # Manager 直接引用各 channel 类型
|
||||
├── ...
|
||||
```
|
||||
@@ -60,7 +59,7 @@ pkg/channels/
|
||||
├── discord/
|
||||
│ ├── init.go
|
||||
│ └── discord.go
|
||||
├── slack/ line/ onebot/ dingtalk/ feishu/ wecom/ qq/ whatsapp/ whatsapp_native/ mqtt/
|
||||
├── line/ onebot/ dingtalk/ feishu/ wecom/ qq/ whatsapp/ whatsapp_native/ mqtt/
|
||||
│ └── ...
|
||||
|
||||
pkg/bus/
|
||||
@@ -80,7 +79,7 @@ pkg/identity/
|
||||
┌────────────┐ InboundMessage ┌───────────┐ LLM + Tools ┌────────────┐
|
||||
│ Telegram │──┐ │ │ │ │
|
||||
│ Discord │──┤ PublishInbound() │ │ PublishOutbound() │ │
|
||||
│ Slack │──┼──────────────────────▶ │ MessageBus │ ◀─────────────────── │ AgentLoop │
|
||||
│ Feishu │──┼──────────────────────▶ │ MessageBus │ ◀─────────────────── │ AgentLoop │
|
||||
│ LINE │──┤ (buffered chan, 64) │ │ (buffered chan, 64) │ │
|
||||
│ ... │──┘ │ │ │ │
|
||||
└────────────┘ └─────┬─────┘ └────────────┘
|
||||
@@ -409,21 +408,21 @@ Agent Loop 的主要变化:
|
||||
|
||||
### 3.1 最小实现清单
|
||||
|
||||
要添加一个新的聊天平台(例如 `matrix`),你需要:
|
||||
要添加一个新的聊天平台(例如 `examplechat`),你需要:
|
||||
|
||||
1. ✅ 创建子包目录 `pkg/channels/matrix/`
|
||||
1. ✅ 创建子包目录 `pkg/channels/examplechat/`
|
||||
2. ✅ 创建 `init.go` — 工厂注册
|
||||
3. ✅ 创建 `matrix.go` — Channel 实现
|
||||
3. ✅ 创建 `examplechat.go` — Channel 实现
|
||||
4. ✅ 在 Gateway helpers 中添加 blank import
|
||||
5. ✅ 在 Manager.initChannels() 中添加配置检查
|
||||
6. ✅ 在 `pkg/config/` 中添加配置结构体
|
||||
|
||||
### 3.2 完整模板
|
||||
|
||||
#### `pkg/channels/matrix/init.go`
|
||||
#### `pkg/channels/examplechat/init.go`
|
||||
|
||||
```go
|
||||
package matrix
|
||||
package examplechat
|
||||
|
||||
import (
|
||||
"github.com/sipeed/picoclaw/pkg/bus"
|
||||
@@ -432,21 +431,21 @@ import (
|
||||
)
|
||||
|
||||
func init() {
|
||||
channels.RegisterFactory(config.ChannelMatrix, func(channelName, channelType string, cfg *config.Config, b *bus.MessageBus) (channels.Channel, error) {
|
||||
channels.RegisterFactory(config.ChannelExampleChat, 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.MatrixSettings)
|
||||
c, ok := decoded.(*config.ExampleChatSettings)
|
||||
if !ok { return nil, channels.ErrSendFailed }
|
||||
return NewMatrixChannel(bc, c, b)
|
||||
return NewExampleChatChannel(bc, c, b)
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
#### `pkg/channels/matrix/matrix.go`
|
||||
#### `pkg/channels/examplechat/examplechat.go`
|
||||
|
||||
```go
|
||||
package matrix
|
||||
package examplechat
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -459,29 +458,29 @@ import (
|
||||
"github.com/sipeed/picoclaw/pkg/logger"
|
||||
)
|
||||
|
||||
// MatrixChannel implements channels.Channel for the Matrix protocol.
|
||||
type MatrixChannel struct {
|
||||
// ExampleChatChannel implements channels.Channel for the ExampleChat protocol.
|
||||
type ExampleChatChannel struct {
|
||||
*channels.BaseChannel // 必须嵌入
|
||||
config *config.Config
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
// ... Matrix SDK 客户端等
|
||||
// ... ExampleChat SDK 客户端等
|
||||
}
|
||||
|
||||
func NewMatrixChannel(cfg *config.Config, msgBus *bus.MessageBus) (*MatrixChannel, error) {
|
||||
matrixCfg := cfg.Channels.Matrix // 假设配置中有此字段
|
||||
func NewExampleChatChannel(cfg *config.Config, msgBus *bus.MessageBus) (*ExampleChatChannel, error) {
|
||||
examplechatCfg := cfg.Channels.ExampleChat // 假设配置中有此字段
|
||||
|
||||
base := channels.NewBaseChannel(
|
||||
"matrix", // channel 名称(全局唯一)
|
||||
matrixCfg, // 原始配置
|
||||
"examplechat", // channel 名称(全局唯一)
|
||||
examplechatCfg, // 原始配置
|
||||
msgBus, // 消息总线
|
||||
matrixCfg.AllowFrom, // 允许列表
|
||||
channels.WithMaxMessageLength(65536), // Matrix 消息长度限制
|
||||
channels.WithGroupTrigger(matrixCfg.GroupTrigger),
|
||||
channels.WithReasoningChannelID(matrixCfg.ReasoningChannelID), // 思维链路由(可选)
|
||||
examplechatCfg.AllowFrom, // 允许列表
|
||||
channels.WithMaxMessageLength(65536), // ExampleChat 消息长度限制
|
||||
channels.WithGroupTrigger(examplechatCfg.GroupTrigger),
|
||||
channels.WithReasoningChannelID(examplechatCfg.ReasoningChannelID), // 思维链路由(可选)
|
||||
)
|
||||
|
||||
return &MatrixChannel{
|
||||
return &ExampleChatChannel{
|
||||
BaseChannel: base,
|
||||
config: cfg,
|
||||
}, nil
|
||||
@@ -489,37 +488,37 @@ func NewMatrixChannel(cfg *config.Config, msgBus *bus.MessageBus) (*MatrixChanne
|
||||
|
||||
// ========== 必须实现的 Channel 接口方法 ==========
|
||||
|
||||
func (c *MatrixChannel) Start(ctx context.Context) error {
|
||||
func (c *ExampleChatChannel) Start(ctx context.Context) error {
|
||||
c.ctx, c.cancel = context.WithCancel(ctx)
|
||||
|
||||
// 1. 初始化 Matrix 客户端
|
||||
// 1. 初始化 ExampleChat 客户端
|
||||
// 2. 开始监听消息
|
||||
// 3. 标记为运行中
|
||||
c.SetRunning(true)
|
||||
|
||||
logger.InfoC("matrix", "Matrix channel started")
|
||||
logger.InfoC("examplechat", "ExampleChat channel started")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *MatrixChannel) Stop(ctx context.Context) error {
|
||||
func (c *ExampleChatChannel) Stop(ctx context.Context) error {
|
||||
c.SetRunning(false)
|
||||
|
||||
if c.cancel != nil {
|
||||
c.cancel()
|
||||
}
|
||||
|
||||
logger.InfoC("matrix", "Matrix channel stopped")
|
||||
logger.InfoC("examplechat", "ExampleChat channel stopped")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *MatrixChannel) Send(ctx context.Context, msg bus.OutboundMessage) ([]string, error) {
|
||||
func (c *ExampleChatChannel) Send(ctx context.Context, msg bus.OutboundMessage) ([]string, error) {
|
||||
// 1. 检查运行状态
|
||||
if !c.IsRunning() {
|
||||
return nil, channels.ErrNotRunning
|
||||
}
|
||||
|
||||
// 2. 发送消息到 Matrix
|
||||
eventID, err := c.sendToMatrix(ctx, msg.ChatID, msg.Content)
|
||||
// 2. 发送消息到 ExampleChat
|
||||
eventID, err := c.sendToExampleChat(ctx, msg.ChatID, msg.Content)
|
||||
if err != nil {
|
||||
// 3. 必须使用错误分类包装
|
||||
// 如果你有 HTTP 状态码:
|
||||
@@ -535,12 +534,12 @@ func (c *MatrixChannel) Send(ctx context.Context, msg bus.OutboundMessage) ([]st
|
||||
|
||||
// ========== 消息接收处理 ==========
|
||||
|
||||
func (c *MatrixChannel) handleIncoming(roomID, senderID, displayName, content string, msgID string) {
|
||||
func (c *ExampleChatChannel) handleIncoming(roomID, senderID, displayName, content string, msgID string) {
|
||||
// 1. 构造结构化发送者身份
|
||||
sender := bus.SenderInfo{
|
||||
Platform: "matrix",
|
||||
Platform: "examplechat",
|
||||
PlatformID: senderID,
|
||||
CanonicalID: identity.BuildCanonicalID("matrix", senderID),
|
||||
CanonicalID: identity.BuildCanonicalID("examplechat", senderID),
|
||||
Username: senderID,
|
||||
DisplayName: displayName,
|
||||
}
|
||||
@@ -590,8 +589,8 @@ func (c *MatrixChannel) handleIncoming(roomID, senderID, displayName, content st
|
||||
|
||||
// ========== 内部方法 ==========
|
||||
|
||||
func (c *MatrixChannel) sendToMatrix(ctx context.Context, roomID, content string) (string, error) {
|
||||
// 实际的 Matrix SDK 调用
|
||||
func (c *ExampleChatChannel) sendToExampleChat(ctx context.Context, roomID, content string) (string, error) {
|
||||
// 实际的 ExampleChat SDK 调用
|
||||
return "event-id", nil
|
||||
}
|
||||
```
|
||||
@@ -604,7 +603,7 @@ func (c *MatrixChannel) sendToMatrix(ctx context.Context, roomID, content string
|
||||
|
||||
```go
|
||||
// 如果平台支持发送图片/文件/音频/视频
|
||||
func (c *MatrixChannel) SendMedia(ctx context.Context, msg bus.OutboundMediaMessage) ([]string, error) {
|
||||
func (c *ExampleChatChannel) SendMedia(ctx context.Context, msg bus.OutboundMediaMessage) ([]string, error) {
|
||||
if !c.IsRunning() {
|
||||
return nil, channels.ErrNotRunning
|
||||
}
|
||||
@@ -618,7 +617,7 @@ func (c *MatrixChannel) SendMedia(ctx context.Context, msg bus.OutboundMediaMess
|
||||
for _, part := range msg.Parts {
|
||||
localPath, err := store.Resolve(part.Ref)
|
||||
if err != nil {
|
||||
logger.ErrorCF("matrix", "Failed to resolve media", map[string]any{
|
||||
logger.ErrorCF("examplechat", "Failed to resolve media", map[string]any{
|
||||
"ref": part.Ref, "error": err.Error(),
|
||||
})
|
||||
continue
|
||||
@@ -627,9 +626,9 @@ func (c *MatrixChannel) SendMedia(ctx context.Context, msg bus.OutboundMediaMess
|
||||
// 根据 part.Type ("image"|"audio"|"video"|"file") 调用对应 API
|
||||
switch part.Type {
|
||||
case "image":
|
||||
// 上传图片到 Matrix
|
||||
// 上传图片到 ExampleChat
|
||||
default:
|
||||
// 上传文件到 Matrix
|
||||
// 上传文件到 ExampleChat
|
||||
}
|
||||
// 如果 API 能返回平台消息 ID,就在这里追加。
|
||||
// messageIDs = append(messageIDs, uploadedMessageID)
|
||||
@@ -642,14 +641,14 @@ func (c *MatrixChannel) SendMedia(ctx context.Context, msg bus.OutboundMediaMess
|
||||
|
||||
```go
|
||||
// 如果平台支持 "正在输入..." 提示
|
||||
func (c *MatrixChannel) StartTyping(ctx context.Context, chatID string) (stop func(), err error) {
|
||||
// 调用 Matrix API 发送 typing 指示器
|
||||
func (c *ExampleChatChannel) StartTyping(ctx context.Context, chatID string) (stop func(), err error) {
|
||||
// 调用 ExampleChat API 发送 typing 指示器
|
||||
// 返回的 stop 函数必须是幂等的
|
||||
stopped := false
|
||||
return func() {
|
||||
if !stopped {
|
||||
stopped = true
|
||||
// 调用 Matrix API 停止 typing
|
||||
// 调用 ExampleChat API 停止 typing
|
||||
}
|
||||
}, nil
|
||||
}
|
||||
@@ -658,9 +657,9 @@ func (c *MatrixChannel) StartTyping(ctx context.Context, chatID string) (stop fu
|
||||
#### ReactionCapable — 消息反应指示器
|
||||
|
||||
```go
|
||||
// 如果平台支持对入站消息添加 emoji 反应(如 Slack 的 👀、OneBot 的表情 289)
|
||||
func (c *MatrixChannel) ReactToMessage(ctx context.Context, chatID, messageID string) (undo func(), err error) {
|
||||
// 调用 Matrix API 添加反应到消息
|
||||
// 如果平台支持对入站消息添加 emoji 反应(如 OneBot 的表情 289)
|
||||
func (c *ExampleChatChannel) ReactToMessage(ctx context.Context, chatID, messageID string) (undo func(), err error) {
|
||||
// 调用 ExampleChat API 添加反应到消息
|
||||
// 返回的 undo 函数移除反应,必须是幂等的
|
||||
err = c.addReaction(chatID, messageID, "eyes")
|
||||
if err != nil {
|
||||
@@ -676,8 +675,8 @@ func (c *MatrixChannel) ReactToMessage(ctx context.Context, chatID, messageID st
|
||||
|
||||
```go
|
||||
// 如果平台支持编辑已发送的消息(用于 Placeholder 替换)
|
||||
func (c *MatrixChannel) EditMessage(ctx context.Context, chatID, messageID, content string) error {
|
||||
// 调用 Matrix API 编辑消息
|
||||
func (c *ExampleChatChannel) EditMessage(ctx context.Context, chatID, messageID, content string) error {
|
||||
// 调用 ExampleChat API 编辑消息
|
||||
return nil
|
||||
}
|
||||
```
|
||||
@@ -689,8 +688,8 @@ func (c *MatrixChannel) EditMessage(ctx context.Context, chatID, messageID, cont
|
||||
// 则 Manager 的 preSend 会在出站时自动将占位消息编辑为最终回复。
|
||||
// SendPlaceholder 内部根据 PlaceholderConfig.Enabled 决定是否发送;
|
||||
// 返回 ("", nil) 表示跳过。
|
||||
func (c *MatrixChannel) SendPlaceholder(ctx context.Context, chatID string) (string, error) {
|
||||
cfg := c.config.Channels.Matrix.Placeholder
|
||||
func (c *ExampleChatChannel) SendPlaceholder(ctx context.Context, chatID string) (string, error) {
|
||||
cfg := c.config.Channels.ExampleChat.Placeholder
|
||||
if !cfg.Enabled {
|
||||
return "", nil
|
||||
}
|
||||
@@ -698,7 +697,7 @@ func (c *MatrixChannel) SendPlaceholder(ctx context.Context, chatID string) (str
|
||||
if text == "" {
|
||||
text = "Thinking... 💭"
|
||||
}
|
||||
// 调用 Matrix API 发送占位消息
|
||||
// 调用 ExampleChat API 发送占位消息
|
||||
msg, err := c.sendText(ctx, chatID, text)
|
||||
if err != nil {
|
||||
return "", err
|
||||
@@ -711,11 +710,11 @@ func (c *MatrixChannel) SendPlaceholder(ctx context.Context, chatID string) (str
|
||||
|
||||
```go
|
||||
// 如果 channel 通过 webhook 接收消息(而非长轮询/WebSocket)
|
||||
func (c *MatrixChannel) WebhookPath() string {
|
||||
return "/webhook/matrix" // 路径会被注册到共享 HTTP 服务器
|
||||
func (c *ExampleChatChannel) WebhookPath() string {
|
||||
return "/webhook/examplechat" // 路径会被注册到共享 HTTP 服务器
|
||||
}
|
||||
|
||||
func (c *MatrixChannel) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
func (c *ExampleChatChannel) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
// 处理 webhook 请求
|
||||
}
|
||||
```
|
||||
@@ -723,11 +722,11 @@ func (c *MatrixChannel) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
#### HealthChecker — 健康检查端点
|
||||
|
||||
```go
|
||||
func (c *MatrixChannel) HealthPath() string {
|
||||
return "/health/matrix"
|
||||
func (c *ExampleChatChannel) HealthPath() string {
|
||||
return "/health/examplechat"
|
||||
}
|
||||
|
||||
func (c *MatrixChannel) HealthHandler(w http.ResponseWriter, r *http.Request) {
|
||||
func (c *ExampleChatChannel) HealthHandler(w http.ResponseWriter, r *http.Request) {
|
||||
if c.IsRunning() {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte("OK"))
|
||||
@@ -767,7 +766,7 @@ if c.owner != nil && c.placeholderRecorder != nil {
|
||||
|
||||
**这意味着**:
|
||||
- 实现 `TypingCapable` 的 channel(Telegram、Discord、LINE)无需在 `handleMessage` 中手动调用 `StartTyping` + `RecordTypingStop`
|
||||
- 实现 `ReactionCapable` 的 channel(Slack、OneBot)无需在 `handleMessage` 中手动调用 `AddReaction` + `RecordTypingStop`
|
||||
- 实现 `ReactionCapable` 的 channel(OneBot)无需在 `handleMessage` 中手动调用 `AddReaction` + `RecordTypingStop`
|
||||
- 实现 `PlaceholderCapable` 的 channel(Telegram、Discord)无需在 `handleMessage` 中手动发送占位消息并调用 `RecordPlaceholder`
|
||||
- Channel 只需实现对应接口,`HandleMessage` 会自动完成编排
|
||||
- 不实现这些接口的 channel 不受影响(类型断言会失败,跳过)
|
||||
@@ -791,12 +790,12 @@ channel 特定的设置放在 `settings` 子键中:
|
||||
```json
|
||||
{
|
||||
"channel_list": {
|
||||
"matrix": {
|
||||
"examplechat": {
|
||||
"enabled": true,
|
||||
"type": "matrix",
|
||||
"type": "examplechat",
|
||||
"allow_from": ["@user:example.com"],
|
||||
"settings": {
|
||||
"home_server": "https://matrix.org",
|
||||
"home_server": "https://examplechat.org",
|
||||
"user_id": "@bot:example.com",
|
||||
"access_token": "enc://..."
|
||||
}
|
||||
@@ -809,8 +808,8 @@ channel 特定的设置放在 `settings` 子键中:
|
||||
|
||||
```yaml
|
||||
channels:
|
||||
matrix:
|
||||
access_token: "your-matrix-access-token"
|
||||
examplechat:
|
||||
access_token: "your-examplechat-access-token"
|
||||
```
|
||||
|
||||
Channel 类型必须在 `pkg/config/config_channel.go` 的 `channelSettingsFactory` 中注册:
|
||||
@@ -818,7 +817,7 @@ Channel 类型必须在 `pkg/config/config_channel.go` 的 `channelSettingsFacto
|
||||
```go
|
||||
var channelSettingsFactory = map[string]any{
|
||||
// ... 现有 channels
|
||||
ChannelMatrix: (MatrixSettings{}),
|
||||
ChannelExampleChat: (ExampleChatSettings{}),
|
||||
}
|
||||
```
|
||||
|
||||
@@ -841,7 +840,7 @@ Manager 使用 `InitChannelList()` 来验证类型和解码设置,
|
||||
```go
|
||||
// cmd/picoclaw/internal/gateway/helpers.go
|
||||
import (
|
||||
_ "github.com/sipeed/picoclaw/pkg/channels/matrix"
|
||||
_ "github.com/sipeed/picoclaw/pkg/channels/examplechat"
|
||||
)
|
||||
```
|
||||
|
||||
@@ -1070,7 +1069,6 @@ type channelWorker struct {
|
||||
var channelRateConfig = map[string]float64{
|
||||
"telegram": 20, // 20 msg/s
|
||||
"discord": 1, // 1 msg/s
|
||||
"slack": 1, // 1 msg/s
|
||||
"line": 10, // 10 msg/s
|
||||
}
|
||||
// 默认: 10 msg/s
|
||||
@@ -1265,7 +1263,7 @@ Manager 创建单一 `http.Server`,自动发现和注册:
|
||||
|
||||
为新 channel 添加测试时:
|
||||
```bash
|
||||
go test ./pkg/channels/matrix/ -v # 子包测试
|
||||
go test ./pkg/channels/examplechat/ -v # 子包测试
|
||||
go test ./pkg/channels/ -run TestSpecific -v # 框架测试
|
||||
make test # 全量测试
|
||||
```
|
||||
@@ -1298,7 +1296,6 @@ make test # 全量测试
|
||||
|------|--------|----------|
|
||||
| `pkg/channels/telegram/` | `"telegram"` | TypingCapable, PlaceholderCapable, MessageEditor, MediaSender |
|
||||
| `pkg/channels/discord/` | `"discord"` | TypingCapable, PlaceholderCapable, MessageEditor, MediaSender |
|
||||
| `pkg/channels/slack/` | `"slack"` | ReactionCapable, MediaSender |
|
||||
| `pkg/channels/line/` | `"line"` | TypingCapable, MediaSender, WebhookHandler |
|
||||
| `pkg/channels/onebot/` | `"onebot"` | ReactionCapable, MediaSender |
|
||||
| `pkg/channels/dingtalk/` | `"dingtalk"` | — |
|
||||
@@ -1407,7 +1404,6 @@ agentLoop.Stop() // 停止 Agent
|
||||
|---------|-------------|-------|
|
||||
| telegram | 20 | 10 |
|
||||
| discord | 1 | 1 |
|
||||
| slack | 1 | 1 |
|
||||
| line | 10 | 5 |
|
||||
| _其他_ | 10 (默认) | 5 |
|
||||
|
||||
@@ -1423,6 +1419,6 @@ agentLoop.Stop() // 停止 Agent
|
||||
|
||||
5. **DingTalk 使用 Stream 模式**:DingTalk 使用 SDK 的 Stream/WebSocket 模式(非 HTTP webhook),因此不实现 `WebhookHandler`。
|
||||
|
||||
6. **PlaceholderConfig 的配置与实现**:`PlaceholderConfig` 出现在 5 个 channel config 中(Telegram、Discord、Slack、LINE、OneBot),但只有实现了 `PlaceholderCapable` + `MessageEditor` 的 channel(Telegram、Discord)能真正使用占位消息编辑功能。其余 channel 的 `PlaceholderConfig` 为预留字段。
|
||||
6. **PlaceholderConfig 的配置与实现**:`PlaceholderConfig` 出现在 4 个 channel config 中(Telegram、Discord、LINE、OneBot),但只有实现了 `PlaceholderCapable` + `MessageEditor` 的 channel(Telegram、Discord)能真正使用占位消息编辑功能。其余 channel 的 `PlaceholderConfig` 为预留字段。
|
||||
|
||||
7. **ReasoningChannelID**:大多数 channel config 都包含 `reasoning_channel_id` 字段,用于将 LLM 的思维链(reasoning/thinking)路由到指定 channel(WhatsApp、Telegram、Feishu、Discord、QQ、DingTalk、Slack、LINE、OneBot、WeCom)。`BaseChannel` 通过 `WithReasoningChannelID` 选项和 `ReasoningChannelID()` 方法暴露此配置。
|
||||
7. **ReasoningChannelID**:大多数 channel config 都包含 `reasoning_channel_id` 字段,用于将 LLM 的思维链(reasoning/thinking)路由到指定 channel(WhatsApp、Telegram、Feishu、Discord、QQ、DingTalk、LINE、OneBot、WeCom)。`BaseChannel` 通过 `WithReasoningChannelID` 选项和 `ReasoningChannelID()` 方法暴露此配置。
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,398 +0,0 @@
|
||||
package deltachat
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"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"
|
||||
)
|
||||
|
||||
// listen is the inbound message loop. It blocks on wait_next_msgs and feeds
|
||||
// each new message into the PicoClaw inbound pipeline.
|
||||
func (c *DeltaChatChannel) listen() {
|
||||
logger.InfoCF("deltachat", "Listening for messages", map[string]any{
|
||||
"account_id": c.accountID,
|
||||
"email": c.selfAddr,
|
||||
})
|
||||
for c.IsRunning() && c.ctx.Err() == nil {
|
||||
raw, err := c.rpc.call(c.ctx, "wait_next_msgs", c.accountID)
|
||||
if err != nil {
|
||||
if c.ctx.Err() != nil || !c.IsRunning() {
|
||||
return
|
||||
}
|
||||
logger.ErrorCF("deltachat", "wait_next_msgs failed", map[string]any{"error": err.Error()})
|
||||
time.Sleep(time.Second)
|
||||
continue
|
||||
}
|
||||
|
||||
var messageIDs []int64
|
||||
if err := json.Unmarshal(raw, &messageIDs); err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
if len(messageIDs) > 0 {
|
||||
logger.DebugCF("deltachat", "Received message batch", map[string]any{
|
||||
"count": len(messageIDs),
|
||||
})
|
||||
}
|
||||
for _, messageID := range messageIDs {
|
||||
c.handleMessage(messageID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// handleMessage fetches one message, applies inbound filtering, and publishes it.
|
||||
func (c *DeltaChatChannel) handleMessage(messageID int64) {
|
||||
msg, err := c.getMessage(messageID)
|
||||
if err != nil {
|
||||
logger.DebugCF("deltachat", "get_message failed", map[string]any{
|
||||
"message_id": messageID,
|
||||
"error": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if msg.IsInfo || (strings.TrimSpace(msg.Text) == "" && msg.File == "") {
|
||||
return
|
||||
}
|
||||
|
||||
senderAddr := ""
|
||||
if msg.Sender != nil {
|
||||
senderAddr = msg.Sender.Address
|
||||
}
|
||||
if senderAddr != "" && strings.EqualFold(senderAddr, c.selfAddr) {
|
||||
logger.DebugCF("deltachat", "Drop: own message", map[string]any{"message_id": messageID})
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := c.getFullChat(msg.ChatID)
|
||||
if err != nil {
|
||||
logger.DebugCF("deltachat", "get_full_chat_by_id failed", map[string]any{
|
||||
"chat_id": msg.ChatID,
|
||||
"error": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
// Device messages are core-generated notices, not real conversations.
|
||||
if chat.IsDeviceChat {
|
||||
logger.DebugCF("deltachat", "Drop: device message", map[string]any{"chat_id": msg.ChatID})
|
||||
return
|
||||
}
|
||||
isGroup := chat.ChatType != chatTypeSingle
|
||||
|
||||
logger.DebugCF("deltachat", "Inbound message", map[string]any{
|
||||
"message_id": messageID,
|
||||
"chat_id": msg.ChatID,
|
||||
"from": senderAddr,
|
||||
"is_group": isGroup,
|
||||
"has_file": msg.File != "",
|
||||
"text_len": len(strings.TrimSpace(msg.Text)),
|
||||
})
|
||||
|
||||
senderName := senderAddr
|
||||
if msg.Sender != nil {
|
||||
if msg.Sender.DisplayName != "" {
|
||||
senderName = msg.Sender.DisplayName
|
||||
} else if msg.Sender.Name != "" {
|
||||
senderName = msg.Sender.Name
|
||||
}
|
||||
}
|
||||
if senderName == "" {
|
||||
senderName = "unknown"
|
||||
}
|
||||
|
||||
chatID := strconv.FormatInt(msg.ChatID, 10)
|
||||
messageIDStr := strconv.FormatInt(msg.ID, 10)
|
||||
|
||||
content := strings.TrimSpace(msg.Text)
|
||||
|
||||
// Register any attachment with the media store so the agent pipeline can
|
||||
// view images and operate on files. The ref is scoped to the same key the
|
||||
// BaseChannel derives for this message, so it is released with the turn.
|
||||
var mediaRefs []string
|
||||
if msg.File != "" {
|
||||
scope := channels.BuildMediaScope(c.Name(), chatID, messageIDStr)
|
||||
if ref := c.registerInboundFile(scope, msg); ref != "" {
|
||||
mediaRefs = append(mediaRefs, ref)
|
||||
} else {
|
||||
// Fallback when no media store is available: surface the path inline
|
||||
// so the attachment is not silently lost.
|
||||
annotation := fmt.Sprintf("[attachment: %s]", msg.File)
|
||||
if content == "" {
|
||||
content = annotation
|
||||
} else {
|
||||
content = content + "\n" + annotation
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A file with no caption still warrants a turn; give the agent a minimal
|
||||
// placeholder so the message survives the empty-content guard below. Audio
|
||||
// gets a "[voice]" tag specifically, so the agent's transcription step can
|
||||
// substitute the transcript in place rather than appending it.
|
||||
if content == "" && len(mediaRefs) > 0 {
|
||||
if utils.IsAudioFile(msg.FileName, msg.FileMime) {
|
||||
content = "[voice]"
|
||||
} else {
|
||||
content = "[media]"
|
||||
}
|
||||
}
|
||||
|
||||
sender := bus.SenderInfo{
|
||||
Platform: config.ChannelDeltaChat,
|
||||
PlatformID: senderAddr,
|
||||
CanonicalID: identity.BuildCanonicalID(config.ChannelDeltaChat, senderAddr),
|
||||
Username: senderAddr,
|
||||
DisplayName: senderName,
|
||||
}
|
||||
|
||||
if !c.IsAllowedSender(sender) {
|
||||
logger.DebugCF("deltachat", "Drop: sender not in allow_from", map[string]any{
|
||||
"from": senderAddr,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
isMentioned := false
|
||||
if isGroup {
|
||||
botName := c.config.DisplayName
|
||||
if botName == "" {
|
||||
botName = c.selfAddr
|
||||
}
|
||||
isMentioned = mentionsBot(content, botName, c.selfAddr)
|
||||
respond, cleaned := c.ShouldRespondInGroup(isMentioned, content)
|
||||
if !respond {
|
||||
logger.DebugCF("deltachat", "Drop: group trigger not satisfied", map[string]any{
|
||||
"chat_id": msg.ChatID,
|
||||
"mentioned": isMentioned,
|
||||
})
|
||||
return
|
||||
}
|
||||
content = cleaned
|
||||
}
|
||||
|
||||
if strings.TrimSpace(content) == "" {
|
||||
return
|
||||
}
|
||||
|
||||
metadata := map[string]string{
|
||||
"platform": config.ChannelDeltaChat,
|
||||
"chat_name": chat.Name,
|
||||
}
|
||||
if msg.File != "" {
|
||||
metadata["file"] = msg.File
|
||||
metadata["file_name"] = msg.FileName
|
||||
metadata["file_mime"] = msg.FileMime
|
||||
}
|
||||
|
||||
inboundCtx := bus.InboundContext{
|
||||
Channel: config.ChannelDeltaChat,
|
||||
ChatID: chatID,
|
||||
SenderID: senderAddr,
|
||||
MessageID: messageIDStr,
|
||||
Mentioned: isMentioned,
|
||||
Raw: metadata,
|
||||
}
|
||||
if isGroup {
|
||||
inboundCtx.ChatType = "group"
|
||||
} else {
|
||||
inboundCtx.ChatType = "direct"
|
||||
}
|
||||
|
||||
logger.DebugCF("deltachat", "Dispatching to agent", map[string]any{
|
||||
"chat_id": chatID,
|
||||
"chat_type": inboundCtx.ChatType,
|
||||
"from": senderAddr,
|
||||
})
|
||||
if err := c.HandleInboundContext(c.ctx, chatID, content, mediaRefs, inboundCtx, sender); err != nil {
|
||||
logger.ErrorCF("deltachat", "Dispatch failed; leaving message unseen", map[string]any{
|
||||
"message_id": messageID,
|
||||
"chat_id": chatID,
|
||||
"error": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
if _, err := c.rpc.call(c.ctx, "markseen_msgs", c.accountID, []int64{messageID}); err != nil {
|
||||
logger.WarnCF("deltachat", "Failed to mark message seen", map[string]any{
|
||||
"message_id": messageID,
|
||||
"chat_id": chatID,
|
||||
"error": err.Error(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// registerInboundFile records an inbound attachment with the media store under
|
||||
// the given scope and returns its media:// ref. Returns "" when there is no
|
||||
// media store or registration fails, letting the caller fall back to an inline
|
||||
// path annotation.
|
||||
//
|
||||
// Delta Chat stores attachments inside the account directory, next to the
|
||||
// credential database — a location tools are intentionally NOT allowed to read.
|
||||
// We therefore copy the single attachment out into the shared media temp dir
|
||||
// (which read_file/load_image are permitted to access) and register that copy,
|
||||
// so the agent can actually open the file. The copy is store-managed and deleted
|
||||
// when the turn's scope is released.
|
||||
func (c *DeltaChatChannel) registerInboundFile(scope string, msg *dcMessage) string {
|
||||
store := c.GetMediaStore()
|
||||
if store == nil {
|
||||
return ""
|
||||
}
|
||||
filename := msg.FileName
|
||||
if filename == "" {
|
||||
filename = filepath.Base(msg.File)
|
||||
}
|
||||
|
||||
localPath, err := copyToMediaTemp(msg.File, filename)
|
||||
if err != nil {
|
||||
logger.WarnCF("deltachat", "Failed to copy attachment into media dir", map[string]any{
|
||||
"file": msg.File,
|
||||
"error": err.Error(),
|
||||
})
|
||||
return ""
|
||||
}
|
||||
|
||||
ref, err := store.Store(localPath, media.MediaMeta{
|
||||
Filename: filename,
|
||||
ContentType: msg.FileMime,
|
||||
Source: config.ChannelDeltaChat,
|
||||
CleanupPolicy: media.CleanupPolicyDeleteOnCleanup,
|
||||
}, scope)
|
||||
if err != nil {
|
||||
logger.WarnCF("deltachat", "Failed to register attachment with media store", map[string]any{
|
||||
"file": localPath,
|
||||
"error": err.Error(),
|
||||
})
|
||||
_ = os.Remove(localPath)
|
||||
return ""
|
||||
}
|
||||
return ref
|
||||
}
|
||||
|
||||
// copyToMediaTemp copies srcPath into the shared media temp directory under a
|
||||
// unique name and returns the destination path. The media temp dir is the
|
||||
// location the read_file/load_image tools are permitted to read, so copying here
|
||||
// makes the attachment readable without exposing Delta Chat's account directory.
|
||||
func copyToMediaTemp(srcPath, filename string) (string, error) {
|
||||
if err := os.MkdirAll(media.TempDir(), 0o700); err != nil {
|
||||
return "", err
|
||||
}
|
||||
safe := utils.SanitizeFilename(filename)
|
||||
if safe == "" {
|
||||
safe = filepath.Base(srcPath)
|
||||
}
|
||||
dstPath := filepath.Join(media.TempDir(), uuid.NewString()[:8]+"_"+safe)
|
||||
|
||||
src, err := os.Open(srcPath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer src.Close()
|
||||
|
||||
dst, err := os.Create(dstPath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if _, err := io.Copy(dst, src); err != nil {
|
||||
dst.Close()
|
||||
_ = os.Remove(dstPath)
|
||||
return "", err
|
||||
}
|
||||
if err := dst.Close(); err != nil {
|
||||
_ = os.Remove(dstPath)
|
||||
return "", err
|
||||
}
|
||||
return dstPath, nil
|
||||
}
|
||||
|
||||
func (c *DeltaChatChannel) getMessage(messageID int64) (*dcMessage, error) {
|
||||
raw, err := c.rpc.call(c.ctx, "get_message", c.accountID, messageID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var msg dcMessage
|
||||
if err := json.Unmarshal(raw, &msg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &msg, nil
|
||||
}
|
||||
|
||||
func (c *DeltaChatChannel) getFullChat(chatID int64) (*dcChat, error) {
|
||||
raw, err := c.rpc.call(c.ctx, "get_full_chat_by_id", c.accountID, chatID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var chat dcChat
|
||||
if err := json.Unmarshal(raw, &chat); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &chat, nil
|
||||
}
|
||||
|
||||
// mentionsBot reports whether the message references the bot by display name or
|
||||
// the local-part of its email address (a common addressing convention).
|
||||
func mentionsBot(content, displayName, email string) bool {
|
||||
if containsMentionToken(content, displayName) {
|
||||
return true
|
||||
}
|
||||
if local, _, ok := strings.Cut(email, "@"); ok && local != "" {
|
||||
if containsMentionToken(content, "@"+local) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func containsMentionToken(content, token string) bool {
|
||||
token = strings.TrimSpace(token)
|
||||
if token == "" {
|
||||
return false
|
||||
}
|
||||
contentRunes := []rune(strings.ToLower(content))
|
||||
tokenRunes := []rune(strings.ToLower(token))
|
||||
if len(tokenRunes) == 0 || len(tokenRunes) > len(contentRunes) {
|
||||
return false
|
||||
}
|
||||
for i := 0; i <= len(contentRunes)-len(tokenRunes); i++ {
|
||||
if !sameRunes(contentRunes[i:i+len(tokenRunes)], tokenRunes) {
|
||||
continue
|
||||
}
|
||||
before := i == 0 || !isMentionWordRune(contentRunes[i-1])
|
||||
afterIdx := i + len(tokenRunes)
|
||||
after := afterIdx >= len(contentRunes) || !isMentionWordRune(contentRunes[afterIdx])
|
||||
if before && after {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func sameRunes(a, b []rune) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
for i := range a {
|
||||
if a[i] != b[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func isMentionWordRune(r rune) bool {
|
||||
return unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_'
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
package deltachat
|
||||
|
||||
import (
|
||||
"github.com/sipeed/picoclaw/pkg/bus"
|
||||
"github.com/sipeed/picoclaw/pkg/channels"
|
||||
"github.com/sipeed/picoclaw/pkg/config"
|
||||
)
|
||||
|
||||
func init() {
|
||||
channels.RegisterFactory(
|
||||
config.ChannelDeltaChat,
|
||||
func(channelName, channelType string, cfg *config.Config, b *bus.MessageBus) (channels.Channel, error) {
|
||||
bc := cfg.Channels[channelName]
|
||||
if bc == nil || !bc.Enabled {
|
||||
return nil, nil
|
||||
}
|
||||
decoded, err := bc.GetDecoded()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c, ok := decoded.(*config.DeltaChatSettings)
|
||||
if !ok {
|
||||
return nil, channels.ErrSendFailed
|
||||
}
|
||||
ch, err := NewDeltaChatChannel(bc, c, b)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if channelName != config.ChannelDeltaChat {
|
||||
ch.SetName(channelName)
|
||||
}
|
||||
return ch, nil
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -1,188 +0,0 @@
|
||||
package deltachat
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os/exec"
|
||||
"sync"
|
||||
|
||||
"github.com/sipeed/picoclaw/pkg/logger"
|
||||
)
|
||||
|
||||
// rpcRequest is a single JSON-RPC 2.0 request. Delta Chat uses positional
|
||||
// (array) parameters.
|
||||
type rpcRequest struct {
|
||||
JSONRPC string `json:"jsonrpc"`
|
||||
ID uint64 `json:"id"`
|
||||
Method string `json:"method"`
|
||||
Params []any `json:"params,omitempty"`
|
||||
}
|
||||
|
||||
// rpcResponse is a single JSON-RPC 2.0 response.
|
||||
type rpcResponse struct {
|
||||
ID uint64 `json:"id"`
|
||||
Result json.RawMessage `json:"result"`
|
||||
Error *rpcError `json:"error"`
|
||||
}
|
||||
|
||||
type rpcError struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
func (e *rpcError) Error() string {
|
||||
return fmt.Sprintf("deltachat rpc error %d: %s", e.Code, e.Message)
|
||||
}
|
||||
|
||||
// rpcClient drives a `deltachat-rpc-server` child process over stdio using
|
||||
// newline-delimited JSON-RPC 2.0. The server answers requests asynchronously
|
||||
// and out of order, so every call is correlated back to its caller by id.
|
||||
type rpcClient struct {
|
||||
cmd *exec.Cmd
|
||||
stdin io.WriteCloser
|
||||
stdout io.ReadCloser
|
||||
|
||||
mu sync.Mutex
|
||||
nextID uint64
|
||||
pending map[uint64]chan rpcResponse
|
||||
closed bool
|
||||
}
|
||||
|
||||
// startRPC spawns the RPC server with DC_ACCOUNTS_PATH pointing at dataDir and
|
||||
// begins the background read loop.
|
||||
func startRPC(serverPath, dataDir string) (*rpcClient, error) {
|
||||
cmd := exec.Command(serverPath)
|
||||
cmd.Env = append(cmd.Environ(), "DC_ACCOUNTS_PATH="+dataDir)
|
||||
|
||||
stdin, err := cmd.StdinPipe()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("deltachat rpc stdin: %w", err)
|
||||
}
|
||||
stdout, err := cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("deltachat rpc stdout: %w", err)
|
||||
}
|
||||
// Let the server's logs flow to our stderr for easy diagnostics.
|
||||
cmd.Stderr = logWriter{}
|
||||
|
||||
if err := cmd.Start(); err != nil {
|
||||
return nil, fmt.Errorf("start deltachat-rpc-server (%s): %w", serverPath, err)
|
||||
}
|
||||
|
||||
c := &rpcClient{
|
||||
cmd: cmd,
|
||||
stdin: stdin,
|
||||
stdout: stdout,
|
||||
pending: make(map[uint64]chan rpcResponse),
|
||||
}
|
||||
go c.readLoop()
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// readLoop reads newline-delimited responses and dispatches them to waiters.
|
||||
func (c *rpcClient) readLoop() {
|
||||
reader := bufio.NewReader(c.stdout)
|
||||
for {
|
||||
line, err := reader.ReadBytes('\n')
|
||||
if len(line) > 0 {
|
||||
var resp rpcResponse
|
||||
if jsonErr := json.Unmarshal(line, &resp); jsonErr == nil && resp.ID != 0 {
|
||||
c.mu.Lock()
|
||||
ch := c.pending[resp.ID]
|
||||
delete(c.pending, resp.ID)
|
||||
c.mu.Unlock()
|
||||
if ch != nil {
|
||||
ch <- resp
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
c.failAll(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// failAll wakes every pending caller with an error (used on EOF / shutdown).
|
||||
func (c *rpcClient) failAll(err error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.closed = true
|
||||
for id, ch := range c.pending {
|
||||
ch <- rpcResponse{Error: &rpcError{Code: -1, Message: "rpc closed: " + err.Error()}}
|
||||
delete(c.pending, id)
|
||||
}
|
||||
}
|
||||
|
||||
// call issues one request and blocks until the matching response arrives, the
|
||||
// context is canceled, or the server goes away.
|
||||
func (c *rpcClient) call(ctx context.Context, method string, params ...any) (json.RawMessage, error) {
|
||||
c.mu.Lock()
|
||||
if c.closed {
|
||||
c.mu.Unlock()
|
||||
return nil, fmt.Errorf("deltachat rpc: connection closed")
|
||||
}
|
||||
c.nextID++
|
||||
id := c.nextID
|
||||
ch := make(chan rpcResponse, 1)
|
||||
c.pending[id] = ch
|
||||
c.mu.Unlock()
|
||||
|
||||
req := rpcRequest{JSONRPC: "2.0", ID: id, Method: method, Params: params}
|
||||
data, err := json.Marshal(req)
|
||||
if err != nil {
|
||||
c.clearPending(id)
|
||||
return nil, err
|
||||
}
|
||||
data = append(data, '\n')
|
||||
|
||||
c.mu.Lock()
|
||||
_, err = c.stdin.Write(data)
|
||||
c.mu.Unlock()
|
||||
if err != nil {
|
||||
c.clearPending(id)
|
||||
return nil, fmt.Errorf("deltachat rpc write %s: %w", method, err)
|
||||
}
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
c.clearPending(id)
|
||||
return nil, ctx.Err()
|
||||
case resp := <-ch:
|
||||
if resp.Error != nil {
|
||||
return nil, resp.Error
|
||||
}
|
||||
return resp.Result, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (c *rpcClient) clearPending(id uint64) {
|
||||
c.mu.Lock()
|
||||
delete(c.pending, id)
|
||||
c.mu.Unlock()
|
||||
}
|
||||
|
||||
// close terminates the RPC server process.
|
||||
func (c *rpcClient) close() {
|
||||
c.mu.Lock()
|
||||
c.closed = true
|
||||
c.mu.Unlock()
|
||||
if c.stdin != nil {
|
||||
_ = c.stdin.Close()
|
||||
}
|
||||
if c.cmd != nil && c.cmd.Process != nil {
|
||||
_ = c.cmd.Process.Kill()
|
||||
_ = c.cmd.Wait()
|
||||
}
|
||||
}
|
||||
|
||||
// logWriter forwards deltachat-rpc-server stderr lines into the logger.
|
||||
type logWriter struct{}
|
||||
|
||||
func (logWriter) Write(p []byte) (int, error) {
|
||||
logger.DebugC("deltachat", string(p))
|
||||
return len(p), nil
|
||||
}
|
||||
@@ -1,167 +0,0 @@
|
||||
package irc
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
"github.com/ergochat/irc-go/ircevent"
|
||||
"github.com/ergochat/irc-go/ircmsg"
|
||||
|
||||
"github.com/sipeed/picoclaw/pkg/bus"
|
||||
"github.com/sipeed/picoclaw/pkg/identity"
|
||||
"github.com/sipeed/picoclaw/pkg/logger"
|
||||
)
|
||||
|
||||
// onConnect is called after a successful connection (and on reconnect).
|
||||
func (c *IRCChannel) onConnect(conn *ircevent.Connection) {
|
||||
// NickServ auth (only if SASL is not configured)
|
||||
if c.config.NickServPassword.String() != "" && c.config.SASLUser == "" {
|
||||
conn.Privmsg("NickServ", "IDENTIFY "+c.config.NickServPassword.String())
|
||||
}
|
||||
|
||||
// Join configured channels
|
||||
for _, ch := range c.config.Channels {
|
||||
conn.Join(ch)
|
||||
logger.InfoCF("irc", "Joined IRC channel", map[string]any{
|
||||
"channel": ch,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// onPrivmsg handles incoming PRIVMSG events.
|
||||
func (c *IRCChannel) onPrivmsg(conn *ircevent.Connection, e ircmsg.Message) {
|
||||
if len(e.Params) < 2 {
|
||||
return
|
||||
}
|
||||
|
||||
nick := e.Nick()
|
||||
currentNick := conn.CurrentNick()
|
||||
|
||||
// Ignore own messages
|
||||
if strings.EqualFold(nick, currentNick) {
|
||||
return
|
||||
}
|
||||
|
||||
target := e.Params[0] // channel name or bot's nick
|
||||
content := e.Params[1] // message text
|
||||
|
||||
// Determine if this is a DM or channel message
|
||||
isDM := !strings.HasPrefix(target, "#") && !strings.HasPrefix(target, "&")
|
||||
|
||||
var chatID string
|
||||
|
||||
if isDM {
|
||||
chatID = nick
|
||||
} else {
|
||||
chatID = target
|
||||
}
|
||||
|
||||
sender := bus.SenderInfo{
|
||||
Platform: "irc",
|
||||
PlatformID: nick,
|
||||
CanonicalID: identity.BuildCanonicalID("irc", nick),
|
||||
Username: nick,
|
||||
DisplayName: nick,
|
||||
}
|
||||
|
||||
if !c.IsAllowedSender(sender) {
|
||||
return
|
||||
}
|
||||
|
||||
isMentioned := false
|
||||
|
||||
// For channel messages, check group trigger (mention detection)
|
||||
if !isDM {
|
||||
isMentioned = isBotMentioned(content, currentNick)
|
||||
if isMentioned {
|
||||
content = stripBotMention(content, currentNick)
|
||||
}
|
||||
respond, cleaned := c.ShouldRespondInGroup(isMentioned, content)
|
||||
if !respond {
|
||||
return
|
||||
}
|
||||
content = cleaned
|
||||
}
|
||||
|
||||
if strings.TrimSpace(content) == "" {
|
||||
return
|
||||
}
|
||||
|
||||
messageID := fmt.Sprintf("%s-%d", nick, time.Now().UnixNano())
|
||||
|
||||
metadata := map[string]string{
|
||||
"platform": "irc",
|
||||
"server": c.config.Server,
|
||||
}
|
||||
if !isDM {
|
||||
metadata["channel"] = target
|
||||
}
|
||||
|
||||
inboundCtx := bus.InboundContext{
|
||||
Channel: "irc",
|
||||
ChatID: chatID,
|
||||
SenderID: nick,
|
||||
MessageID: messageID,
|
||||
Mentioned: isMentioned,
|
||||
Raw: metadata,
|
||||
}
|
||||
if isDM {
|
||||
inboundCtx.ChatType = "direct"
|
||||
} else {
|
||||
inboundCtx.ChatType = "group"
|
||||
}
|
||||
|
||||
c.HandleInboundContext(c.ctx, chatID, content, nil, inboundCtx, sender)
|
||||
}
|
||||
|
||||
// nickMentionedAt returns the byte index where botNick is mentioned in content
|
||||
// with word-boundary checks, or -1 if not found. Also checks for "nick:" /
|
||||
// "nick," prefix convention.
|
||||
func nickMentionedAt(content, botNick string) int {
|
||||
lower := strings.ToLower(content)
|
||||
lowerNick := strings.ToLower(botNick)
|
||||
|
||||
// "nick:" or "nick," at start (most common IRC convention)
|
||||
if strings.HasPrefix(lower, lowerNick+":") || strings.HasPrefix(lower, lowerNick+",") {
|
||||
return 0
|
||||
}
|
||||
|
||||
// Word-boundary match anywhere in the message
|
||||
idx := strings.Index(lower, lowerNick)
|
||||
if idx < 0 {
|
||||
return -1
|
||||
}
|
||||
runes := []rune(lower)
|
||||
nickRunes := []rune(lowerNick)
|
||||
endIdx := idx + len(string(nickRunes))
|
||||
before := idx == 0 || !unicode.IsLetter(runes[idx-1]) && !unicode.IsDigit(runes[idx-1])
|
||||
after := endIdx >= len(lower) || !unicode.IsLetter(rune(lower[endIdx])) && !unicode.IsDigit(rune(lower[endIdx]))
|
||||
if before && after {
|
||||
return idx
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// isBotMentioned checks if the bot's nick appears in the message.
|
||||
func isBotMentioned(content, botNick string) bool {
|
||||
return nickMentionedAt(content, botNick) >= 0
|
||||
}
|
||||
|
||||
// stripBotMention removes "nick: " or "nick, " prefix from content.
|
||||
func stripBotMention(content, botNick string) string {
|
||||
idx := nickMentionedAt(content, botNick)
|
||||
if idx != 0 {
|
||||
return content
|
||||
}
|
||||
lowerNick := strings.ToLower(botNick)
|
||||
lower := strings.ToLower(content)
|
||||
for _, sep := range []string{":", ","} {
|
||||
prefix := lowerNick + sep
|
||||
if strings.HasPrefix(lower, prefix) {
|
||||
return strings.TrimSpace(content[len(prefix):])
|
||||
}
|
||||
}
|
||||
return content
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
package irc
|
||||
|
||||
import (
|
||||
"github.com/sipeed/picoclaw/pkg/bus"
|
||||
"github.com/sipeed/picoclaw/pkg/channels"
|
||||
"github.com/sipeed/picoclaw/pkg/config"
|
||||
)
|
||||
|
||||
func init() {
|
||||
channels.RegisterFactory(
|
||||
config.ChannelIRC,
|
||||
func(channelName, channelType string, cfg *config.Config, b *bus.MessageBus) (channels.Channel, error) {
|
||||
bc := cfg.Channels[channelName]
|
||||
if bc == nil || !bc.Enabled {
|
||||
return nil, nil
|
||||
}
|
||||
decoded, err := bc.GetDecoded()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c, ok := decoded.(*config.IRCSettings)
|
||||
if !ok {
|
||||
return nil, channels.ErrSendFailed
|
||||
}
|
||||
ch, err := NewIRCChannel(bc, c, b)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if channelName != config.ChannelIRC {
|
||||
ch.SetName(channelName)
|
||||
}
|
||||
return ch, nil
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -1,196 +0,0 @@
|
||||
package irc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/ergochat/irc-go/ircevent"
|
||||
"github.com/ergochat/irc-go/ircmsg"
|
||||
|
||||
"github.com/sipeed/picoclaw/pkg/bus"
|
||||
"github.com/sipeed/picoclaw/pkg/channels"
|
||||
"github.com/sipeed/picoclaw/pkg/config"
|
||||
"github.com/sipeed/picoclaw/pkg/logger"
|
||||
)
|
||||
|
||||
// IRCChannel implements the Channel interface for IRC servers.
|
||||
type IRCChannel struct {
|
||||
*channels.BaseChannel
|
||||
bc *config.Channel
|
||||
config *config.IRCSettings
|
||||
conn *ircevent.Connection
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
// NewIRCChannel creates a new IRC channel.
|
||||
func NewIRCChannel(bc *config.Channel, cfg *config.IRCSettings, messageBus *bus.MessageBus) (*IRCChannel, error) {
|
||||
if cfg.Server == "" {
|
||||
return nil, fmt.Errorf("irc server is required")
|
||||
}
|
||||
if cfg.Nick == "" {
|
||||
return nil, fmt.Errorf("irc nick is required")
|
||||
}
|
||||
|
||||
base := channels.NewBaseChannel("irc", cfg, messageBus, bc.AllowFrom,
|
||||
channels.WithMaxMessageLength(400),
|
||||
channels.WithGroupTrigger(bc.GroupTrigger),
|
||||
channels.WithReasoningChannelID(bc.ReasoningChannelID),
|
||||
)
|
||||
|
||||
return &IRCChannel{
|
||||
BaseChannel: base,
|
||||
bc: bc,
|
||||
config: cfg,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Start connects to the IRC server and begins listening.
|
||||
func (c *IRCChannel) Start(ctx context.Context) error {
|
||||
logger.InfoC("irc", "Starting IRC channel")
|
||||
c.ctx, c.cancel = context.WithCancel(ctx)
|
||||
|
||||
user := c.config.User
|
||||
if user == "" {
|
||||
user = c.config.Nick
|
||||
}
|
||||
realName := c.config.RealName
|
||||
if realName == "" {
|
||||
realName = c.config.Nick
|
||||
}
|
||||
caps := []string(c.config.RequestCaps)
|
||||
if len(caps) == 0 {
|
||||
caps = []string{"server-time", "message-tags"}
|
||||
}
|
||||
|
||||
conn := &ircevent.Connection{
|
||||
Server: c.config.Server,
|
||||
Nick: c.config.Nick,
|
||||
User: user,
|
||||
RealName: realName,
|
||||
Password: c.config.Password.String(),
|
||||
UseTLS: c.config.TLS,
|
||||
RequestCaps: caps,
|
||||
QuitMessage: "Goodbye",
|
||||
Debug: false,
|
||||
Log: nil,
|
||||
}
|
||||
|
||||
if c.config.TLS {
|
||||
conn.TLSConfig = &tls.Config{
|
||||
ServerName: extractHost(c.config.Server),
|
||||
}
|
||||
}
|
||||
|
||||
// SASL auth (takes priority over NickServ)
|
||||
if c.config.SASLUser != "" && c.config.SASLPassword.String() != "" {
|
||||
conn.SASLLogin = c.config.SASLUser
|
||||
conn.SASLPassword = c.config.SASLPassword.String()
|
||||
}
|
||||
|
||||
// Register event handlers
|
||||
conn.AddConnectCallback(func(e ircmsg.Message) {
|
||||
c.onConnect(conn)
|
||||
})
|
||||
conn.AddCallback("PRIVMSG", func(e ircmsg.Message) {
|
||||
c.onPrivmsg(conn, e)
|
||||
})
|
||||
|
||||
if err := conn.Connect(); err != nil {
|
||||
return fmt.Errorf("irc connect failed: %w", err)
|
||||
}
|
||||
|
||||
c.conn = conn
|
||||
|
||||
// ircevent.Connection.Loop() handles reconnection internally.
|
||||
go conn.Loop()
|
||||
|
||||
c.SetRunning(true)
|
||||
logger.InfoCF("irc", "IRC channel started", map[string]any{
|
||||
"server": c.config.Server,
|
||||
"nick": c.config.Nick,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stop disconnects from the IRC server.
|
||||
func (c *IRCChannel) Stop(ctx context.Context) error {
|
||||
logger.InfoC("irc", "Stopping IRC channel")
|
||||
c.SetRunning(false)
|
||||
|
||||
if c.conn != nil {
|
||||
c.conn.Quit()
|
||||
}
|
||||
if c.cancel != nil {
|
||||
c.cancel()
|
||||
}
|
||||
|
||||
logger.InfoC("irc", "IRC channel stopped")
|
||||
return nil
|
||||
}
|
||||
|
||||
// Send sends a message to an IRC channel or user.
|
||||
func (c *IRCChannel) Send(ctx context.Context, msg bus.OutboundMessage) ([]string, error) {
|
||||
if !c.IsRunning() {
|
||||
return nil, channels.ErrNotRunning
|
||||
}
|
||||
|
||||
target := msg.ChatID
|
||||
if target == "" {
|
||||
return nil, fmt.Errorf("chat ID is empty: %w", channels.ErrSendFailed)
|
||||
}
|
||||
|
||||
if strings.TrimSpace(msg.Content) == "" {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// Send each line separately (IRC is line-oriented)
|
||||
lines := strings.Split(msg.Content, "\n")
|
||||
for _, line := range lines {
|
||||
line = strings.TrimRight(line, "\r")
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
c.conn.Privmsg(target, line)
|
||||
}
|
||||
|
||||
logger.DebugCF("irc", "Message sent", map[string]any{
|
||||
"target": target,
|
||||
"lines": len(lines),
|
||||
})
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// StartTyping implements channels.TypingCapable using IRCv3 +typing client tag.
|
||||
// Requires typing.enabled in config and server support for message-tags capability.
|
||||
func (c *IRCChannel) StartTyping(ctx context.Context, chatID string) (func(), error) {
|
||||
noop := func() {}
|
||||
|
||||
if !c.bc.Typing.Enabled || !c.IsRunning() || c.conn == nil {
|
||||
return noop, nil
|
||||
}
|
||||
|
||||
// Check if server supports message-tags (required for TAGMSG)
|
||||
if _, ok := c.conn.AcknowledgedCaps()["message-tags"]; !ok {
|
||||
return noop, nil
|
||||
}
|
||||
|
||||
c.conn.SendWithTags(map[string]string{"+typing": "active"}, "TAGMSG", chatID)
|
||||
|
||||
return func() {
|
||||
if c.IsRunning() && c.conn != nil {
|
||||
c.conn.SendWithTags(map[string]string{"+typing": "done"}, "TAGMSG", chatID)
|
||||
}
|
||||
}, nil
|
||||
}
|
||||
|
||||
// extractHost returns the hostname portion of a host:port string.
|
||||
func extractHost(server string) string {
|
||||
host, _, found := strings.Cut(server, ":")
|
||||
if found {
|
||||
return host
|
||||
}
|
||||
return server
|
||||
}
|
||||
@@ -1,148 +0,0 @@
|
||||
package irc
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/sipeed/picoclaw/pkg/bus"
|
||||
"github.com/sipeed/picoclaw/pkg/config"
|
||||
)
|
||||
|
||||
func TestNewIRCChannel(t *testing.T) {
|
||||
msgBus := bus.NewMessageBus()
|
||||
|
||||
t.Run("missing server", func(t *testing.T) {
|
||||
bc := &config.Channel{Type: config.ChannelIRC, Enabled: true}
|
||||
cfg := &config.IRCSettings{Nick: "bot"}
|
||||
_, err := NewIRCChannel(bc, cfg, msgBus)
|
||||
if err == nil {
|
||||
t.Error("expected error for missing server, got nil")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("missing nick", func(t *testing.T) {
|
||||
bc := &config.Channel{Type: config.ChannelIRC, Enabled: true}
|
||||
cfg := &config.IRCSettings{Server: "irc.example.com:6667"}
|
||||
_, err := NewIRCChannel(bc, cfg, msgBus)
|
||||
if err == nil {
|
||||
t.Error("expected error for missing nick, got nil")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("valid config", func(t *testing.T) {
|
||||
bc := &config.Channel{Type: config.ChannelIRC, Enabled: true}
|
||||
cfg := &config.IRCSettings{
|
||||
Server: "irc.example.com:6667",
|
||||
Nick: "testbot",
|
||||
Channels: []string{"#test"},
|
||||
}
|
||||
ch, err := NewIRCChannel(bc, cfg, msgBus)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if ch.Name() != "irc" {
|
||||
t.Errorf("Name() = %q, want %q", ch.Name(), "irc")
|
||||
}
|
||||
if ch.IsRunning() {
|
||||
t.Error("new channel should not be running")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestExtractHost(t *testing.T) {
|
||||
tests := []struct {
|
||||
server string
|
||||
want string
|
||||
}{
|
||||
{"irc.libera.chat:6697", "irc.libera.chat"},
|
||||
{"localhost:6667", "localhost"},
|
||||
{"irc.example.com", "irc.example.com"},
|
||||
{"", ""},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.server, func(t *testing.T) {
|
||||
got := extractHost(tt.server)
|
||||
if got != tt.want {
|
||||
t.Errorf("extractHost(%q) = %q, want %q", tt.server, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNickMentionedAt(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
content string
|
||||
nick string
|
||||
want int
|
||||
}{
|
||||
{"colon prefix", "bot: hello", "bot", 0},
|
||||
{"comma prefix", "bot, hello", "bot", 0},
|
||||
{"case insensitive", "BOT: hello", "bot", 0},
|
||||
{"word boundary mid", "hey bot what's up", "bot", 4},
|
||||
{"no mention", "hello world", "bot", -1},
|
||||
{"substring mismatch", "robotics are cool", "bot", -1},
|
||||
{"nick at end", "hello bot", "bot", 6},
|
||||
{"empty content", "", "bot", -1},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := nickMentionedAt(tt.content, tt.nick)
|
||||
if got != tt.want {
|
||||
t.Errorf("nickMentionedAt(%q, %q) = %d, want %d", tt.content, tt.nick, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsBotMentioned(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
content string
|
||||
nick string
|
||||
want bool
|
||||
}{
|
||||
{"colon prefix", "bot: hello", "bot", true},
|
||||
{"comma prefix", "bot, hello", "bot", true},
|
||||
{"case insensitive", "BOT: hello", "bot", true},
|
||||
{"word boundary mid", "hey bot what's up", "bot", true},
|
||||
{"no mention", "hello world", "bot", false},
|
||||
{"substring mismatch", "robotics are cool", "bot", false},
|
||||
{"nick at end", "hello bot", "bot", true},
|
||||
{"empty content", "", "bot", false},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := isBotMentioned(tt.content, tt.nick)
|
||||
if got != tt.want {
|
||||
t.Errorf("isBotMentioned(%q, %q) = %v, want %v", tt.content, tt.nick, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStripBotMention(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
content string
|
||||
nick string
|
||||
want string
|
||||
}{
|
||||
{"colon prefix", "bot: hello there", "bot", "hello there"},
|
||||
{"comma prefix", "bot, help me", "bot", "help me"},
|
||||
{"case insensitive", "BOT: hello", "bot", "hello"},
|
||||
{"no prefix match", "hello bot", "bot", "hello bot"},
|
||||
{"only prefix", "bot:", "bot", ""},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := stripBotMention(tt.content, tt.nick)
|
||||
if got != tt.want {
|
||||
t.Errorf("stripBotMention(%q, %q) = %q, want %q", tt.content, tt.nick, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -68,11 +68,8 @@ type placeholderEntry struct {
|
||||
var channelRateConfig = map[string]float64{
|
||||
"telegram": 20,
|
||||
"discord": 1,
|
||||
"slack": 1,
|
||||
"matrix": 2,
|
||||
"line": 10,
|
||||
"qq": 5,
|
||||
"irc": 2,
|
||||
}
|
||||
|
||||
type channelWorker struct {
|
||||
@@ -1056,18 +1053,12 @@ func (m *Manager) getChannelConfigAndEnabled(channelName string) (*config.Channe
|
||||
return bc, settings.BridgeURL != ""
|
||||
}
|
||||
return bc, channelType == config.ChannelWhatsAppNative && settings.UseNative
|
||||
case *config.MatrixSettings:
|
||||
return bc, settings.Homeserver != "" && settings.UserID != "" && settings.AccessToken.String() != ""
|
||||
case *config.WeComSettings:
|
||||
return bc, settings.BotID != "" && settings.Secret.String() != ""
|
||||
case *config.DingTalkSettings:
|
||||
return bc, settings.ClientID != ""
|
||||
case *config.SlackSettings:
|
||||
return bc, settings.BotToken.String() != ""
|
||||
case *config.WeixinSettings:
|
||||
return bc, settings.Token.String() != ""
|
||||
case *config.IRCSettings:
|
||||
return bc, settings.Server != ""
|
||||
case *config.LINESettings:
|
||||
return bc, settings.ChannelAccessToken.String() != ""
|
||||
case *config.OneBotSettings:
|
||||
@@ -1078,14 +1069,8 @@ func (m *Manager) getChannelConfigAndEnabled(channelName string) (*config.Channe
|
||||
return bc, settings.Token.String() != ""
|
||||
case *config.FeishuSettings:
|
||||
return bc, settings.AppSecret.String() != ""
|
||||
case *config.TeamsWebhookSettings:
|
||||
return bc, true
|
||||
case *config.SlackWebhookSettings:
|
||||
return bc, true
|
||||
case *config.DiscordSettings:
|
||||
return bc, settings.Token.String() != ""
|
||||
case *config.VKSettings:
|
||||
return bc, settings.GroupID != 0 && settings.Token.String() != ""
|
||||
case *config.MQTTSettings:
|
||||
return bc, settings.Broker != "" && settings.AgentID != ""
|
||||
}
|
||||
|
||||
@@ -54,15 +54,6 @@ func hiddenValues(key string, value map[string]any, ch *config.Channel) {
|
||||
if settings, ok := v.(*config.DiscordSettings); ok {
|
||||
value["token"] = settings.Token.String()
|
||||
}
|
||||
case "slack":
|
||||
if settings, ok := v.(*config.SlackSettings); ok {
|
||||
value["bot_token"] = settings.BotToken.String()
|
||||
value["app_token"] = settings.AppToken.String()
|
||||
}
|
||||
case "matrix":
|
||||
if settings, ok := v.(*config.MatrixSettings); ok {
|
||||
value["token"] = settings.AccessToken.String()
|
||||
}
|
||||
case "onebot":
|
||||
if settings, ok := v.(*config.OneBotSettings); ok {
|
||||
value["token"] = settings.AccessToken.String()
|
||||
@@ -84,57 +75,17 @@ func hiddenValues(key string, value map[string]any, ch *config.Channel) {
|
||||
if settings, ok := v.(*config.QQSettings); ok {
|
||||
value["secret"] = settings.AppSecret.String()
|
||||
}
|
||||
case "irc":
|
||||
if settings, ok := v.(*config.IRCSettings); ok {
|
||||
value["password"] = settings.Password.String()
|
||||
value["serv_password"] = settings.NickServPassword.String()
|
||||
value["sasl_password"] = settings.SASLPassword.String()
|
||||
}
|
||||
case "feishu":
|
||||
if settings, ok := v.(*config.FeishuSettings); ok {
|
||||
value["app_secret"] = settings.AppSecret.String()
|
||||
value["encrypt_key"] = settings.EncryptKey.String()
|
||||
value["verification_token"] = settings.VerificationToken.String()
|
||||
}
|
||||
case "teams_webhook":
|
||||
// Expose webhook URLs for hash computation (they contain secrets)
|
||||
vv := value["webhooks"]
|
||||
webhooks := make(map[string]string)
|
||||
if vv != nil {
|
||||
if m, ok := vv.(map[string]string); ok {
|
||||
webhooks = m
|
||||
} else if m, ok := vv.(map[string]any); ok {
|
||||
for k, w := range m {
|
||||
if s, ok := w.(string); ok {
|
||||
webhooks[k] = s
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if settings, ok := v.(*config.TeamsWebhookSettings); ok {
|
||||
for name, target := range settings.Webhooks {
|
||||
webhooks[name] = target.WebhookURL.String()
|
||||
}
|
||||
}
|
||||
value["webhooks"] = webhooks
|
||||
case "mqtt":
|
||||
if settings, ok := v.(*config.MQTTSettings); ok {
|
||||
value["username"] = settings.Username.String()
|
||||
value["password"] = settings.Password.String()
|
||||
}
|
||||
case "slack_webhook":
|
||||
// Expose webhook URLs for hash computation (they contain secrets)
|
||||
if settings, ok := v.(*config.SlackWebhookSettings); ok {
|
||||
webhooks := make(map[string]any)
|
||||
for name, target := range settings.Webhooks {
|
||||
webhooks[name] = map[string]any{
|
||||
"webhook_url": target.WebhookURL.String(),
|
||||
"username": target.Username,
|
||||
"icon_emoji": target.IconEmoji,
|
||||
}
|
||||
}
|
||||
value["webhooks"] = webhooks
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -180,28 +180,3 @@ func TestToChannelHashes_EnabledNotBool(t *testing.T) {
|
||||
h := toChannelHashes(cfg)
|
||||
assert.Equal(t, 0, len(h), "string enabled not treated as true")
|
||||
}
|
||||
|
||||
func TestToChannelHashes_TeamsWebhookWithWebhooks(t *testing.T) {
|
||||
cfg := config.DefaultConfig()
|
||||
// teams_webhook with configured webhooks — this is the real-world
|
||||
// scenario where the map type from JSON unmarshal (map[string]any)
|
||||
// would cause a panic on the old unchecked vv.(map[string]string)
|
||||
settings, _ := json.Marshal(map[string]any{
|
||||
"enabled": true,
|
||||
"webhooks": map[string]any{
|
||||
"hook1": "https://example.com/webhook",
|
||||
},
|
||||
})
|
||||
cfg.Channels["teams_webhook"] = &config.Channel{
|
||||
Enabled: true,
|
||||
Type: config.ChannelTeamsWebHook,
|
||||
Settings: config.RawNode(settings),
|
||||
}
|
||||
|
||||
assert.NotPanics(t, func() {
|
||||
_ = toChannelHashes(cfg)
|
||||
})
|
||||
h := toChannelHashes(cfg)
|
||||
assert.Equal(t, 1, len(h))
|
||||
assert.Contains(t, h, "teams_webhook")
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
package matrix
|
||||
|
||||
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.ChannelMatrix,
|
||||
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.MatrixSettings)
|
||||
if !ok {
|
||||
return nil, channels.ErrSendFailed
|
||||
}
|
||||
cryptoDatabasePath := c.CryptoDatabasePath
|
||||
if cryptoDatabasePath == "" {
|
||||
cryptoDatabasePath = filepath.Join(cfg.WorkspacePath(), "matrix")
|
||||
}
|
||||
ch, err := NewMatrixChannel(bc, c, b, cryptoDatabasePath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if channelName != config.ChannelMatrix {
|
||||
ch.SetName(channelName)
|
||||
}
|
||||
return ch, nil
|
||||
},
|
||||
)
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,506 +0,0 @@
|
||||
package matrix
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"maunium.net/go/mautrix"
|
||||
"maunium.net/go/mautrix/event"
|
||||
"maunium.net/go/mautrix/id"
|
||||
|
||||
"github.com/sipeed/picoclaw/pkg/bus"
|
||||
"github.com/sipeed/picoclaw/pkg/channels"
|
||||
"github.com/sipeed/picoclaw/pkg/config"
|
||||
"github.com/sipeed/picoclaw/pkg/media"
|
||||
)
|
||||
|
||||
func TestMatrixLocalpartMentionRegexp(t *testing.T) {
|
||||
re := localpartMentionRegexp("picoclaw")
|
||||
|
||||
cases := []struct {
|
||||
text string
|
||||
want bool
|
||||
}{
|
||||
{text: "@picoclaw hello", want: true},
|
||||
{text: "hi @picoclaw:matrix.org", want: true},
|
||||
{
|
||||
text: "\u6b22\u8fce\u4e00\u4e0bpicoclaw\u5c0f\u9f99\u867e",
|
||||
want: false, // historical false-positive case in PR #356
|
||||
},
|
||||
{text: "mail test@example.com", want: false},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
if got := re.MatchString(tc.text); got != tc.want {
|
||||
t.Fatalf("text=%q match=%v want=%v", tc.text, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFinalizeTrackedToolFeedbackMessage_StopsTrackingBeforeEdit(t *testing.T) {
|
||||
ch := &MatrixChannel{
|
||||
progress: channels.NewToolFeedbackAnimator(nil),
|
||||
}
|
||||
ch.RecordToolFeedbackMessage("!room:matrix.org", "$event1", "🔧 `read_file`")
|
||||
|
||||
msgIDs, handled := ch.finalizeTrackedToolFeedbackMessage(
|
||||
context.Background(),
|
||||
"!room:matrix.org",
|
||||
"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 != "!room:matrix.org" || messageID != "$event1" || 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 len(msgIDs) != 1 || msgIDs[0] != "$event1" {
|
||||
t.Fatalf("finalizeTrackedToolFeedbackMessage() ids = %v, want [$event1]", msgIDs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFinalizeToolFeedbackMessage_CommandReplyPreservesProgress(t *testing.T) {
|
||||
ch := &MatrixChannel{progress: channels.NewToolFeedbackAnimator(nil)}
|
||||
ch.RecordToolFeedbackMessage("!room:matrix.org", "$progress", "Working")
|
||||
_, handled := ch.FinalizeToolFeedbackMessage(t.Context(), bus.OutboundMessage{
|
||||
ChatID: "!room:matrix.org", 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("!room:matrix.org"); !ok || id != "$progress" {
|
||||
t.Fatal("task progress was removed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStripUserMention(t *testing.T) {
|
||||
userID := id.UserID("@picoclaw:matrix.org")
|
||||
|
||||
cases := []struct {
|
||||
in string
|
||||
want string
|
||||
}{
|
||||
{in: "@picoclaw:matrix.org hello", want: "hello"},
|
||||
{in: "@picoclaw, hello", want: "hello"},
|
||||
{in: "no mention here", want: "no mention here"},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
if got := stripUserMention(tc.in, userID); got != tc.want {
|
||||
t.Fatalf("stripUserMention(%q)=%q want=%q", tc.in, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsBotMentioned(t *testing.T) {
|
||||
ch := &MatrixChannel{
|
||||
client: &mautrix.Client{
|
||||
UserID: id.UserID("@picoclaw:matrix.org"),
|
||||
},
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
msg event.MessageEventContent
|
||||
want bool
|
||||
}{
|
||||
{
|
||||
name: "mentions field",
|
||||
msg: event.MessageEventContent{
|
||||
Body: "hello",
|
||||
Mentions: &event.Mentions{
|
||||
UserIDs: []id.UserID{id.UserID("@picoclaw:matrix.org")},
|
||||
},
|
||||
},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "full user id in body",
|
||||
msg: event.MessageEventContent{
|
||||
Body: "@picoclaw:matrix.org hello",
|
||||
},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "localpart with at sign",
|
||||
msg: event.MessageEventContent{
|
||||
Body: "@picoclaw hello",
|
||||
},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "localpart without at sign should not match",
|
||||
msg: event.MessageEventContent{
|
||||
Body: "\u6b22\u8fce\u4e00\u4e0bpicoclaw\u5c0f\u9f99\u867e",
|
||||
},
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "formatted mention href matrix.to plain",
|
||||
msg: event.MessageEventContent{
|
||||
Body: "hello bot",
|
||||
FormattedBody: `<a href="https://matrix.to/#/@picoclaw:matrix.org">PicoClaw</a> hello`,
|
||||
},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "formatted mention href matrix.to encoded",
|
||||
msg: event.MessageEventContent{
|
||||
Body: "hello bot",
|
||||
FormattedBody: `<a href="https://matrix.to/#/%40picoclaw%3Amatrix.org">PicoClaw</a> hello`,
|
||||
},
|
||||
want: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
if got := ch.isBotMentioned(&tc.msg); got != tc.want {
|
||||
t.Fatalf("%s: got=%v want=%v", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoomKindCache_ExpiresEntries(t *testing.T) {
|
||||
cache := newRoomKindCache(4, 5*time.Second)
|
||||
now := time.Unix(100, 0)
|
||||
cache.set("!room:matrix.org", true, now)
|
||||
|
||||
if got, ok := cache.get("!room:matrix.org", now.Add(2*time.Second)); !ok || !got {
|
||||
t.Fatalf("expected cached group room before ttl, got ok=%v group=%v", ok, got)
|
||||
}
|
||||
|
||||
if _, ok := cache.get("!room:matrix.org", now.Add(6*time.Second)); ok {
|
||||
t.Fatal("expected cache miss after ttl expiry")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoomKindCache_EvictsOldestWhenFull(t *testing.T) {
|
||||
cache := newRoomKindCache(2, time.Minute)
|
||||
now := time.Unix(200, 0)
|
||||
|
||||
cache.set("!room1:matrix.org", false, now)
|
||||
cache.set("!room2:matrix.org", false, now.Add(1*time.Second))
|
||||
cache.set("!room3:matrix.org", true, now.Add(2*time.Second))
|
||||
|
||||
if _, ok := cache.get("!room1:matrix.org", now.Add(2*time.Second)); ok {
|
||||
t.Fatal("expected oldest cache entry to be evicted")
|
||||
}
|
||||
if got, ok := cache.get("!room2:matrix.org", now.Add(2*time.Second)); !ok || got {
|
||||
t.Fatalf("expected room2 to remain and be direct, got ok=%v group=%v", ok, got)
|
||||
}
|
||||
if got, ok := cache.get("!room3:matrix.org", now.Add(2*time.Second)); !ok || !got {
|
||||
t.Fatalf("expected room3 to remain and be group, got ok=%v group=%v", ok, got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatrixMediaTempDir(t *testing.T) {
|
||||
dir, err := matrixMediaTempDir()
|
||||
if err != nil {
|
||||
t.Fatalf("matrixMediaTempDir failed: %v", err)
|
||||
}
|
||||
if filepath.Base(dir) != media.TempDirName {
|
||||
t.Fatalf("unexpected media dir base: %q", filepath.Base(dir))
|
||||
}
|
||||
|
||||
info, err := os.Stat(dir)
|
||||
if err != nil {
|
||||
t.Fatalf("media dir not created: %v", err)
|
||||
}
|
||||
if !info.IsDir() {
|
||||
t.Fatalf("expected directory, got mode=%v", info.Mode())
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatrixMediaExt(t *testing.T) {
|
||||
if got := matrixMediaExt("photo.png", "", "image"); got != ".png" {
|
||||
t.Fatalf("filename extension mismatch: got=%q", got)
|
||||
}
|
||||
if got := matrixMediaExt("", "image/webp", "image"); got != ".webp" {
|
||||
t.Fatalf("content-type extension mismatch: got=%q", got)
|
||||
}
|
||||
if got := matrixMediaExt("", "", "image"); got != ".jpg" {
|
||||
t.Fatalf("default image extension mismatch: got=%q", got)
|
||||
}
|
||||
if got := matrixMediaExt("", "", "audio"); got != ".ogg" {
|
||||
t.Fatalf("default audio extension mismatch: got=%q", got)
|
||||
}
|
||||
if got := matrixMediaExt("", "", "video"); got != ".mp4" {
|
||||
t.Fatalf("default video extension mismatch: got=%q", got)
|
||||
}
|
||||
if got := matrixMediaExt("", "", "file"); got != ".bin" {
|
||||
t.Fatalf("default file extension mismatch: got=%q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownloadMedia_WritesResponseToTempFile(t *testing.T) {
|
||||
const wantBody = "matrix-media-payload"
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if !strings.HasSuffix(r.URL.Path, "/_matrix/client/v1/media/download/matrix.test/abc123") {
|
||||
t.Fatalf("unexpected download path: %s", r.URL.Path)
|
||||
}
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
_, _ = w.Write([]byte(wantBody))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
client, err := mautrix.NewClient(server.URL, id.UserID("@picoclaw:matrix.test"), "")
|
||||
if err != nil {
|
||||
t.Fatalf("NewClient: %v", err)
|
||||
}
|
||||
|
||||
ch := &MatrixChannel{client: client}
|
||||
msg := &event.MessageEventContent{
|
||||
MsgType: event.MsgImage,
|
||||
Body: "image.png",
|
||||
URL: id.ContentURIString("mxc://matrix.test/abc123"),
|
||||
Info: &event.FileInfo{MimeType: "image/png"},
|
||||
}
|
||||
|
||||
path, err := ch.downloadMedia(context.Background(), msg, "image")
|
||||
if err != nil {
|
||||
t.Fatalf("downloadMedia: %v", err)
|
||||
}
|
||||
defer os.Remove(path)
|
||||
|
||||
if ext := filepath.Ext(path); ext != ".png" {
|
||||
t.Fatalf("temp file extension=%q want=.png", ext)
|
||||
}
|
||||
|
||||
got, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatalf("ReadFile: %v", err)
|
||||
}
|
||||
if string(got) != wantBody {
|
||||
t.Fatalf("file contents=%q want=%q", string(got), wantBody)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractInboundContent_ImageNoURLFallback(t *testing.T) {
|
||||
ch := &MatrixChannel{}
|
||||
msg := &event.MessageEventContent{
|
||||
MsgType: event.MsgImage,
|
||||
Body: "test.png",
|
||||
}
|
||||
|
||||
content, mediaRefs, ok := ch.extractInboundContent(context.Background(), msg, "matrix:room:event")
|
||||
if !ok {
|
||||
t.Fatal("expected ok for image fallback")
|
||||
}
|
||||
if content != "[image: test.png]" {
|
||||
t.Fatalf("unexpected content: %q", content)
|
||||
}
|
||||
if len(mediaRefs) != 0 {
|
||||
t.Fatalf("expected no media refs, got %d", len(mediaRefs))
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractInboundContent_AudioNoURLFallback(t *testing.T) {
|
||||
ch := &MatrixChannel{}
|
||||
msg := &event.MessageEventContent{
|
||||
MsgType: event.MsgAudio,
|
||||
FileName: "voice.ogg",
|
||||
Body: "please transcribe",
|
||||
}
|
||||
|
||||
content, mediaRefs, ok := ch.extractInboundContent(context.Background(), msg, "matrix:room:event")
|
||||
if !ok {
|
||||
t.Fatal("expected ok for audio fallback")
|
||||
}
|
||||
if content != "please transcribe\n[audio: voice.ogg]" {
|
||||
t.Fatalf("unexpected content: %q", content)
|
||||
}
|
||||
if len(mediaRefs) != 0 {
|
||||
t.Fatalf("expected no media refs, got %d", len(mediaRefs))
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatrixOutboundMsgType(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
partType string
|
||||
filename string
|
||||
contentType string
|
||||
want event.MessageType
|
||||
}{
|
||||
{name: "explicit image", partType: "image", want: event.MsgImage},
|
||||
{name: "explicit audio", partType: "audio", want: event.MsgAudio},
|
||||
{name: "mime fallback video", contentType: "video/mp4", want: event.MsgVideo},
|
||||
{name: "extension fallback audio", filename: "voice.ogg", want: event.MsgAudio},
|
||||
{name: "unknown defaults file", filename: "report.txt", want: event.MsgFile},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
if got := matrixOutboundMsgType(tc.partType, tc.filename, tc.contentType); got != tc.want {
|
||||
t.Fatalf("%s: got=%q want=%q", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatrixOutboundContent(t *testing.T) {
|
||||
content := matrixOutboundContent(
|
||||
"please review",
|
||||
"voice.ogg",
|
||||
event.MsgAudio,
|
||||
"audio/ogg",
|
||||
1234,
|
||||
id.ContentURIString("mxc://matrix.org/abc"),
|
||||
)
|
||||
if content.Body != "please review" {
|
||||
t.Fatalf("unexpected body: %q", content.Body)
|
||||
}
|
||||
if content.FileName != "voice.ogg" {
|
||||
t.Fatalf("unexpected filename: %q", content.FileName)
|
||||
}
|
||||
if content.Info == nil || content.Info.MimeType != "audio/ogg" {
|
||||
t.Fatalf("unexpected content type: %+v", content.Info)
|
||||
}
|
||||
if content.Info == nil || content.Info.Size != 1234 {
|
||||
t.Fatalf("unexpected size: %+v", content.Info)
|
||||
}
|
||||
|
||||
noCaption := matrixOutboundContent(
|
||||
"",
|
||||
"image.png",
|
||||
event.MsgImage,
|
||||
"image/png",
|
||||
0,
|
||||
id.ContentURIString("mxc://matrix.org/def"),
|
||||
)
|
||||
if noCaption.Body != "image.png" {
|
||||
t.Fatalf("unexpected fallback body: %q", noCaption.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMarkdownToHTML(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
md string
|
||||
rendered string
|
||||
}{
|
||||
{
|
||||
name: "paragraph",
|
||||
md: "just **some** text with _custom_ formatting and `inline` code",
|
||||
rendered: "<p>just <strong>some</strong> text with <em>custom</em> formatting and <code>inline</code> code</p>",
|
||||
},
|
||||
{
|
||||
name: "heading",
|
||||
md: "### Title",
|
||||
rendered: `<h3>Title</h3>`,
|
||||
},
|
||||
{
|
||||
name: "fenced code block",
|
||||
md: "```\nfoo()\n```",
|
||||
rendered: "<pre><code>foo()\n</code></pre>",
|
||||
},
|
||||
{
|
||||
name: "loose list",
|
||||
md: "- Item one\n\n- Item two\n",
|
||||
rendered: `<ul>
|
||||
<li><p>Item one</p></li>
|
||||
|
||||
<li><p>Item two</p></li>
|
||||
</ul>`,
|
||||
},
|
||||
{
|
||||
name: "tight list",
|
||||
md: "- Alpha\n- Beta\n",
|
||||
rendered: `<ul>
|
||||
<li>Alpha</li>
|
||||
<li>Beta</li>
|
||||
</ul>`,
|
||||
},
|
||||
{
|
||||
name: "list item with nested sublist",
|
||||
md: "1. Steps overview:\n\n - Step A\n - Step B\n",
|
||||
rendered: `<ol>
|
||||
<li><p>Steps overview:</p>
|
||||
|
||||
<ul>
|
||||
<li>Step A</li>
|
||||
<li>Step B</li>
|
||||
</ul></li>
|
||||
</ol>`,
|
||||
},
|
||||
{
|
||||
// Definition list syntax is not enabled; the term and definition are
|
||||
// rendered as a plain paragraph rather than <dl>/<dt>/<dd> elements.
|
||||
name: "definition list syntax renders as plain paragraph",
|
||||
md: "Term\n: Definition of the term.\n",
|
||||
rendered: "<p>Term\n: Definition of the term.</p>",
|
||||
},
|
||||
{
|
||||
name: "comprehensive document with headings, paragraphs, list, and code block",
|
||||
md: "# Overview\n\nThis is a sample document designed to demonstrate various Markdown elements in a single block of text.\n\nThe first paragraph introduces the concept of structured data.\n\n## Details\n\nThe following is a list:\n\n* First\n* Second\n* Third\n\nThe second paragraph focuses on details. Below is a generic code snippet:\n\n```python\ndef calculate_area(radius):\n import math\n return math.pi * (radius ** 2)\n```\n\nThis concludes the generic sample text.\n",
|
||||
rendered: `<h1>Overview</h1>
|
||||
|
||||
<p>This is a sample document designed to demonstrate various Markdown elements in a single block of text.</p>
|
||||
|
||||
<p>The first paragraph introduces the concept of structured data.</p>
|
||||
|
||||
<h2>Details</h2>
|
||||
|
||||
<p>The following is a list:</p>
|
||||
|
||||
<ul>
|
||||
<li>First</li>
|
||||
<li>Second</li>
|
||||
<li>Third</li>
|
||||
</ul>
|
||||
|
||||
<p>The second paragraph focuses on details. Below is a generic code snippet:</p>
|
||||
|
||||
<pre><code class="language-python">def calculate_area(radius):
|
||||
import math
|
||||
return math.pi * (radius ** 2)
|
||||
</code></pre>
|
||||
|
||||
<p>This concludes the generic sample text.</p>`,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := markdownToHTML(tc.md); got != tc.rendered {
|
||||
t.Fatalf("markdownToHTML(%q)\n got: %q\nwant: %q", tc.md, got, tc.rendered)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageContent(t *testing.T) {
|
||||
richtext := &MatrixChannel{config: &config.MatrixSettings{MessageFormat: "richtext"}}
|
||||
plain := &MatrixChannel{config: &config.MatrixSettings{MessageFormat: "plain"}}
|
||||
defaultt := &MatrixChannel{config: &config.MatrixSettings{}}
|
||||
|
||||
for _, c := range []*MatrixChannel{richtext, defaultt} {
|
||||
mc := c.messageContent("**hi**")
|
||||
if mc.Format != event.FormatHTML {
|
||||
t.Errorf("format %q: expected FormatHTML, got %q", c.config.MessageFormat, mc.Format)
|
||||
}
|
||||
if !strings.Contains(mc.FormattedBody, "<strong>hi</strong>") {
|
||||
t.Errorf("format %q: FormattedBody %q missing <strong>", c.config.MessageFormat, mc.FormattedBody)
|
||||
}
|
||||
if mc.Body != "**hi**" {
|
||||
t.Errorf("format %q: Body should remain plain, got %q", c.config.MessageFormat, mc.Body)
|
||||
}
|
||||
}
|
||||
|
||||
mc := plain.messageContent("**hi**")
|
||||
if mc.Format != "" || mc.FormattedBody != "" {
|
||||
t.Errorf("plain: expected no formatting, got format=%q formattedBody=%q", mc.Format, mc.FormattedBody)
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
package slack
|
||||
|
||||
import (
|
||||
"github.com/sipeed/picoclaw/pkg/bus"
|
||||
"github.com/sipeed/picoclaw/pkg/channels"
|
||||
"github.com/sipeed/picoclaw/pkg/config"
|
||||
)
|
||||
|
||||
func init() {
|
||||
channels.RegisterFactory(
|
||||
config.ChannelSlack,
|
||||
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.SlackSettings)
|
||||
if !ok {
|
||||
return nil, channels.ErrSendFailed
|
||||
}
|
||||
return NewSlackChannel(bc, c, b)
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -1,633 +0,0 @@
|
||||
package slack
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/slack-go/slack"
|
||||
"github.com/slack-go/slack/slackevents"
|
||||
"github.com/slack-go/slack/socketmode"
|
||||
|
||||
"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"
|
||||
)
|
||||
|
||||
type SlackChannel struct {
|
||||
*channels.BaseChannel
|
||||
config *config.SlackSettings
|
||||
api *slack.Client
|
||||
socketClient *socketmode.Client
|
||||
botUserID string
|
||||
teamID string
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
pendingAcks sync.Map
|
||||
uploadFileFn func(context.Context, slack.UploadFileParameters) error
|
||||
postTextFn func(context.Context, string, string, string) error
|
||||
}
|
||||
|
||||
type slackMessageRef struct {
|
||||
ChannelID string
|
||||
Timestamp string
|
||||
}
|
||||
|
||||
func NewSlackChannel(
|
||||
bc *config.Channel,
|
||||
cfg *config.SlackSettings,
|
||||
messageBus *bus.MessageBus,
|
||||
) (*SlackChannel, error) {
|
||||
if cfg.BotToken.String() == "" || cfg.AppToken.String() == "" {
|
||||
return nil, fmt.Errorf("slack bot_token and app_token are required")
|
||||
}
|
||||
|
||||
api := slack.New(
|
||||
cfg.BotToken.String(),
|
||||
slack.OptionAppLevelToken(cfg.AppToken.String()),
|
||||
)
|
||||
|
||||
socketClient := socketmode.New(api)
|
||||
|
||||
base := channels.NewBaseChannel("slack", cfg, messageBus, bc.AllowFrom,
|
||||
channels.WithMaxMessageLength(40000),
|
||||
channels.WithGroupTrigger(bc.GroupTrigger),
|
||||
channels.WithReasoningChannelID(bc.ReasoningChannelID),
|
||||
)
|
||||
|
||||
return &SlackChannel{
|
||||
BaseChannel: base,
|
||||
config: cfg,
|
||||
api: api,
|
||||
socketClient: socketClient,
|
||||
uploadFileFn: func(ctx context.Context, params slack.UploadFileParameters) error {
|
||||
_, err := api.UploadFileContext(ctx, params)
|
||||
return err
|
||||
},
|
||||
postTextFn: func(ctx context.Context, channelID, threadTS, text string) error {
|
||||
opts := []slack.MsgOption{slack.MsgOptionText(text, false)}
|
||||
if threadTS != "" {
|
||||
opts = append(opts, slack.MsgOptionTS(threadTS))
|
||||
}
|
||||
_, _, err := api.PostMessageContext(ctx, channelID, opts...)
|
||||
return err
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *SlackChannel) Start(ctx context.Context) error {
|
||||
logger.InfoC("slack", "Starting Slack channel (Socket Mode)")
|
||||
|
||||
c.ctx, c.cancel = context.WithCancel(ctx)
|
||||
|
||||
authResp, err := c.api.AuthTest()
|
||||
if err != nil {
|
||||
return fmt.Errorf("slack auth test failed: %w", err)
|
||||
}
|
||||
c.botUserID = authResp.UserID
|
||||
c.teamID = authResp.TeamID
|
||||
|
||||
logger.InfoCF("slack", "Slack bot connected", map[string]any{
|
||||
"bot_user_id": c.botUserID,
|
||||
"team": authResp.Team,
|
||||
})
|
||||
|
||||
go c.eventLoop()
|
||||
|
||||
go func() {
|
||||
if err := c.socketClient.RunContext(c.ctx); err != nil {
|
||||
if c.ctx.Err() == nil {
|
||||
logger.ErrorCF("slack", "Socket Mode connection error", map[string]any{
|
||||
"error": err.Error(),
|
||||
})
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
c.SetRunning(true)
|
||||
logger.InfoC("slack", "Slack channel started (Socket Mode)")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *SlackChannel) Stop(ctx context.Context) error {
|
||||
logger.InfoC("slack", "Stopping Slack channel")
|
||||
|
||||
if c.cancel != nil {
|
||||
c.cancel()
|
||||
}
|
||||
|
||||
c.SetRunning(false)
|
||||
logger.InfoC("slack", "Slack channel stopped")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *SlackChannel) Send(ctx context.Context, msg bus.OutboundMessage) ([]string, error) {
|
||||
if !c.IsRunning() {
|
||||
return nil, channels.ErrNotRunning
|
||||
}
|
||||
|
||||
deliveryChatID, channelID, threadTS := resolveSlackOutboundTarget(msg.ChatID, &msg.Context)
|
||||
if channelID == "" {
|
||||
return nil, fmt.Errorf("invalid slack chat ID: %s", msg.ChatID)
|
||||
}
|
||||
|
||||
opts := []slack.MsgOption{
|
||||
slack.MsgOptionText(msg.Content, false),
|
||||
}
|
||||
|
||||
if msg.ReplyToMessageID != "" && threadTS == "" {
|
||||
// Answer to the message by creating a Thread under it
|
||||
opts = append(opts, slack.MsgOptionTS(msg.ReplyToMessageID))
|
||||
} else if threadTS != "" {
|
||||
// If we are already in a thread, continue in the thread
|
||||
opts = append(opts, slack.MsgOptionTS(threadTS))
|
||||
}
|
||||
|
||||
_, ts, err := c.api.PostMessageContext(ctx, channelID, opts...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("slack send: %w", channels.ErrTemporary)
|
||||
}
|
||||
|
||||
if ref, ok := c.pendingAcks.LoadAndDelete(deliveryChatID); ok {
|
||||
msgRef, ok := ref.(slackMessageRef)
|
||||
if !ok {
|
||||
return []string{ts}, nil
|
||||
}
|
||||
c.api.AddReaction("white_check_mark", slack.ItemRef{
|
||||
Channel: msgRef.ChannelID,
|
||||
Timestamp: msgRef.Timestamp,
|
||||
})
|
||||
}
|
||||
|
||||
logger.DebugCF("slack", "Message sent", map[string]any{
|
||||
"channel_id": channelID,
|
||||
"thread_ts": threadTS,
|
||||
})
|
||||
|
||||
return []string{ts}, nil
|
||||
}
|
||||
|
||||
// SendMedia implements the channels.MediaSender interface.
|
||||
func (c *SlackChannel) SendMedia(ctx context.Context, msg bus.OutboundMediaMessage) ([]string, error) {
|
||||
if !c.IsRunning() {
|
||||
return nil, channels.ErrNotRunning
|
||||
}
|
||||
|
||||
_, channelID, threadTS := resolveSlackMediaOutboundTarget(msg.ChatID, &msg.Context)
|
||||
if channelID == "" {
|
||||
return nil, fmt.Errorf("invalid slack chat ID: %s", msg.ChatID)
|
||||
}
|
||||
|
||||
store := c.GetMediaStore()
|
||||
if store == nil {
|
||||
return nil, fmt.Errorf("no media store available: %w", channels.ErrSendFailed)
|
||||
}
|
||||
|
||||
caption := slackFirstMediaCaption(msg.Parts)
|
||||
sentAny := false
|
||||
for _, part := range msg.Parts {
|
||||
localPath, err := store.Resolve(part.Ref)
|
||||
if err != nil {
|
||||
logger.ErrorCF("slack", "Failed to resolve media ref", map[string]any{
|
||||
"ref": part.Ref,
|
||||
"error": err.Error(),
|
||||
})
|
||||
continue
|
||||
}
|
||||
|
||||
filename := part.Filename
|
||||
if filename == "" {
|
||||
filename = "file"
|
||||
}
|
||||
|
||||
title := part.Caption
|
||||
if title == "" {
|
||||
title = filename
|
||||
}
|
||||
|
||||
err = c.uploadFileFn(ctx, slack.UploadFileParameters{
|
||||
Channel: channelID,
|
||||
ThreadTimestamp: threadTS,
|
||||
File: localPath,
|
||||
Filename: filename,
|
||||
Title: title,
|
||||
})
|
||||
if err != nil {
|
||||
logger.ErrorCF("slack", "Failed to upload media", map[string]any{
|
||||
"filename": filename,
|
||||
"error": err.Error(),
|
||||
})
|
||||
return nil, fmt.Errorf("slack send media: %w", channels.ErrTemporary)
|
||||
}
|
||||
sentAny = true
|
||||
}
|
||||
|
||||
if sentAny && caption != "" {
|
||||
if err := c.postTextFn(ctx, channelID, threadTS, caption); err != nil {
|
||||
return nil, fmt.Errorf("slack send media caption fallback: %w", channels.ErrTemporary)
|
||||
}
|
||||
}
|
||||
|
||||
// UploadFile does not expose the posted message timestamp in its
|
||||
// response; returning nil avoids conflating file IDs with message IDs.
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func slackFirstMediaCaption(parts []bus.MediaPart) string {
|
||||
for _, part := range parts {
|
||||
if caption := strings.TrimSpace(part.Caption); caption != "" {
|
||||
return caption
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// ReactToMessage implements channels.ReactionCapable.
|
||||
// It adds an "eyes" (👀) reaction to the inbound message and returns an undo function
|
||||
// that removes the reaction.
|
||||
func (c *SlackChannel) ReactToMessage(ctx context.Context, chatID, messageID string) (func(), error) {
|
||||
channelID, _ := parseSlackChatID(chatID)
|
||||
if channelID == "" {
|
||||
return func() {}, nil
|
||||
}
|
||||
|
||||
c.api.AddReaction("eyes", slack.ItemRef{
|
||||
Channel: channelID,
|
||||
Timestamp: messageID,
|
||||
})
|
||||
|
||||
return func() {
|
||||
c.api.RemoveReaction("eyes", slack.ItemRef{
|
||||
Channel: channelID,
|
||||
Timestamp: messageID,
|
||||
})
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *SlackChannel) eventLoop() {
|
||||
for {
|
||||
select {
|
||||
case <-c.ctx.Done():
|
||||
return
|
||||
case event, ok := <-c.socketClient.Events:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
switch event.Type {
|
||||
case socketmode.EventTypeEventsAPI:
|
||||
c.handleEventsAPI(event)
|
||||
case socketmode.EventTypeSlashCommand:
|
||||
c.handleSlashCommand(event)
|
||||
case socketmode.EventTypeInteractive:
|
||||
if event.Request != nil {
|
||||
c.socketClient.Ack(*event.Request)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *SlackChannel) handleEventsAPI(event socketmode.Event) {
|
||||
if event.Request != nil {
|
||||
c.socketClient.Ack(*event.Request)
|
||||
}
|
||||
|
||||
eventsAPIEvent, ok := event.Data.(slackevents.EventsAPIEvent)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
switch ev := eventsAPIEvent.InnerEvent.Data.(type) {
|
||||
case *slackevents.MessageEvent:
|
||||
c.handleMessageEvent(ev)
|
||||
case *slackevents.AppMentionEvent:
|
||||
c.handleAppMention(ev)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *SlackChannel) handleMessageEvent(ev *slackevents.MessageEvent) {
|
||||
if ev.User == c.botUserID || ev.User == "" {
|
||||
return
|
||||
}
|
||||
if ev.BotID != "" {
|
||||
return
|
||||
}
|
||||
if ev.SubType != "" && ev.SubType != "file_share" {
|
||||
return
|
||||
}
|
||||
|
||||
// check allowlist to avoid downloading attachments for rejected users
|
||||
sender := bus.SenderInfo{
|
||||
Platform: "slack",
|
||||
PlatformID: ev.User,
|
||||
CanonicalID: identity.BuildCanonicalID("slack", ev.User),
|
||||
}
|
||||
if !c.IsAllowedSender(sender) {
|
||||
logger.DebugCF("slack", "Message rejected by allowlist", map[string]any{
|
||||
"user_id": ev.User,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
senderID := ev.User
|
||||
channelID := ev.Channel
|
||||
threadTS := ev.ThreadTimeStamp
|
||||
messageTS := ev.TimeStamp
|
||||
|
||||
chatID := channelID
|
||||
if threadTS != "" {
|
||||
chatID = channelID + "/" + threadTS
|
||||
}
|
||||
|
||||
c.pendingAcks.Store(chatID, slackMessageRef{
|
||||
ChannelID: channelID,
|
||||
Timestamp: messageTS,
|
||||
})
|
||||
|
||||
content := ev.Text
|
||||
content = c.stripBotMention(content)
|
||||
|
||||
// In non-DM channels, apply group trigger filtering
|
||||
if !strings.HasPrefix(channelID, "D") {
|
||||
respond, cleaned := c.ShouldRespondInGroup(false, content)
|
||||
if !respond {
|
||||
return
|
||||
}
|
||||
content = cleaned
|
||||
}
|
||||
|
||||
var mediaPaths []string
|
||||
|
||||
scope := channels.BuildMediaScope("slack", chatID, messageTS)
|
||||
|
||||
// Helper to register a local file with the media store
|
||||
storeMedia := func(localPath, filename string) string {
|
||||
if store := c.GetMediaStore(); store != nil {
|
||||
ref, err := store.Store(localPath, media.MediaMeta{
|
||||
Filename: filename,
|
||||
Source: "slack",
|
||||
CleanupPolicy: media.CleanupPolicyDeleteOnCleanup,
|
||||
}, scope)
|
||||
if err == nil {
|
||||
return ref
|
||||
}
|
||||
}
|
||||
return localPath // fallback
|
||||
}
|
||||
|
||||
if ev.Message != nil && len(ev.Message.Files) > 0 {
|
||||
for _, file := range ev.Message.Files {
|
||||
localPath := c.downloadSlackFile(file)
|
||||
if localPath == "" {
|
||||
continue
|
||||
}
|
||||
mediaPaths = append(mediaPaths, storeMedia(localPath, file.Name))
|
||||
content += fmt.Sprintf("\n[file: %s]", file.Name)
|
||||
}
|
||||
}
|
||||
|
||||
if strings.TrimSpace(content) == "" {
|
||||
return
|
||||
}
|
||||
|
||||
peerKind := "channel"
|
||||
if strings.HasPrefix(channelID, "D") {
|
||||
peerKind = "direct"
|
||||
}
|
||||
|
||||
metadata := map[string]string{
|
||||
"message_ts": messageTS,
|
||||
"channel_id": channelID,
|
||||
"thread_ts": threadTS,
|
||||
"platform": "slack",
|
||||
"team_id": c.teamID,
|
||||
}
|
||||
|
||||
logger.DebugCF("slack", "Received message", map[string]any{
|
||||
"sender_id": senderID,
|
||||
"chat_id": chatID,
|
||||
"preview": utils.Truncate(content, 50),
|
||||
"has_thread": threadTS != "",
|
||||
})
|
||||
|
||||
inboundCtx := bus.InboundContext{
|
||||
Channel: c.Name(),
|
||||
Account: c.teamID,
|
||||
ChatID: channelID,
|
||||
ChatType: peerKind,
|
||||
SenderID: senderID,
|
||||
MessageID: messageTS,
|
||||
SpaceID: c.teamID,
|
||||
SpaceType: "workspace",
|
||||
Raw: metadata,
|
||||
}
|
||||
if threadTS != "" {
|
||||
inboundCtx.TopicID = threadTS
|
||||
}
|
||||
|
||||
c.HandleInboundContext(c.ctx, chatID, content, mediaPaths, inboundCtx, sender)
|
||||
}
|
||||
|
||||
func (c *SlackChannel) handleAppMention(ev *slackevents.AppMentionEvent) {
|
||||
if ev.User == c.botUserID {
|
||||
return
|
||||
}
|
||||
|
||||
if !c.IsAllowedSender(bus.SenderInfo{
|
||||
Platform: "slack",
|
||||
PlatformID: ev.User,
|
||||
CanonicalID: identity.BuildCanonicalID("slack", ev.User),
|
||||
}) {
|
||||
logger.DebugCF("slack", "Mention rejected by allowlist", map[string]any{
|
||||
"user_id": ev.User,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
senderID := ev.User
|
||||
mentionSender := bus.SenderInfo{
|
||||
Platform: "slack",
|
||||
PlatformID: senderID,
|
||||
CanonicalID: identity.BuildCanonicalID("slack", senderID),
|
||||
}
|
||||
channelID := ev.Channel
|
||||
threadTS := ev.ThreadTimeStamp
|
||||
messageTS := ev.TimeStamp
|
||||
|
||||
var chatID string
|
||||
if threadTS != "" {
|
||||
chatID = channelID + "/" + threadTS
|
||||
} else {
|
||||
chatID = channelID + "/" + messageTS
|
||||
}
|
||||
|
||||
c.pendingAcks.Store(chatID, slackMessageRef{
|
||||
ChannelID: channelID,
|
||||
Timestamp: messageTS,
|
||||
})
|
||||
|
||||
content := c.stripBotMention(ev.Text)
|
||||
|
||||
if strings.TrimSpace(content) == "" {
|
||||
return
|
||||
}
|
||||
|
||||
mentionPeerKind := "channel"
|
||||
if strings.HasPrefix(channelID, "D") {
|
||||
mentionPeerKind = "direct"
|
||||
}
|
||||
|
||||
metadata := map[string]string{
|
||||
"message_ts": messageTS,
|
||||
"channel_id": channelID,
|
||||
"thread_ts": threadTS,
|
||||
"platform": "slack",
|
||||
"is_mention": "true",
|
||||
"team_id": c.teamID,
|
||||
}
|
||||
inboundCtx := bus.InboundContext{
|
||||
Channel: c.Name(),
|
||||
Account: c.teamID,
|
||||
ChatID: channelID,
|
||||
ChatType: mentionPeerKind,
|
||||
TopicID: threadTS,
|
||||
SenderID: senderID,
|
||||
MessageID: messageTS,
|
||||
SpaceID: c.teamID,
|
||||
SpaceType: "workspace",
|
||||
Mentioned: true,
|
||||
Raw: metadata,
|
||||
}
|
||||
|
||||
c.HandleInboundContext(c.ctx, chatID, content, nil, inboundCtx, mentionSender)
|
||||
}
|
||||
|
||||
func (c *SlackChannel) handleSlashCommand(event socketmode.Event) {
|
||||
cmd, ok := event.Data.(slack.SlashCommand)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
if event.Request != nil {
|
||||
c.socketClient.Ack(*event.Request)
|
||||
}
|
||||
|
||||
cmdSender := bus.SenderInfo{
|
||||
Platform: "slack",
|
||||
PlatformID: cmd.UserID,
|
||||
CanonicalID: identity.BuildCanonicalID("slack", cmd.UserID),
|
||||
}
|
||||
if !c.IsAllowedSender(cmdSender) {
|
||||
logger.DebugCF("slack", "Slash command rejected by allowlist", map[string]any{
|
||||
"user_id": cmd.UserID,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
senderID := cmd.UserID
|
||||
channelID := cmd.ChannelID
|
||||
chatID := channelID
|
||||
content := cmd.Text
|
||||
|
||||
if strings.TrimSpace(content) == "" {
|
||||
content = "help"
|
||||
}
|
||||
|
||||
metadata := map[string]string{
|
||||
"channel_id": channelID,
|
||||
"platform": "slack",
|
||||
"is_command": "true",
|
||||
"trigger_id": cmd.TriggerID,
|
||||
"team_id": c.teamID,
|
||||
}
|
||||
|
||||
logger.DebugCF("slack", "Slash command received", map[string]any{
|
||||
"sender_id": senderID,
|
||||
"command": cmd.Command,
|
||||
"text": utils.Truncate(content, 50),
|
||||
})
|
||||
peerKind := "channel"
|
||||
if strings.HasPrefix(channelID, "D") {
|
||||
peerKind = "direct"
|
||||
}
|
||||
inboundCtx := bus.InboundContext{
|
||||
Channel: c.Name(),
|
||||
Account: c.teamID,
|
||||
ChatID: channelID,
|
||||
ChatType: peerKind,
|
||||
SenderID: senderID,
|
||||
SpaceID: c.teamID,
|
||||
SpaceType: "workspace",
|
||||
Raw: metadata,
|
||||
}
|
||||
|
||||
c.HandleInboundContext(c.ctx, chatID, content, nil, inboundCtx, cmdSender)
|
||||
}
|
||||
|
||||
func (c *SlackChannel) downloadSlackFile(file slack.File) string {
|
||||
downloadURL := file.URLPrivateDownload
|
||||
if downloadURL == "" {
|
||||
downloadURL = file.URLPrivate
|
||||
}
|
||||
if downloadURL == "" {
|
||||
logger.ErrorCF("slack", "No download URL for file", map[string]any{"file_id": file.ID})
|
||||
return ""
|
||||
}
|
||||
|
||||
return utils.DownloadFile(downloadURL, file.Name, utils.DownloadOptions{
|
||||
LoggerPrefix: "slack",
|
||||
ExtraHeaders: map[string]string{
|
||||
"Authorization": "Bearer " + c.config.BotToken.String(),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (c *SlackChannel) stripBotMention(text string) string {
|
||||
mention := fmt.Sprintf("<@%s>", c.botUserID)
|
||||
text = strings.ReplaceAll(text, mention, "")
|
||||
return strings.TrimSpace(text)
|
||||
}
|
||||
|
||||
func parseSlackChatID(chatID string) (channelID, threadTS string) {
|
||||
parts := strings.SplitN(chatID, "/", 2)
|
||||
channelID = parts[0]
|
||||
if len(parts) > 1 {
|
||||
threadTS = parts[1]
|
||||
}
|
||||
return channelID, threadTS
|
||||
}
|
||||
|
||||
func resolveSlackOutboundTarget(chatID string, outboundCtx *bus.InboundContext) (string, string, string) {
|
||||
deliveryChatID := strings.TrimSpace(chatID)
|
||||
if deliveryChatID == "" && outboundCtx != nil {
|
||||
deliveryChatID = strings.TrimSpace(outboundCtx.ChatID)
|
||||
}
|
||||
channelID, threadTS := parseSlackChatID(deliveryChatID)
|
||||
if threadTS == "" && outboundCtx != nil {
|
||||
threadTS = strings.TrimSpace(outboundCtx.TopicID)
|
||||
if threadTS != "" && channelID != "" {
|
||||
deliveryChatID = channelID + "/" + threadTS
|
||||
}
|
||||
}
|
||||
return deliveryChatID, channelID, threadTS
|
||||
}
|
||||
|
||||
func resolveSlackMediaOutboundTarget(chatID string, outboundCtx *bus.InboundContext) (string, string, string) {
|
||||
deliveryChatID := strings.TrimSpace(chatID)
|
||||
if deliveryChatID == "" && outboundCtx != nil {
|
||||
deliveryChatID = strings.TrimSpace(outboundCtx.ChatID)
|
||||
}
|
||||
channelID, threadTS := parseSlackChatID(deliveryChatID)
|
||||
if threadTS == "" && outboundCtx != nil {
|
||||
threadTS = strings.TrimSpace(outboundCtx.TopicID)
|
||||
if threadTS != "" && channelID != "" {
|
||||
deliveryChatID = channelID + "/" + threadTS
|
||||
}
|
||||
}
|
||||
return deliveryChatID, channelID, threadTS
|
||||
}
|
||||
@@ -1,264 +0,0 @@
|
||||
package slack
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
slacksdk "github.com/slack-go/slack"
|
||||
|
||||
"github.com/sipeed/picoclaw/pkg/bus"
|
||||
"github.com/sipeed/picoclaw/pkg/channels"
|
||||
"github.com/sipeed/picoclaw/pkg/config"
|
||||
"github.com/sipeed/picoclaw/pkg/media"
|
||||
)
|
||||
|
||||
func TestParseSlackChatID(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
chatID string
|
||||
wantChanID string
|
||||
wantThread string
|
||||
}{
|
||||
{
|
||||
name: "channel only",
|
||||
chatID: "C123456",
|
||||
wantChanID: "C123456",
|
||||
wantThread: "",
|
||||
},
|
||||
{
|
||||
name: "channel with thread",
|
||||
chatID: "C123456/1234567890.123456",
|
||||
wantChanID: "C123456",
|
||||
wantThread: "1234567890.123456",
|
||||
},
|
||||
{
|
||||
name: "DM channel",
|
||||
chatID: "D987654",
|
||||
wantChanID: "D987654",
|
||||
wantThread: "",
|
||||
},
|
||||
{
|
||||
name: "empty string",
|
||||
chatID: "",
|
||||
wantChanID: "",
|
||||
wantThread: "",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
chanID, threadTS := parseSlackChatID(tt.chatID)
|
||||
if chanID != tt.wantChanID {
|
||||
t.Errorf("parseSlackChatID(%q) channelID = %q, want %q", tt.chatID, chanID, tt.wantChanID)
|
||||
}
|
||||
if threadTS != tt.wantThread {
|
||||
t.Errorf("parseSlackChatID(%q) threadTS = %q, want %q", tt.chatID, threadTS, tt.wantThread)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveSlackOutboundTarget_PrefersContextTopicID(t *testing.T) {
|
||||
deliveryChatID, channelID, threadTS := resolveSlackOutboundTarget("C123456", &bus.InboundContext{
|
||||
Channel: "slack",
|
||||
ChatID: "C123456",
|
||||
TopicID: "1234567890.123456",
|
||||
})
|
||||
|
||||
if deliveryChatID != "C123456/1234567890.123456" {
|
||||
t.Fatalf("deliveryChatID = %q, want %q", deliveryChatID, "C123456/1234567890.123456")
|
||||
}
|
||||
if channelID != "C123456" {
|
||||
t.Fatalf("channelID = %q, want %q", channelID, "C123456")
|
||||
}
|
||||
if threadTS != "1234567890.123456" {
|
||||
t.Fatalf("threadTS = %q, want %q", threadTS, "1234567890.123456")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStripBotMention(t *testing.T) {
|
||||
ch := &SlackChannel{botUserID: "U12345BOT"}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "mention at start",
|
||||
input: "<@U12345BOT> hello there",
|
||||
want: "hello there",
|
||||
},
|
||||
{
|
||||
name: "mention in middle",
|
||||
input: "hey <@U12345BOT> can you help",
|
||||
want: "hey can you help",
|
||||
},
|
||||
{
|
||||
name: "no mention",
|
||||
input: "hello world",
|
||||
want: "hello world",
|
||||
},
|
||||
{
|
||||
name: "empty string",
|
||||
input: "",
|
||||
want: "",
|
||||
},
|
||||
{
|
||||
name: "only mention",
|
||||
input: "<@U12345BOT>",
|
||||
want: "",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := ch.stripBotMention(tt.input)
|
||||
if got != tt.want {
|
||||
t.Errorf("stripBotMention(%q) = %q, want %q", tt.input, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewSlackChannel(t *testing.T) {
|
||||
msgBus := bus.NewMessageBus()
|
||||
bc := &config.Channel{Type: "slack", Enabled: true}
|
||||
|
||||
t.Run("missing bot token", func(t *testing.T) {
|
||||
cfg := &config.SlackSettings{}
|
||||
cfg.AppToken = *config.NewSecureString("xapp-test")
|
||||
_, err := NewSlackChannel(bc, cfg, msgBus)
|
||||
if err == nil {
|
||||
t.Error("expected error for missing bot_token, got nil")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("missing app token", func(t *testing.T) {
|
||||
cfg := &config.SlackSettings{}
|
||||
cfg.BotToken = *config.NewSecureString("xoxb-test")
|
||||
_, err := NewSlackChannel(bc, cfg, msgBus)
|
||||
if err == nil {
|
||||
t.Error("expected error for missing app_token, got nil")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("valid config", func(t *testing.T) {
|
||||
cfg := &config.SlackSettings{}
|
||||
cfg.BotToken = *config.NewSecureString("xoxb-test")
|
||||
cfg.AppToken = *config.NewSecureString("xapp-test")
|
||||
bc := &config.Channel{Type: "slack", Enabled: true, AllowFrom: []string{"U123"}}
|
||||
ch, err := NewSlackChannel(bc, cfg, msgBus)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if ch.Name() != "slack" {
|
||||
t.Errorf("Name() = %q, want %q", ch.Name(), "slack")
|
||||
}
|
||||
if ch.IsRunning() {
|
||||
t.Error("new channel should not be running")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestSlackChannelIsAllowed(t *testing.T) {
|
||||
msgBus := bus.NewMessageBus()
|
||||
|
||||
t.Run("empty allowlist allows all", func(t *testing.T) {
|
||||
bc := &config.Channel{Type: config.ChannelSlack, Enabled: true, AllowFrom: []string{}}
|
||||
cfg := &config.SlackSettings{}
|
||||
cfg.BotToken = *config.NewSecureString("xoxb-test")
|
||||
cfg.AppToken = *config.NewSecureString("xapp-test")
|
||||
ch, _ := NewSlackChannel(bc, cfg, msgBus)
|
||||
if !ch.IsAllowed("U_ANYONE") {
|
||||
t.Error("empty allowlist should allow all users")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("allowlist restricts users", func(t *testing.T) {
|
||||
bc := &config.Channel{Type: config.ChannelSlack, Enabled: true, AllowFrom: []string{"U_ALLOWED"}}
|
||||
cfg := &config.SlackSettings{}
|
||||
cfg.BotToken = *config.NewSecureString("xoxb-test")
|
||||
cfg.AppToken = *config.NewSecureString("xapp-test")
|
||||
ch, _ := NewSlackChannel(bc, cfg, msgBus)
|
||||
if !ch.IsAllowed("U_ALLOWED") {
|
||||
t.Error("allowed user should pass allowlist check")
|
||||
}
|
||||
if ch.IsAllowed("U_BLOCKED") {
|
||||
t.Error("non-allowed user should be blocked")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestSendMedia_SendsCaptionFallbackAfterUploads(t *testing.T) {
|
||||
ch := &SlackChannel{
|
||||
BaseChannel: channels.NewBaseChannel("slack", nil, nil, nil),
|
||||
}
|
||||
ch.SetRunning(true)
|
||||
|
||||
store := media.NewFileMediaStore()
|
||||
ch.SetMediaStore(store)
|
||||
|
||||
tmpDir := t.TempDir()
|
||||
localPath := filepath.Join(tmpDir, "report.txt")
|
||||
if err := os.WriteFile(localPath, []byte("attachment body"), 0o600); err != nil {
|
||||
t.Fatalf("WriteFile() error = %v", err)
|
||||
}
|
||||
ref, err := store.Store(localPath, media.MediaMeta{
|
||||
Filename: "report.txt",
|
||||
ContentType: "text/plain",
|
||||
}, "test-scope")
|
||||
if err != nil {
|
||||
t.Fatalf("Store() error = %v", err)
|
||||
}
|
||||
|
||||
var uploaded []slackUploadRecord
|
||||
var posted []string
|
||||
ch.uploadFileFn = func(ctx context.Context, params slacksdk.UploadFileParameters) error {
|
||||
uploaded = append(uploaded, slackUploadRecord{
|
||||
Channel: params.Channel,
|
||||
Thread: params.ThreadTimestamp,
|
||||
File: params.File,
|
||||
Name: params.Filename,
|
||||
Title: params.Title,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
ch.postTextFn = func(ctx context.Context, channelID, threadTS, text string) error {
|
||||
posted = append(posted, channelID+"|"+threadTS+"|"+text)
|
||||
return nil
|
||||
}
|
||||
|
||||
_, err = ch.SendMedia(context.Background(), bus.OutboundMediaMessage{
|
||||
ChatID: "C123456/1234567890.123456",
|
||||
Parts: []bus.MediaPart{{
|
||||
Ref: ref,
|
||||
Type: "file",
|
||||
Filename: "report.txt",
|
||||
ContentType: "text/plain",
|
||||
Caption: "shared caption",
|
||||
}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("SendMedia() error = %v", err)
|
||||
}
|
||||
if len(uploaded) != 1 {
|
||||
t.Fatalf("uploads = %v, want 1 upload", uploaded)
|
||||
}
|
||||
if uploaded[0].Title != "shared caption" {
|
||||
t.Fatalf("upload title = %q, want shared caption", uploaded[0].Title)
|
||||
}
|
||||
if len(posted) != 1 || posted[0] != "C123456|1234567890.123456|shared caption" {
|
||||
t.Fatalf("posted = %v, want fallback text in same thread", posted)
|
||||
}
|
||||
}
|
||||
|
||||
type slackUploadRecord struct {
|
||||
Channel string
|
||||
Thread string
|
||||
File string
|
||||
Name string
|
||||
Title string
|
||||
}
|
||||
@@ -1,263 +0,0 @@
|
||||
package slackwebhook
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const maxTableRowWidth = 60
|
||||
|
||||
var (
|
||||
boldRe = regexp.MustCompile(`\*\*([^*]+)\*\*`)
|
||||
strikeRe = regexp.MustCompile(`~~([^~]+)~~`)
|
||||
linkRe = regexp.MustCompile(`\[([^\]]+)\]\(([^)]+)\)`)
|
||||
headerRe = regexp.MustCompile(`(?m)^#{1,6}\s+(.+)$`)
|
||||
bulletRe = regexp.MustCompile(`(?m)^- (.+)$`)
|
||||
markdownTableRe = regexp.MustCompile(`(?m)^(\|[^\n]+\|)\n(\|[-:\|\s]+\|)\n((?:\|[^\n]+\|\n?)+)`)
|
||||
codeBlockRe = regexp.MustCompile("(?s)```.*?```")
|
||||
inlineCodeRe = regexp.MustCompile("`[^`]+`")
|
||||
italicRe = regexp.MustCompile(`(?:^|[^*])\*([^*]+)\*(?:[^*]|$)`)
|
||||
)
|
||||
|
||||
type contentSegment struct {
|
||||
content string
|
||||
isTable bool
|
||||
}
|
||||
|
||||
func convertMarkdownToMrkdwn(text string) string {
|
||||
// Protect code blocks from conversion
|
||||
var codeBlocks []string
|
||||
text = codeBlockRe.ReplaceAllStringFunc(text, func(match string) string {
|
||||
codeBlocks = append(codeBlocks, match)
|
||||
return "\x00CODEBLOCK\x00"
|
||||
})
|
||||
|
||||
// Protect inline code
|
||||
var inlineCode []string
|
||||
text = inlineCodeRe.ReplaceAllStringFunc(text, func(match string) string {
|
||||
inlineCode = append(inlineCode, match)
|
||||
return "\x00INLINE\x00"
|
||||
})
|
||||
|
||||
// Convert italic *text* → _text_ BEFORE bold conversion
|
||||
text = italicRe.ReplaceAllStringFunc(text, func(match string) string {
|
||||
// Find the asterisk positions
|
||||
firstAsterisk := strings.Index(match, "*")
|
||||
lastAsterisk := strings.LastIndex(match, "*")
|
||||
if firstAsterisk == lastAsterisk {
|
||||
return match // Only one asterisk, not italic
|
||||
}
|
||||
|
||||
// Extract content between asterisks
|
||||
content := match[firstAsterisk+1 : lastAsterisk]
|
||||
|
||||
// Replace with underscores, preserving any prefix/suffix
|
||||
return match[:firstAsterisk] + "_" + content + "_" + match[lastAsterisk+1:]
|
||||
})
|
||||
|
||||
// Convert bold **text** → *text*
|
||||
text = boldRe.ReplaceAllString(text, "*$1*")
|
||||
|
||||
// Convert strikethrough ~~text~~ → ~text~
|
||||
text = strikeRe.ReplaceAllString(text, "~$1~")
|
||||
|
||||
// Convert links [text](url) → <url|text>
|
||||
text = linkRe.ReplaceAllString(text, "<$2|$1>")
|
||||
|
||||
// Convert headers # text → *text*
|
||||
text = headerRe.ReplaceAllString(text, "*$1*")
|
||||
|
||||
// Convert bullet lists - item → • item
|
||||
text = bulletRe.ReplaceAllString(text, "• $1")
|
||||
|
||||
// Restore inline code
|
||||
for _, code := range inlineCode {
|
||||
text = strings.Replace(text, "\x00INLINE\x00", code, 1)
|
||||
}
|
||||
|
||||
// Restore code blocks
|
||||
for _, block := range codeBlocks {
|
||||
text = strings.Replace(text, "\x00CODEBLOCK\x00", block, 1)
|
||||
}
|
||||
|
||||
return text
|
||||
}
|
||||
|
||||
func splitContentWithTables(content string) []contentSegment {
|
||||
var segments []contentSegment
|
||||
|
||||
// Protect code blocks from table detection using unique placeholders
|
||||
var codeBlocks []string
|
||||
blockIdx := 0
|
||||
protected := codeBlockRe.ReplaceAllStringFunc(content, func(match string) string {
|
||||
codeBlocks = append(codeBlocks, match)
|
||||
placeholder := fmt.Sprintf("\x00CODEBLOCK_%d\x00", blockIdx)
|
||||
blockIdx++
|
||||
return placeholder
|
||||
})
|
||||
|
||||
matches := markdownTableRe.FindAllStringSubmatchIndex(protected, -1)
|
||||
if len(matches) == 0 {
|
||||
return []contentSegment{{content: content, isTable: false}}
|
||||
}
|
||||
|
||||
// Restore code blocks using indexed placeholders
|
||||
restoreCodeBlocks := func(s string) string {
|
||||
result := s
|
||||
for i, block := range codeBlocks {
|
||||
placeholder := fmt.Sprintf("\x00CODEBLOCK_%d\x00", i)
|
||||
result = strings.Replace(result, placeholder, block, 1)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
lastEnd := 0
|
||||
for _, match := range matches {
|
||||
if match[0] > lastEnd {
|
||||
segments = append(segments, contentSegment{
|
||||
content: restoreCodeBlocks(protected[lastEnd:match[0]]),
|
||||
isTable: false,
|
||||
})
|
||||
}
|
||||
segments = append(segments, contentSegment{
|
||||
content: restoreCodeBlocks(protected[match[0]:match[1]]),
|
||||
isTable: true,
|
||||
})
|
||||
lastEnd = match[1]
|
||||
}
|
||||
|
||||
if lastEnd < len(protected) {
|
||||
segments = append(segments, contentSegment{
|
||||
content: restoreCodeBlocks(protected[lastEnd:]),
|
||||
isTable: false,
|
||||
})
|
||||
}
|
||||
|
||||
return segments
|
||||
}
|
||||
|
||||
func renderTable(tableStr string) string {
|
||||
lines := strings.Split(strings.TrimSpace(tableStr), "\n")
|
||||
if len(lines) < 2 {
|
||||
return "```\n" + tableStr + "\n```"
|
||||
}
|
||||
|
||||
// Parse all rows to get column widths
|
||||
var allRows [][]string
|
||||
maxCols := 0
|
||||
for i, line := range lines {
|
||||
if i == 1 && isSeparatorRow(line) {
|
||||
continue
|
||||
}
|
||||
cells := parseTableRow(line)
|
||||
if len(cells) > 0 {
|
||||
allRows = append(allRows, cells)
|
||||
if len(cells) > maxCols {
|
||||
maxCols = len(cells)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(allRows) == 0 {
|
||||
return "```\n" + tableStr + "\n```"
|
||||
}
|
||||
|
||||
// Calculate max width for each column using rune count
|
||||
colWidths := make([]int, maxCols)
|
||||
for _, row := range allRows {
|
||||
for i, cell := range row {
|
||||
runeLen := len([]rune(cell))
|
||||
if runeLen > colWidths[i] {
|
||||
colWidths[i] = runeLen
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check if table is narrow enough for mrkdwn format
|
||||
totalWidth := 0
|
||||
for _, w := range colWidths {
|
||||
totalWidth += w
|
||||
}
|
||||
if len(colWidths) > 1 {
|
||||
totalWidth += 3 * (len(colWidths) - 1) // " | " separators between columns
|
||||
}
|
||||
if totalWidth <= maxTableRowWidth {
|
||||
// Render as formatted text with bold headers
|
||||
var result strings.Builder
|
||||
for i, row := range allRows {
|
||||
if i == 0 {
|
||||
var boldCells []string
|
||||
for _, cell := range row {
|
||||
boldCells = append(boldCells, "*"+cell+"*")
|
||||
}
|
||||
result.WriteString(strings.Join(boldCells, " | "))
|
||||
} else {
|
||||
result.WriteString(strings.Join(row, " | "))
|
||||
}
|
||||
result.WriteString("\n")
|
||||
}
|
||||
return strings.TrimSuffix(result.String(), "\n")
|
||||
}
|
||||
|
||||
// Render as aligned code block
|
||||
var result strings.Builder
|
||||
result.WriteString("```\n")
|
||||
for i, row := range allRows {
|
||||
var paddedCells []string
|
||||
for j, cell := range row {
|
||||
if j < len(colWidths) {
|
||||
paddedCells = append(paddedCells, padRight(cell, colWidths[j]))
|
||||
} else {
|
||||
paddedCells = append(paddedCells, cell)
|
||||
}
|
||||
}
|
||||
result.WriteString("| ")
|
||||
result.WriteString(strings.Join(paddedCells, " | "))
|
||||
result.WriteString(" |\n")
|
||||
|
||||
// Add separator after header
|
||||
if i == 0 {
|
||||
var sepParts []string
|
||||
for _, w := range colWidths {
|
||||
sepParts = append(sepParts, strings.Repeat("-", w))
|
||||
}
|
||||
result.WriteString("|-")
|
||||
result.WriteString(strings.Join(sepParts, "-|-"))
|
||||
result.WriteString("-|\n")
|
||||
}
|
||||
}
|
||||
result.WriteString("```")
|
||||
return result.String()
|
||||
}
|
||||
|
||||
func padRight(s string, width int) string {
|
||||
runeLen := len([]rune(s))
|
||||
if runeLen >= width {
|
||||
return s
|
||||
}
|
||||
return s + strings.Repeat(" ", width-runeLen)
|
||||
}
|
||||
|
||||
func isSeparatorRow(line string) bool {
|
||||
cleaned := strings.ReplaceAll(line, "|", "")
|
||||
cleaned = strings.ReplaceAll(cleaned, " ", "")
|
||||
cleaned = strings.ReplaceAll(cleaned, "-", "")
|
||||
cleaned = strings.ReplaceAll(cleaned, ":", "")
|
||||
return cleaned == ""
|
||||
}
|
||||
|
||||
func parseTableRow(line string) []string {
|
||||
line = strings.TrimSpace(line)
|
||||
line = strings.TrimPrefix(line, "|")
|
||||
line = strings.TrimSuffix(line, "|")
|
||||
if line == "" {
|
||||
return nil
|
||||
}
|
||||
parts := strings.Split(line, "|")
|
||||
var cells []string
|
||||
for _, p := range parts {
|
||||
cells = append(cells, strings.TrimSpace(p))
|
||||
}
|
||||
return cells
|
||||
}
|
||||
@@ -1,187 +0,0 @@
|
||||
package slackwebhook
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestConvertMarkdownToMrkdwn(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
name: "bold double asterisk",
|
||||
input: "This is **bold** text",
|
||||
expected: "This is *bold* text",
|
||||
},
|
||||
{
|
||||
name: "italic single asterisk",
|
||||
input: "This is *italic* text",
|
||||
expected: "This is _italic_ text",
|
||||
},
|
||||
{
|
||||
name: "italic underscore",
|
||||
input: "This is _italic_ text",
|
||||
expected: "This is _italic_ text",
|
||||
},
|
||||
{
|
||||
name: "strikethrough",
|
||||
input: "This is ~~struck~~ text",
|
||||
expected: "This is ~struck~ text",
|
||||
},
|
||||
{
|
||||
name: "inline code unchanged",
|
||||
input: "Use `code` here",
|
||||
expected: "Use `code` here",
|
||||
},
|
||||
{
|
||||
name: "link conversion",
|
||||
input: "Click [here](https://example.com) now",
|
||||
expected: "Click <https://example.com|here> now",
|
||||
},
|
||||
{
|
||||
name: "header to bold",
|
||||
input: "# Header One",
|
||||
expected: "*Header One*",
|
||||
},
|
||||
{
|
||||
name: "header level 2",
|
||||
input: "## Header Two",
|
||||
expected: "*Header Two*",
|
||||
},
|
||||
{
|
||||
name: "bullet list",
|
||||
input: "- item one\n- item two",
|
||||
expected: "• item one\n• item two",
|
||||
},
|
||||
{
|
||||
name: "mixed formatting",
|
||||
input: "**bold** and *italic* and [link](http://x.com)",
|
||||
expected: "*bold* and _italic_ and <http://x.com|link>",
|
||||
},
|
||||
{
|
||||
name: "code block unchanged",
|
||||
input: "```\ncode here\n```",
|
||||
expected: "```\ncode here\n```",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result := convertMarkdownToMrkdwn(tt.input)
|
||||
assert.Equal(t, tt.expected, result)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitContentWithTables(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
expectedCount int
|
||||
expectedTables int
|
||||
}{
|
||||
{
|
||||
name: "no table",
|
||||
input: "Just some text",
|
||||
expectedCount: 1,
|
||||
expectedTables: 0,
|
||||
},
|
||||
{
|
||||
name: "simple table",
|
||||
input: "| A | B |\n|---|---|\n| 1 | 2 |",
|
||||
expectedCount: 1,
|
||||
expectedTables: 1,
|
||||
},
|
||||
{
|
||||
name: "text before table",
|
||||
input: "Intro text\n\n| A | B |\n|---|---|\n| 1 | 2 |",
|
||||
expectedCount: 2,
|
||||
expectedTables: 1,
|
||||
},
|
||||
{
|
||||
name: "text before and after table",
|
||||
input: "Before\n\n| A | B |\n|---|---|\n| 1 | 2 |\n\nAfter",
|
||||
expectedCount: 3,
|
||||
expectedTables: 1,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
segments := splitContentWithTables(tt.input)
|
||||
assert.Equal(t, tt.expectedCount, len(segments))
|
||||
tableCount := 0
|
||||
for _, seg := range segments {
|
||||
if seg.isTable {
|
||||
tableCount++
|
||||
}
|
||||
}
|
||||
assert.Equal(t, tt.expectedTables, tableCount)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderTable(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
expectCode bool
|
||||
}{
|
||||
{
|
||||
name: "narrow table renders as text",
|
||||
input: "| A | B |\n|---|---|\n| 1 | 2 |",
|
||||
expectCode: false,
|
||||
},
|
||||
{
|
||||
name: "wide table renders as code block",
|
||||
input: "| This is a very long column header | Another extremely long column header here |\n|---|---|\n| Some long value content here | More long value content |",
|
||||
expectCode: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result := renderTable(tt.input)
|
||||
if tt.expectCode {
|
||||
assert.Contains(t, result, "```")
|
||||
} else {
|
||||
assert.NotContains(t, result, "```")
|
||||
assert.Contains(t, result, "*") // Bold headers
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderTable_Alignment(t *testing.T) {
|
||||
input := "| Name | Status | Count |\n|---|---|---|\n| foo | OK | 1 |\n| barbaz | PENDING | 123 |"
|
||||
result := renderTable(input)
|
||||
|
||||
// Should be mrkdwn (narrow table)
|
||||
assert.NotContains(t, result, "```")
|
||||
assert.Contains(t, result, "*Name*")
|
||||
|
||||
// Test wide table alignment
|
||||
wideInput := "| This is a very long column header | Another extremely long column header here |\n|---|---|\n| Short | Longer value here |"
|
||||
wideResult := renderTable(wideInput)
|
||||
|
||||
assert.Contains(t, wideResult, "```")
|
||||
// Check that columns are padded - header and value should have same column width
|
||||
lines := strings.Split(wideResult, "\n")
|
||||
// Find the header line and a data line
|
||||
var headerLine, dataLine string
|
||||
for _, line := range lines {
|
||||
if strings.Contains(line, "This is a very long") {
|
||||
headerLine = line
|
||||
}
|
||||
if strings.Contains(line, "Short") {
|
||||
dataLine = line
|
||||
}
|
||||
}
|
||||
// Both lines should have same length (aligned columns)
|
||||
assert.Equal(t, len(headerLine), len(dataLine), "columns should be aligned")
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
package slackwebhook
|
||||
|
||||
import (
|
||||
"github.com/sipeed/picoclaw/pkg/bus"
|
||||
"github.com/sipeed/picoclaw/pkg/channels"
|
||||
"github.com/sipeed/picoclaw/pkg/config"
|
||||
)
|
||||
|
||||
func init() {
|
||||
channels.RegisterFactory(
|
||||
config.ChannelSlackWebHook,
|
||||
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.SlackWebhookSettings)
|
||||
if !ok {
|
||||
return nil, channels.ErrSendFailed
|
||||
}
|
||||
ch, err := NewSlackWebhookChannel(bc, c, b)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if channelName != config.ChannelSlackWebHook {
|
||||
ch.SetName(channelName)
|
||||
}
|
||||
return ch, nil
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -1,316 +0,0 @@
|
||||
package slackwebhook
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/sipeed/picoclaw/pkg/bus"
|
||||
"github.com/sipeed/picoclaw/pkg/channels"
|
||||
"github.com/sipeed/picoclaw/pkg/config"
|
||||
"github.com/sipeed/picoclaw/pkg/logger"
|
||||
)
|
||||
|
||||
const maxTextBlockLength = 3000
|
||||
|
||||
// SlackWebhookChannel is an output-only channel that sends messages
|
||||
// to Slack via Incoming Webhooks using Block Kit formatting.
|
||||
type SlackWebhookChannel struct {
|
||||
*channels.BaseChannel
|
||||
bc *config.Channel
|
||||
config *config.SlackWebhookSettings
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
// NewSlackWebhookChannel creates a new Slack webhook channel.
|
||||
func NewSlackWebhookChannel(
|
||||
bc *config.Channel,
|
||||
cfg *config.SlackWebhookSettings,
|
||||
bus *bus.MessageBus,
|
||||
) (*SlackWebhookChannel, error) {
|
||||
if len(cfg.Webhooks) == 0 {
|
||||
return nil, fmt.Errorf("slack_webhook: at least one webhook target is required")
|
||||
}
|
||||
|
||||
if _, hasDefault := cfg.Webhooks["default"]; !hasDefault {
|
||||
return nil, fmt.Errorf("slack_webhook: a 'default' webhook target is required")
|
||||
}
|
||||
|
||||
for name, target := range cfg.Webhooks {
|
||||
webhookURL := target.WebhookURL.String()
|
||||
if webhookURL == "" {
|
||||
return nil, fmt.Errorf("slack_webhook: webhook %q has empty webhook_url", name)
|
||||
}
|
||||
parsed, err := url.Parse(webhookURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("slack_webhook: webhook %q has invalid URL format: %w", name, err)
|
||||
}
|
||||
if !strings.EqualFold(parsed.Scheme, "https") {
|
||||
return nil, fmt.Errorf("slack_webhook: webhook %q must use HTTPS (got %q)", name, parsed.Scheme)
|
||||
}
|
||||
}
|
||||
|
||||
base := channels.NewBaseChannel(
|
||||
"slack_webhook",
|
||||
cfg,
|
||||
bus,
|
||||
[]string{"*"},
|
||||
channels.WithMaxMessageLength(40000),
|
||||
)
|
||||
|
||||
return &SlackWebhookChannel{
|
||||
BaseChannel: base,
|
||||
bc: bc,
|
||||
config: cfg,
|
||||
client: &http.Client{
|
||||
Timeout: 30 * time.Second,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Start initializes the channel. For output-only channels, this is a no-op.
|
||||
func (c *SlackWebhookChannel) Start(ctx context.Context) error {
|
||||
targets := make([]string, 0, len(c.config.Webhooks))
|
||||
for name := range c.config.Webhooks {
|
||||
targets = append(targets, name)
|
||||
}
|
||||
sort.Strings(targets)
|
||||
logger.InfoCF("slack_webhook", "Starting Slack webhook channel (output-only)", map[string]any{
|
||||
"targets": targets,
|
||||
})
|
||||
c.SetRunning(true)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stop shuts down the channel.
|
||||
func (c *SlackWebhookChannel) Stop(ctx context.Context) error {
|
||||
logger.InfoC("slack_webhook", "Stopping Slack webhook channel")
|
||||
c.SetRunning(false)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Send delivers a message to the specified Slack webhook target.
|
||||
func (c *SlackWebhookChannel) Send(ctx context.Context, msg bus.OutboundMessage) ([]string, error) {
|
||||
if !c.IsRunning() {
|
||||
return nil, channels.ErrNotRunning
|
||||
}
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
default:
|
||||
}
|
||||
|
||||
targetName := msg.ChatID
|
||||
if targetName == "" {
|
||||
targetName = "default"
|
||||
}
|
||||
|
||||
target, ok := c.config.Webhooks[targetName]
|
||||
if !ok {
|
||||
logger.WarnCF("slack_webhook", "Unknown target, falling back to default", map[string]any{
|
||||
"requested": msg.ChatID,
|
||||
"using": "default",
|
||||
})
|
||||
target = c.config.Webhooks["default"]
|
||||
targetName = "default"
|
||||
}
|
||||
|
||||
payload := c.buildPayload(msg, target)
|
||||
|
||||
jsonData, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("slack_webhook: failed to marshal payload: %w", err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, target.WebhookURL.String(), bytes.NewReader(jsonData))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("slack_webhook: failed to create request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := c.client.Do(req)
|
||||
if err != nil {
|
||||
logger.ErrorCF("slack_webhook", "Failed to send message", map[string]any{
|
||||
"target": targetName,
|
||||
})
|
||||
// Don't expose raw error - it may contain webhook URL secrets
|
||||
return nil, fmt.Errorf("slack_webhook: network error: %w", channels.ErrTemporary)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode >= 400 {
|
||||
respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
|
||||
respText := strings.TrimSpace(string(respBody))
|
||||
if respText == "" {
|
||||
respText = http.StatusText(resp.StatusCode)
|
||||
if respText == "" {
|
||||
respText = "unknown error"
|
||||
}
|
||||
}
|
||||
logger.ErrorCF("slack_webhook", "Slack API error", map[string]any{
|
||||
"target": targetName,
|
||||
"status": resp.StatusCode,
|
||||
"response": respText,
|
||||
})
|
||||
sendErr := fmt.Errorf("status %d: %s", resp.StatusCode, respText)
|
||||
return nil, fmt.Errorf("slack_webhook: %w", channels.ClassifySendError(resp.StatusCode, sendErr))
|
||||
}
|
||||
|
||||
logger.DebugCF("slack_webhook", "Message sent successfully", map[string]any{
|
||||
"target": targetName,
|
||||
})
|
||||
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (c *SlackWebhookChannel) buildPayload(msg bus.OutboundMessage, target config.SlackWebhookTarget) map[string]any {
|
||||
payload := make(map[string]any)
|
||||
|
||||
if target.Username != "" {
|
||||
payload["username"] = target.Username
|
||||
}
|
||||
if target.IconEmoji != "" {
|
||||
payload["icon_emoji"] = target.IconEmoji
|
||||
}
|
||||
|
||||
content := msg.Content
|
||||
if content == "" {
|
||||
content = "(empty message)"
|
||||
}
|
||||
|
||||
blocks := c.buildBlocks(content)
|
||||
payload["blocks"] = blocks
|
||||
|
||||
return payload
|
||||
}
|
||||
|
||||
func (c *SlackWebhookChannel) buildBlocks(content string) []map[string]any {
|
||||
var blocks []map[string]any
|
||||
|
||||
segments := splitContentWithTables(content)
|
||||
|
||||
for _, seg := range segments {
|
||||
if seg.isTable {
|
||||
tableText := renderTable(seg.content)
|
||||
for _, chunk := range splitText(tableText, maxTextBlockLength) {
|
||||
blocks = append(blocks, c.textSection(chunk))
|
||||
}
|
||||
} else {
|
||||
text := strings.TrimSpace(seg.content)
|
||||
if text == "" {
|
||||
continue
|
||||
}
|
||||
converted := convertMarkdownToMrkdwn(text)
|
||||
for _, chunk := range splitText(converted, maxTextBlockLength) {
|
||||
blocks = append(blocks, c.textSection(chunk))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(blocks) == 0 {
|
||||
blocks = append(blocks, c.textSection("(empty message)"))
|
||||
}
|
||||
|
||||
return blocks
|
||||
}
|
||||
|
||||
func (c *SlackWebhookChannel) textSection(text string) map[string]any {
|
||||
return map[string]any{
|
||||
"type": "section",
|
||||
"text": map[string]any{
|
||||
"type": "mrkdwn",
|
||||
"text": text,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func splitText(text string, maxLen int) []string {
|
||||
runes := []rune(text)
|
||||
if len(runes) <= maxLen {
|
||||
return []string{text}
|
||||
}
|
||||
|
||||
const fencePrefix = "```\n"
|
||||
const fenceSuffix = "\n```"
|
||||
fencePrefixLen := len([]rune(fencePrefix))
|
||||
fenceSuffixLen := len([]rune(fenceSuffix))
|
||||
|
||||
var chunks []string
|
||||
inFence := false
|
||||
|
||||
for len(runes) > 0 {
|
||||
// Calculate content budget reserving space for fence markers
|
||||
prefixLen := 0
|
||||
if inFence {
|
||||
prefixLen = fencePrefixLen
|
||||
}
|
||||
contentBudget := maxLen - prefixLen - fenceSuffixLen
|
||||
if contentBudget <= 0 {
|
||||
contentBudget = maxLen
|
||||
}
|
||||
|
||||
splitAt := len(runes)
|
||||
if splitAt > contentBudget {
|
||||
splitAt = findSplitPoint(runes, contentBudget)
|
||||
if splitAt <= 0 || splitAt > contentBudget {
|
||||
splitAt = contentBudget
|
||||
}
|
||||
}
|
||||
|
||||
chunkBody := string(runes[:splitAt])
|
||||
chunkEndsInFence := endsInsideFence(chunkBody, inFence)
|
||||
chunk := wrapFenceChunk(chunkBody, inFence, chunkEndsInFence)
|
||||
|
||||
chunks = append(chunks, chunk)
|
||||
inFence = chunkEndsInFence
|
||||
runes = runes[splitAt:]
|
||||
}
|
||||
|
||||
return chunks
|
||||
}
|
||||
|
||||
func wrapFenceChunk(text string, wasInFence bool, endsInFence bool) string {
|
||||
if wasInFence && !strings.HasPrefix(strings.TrimSpace(text), "```") {
|
||||
text = "```\n" + text
|
||||
}
|
||||
if endsInFence {
|
||||
text = strings.TrimSuffix(text, "\n") + "\n```"
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
func findSplitPoint(runes []rune, maxLen int) int {
|
||||
if len(runes) <= maxLen {
|
||||
return len(runes)
|
||||
}
|
||||
window := string(runes[:maxLen])
|
||||
|
||||
// Try splitting on newline
|
||||
if idx := strings.LastIndex(window, "\n"); idx > 0 {
|
||||
return len([]rune(window[:idx])) + 1
|
||||
}
|
||||
|
||||
// Try splitting on space
|
||||
if idx := strings.LastIndex(window, " "); idx > 0 {
|
||||
return len([]rune(window[:idx])) + 1
|
||||
}
|
||||
|
||||
// Try to split before a fence marker
|
||||
if idx := strings.LastIndex(window, "```"); idx > 0 {
|
||||
return len([]rune(window[:idx]))
|
||||
}
|
||||
|
||||
return maxLen
|
||||
}
|
||||
|
||||
func endsInsideFence(text string, wasInFence bool) bool {
|
||||
return wasInFence != (strings.Count(text, "```")%2 == 1)
|
||||
}
|
||||
@@ -1,281 +0,0 @@
|
||||
package slackwebhook
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/sipeed/picoclaw/pkg/bus"
|
||||
"github.com/sipeed/picoclaw/pkg/channels"
|
||||
"github.com/sipeed/picoclaw/pkg/config"
|
||||
)
|
||||
|
||||
func TestNewSlackWebhookChannel_Validation(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
webhooks map[string]config.SlackWebhookTarget
|
||||
expectErr string
|
||||
}{
|
||||
{
|
||||
name: "empty webhooks",
|
||||
webhooks: map[string]config.SlackWebhookTarget{},
|
||||
expectErr: "at least one webhook target is required",
|
||||
},
|
||||
{
|
||||
name: "missing default",
|
||||
webhooks: map[string]config.SlackWebhookTarget{
|
||||
"alerts": {
|
||||
WebhookURL: *config.NewSecureString("https://hooks.slack.com/services/T/B/x"),
|
||||
},
|
||||
},
|
||||
expectErr: "a 'default' webhook target is required",
|
||||
},
|
||||
{
|
||||
name: "empty webhook URL",
|
||||
webhooks: map[string]config.SlackWebhookTarget{
|
||||
"default": {WebhookURL: *config.NewSecureString("")},
|
||||
},
|
||||
expectErr: "has empty webhook_url",
|
||||
},
|
||||
{
|
||||
name: "non-HTTPS URL",
|
||||
webhooks: map[string]config.SlackWebhookTarget{
|
||||
"default": {
|
||||
WebhookURL: *config.NewSecureString("http://hooks.slack.com/services/T/B/x"),
|
||||
},
|
||||
},
|
||||
expectErr: "must use HTTPS",
|
||||
},
|
||||
{
|
||||
name: "valid config",
|
||||
webhooks: map[string]config.SlackWebhookTarget{
|
||||
"default": {
|
||||
WebhookURL: *config.NewSecureString("https://hooks.slack.com/services/T/B/x"),
|
||||
Username: "TestBot",
|
||||
IconEmoji: ":robot_face:",
|
||||
},
|
||||
},
|
||||
expectErr: "",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
cfg := &config.SlackWebhookSettings{Webhooks: tt.webhooks}
|
||||
bc := &config.Channel{Enabled: true}
|
||||
mb := bus.NewMessageBus()
|
||||
|
||||
ch, err := NewSlackWebhookChannel(bc, cfg, mb)
|
||||
if tt.expectErr != "" {
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), tt.expectErr)
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
assert.NotNil(t, ch)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlackWebhookChannel_Send(t *testing.T) {
|
||||
payloadCh := make(chan map[string]any, 1)
|
||||
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
var payload map[string]any
|
||||
json.Unmarshal(body, &payload)
|
||||
payloadCh <- payload
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
cfg := &config.SlackWebhookSettings{
|
||||
Webhooks: map[string]config.SlackWebhookTarget{
|
||||
"default": {
|
||||
WebhookURL: *config.NewSecureString(server.URL),
|
||||
Username: "TestBot",
|
||||
IconEmoji: ":test:",
|
||||
},
|
||||
},
|
||||
}
|
||||
bc := &config.Channel{Enabled: true}
|
||||
mb := bus.NewMessageBus()
|
||||
|
||||
ch, err := NewSlackWebhookChannel(bc, cfg, mb)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Use the test server's client to skip TLS verification
|
||||
ch.client = server.Client()
|
||||
|
||||
err = ch.Start(context.Background())
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = ch.Send(context.Background(), bus.OutboundMessage{
|
||||
Content: "Hello **world**",
|
||||
ChatID: "default",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Verify payload structure
|
||||
receivedPayload := <-payloadCh
|
||||
assert.Equal(t, "TestBot", receivedPayload["username"])
|
||||
assert.Equal(t, ":test:", receivedPayload["icon_emoji"])
|
||||
blocks, ok := receivedPayload["blocks"].([]any)
|
||||
require.True(t, ok)
|
||||
require.Len(t, blocks, 1)
|
||||
}
|
||||
|
||||
func TestSlackWebhookChannel_FallbackToDefault(t *testing.T) {
|
||||
var requestCount atomic.Int32
|
||||
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requestCount.Add(1)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
cfg := &config.SlackWebhookSettings{
|
||||
Webhooks: map[string]config.SlackWebhookTarget{
|
||||
"default": {WebhookURL: *config.NewSecureString(server.URL)},
|
||||
},
|
||||
}
|
||||
bc := &config.Channel{Enabled: true}
|
||||
mb := bus.NewMessageBus()
|
||||
|
||||
ch, err := NewSlackWebhookChannel(bc, cfg, mb)
|
||||
require.NoError(t, err)
|
||||
ch.client = server.Client()
|
||||
err = ch.Start(context.Background())
|
||||
require.NoError(t, err)
|
||||
|
||||
// Send to unknown target - should fall back to default
|
||||
_, err = ch.Send(context.Background(), bus.OutboundMessage{
|
||||
Content: "Test",
|
||||
ChatID: "unknown_target",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int32(1), requestCount.Load())
|
||||
}
|
||||
|
||||
func TestSlackWebhookChannel_ErrorClassification(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
statusCode int
|
||||
expectTemp bool
|
||||
}{
|
||||
{"400 Bad Request", 400, false},
|
||||
{"401 Unauthorized", 401, false},
|
||||
{"403 Forbidden", 403, false},
|
||||
{"404 Not Found", 404, false},
|
||||
{"500 Internal Error", 500, true},
|
||||
{"502 Bad Gateway", 502, true},
|
||||
{"503 Service Unavailable", 503, true},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
server := httptest.NewTLSServer(
|
||||
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(tt.statusCode)
|
||||
}),
|
||||
)
|
||||
defer server.Close()
|
||||
|
||||
cfg := &config.SlackWebhookSettings{
|
||||
Webhooks: map[string]config.SlackWebhookTarget{
|
||||
"default": {WebhookURL: *config.NewSecureString(server.URL)},
|
||||
},
|
||||
}
|
||||
bc := &config.Channel{Enabled: true}
|
||||
mb := bus.NewMessageBus()
|
||||
|
||||
ch, err := NewSlackWebhookChannel(bc, cfg, mb)
|
||||
require.NoError(t, err)
|
||||
ch.client = server.Client()
|
||||
err = ch.Start(context.Background())
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = ch.Send(context.Background(), bus.OutboundMessage{Content: "Test"})
|
||||
require.Error(t, err)
|
||||
|
||||
if tt.expectTemp {
|
||||
assert.True(
|
||||
t,
|
||||
errors.Is(err, channels.ErrTemporary),
|
||||
"expected temporary error for %d",
|
||||
tt.statusCode,
|
||||
)
|
||||
} else {
|
||||
assert.True(t, errors.Is(err, channels.ErrSendFailed), "expected permanent error for %d", tt.statusCode)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitText_ChunkSizeLimit(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
maxLen int
|
||||
}{
|
||||
{
|
||||
name: "plain text",
|
||||
input: strings.Repeat("a", 5000),
|
||||
maxLen: 3000,
|
||||
},
|
||||
{
|
||||
name: "text with code block",
|
||||
input: "```\n" + strings.Repeat("x", 5000) + "\n```",
|
||||
maxLen: 3000,
|
||||
},
|
||||
{
|
||||
name: "multiple code blocks",
|
||||
input: "text\n```\n" + strings.Repeat(
|
||||
"code ",
|
||||
800,
|
||||
) + "\n```\nmore text\n```\n" + strings.Repeat(
|
||||
"more ",
|
||||
800,
|
||||
) + "\n```",
|
||||
maxLen: 3000,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
chunks := splitText(tt.input, tt.maxLen)
|
||||
for i, chunk := range chunks {
|
||||
runeLen := len([]rune(chunk))
|
||||
assert.LessOrEqual(t, runeLen, tt.maxLen,
|
||||
"chunk %d has %d runes, exceeds max %d", i, runeLen, tt.maxLen)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitText_FenceIntegrity(t *testing.T) {
|
||||
input := "```\n" + strings.Repeat("line of code\n", 300) + "```"
|
||||
|
||||
chunks := splitText(input, 3000)
|
||||
require.Greater(t, len(chunks), 1, "expected multiple chunks")
|
||||
|
||||
for i, chunk := range chunks {
|
||||
openCount := strings.Count(chunk, "```")
|
||||
assert.Equal(t, 0, openCount%2,
|
||||
"chunk %d has unbalanced fence markers (count=%d)", i, openCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitText_ShortText(t *testing.T) {
|
||||
input := "short text"
|
||||
chunks := splitText(input, 3000)
|
||||
require.Len(t, chunks, 1)
|
||||
assert.Equal(t, input, chunks[0])
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
package teamswebhook
|
||||
|
||||
import (
|
||||
"github.com/sipeed/picoclaw/pkg/bus"
|
||||
"github.com/sipeed/picoclaw/pkg/channels"
|
||||
"github.com/sipeed/picoclaw/pkg/config"
|
||||
)
|
||||
|
||||
func init() {
|
||||
channels.RegisterFactory(
|
||||
config.ChannelTeamsWebHook,
|
||||
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.TeamsWebhookSettings)
|
||||
if !ok {
|
||||
return nil, channels.ErrSendFailed
|
||||
}
|
||||
ch, err := NewTeamsWebhookChannel(bc, c, b)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if channelName != config.ChannelTeamsWebHook {
|
||||
ch.SetName(channelName)
|
||||
}
|
||||
return ch, nil
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -1,425 +0,0 @@
|
||||
package teamswebhook
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
goteamsnotify "github.com/atc0005/go-teams-notify/v2"
|
||||
"github.com/atc0005/go-teams-notify/v2/adaptivecard"
|
||||
|
||||
"github.com/sipeed/picoclaw/pkg/bus"
|
||||
"github.com/sipeed/picoclaw/pkg/channels"
|
||||
"github.com/sipeed/picoclaw/pkg/config"
|
||||
"github.com/sipeed/picoclaw/pkg/logger"
|
||||
)
|
||||
|
||||
// statusCodeRe extracts HTTP status codes from error messages like "401 Unauthorized".
|
||||
var statusCodeRe = regexp.MustCompile(`\b([45]\d{2})\b`)
|
||||
|
||||
// markdownTableRe matches a markdown table block (header + separator + rows).
|
||||
// It captures the entire table including all rows.
|
||||
var markdownTableRe = regexp.MustCompile(`(?m)^(\|[^\n]+\|)\n(\|[-:\|\s]+\|)\n((?:\|[^\n]+\|\n?)+)`)
|
||||
|
||||
// teamsMessageSender abstracts the Teams client for testability.
|
||||
type teamsMessageSender interface {
|
||||
SendWithContext(ctx context.Context, webhookURL string, message goteamsnotify.TeamsMessage) error
|
||||
}
|
||||
|
||||
// classifyTeamsError extracts HTTP status code from error message and classifies it.
|
||||
// The go-teams-notify library returns errors like "error on notification: 401 Unauthorized, ...".
|
||||
// This allows proper retry behavior: 4xx errors are permanent, 5xx are temporary.
|
||||
func classifyTeamsError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
errMsg := err.Error()
|
||||
if matches := statusCodeRe.FindStringSubmatch(errMsg); len(matches) > 1 {
|
||||
if statusCode, parseErr := strconv.Atoi(matches[1]); parseErr == nil {
|
||||
return channels.ClassifySendError(statusCode, err)
|
||||
}
|
||||
}
|
||||
// Fallback: treat as temporary network error (retryable)
|
||||
return channels.ClassifyNetError(err)
|
||||
}
|
||||
|
||||
// TeamsWebhookChannel is an output-only channel that sends messages
|
||||
// to Microsoft Teams via Power Automate workflow webhooks.
|
||||
// Multiple webhook targets can be configured and selected via ChatID.
|
||||
type TeamsWebhookChannel struct {
|
||||
*channels.BaseChannel
|
||||
bc *config.Channel
|
||||
config *config.TeamsWebhookSettings
|
||||
client teamsMessageSender
|
||||
}
|
||||
|
||||
// NewTeamsWebhookChannel creates a new Teams webhook channel.
|
||||
func NewTeamsWebhookChannel(
|
||||
bc *config.Channel,
|
||||
cfg *config.TeamsWebhookSettings,
|
||||
bus *bus.MessageBus,
|
||||
) (*TeamsWebhookChannel, error) {
|
||||
if len(cfg.Webhooks) == 0 {
|
||||
return nil, fmt.Errorf("teams_webhook: at least one webhook target is required")
|
||||
}
|
||||
|
||||
// Require "default" webhook target
|
||||
if _, hasDefault := cfg.Webhooks["default"]; !hasDefault {
|
||||
return nil, fmt.Errorf("teams_webhook: a 'default' webhook target is required")
|
||||
}
|
||||
|
||||
// Validate all webhook targets have valid HTTPS URLs
|
||||
for name, target := range cfg.Webhooks {
|
||||
webhookURL := target.WebhookURL.String()
|
||||
if webhookURL == "" {
|
||||
return nil, fmt.Errorf("teams_webhook: webhook %q has empty webhook_url", name)
|
||||
}
|
||||
parsed, err := url.Parse(webhookURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("teams_webhook: webhook %q has invalid URL: %w", name, err)
|
||||
}
|
||||
if !strings.EqualFold(parsed.Scheme, "https") {
|
||||
return nil, fmt.Errorf("teams_webhook: webhook %q must use HTTPS (got %q)", name, parsed.Scheme)
|
||||
}
|
||||
}
|
||||
|
||||
base := channels.NewBaseChannel(
|
||||
"teams_webhook",
|
||||
cfg,
|
||||
bus,
|
||||
[]string{
|
||||
"*",
|
||||
}, // Output-only channel; "*" suppresses misleading "allows EVERYONE" audit warning
|
||||
channels.WithMaxMessageLength(24000), // Power Automate webhook payload limit is 28KB
|
||||
)
|
||||
|
||||
client := goteamsnotify.NewTeamsClient()
|
||||
|
||||
return &TeamsWebhookChannel{
|
||||
BaseChannel: base,
|
||||
bc: bc,
|
||||
config: cfg,
|
||||
client: client,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Start initializes the channel. For output-only channels, this is a no-op.
|
||||
func (c *TeamsWebhookChannel) Start(ctx context.Context) error {
|
||||
targets := make([]string, 0, len(c.config.Webhooks))
|
||||
for name := range c.config.Webhooks {
|
||||
targets = append(targets, name)
|
||||
}
|
||||
sort.Strings(targets)
|
||||
logger.InfoCF("teams_webhook", "Starting Teams webhook channel (output-only)", map[string]any{
|
||||
"targets": targets,
|
||||
})
|
||||
c.SetRunning(true)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stop shuts down the channel.
|
||||
func (c *TeamsWebhookChannel) Stop(ctx context.Context) error {
|
||||
logger.InfoC("teams_webhook", "Stopping Teams webhook channel")
|
||||
c.SetRunning(false)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Send delivers a message to the specified Teams webhook target.
|
||||
// The target is selected by msg.ChatID which must match a key in the webhooks map.
|
||||
func (c *TeamsWebhookChannel) Send(ctx context.Context, msg bus.OutboundMessage) ([]string, error) {
|
||||
if !c.IsRunning() {
|
||||
return nil, channels.ErrNotRunning
|
||||
}
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
default:
|
||||
}
|
||||
|
||||
// Look up webhook target by ChatID, fall back to "default" if empty or unknown
|
||||
targetName := msg.ChatID
|
||||
if targetName == "" {
|
||||
targetName = "default"
|
||||
}
|
||||
|
||||
target, ok := c.config.Webhooks[targetName]
|
||||
if !ok {
|
||||
// Log warning and fall back to default target
|
||||
logger.WarnCF("teams_webhook", "Unknown target, falling back to default", map[string]any{
|
||||
"requested": msg.ChatID,
|
||||
"using": "default",
|
||||
})
|
||||
target = c.config.Webhooks["default"]
|
||||
}
|
||||
|
||||
// Build an Adaptive Card for rich formatting
|
||||
card, err := c.buildAdaptiveCard(msg, target)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("teams_webhook: failed to build card: %w", err)
|
||||
}
|
||||
|
||||
// Create the message with the card
|
||||
teamsMsg, err := adaptivecard.NewMessageFromCard(card)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("teams_webhook: failed to create message: %w", err)
|
||||
}
|
||||
|
||||
// Send to Teams
|
||||
if err := c.client.SendWithContext(ctx, target.WebhookURL.String(), teamsMsg); err != nil {
|
||||
// Log without raw error to avoid leaking webhook URL (embedded in net/http errors)
|
||||
logger.ErrorCF("teams_webhook", "Failed to send message to Teams webhook", map[string]any{
|
||||
"target": msg.ChatID,
|
||||
})
|
||||
// Classify error based on status code extracted from error message.
|
||||
// The go-teams-notify library includes status in errors like "401 Unauthorized".
|
||||
// Use ClassifySendError for proper retry behavior (4xx = permanent, 5xx = temporary).
|
||||
classifiedErr := classifyTeamsError(err)
|
||||
return nil, fmt.Errorf("teams_webhook: send failed: %w", classifiedErr)
|
||||
}
|
||||
|
||||
logger.DebugCF("teams_webhook", "Message sent successfully", map[string]any{
|
||||
"target": msg.ChatID,
|
||||
})
|
||||
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// buildAdaptiveCard creates a formatted Adaptive Card from the outbound message.
|
||||
// It detects markdown tables and converts them to native Adaptive Card Table elements,
|
||||
// since TextBlocks only support a limited markdown subset (no tables).
|
||||
func (c *TeamsWebhookChannel) buildAdaptiveCard(
|
||||
msg bus.OutboundMessage,
|
||||
target config.TeamsWebhookTarget,
|
||||
) (adaptivecard.Card, error) {
|
||||
card := adaptivecard.NewCard()
|
||||
card.Type = adaptivecard.TypeAdaptiveCard
|
||||
|
||||
// Set full width for Teams rendering
|
||||
card.MSTeams.Width = "Full"
|
||||
|
||||
// Add title if configured on the target
|
||||
title := target.Title
|
||||
if title == "" {
|
||||
title = "PicoClaw Notification"
|
||||
}
|
||||
|
||||
titleBlock := adaptivecard.NewTextBlock(title, true)
|
||||
titleBlock.Size = adaptivecard.SizeLarge
|
||||
titleBlock.Weight = adaptivecard.WeightBolder
|
||||
titleBlock.Style = adaptivecard.TextBlockStyleHeading
|
||||
|
||||
if err := card.AddElement(false, titleBlock); err != nil {
|
||||
return card, err
|
||||
}
|
||||
|
||||
content := msg.Content
|
||||
if content == "" {
|
||||
content = "(empty message)"
|
||||
}
|
||||
|
||||
// Split content into text segments and tables
|
||||
// TextBlocks support: bold, italic, bullet/numbered lists, links
|
||||
// TextBlocks do NOT support: headers, tables, images
|
||||
segments := splitContentWithTables(content)
|
||||
|
||||
for _, seg := range segments {
|
||||
if seg.isTable {
|
||||
// Convert markdown table to Adaptive Card Table element
|
||||
tableElement, err := parseMarkdownTable(seg.content)
|
||||
if err != nil {
|
||||
// Fallback: render as preformatted text if parsing fails
|
||||
logger.WarnCF("teams_webhook", "Failed to parse markdown table, using fallback", map[string]any{
|
||||
"error": err.Error(),
|
||||
})
|
||||
block := adaptivecard.NewTextBlock("```\n"+seg.content+"\n```", true)
|
||||
block.Wrap = true
|
||||
if err := card.AddElement(false, block); err != nil {
|
||||
return card, err
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err := card.AddElement(false, tableElement); err != nil {
|
||||
return card, err
|
||||
}
|
||||
} else {
|
||||
// Regular text content
|
||||
text := strings.TrimSpace(seg.content)
|
||||
if text == "" {
|
||||
continue
|
||||
}
|
||||
block := adaptivecard.NewTextBlock(text, true)
|
||||
block.Wrap = true
|
||||
if err := card.AddElement(false, block); err != nil {
|
||||
return card, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return card, nil
|
||||
}
|
||||
|
||||
// contentSegment represents either a text block or a table in the message content.
|
||||
type contentSegment struct {
|
||||
content string
|
||||
isTable bool
|
||||
}
|
||||
|
||||
// splitContentWithTables splits content into alternating text and table segments.
|
||||
func splitContentWithTables(content string) []contentSegment {
|
||||
var segments []contentSegment
|
||||
|
||||
matches := markdownTableRe.FindAllStringSubmatchIndex(content, -1)
|
||||
if len(matches) == 0 {
|
||||
// No tables found, return entire content as text
|
||||
return []contentSegment{{content: content, isTable: false}}
|
||||
}
|
||||
|
||||
lastEnd := 0
|
||||
for _, match := range matches {
|
||||
// Text before this table
|
||||
if match[0] > lastEnd {
|
||||
segments = append(segments, contentSegment{
|
||||
content: content[lastEnd:match[0]],
|
||||
isTable: false,
|
||||
})
|
||||
}
|
||||
// The table itself
|
||||
segments = append(segments, contentSegment{
|
||||
content: content[match[0]:match[1]],
|
||||
isTable: true,
|
||||
})
|
||||
lastEnd = match[1]
|
||||
}
|
||||
|
||||
// Text after the last table
|
||||
if lastEnd < len(content) {
|
||||
segments = append(segments, contentSegment{
|
||||
content: content[lastEnd:],
|
||||
isTable: false,
|
||||
})
|
||||
}
|
||||
|
||||
return segments
|
||||
}
|
||||
|
||||
// parseMarkdownTable converts a markdown table string to an Adaptive Card Table element.
|
||||
func parseMarkdownTable(tableStr string) (adaptivecard.Element, error) {
|
||||
lines := strings.Split(strings.TrimSpace(tableStr), "\n")
|
||||
if len(lines) < 2 {
|
||||
return adaptivecard.Element{}, fmt.Errorf("table must have at least header and separator rows")
|
||||
}
|
||||
|
||||
// Track header content length per column for width calculation
|
||||
var headerLengths []int
|
||||
|
||||
// Parse all rows (header + data rows, skip separator)
|
||||
var allRows [][]adaptivecard.TableCell
|
||||
for i, line := range lines {
|
||||
// Skip separator row (contains only |, -, :, and spaces)
|
||||
if i == 1 && isSeparatorRow(line) {
|
||||
continue
|
||||
}
|
||||
|
||||
cells := parseTableRow(line)
|
||||
if len(cells) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
var tableCells []adaptivecard.TableCell
|
||||
for _, cellText := range cells {
|
||||
trimmedText := strings.TrimSpace(cellText)
|
||||
|
||||
// Use header row (first row) to determine column widths
|
||||
if i == 0 {
|
||||
headerLengths = append(headerLengths, len(trimmedText))
|
||||
}
|
||||
|
||||
textBlock := adaptivecard.Element{
|
||||
Type: adaptivecard.TypeElementTextBlock,
|
||||
Text: trimmedText,
|
||||
Wrap: true,
|
||||
}
|
||||
cell := adaptivecard.TableCell{
|
||||
Type: adaptivecard.TypeTableCell,
|
||||
Items: []*adaptivecard.Element{&textBlock},
|
||||
}
|
||||
tableCells = append(tableCells, cell)
|
||||
}
|
||||
allRows = append(allRows, tableCells)
|
||||
}
|
||||
|
||||
if len(allRows) == 0 {
|
||||
return adaptivecard.Element{}, fmt.Errorf("no valid rows found in table")
|
||||
}
|
||||
|
||||
// Create table with first row as headers
|
||||
firstRowAsHeaders := true
|
||||
showGridLines := true
|
||||
|
||||
table, err := adaptivecard.NewTableFromTableCells(allRows, 0, firstRowAsHeaders, showGridLines)
|
||||
if err != nil {
|
||||
return adaptivecard.Element{}, fmt.Errorf("failed to create table: %w", err)
|
||||
}
|
||||
|
||||
// Set column widths based on header content length
|
||||
table.Columns = calculateColumnWidths(headerLengths)
|
||||
|
||||
return table, nil
|
||||
}
|
||||
|
||||
// calculateColumnWidths creates TableColumnDefinition entries with widths
|
||||
// proportional to the max content length of each column.
|
||||
func calculateColumnWidths(maxLengths []int) []adaptivecard.Column {
|
||||
if len(maxLengths) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Use content length as relative weight, with a minimum of 1
|
||||
columns := make([]adaptivecard.Column, len(maxLengths))
|
||||
for i, length := range maxLengths {
|
||||
weight := length
|
||||
if weight < 1 {
|
||||
weight = 1
|
||||
}
|
||||
columns[i] = adaptivecard.Column{
|
||||
Type: "TableColumnDefinition",
|
||||
Width: weight,
|
||||
}
|
||||
}
|
||||
|
||||
return columns
|
||||
}
|
||||
|
||||
// isSeparatorRow checks if a line is a markdown table separator (e.g., |---|---|).
|
||||
func isSeparatorRow(line string) bool {
|
||||
// Remove pipes and spaces, check if only dashes and colons remain
|
||||
cleaned := strings.ReplaceAll(line, "|", "")
|
||||
cleaned = strings.ReplaceAll(cleaned, " ", "")
|
||||
cleaned = strings.ReplaceAll(cleaned, "-", "")
|
||||
cleaned = strings.ReplaceAll(cleaned, ":", "")
|
||||
return cleaned == ""
|
||||
}
|
||||
|
||||
// parseTableRow extracts cell values from a markdown table row.
|
||||
func parseTableRow(line string) []string {
|
||||
// Trim leading/trailing pipes and split by |
|
||||
line = strings.TrimSpace(line)
|
||||
line = strings.TrimPrefix(line, "|")
|
||||
line = strings.TrimSuffix(line, "|")
|
||||
|
||||
if line == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
parts := strings.Split(line, "|")
|
||||
var cells []string
|
||||
for _, p := range parts {
|
||||
cells = append(cells, strings.TrimSpace(p))
|
||||
}
|
||||
return cells
|
||||
}
|
||||
@@ -1,582 +0,0 @@
|
||||
package teamswebhook
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
goteamsnotify "github.com/atc0005/go-teams-notify/v2"
|
||||
|
||||
"github.com/sipeed/picoclaw/pkg/bus"
|
||||
"github.com/sipeed/picoclaw/pkg/config"
|
||||
)
|
||||
|
||||
// mockTeamsClient implements teamsMessageSender for testing.
|
||||
type mockTeamsClient struct {
|
||||
sendFunc func(ctx context.Context, webhookURL string, message goteamsnotify.TeamsMessage) error
|
||||
}
|
||||
|
||||
func (m *mockTeamsClient) SendWithContext(
|
||||
ctx context.Context,
|
||||
webhookURL string,
|
||||
message goteamsnotify.TeamsMessage,
|
||||
) error {
|
||||
if m.sendFunc != nil {
|
||||
return m.sendFunc(ctx, webhookURL, message)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestNewTeamsWebhookChannel(t *testing.T) {
|
||||
msgBus := bus.NewMessageBus()
|
||||
|
||||
// Test missing webhooks
|
||||
bc := &config.Channel{Type: config.ChannelTeamsWebHook, Enabled: true}
|
||||
cfg := config.TeamsWebhookSettings{
|
||||
Webhooks: nil,
|
||||
}
|
||||
_, err := NewTeamsWebhookChannel(bc, &cfg, msgBus)
|
||||
if err == nil {
|
||||
t.Error("expected error for missing webhooks")
|
||||
}
|
||||
|
||||
// Test missing "default" webhook
|
||||
cfg.Webhooks = map[string]config.TeamsWebhookTarget{
|
||||
"alerts": {
|
||||
WebhookURL: *config.NewSecureString("https://example.com/webhook"),
|
||||
Title: "Alerts",
|
||||
},
|
||||
}
|
||||
_, err = NewTeamsWebhookChannel(bc, &cfg, msgBus)
|
||||
if err == nil {
|
||||
t.Error("expected error for missing 'default' webhook")
|
||||
}
|
||||
|
||||
// Test empty webhook URL
|
||||
cfg.Webhooks = map[string]config.TeamsWebhookTarget{
|
||||
"default": {Title: "Default"},
|
||||
}
|
||||
_, err = NewTeamsWebhookChannel(bc, &cfg, msgBus)
|
||||
if err == nil {
|
||||
t.Error("expected error for empty webhook_url")
|
||||
}
|
||||
|
||||
// Test HTTP URL (should fail, must be HTTPS)
|
||||
cfg.Webhooks = map[string]config.TeamsWebhookTarget{
|
||||
"default": {
|
||||
WebhookURL: *config.NewSecureString("http://example.com/webhook"),
|
||||
Title: "Default",
|
||||
},
|
||||
}
|
||||
_, err = NewTeamsWebhookChannel(bc, &cfg, msgBus)
|
||||
if err == nil {
|
||||
t.Error("expected error for HTTP webhook URL (must be HTTPS)")
|
||||
}
|
||||
|
||||
// Test valid config with HTTPS (must include "default")
|
||||
cfg.Webhooks = map[string]config.TeamsWebhookTarget{
|
||||
"default": {
|
||||
WebhookURL: *config.NewSecureString("https://example.com/webhook-default"),
|
||||
Title: "Default",
|
||||
},
|
||||
"alerts": {
|
||||
WebhookURL: *config.NewSecureString("https://example.com/webhook1"),
|
||||
Title: "Alerts",
|
||||
},
|
||||
}
|
||||
ch, err := NewTeamsWebhookChannel(bc, &cfg, msgBus)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if ch.Name() != "teams_webhook" {
|
||||
t.Errorf("expected name 'teams_webhook', got %q", ch.Name())
|
||||
}
|
||||
}
|
||||
|
||||
func TestTeamsWebhookChannel_StartStop(t *testing.T) {
|
||||
msgBus := bus.NewMessageBus()
|
||||
bc := &config.Channel{Type: config.ChannelTeamsWebHook, Enabled: true}
|
||||
cfg := config.TeamsWebhookSettings{
|
||||
Webhooks: map[string]config.TeamsWebhookTarget{
|
||||
"default": {
|
||||
WebhookURL: *config.NewSecureString("https://example.com/webhook"),
|
||||
},
|
||||
},
|
||||
}
|
||||
ch, err := NewTeamsWebhookChannel(bc, &cfg, msgBus)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
if ch.IsRunning() {
|
||||
t.Error("channel should not be running before Start")
|
||||
}
|
||||
|
||||
if err := ch.Start(ctx); err != nil {
|
||||
t.Fatalf("Start failed: %v", err)
|
||||
}
|
||||
|
||||
if !ch.IsRunning() {
|
||||
t.Error("channel should be running after Start")
|
||||
}
|
||||
|
||||
if err := ch.Stop(ctx); err != nil {
|
||||
t.Fatalf("Stop failed: %v", err)
|
||||
}
|
||||
|
||||
if ch.IsRunning() {
|
||||
t.Error("channel should not be running after Stop")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTeamsWebhookChannel_BuildAdaptiveCard(t *testing.T) {
|
||||
msgBus := bus.NewMessageBus()
|
||||
bc := &config.Channel{Type: config.ChannelTeamsWebHook, Enabled: true}
|
||||
cfg := config.TeamsWebhookSettings{
|
||||
Webhooks: map[string]config.TeamsWebhookTarget{
|
||||
"default": {
|
||||
WebhookURL: *config.NewSecureString("https://example.com/webhook-default"),
|
||||
Title: "Default",
|
||||
},
|
||||
"alerts": {
|
||||
WebhookURL: *config.NewSecureString("https://example.com/webhook"),
|
||||
Title: "Custom Title",
|
||||
},
|
||||
},
|
||||
}
|
||||
ch, err := NewTeamsWebhookChannel(bc, &cfg, msgBus)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
target := ch.config.Webhooks["alerts"]
|
||||
msg := bus.OutboundMessage{
|
||||
Content: "Test message content",
|
||||
ChatID: "alerts",
|
||||
}
|
||||
|
||||
card, err := ch.buildAdaptiveCard(msg, target)
|
||||
if err != nil {
|
||||
t.Fatalf("buildAdaptiveCard failed: %v", err)
|
||||
}
|
||||
|
||||
if card.Type != "AdaptiveCard" {
|
||||
t.Errorf("expected card type 'AdaptiveCard', got %q", card.Type)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTeamsWebhookChannel_SendNotRunning(t *testing.T) {
|
||||
msgBus := bus.NewMessageBus()
|
||||
bc := &config.Channel{Type: config.ChannelTeamsWebHook, Enabled: true}
|
||||
cfg := config.TeamsWebhookSettings{
|
||||
Webhooks: map[string]config.TeamsWebhookTarget{
|
||||
"default": {
|
||||
WebhookURL: *config.NewSecureString("https://example.com/webhook"),
|
||||
},
|
||||
},
|
||||
}
|
||||
ch, err := NewTeamsWebhookChannel(bc, &cfg, msgBus)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
msg := bus.OutboundMessage{Content: "test", ChatID: "default"}
|
||||
|
||||
_, err = ch.Send(ctx, msg)
|
||||
if err == nil {
|
||||
t.Error("expected error when sending while not running")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTeamsWebhookChannel_SendDefaultTargetFallback(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
chatID string
|
||||
}{
|
||||
{"unknown target falls back to default", "unknown"},
|
||||
{"empty ChatID uses default", ""},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
msgBus := bus.NewMessageBus()
|
||||
bc := &config.Channel{Type: config.ChannelTeamsWebHook, Enabled: true}
|
||||
cfg := config.TeamsWebhookSettings{
|
||||
Webhooks: map[string]config.TeamsWebhookTarget{
|
||||
"default": {
|
||||
WebhookURL: *config.NewSecureString("https://example.com/webhook-default"),
|
||||
},
|
||||
"alerts": {
|
||||
WebhookURL: *config.NewSecureString("https://example.com/webhook-alerts"),
|
||||
},
|
||||
},
|
||||
}
|
||||
ch, err := NewTeamsWebhookChannel(bc, &cfg, msgBus)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
var sentURL string
|
||||
ch.client = &mockTeamsClient{
|
||||
sendFunc: func(ctx context.Context, webhookURL string, message goteamsnotify.TeamsMessage) error {
|
||||
sentURL = webhookURL
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
_ = ch.Start(ctx)
|
||||
defer ch.Stop(ctx)
|
||||
|
||||
msg := bus.OutboundMessage{Content: "test", ChatID: tt.chatID}
|
||||
_, err = ch.Send(ctx, msg)
|
||||
if err != nil {
|
||||
t.Fatalf("expected success, got error: %v", err)
|
||||
}
|
||||
|
||||
if sentURL != "https://example.com/webhook-default" {
|
||||
t.Errorf("expected default webhook URL, got %q", sentURL)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTeamsWebhookChannel_SendSuccess(t *testing.T) {
|
||||
msgBus := bus.NewMessageBus()
|
||||
bc := &config.Channel{Type: config.ChannelTeamsWebHook, Enabled: true}
|
||||
cfg := config.TeamsWebhookSettings{
|
||||
Webhooks: map[string]config.TeamsWebhookTarget{
|
||||
"default": {
|
||||
WebhookURL: *config.NewSecureString("https://example.com/webhook-default"),
|
||||
Title: "Default",
|
||||
},
|
||||
"alerts": {
|
||||
WebhookURL: *config.NewSecureString("https://example.com/webhook-alerts"),
|
||||
Title: "Test Alerts",
|
||||
},
|
||||
},
|
||||
}
|
||||
ch, err := NewTeamsWebhookChannel(bc, &cfg, msgBus)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
// Inject mock client
|
||||
var sentURL string
|
||||
ch.client = &mockTeamsClient{
|
||||
sendFunc: func(ctx context.Context, webhookURL string, message goteamsnotify.TeamsMessage) error {
|
||||
sentURL = webhookURL
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
_ = ch.Start(ctx)
|
||||
defer ch.Stop(ctx)
|
||||
|
||||
msg := bus.OutboundMessage{Content: "Hello Teams!", ChatID: "alerts"}
|
||||
|
||||
_, err = ch.Send(ctx, msg)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if sentURL != "https://example.com/webhook-alerts" {
|
||||
t.Errorf("expected webhook URL 'https://example.com/webhook-alerts', got %q", sentURL)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTeamsWebhookChannel_SendError(t *testing.T) {
|
||||
msgBus := bus.NewMessageBus()
|
||||
bc := &config.Channel{Type: config.ChannelTeamsWebHook, Enabled: true}
|
||||
cfg := config.TeamsWebhookSettings{
|
||||
Webhooks: map[string]config.TeamsWebhookTarget{
|
||||
"default": {
|
||||
WebhookURL: *config.NewSecureString("https://example.com/webhook-default"),
|
||||
},
|
||||
"alerts": {
|
||||
WebhookURL: *config.NewSecureString("https://example.com/webhook-alerts"),
|
||||
},
|
||||
},
|
||||
}
|
||||
ch, err := NewTeamsWebhookChannel(bc, &cfg, msgBus)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
// Inject mock client that returns an error
|
||||
ch.client = &mockTeamsClient{
|
||||
sendFunc: func(ctx context.Context, webhookURL string, message goteamsnotify.TeamsMessage) error {
|
||||
return errors.New("error on notification: 401 Unauthorized, forbidden")
|
||||
},
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
_ = ch.Start(ctx)
|
||||
defer ch.Stop(ctx)
|
||||
|
||||
msg := bus.OutboundMessage{Content: "test", ChatID: "alerts"}
|
||||
|
||||
_, err = ch.Send(ctx, msg)
|
||||
if err == nil {
|
||||
t.Error("expected error from failed send")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitContentWithTables(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
content string
|
||||
wantSegs int
|
||||
wantTbl int // number of table segments
|
||||
}{
|
||||
{
|
||||
name: "no tables",
|
||||
content: "Just some text\nwith multiple lines",
|
||||
wantSegs: 1,
|
||||
wantTbl: 0,
|
||||
},
|
||||
{
|
||||
name: "single table",
|
||||
content: `| Col1 | Col2 |
|
||||
|------|------|
|
||||
| A | B |
|
||||
| C | D |`,
|
||||
wantSegs: 1,
|
||||
wantTbl: 1,
|
||||
},
|
||||
{
|
||||
name: "text before table",
|
||||
content: `Here is some text.
|
||||
|
||||
| Col1 | Col2 |
|
||||
|------|------|
|
||||
| A | B |`,
|
||||
wantSegs: 2,
|
||||
wantTbl: 1,
|
||||
},
|
||||
{
|
||||
name: "text before and after table",
|
||||
content: `Before table.
|
||||
|
||||
| Col1 | Col2 |
|
||||
|------|------|
|
||||
| A | B |
|
||||
|
||||
After table.`,
|
||||
wantSegs: 3,
|
||||
wantTbl: 1,
|
||||
},
|
||||
{
|
||||
name: "multiple tables",
|
||||
content: `First table:
|
||||
|
||||
| A | B |
|
||||
|---|---|
|
||||
| 1 | 2 |
|
||||
|
||||
Second table:
|
||||
|
||||
| X | Y |
|
||||
|---|---|
|
||||
| 3 | 4 |`,
|
||||
wantSegs: 4,
|
||||
wantTbl: 2,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
segs := splitContentWithTables(tt.content)
|
||||
if len(segs) != tt.wantSegs {
|
||||
t.Errorf("got %d segments, want %d", len(segs), tt.wantSegs)
|
||||
}
|
||||
tableCount := 0
|
||||
for _, s := range segs {
|
||||
if s.isTable {
|
||||
tableCount++
|
||||
}
|
||||
}
|
||||
if tableCount != tt.wantTbl {
|
||||
t.Errorf("got %d tables, want %d", tableCount, tt.wantTbl)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseMarkdownTable(t *testing.T) {
|
||||
tableStr := `| Name | Value |
|
||||
|------|-------|
|
||||
| foo | 123 |
|
||||
| bar | 456 |`
|
||||
|
||||
elem, err := parseMarkdownTable(tableStr)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if elem.Type != "Table" {
|
||||
t.Errorf("expected type 'Table', got %q", elem.Type)
|
||||
}
|
||||
|
||||
// Should have 3 rows (header + 2 data rows)
|
||||
if len(elem.Rows) != 3 {
|
||||
t.Errorf("expected 3 rows, got %d", len(elem.Rows))
|
||||
}
|
||||
|
||||
// Should have 2 columns with widths based on content length
|
||||
if len(elem.Columns) != 2 {
|
||||
t.Errorf("expected 2 columns, got %d", len(elem.Columns))
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseMarkdownTableColumnWidths(t *testing.T) {
|
||||
// Column widths are based on HEADER row only:
|
||||
// Col1: "Description" (11 chars)
|
||||
// Col2: "X" (1 char)
|
||||
// Col3: "Amount" (6 chars)
|
||||
tableStr := `| Description | X | Amount |
|
||||
|-------------|---|--------|
|
||||
| Short | Y | 100 |
|
||||
| Longer text | Z | 50 |`
|
||||
|
||||
elem, err := parseMarkdownTable(tableStr)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if len(elem.Columns) != 3 {
|
||||
t.Fatalf("expected 3 columns, got %d", len(elem.Columns))
|
||||
}
|
||||
|
||||
// Verify column widths are based on header content length
|
||||
w1, ok1 := elem.Columns[0].Width.(int)
|
||||
w2, ok2 := elem.Columns[1].Width.(int)
|
||||
w3, ok3 := elem.Columns[2].Width.(int)
|
||||
|
||||
if !ok1 || !ok2 || !ok3 {
|
||||
t.Fatalf("expected int widths, got types: %T, %T, %T",
|
||||
elem.Columns[0].Width, elem.Columns[1].Width, elem.Columns[2].Width)
|
||||
}
|
||||
|
||||
// Header lengths: "Description" = 11, "X" = 1, "Amount" = 6
|
||||
if w1 != 11 {
|
||||
t.Errorf("expected col1 width 11 (from 'Description'), got %d", w1)
|
||||
}
|
||||
if w2 != 1 {
|
||||
t.Errorf("expected col2 width 1 (from 'X'), got %d", w2)
|
||||
}
|
||||
if w3 != 6 {
|
||||
t.Errorf("expected col3 width 6 (from 'Amount'), got %d", w3)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCalculateColumnWidths(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
maxLengths []int
|
||||
wantWidths []int
|
||||
}{
|
||||
{
|
||||
name: "equal lengths",
|
||||
maxLengths: []int{10, 10, 10},
|
||||
wantWidths: []int{10, 10, 10},
|
||||
},
|
||||
{
|
||||
name: "varying lengths",
|
||||
maxLengths: []int{5, 20, 10},
|
||||
wantWidths: []int{5, 20, 10},
|
||||
},
|
||||
{
|
||||
name: "zero length gets minimum of 1",
|
||||
maxLengths: []int{0, 5, 0},
|
||||
wantWidths: []int{1, 5, 1},
|
||||
},
|
||||
{
|
||||
name: "empty input",
|
||||
maxLengths: []int{},
|
||||
wantWidths: nil,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
cols := calculateColumnWidths(tt.maxLengths)
|
||||
|
||||
if tt.wantWidths == nil {
|
||||
if cols != nil {
|
||||
t.Errorf("expected nil, got %v", cols)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if len(cols) != len(tt.wantWidths) {
|
||||
t.Fatalf("expected %d columns, got %d", len(tt.wantWidths), len(cols))
|
||||
}
|
||||
|
||||
for i, col := range cols {
|
||||
width, ok := col.Width.(int)
|
||||
if !ok {
|
||||
t.Errorf("column %d: expected int width, got %T", i, col.Width)
|
||||
continue
|
||||
}
|
||||
if width != tt.wantWidths[i] {
|
||||
t.Errorf("column %d: expected width %d, got %d", i, tt.wantWidths[i], width)
|
||||
}
|
||||
if col.Type != "TableColumnDefinition" {
|
||||
t.Errorf("column %d: expected type 'TableColumnDefinition', got %q", i, col.Type)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseTableRow(t *testing.T) {
|
||||
tests := []struct {
|
||||
line string
|
||||
want []string
|
||||
}{
|
||||
{"| A | B | C |", []string{"A", "B", "C"}},
|
||||
{"|A|B|C|", []string{"A", "B", "C"}},
|
||||
{"| foo | bar |", []string{"foo", "bar"}},
|
||||
{"", nil},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
got := parseTableRow(tt.line)
|
||||
if len(got) != len(tt.want) {
|
||||
t.Errorf("parseTableRow(%q): got %v, want %v", tt.line, got, tt.want)
|
||||
continue
|
||||
}
|
||||
for i := range got {
|
||||
if got[i] != tt.want[i] {
|
||||
t.Errorf("parseTableRow(%q)[%d]: got %q, want %q", tt.line, i, got[i], tt.want[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsSeparatorRow(t *testing.T) {
|
||||
tests := []struct {
|
||||
line string
|
||||
want bool
|
||||
}{
|
||||
{"|---|---|", true},
|
||||
{"| --- | --- |", true},
|
||||
{"|:---|---:|", true},
|
||||
{"| :---: | :---: |", true},
|
||||
{"| A | B |", false},
|
||||
{"| foo | bar |", false},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
got := isSeparatorRow(tt.line)
|
||||
if got != tt.want {
|
||||
t.Errorf("isSeparatorRow(%q): got %v, want %v", tt.line, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package vk
|
||||
|
||||
import (
|
||||
"github.com/sipeed/picoclaw/pkg/bus"
|
||||
"github.com/sipeed/picoclaw/pkg/channels"
|
||||
"github.com/sipeed/picoclaw/pkg/config"
|
||||
)
|
||||
|
||||
func init() {
|
||||
channels.RegisterFactory(
|
||||
config.ChannelVK,
|
||||
func(channelName, channelType string, cfg *config.Config, b *bus.MessageBus) (channels.Channel, error) {
|
||||
bc := cfg.Channels[channelName]
|
||||
if bc == nil {
|
||||
return nil, channels.ErrSendFailed
|
||||
}
|
||||
return NewVKChannel(channelName, bc, b)
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -1,295 +0,0 @@
|
||||
package vk
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/SevereCloud/vksdk/v3/api"
|
||||
"github.com/SevereCloud/vksdk/v3/api/params"
|
||||
"github.com/SevereCloud/vksdk/v3/events"
|
||||
"github.com/SevereCloud/vksdk/v3/longpoll-bot"
|
||||
"github.com/SevereCloud/vksdk/v3/object"
|
||||
|
||||
"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"
|
||||
)
|
||||
|
||||
type VKChannel struct {
|
||||
*channels.BaseChannel
|
||||
vk *api.VK
|
||||
lp *longpoll.LongPoll
|
||||
channelName string
|
||||
bc *config.Channel
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func NewVKChannel(channelName string, bc *config.Channel, bus *bus.MessageBus) (*VKChannel, error) {
|
||||
var vkCfg config.VKSettings
|
||||
if err := bc.Decode(&vkCfg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
vk := api.NewVK(vkCfg.Token.String())
|
||||
|
||||
base := channels.NewBaseChannel(
|
||||
channelName,
|
||||
&vkCfg,
|
||||
bus,
|
||||
bc.AllowFrom,
|
||||
channels.WithMaxMessageLength(4000),
|
||||
channels.WithGroupTrigger(bc.GroupTrigger),
|
||||
channels.WithReasoningChannelID(bc.ReasoningChannelID),
|
||||
)
|
||||
|
||||
return &VKChannel{
|
||||
BaseChannel: base,
|
||||
vk: vk,
|
||||
channelName: channelName,
|
||||
bc: bc,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *VKChannel) getVKCfg() *config.VKSettings {
|
||||
var v config.VKSettings
|
||||
if err := c.bc.Decode(&v); err != nil {
|
||||
return nil
|
||||
}
|
||||
return &v
|
||||
}
|
||||
|
||||
func (c *VKChannel) Start(ctx context.Context) error {
|
||||
logger.InfoC("vk", "Starting VK bot (Long Poll mode)...")
|
||||
|
||||
c.ctx, c.cancel = context.WithCancel(ctx)
|
||||
|
||||
groupID := c.getVKCfg().GroupID
|
||||
if groupID == 0 {
|
||||
c.cancel()
|
||||
return fmt.Errorf("group_id is required for VK bot")
|
||||
}
|
||||
|
||||
lp, err := longpoll.NewLongPoll(c.vk, groupID)
|
||||
if err != nil {
|
||||
c.cancel()
|
||||
return fmt.Errorf("failed to create long poll: %w", err)
|
||||
}
|
||||
c.lp = lp
|
||||
|
||||
lp.MessageNew(func(_ context.Context, obj events.MessageNewObject) {
|
||||
c.handleMessage(obj.Message)
|
||||
})
|
||||
|
||||
c.SetRunning(true)
|
||||
|
||||
logger.InfoCF("vk", "VK bot connected", map[string]any{
|
||||
"group_id": groupID,
|
||||
})
|
||||
|
||||
go func() {
|
||||
if err := lp.Run(); err != nil {
|
||||
logger.ErrorCF("vk", "Long poll failed", map[string]any{
|
||||
"error": err.Error(),
|
||||
})
|
||||
}
|
||||
}()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *VKChannel) Stop(ctx context.Context) error {
|
||||
logger.InfoC("vk", "Stopping VK bot...")
|
||||
c.SetRunning(false)
|
||||
|
||||
if c.lp != nil {
|
||||
c.lp.Shutdown()
|
||||
}
|
||||
|
||||
if c.cancel != nil {
|
||||
c.cancel()
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *VKChannel) handleMessage(msg object.MessagesMessage) {
|
||||
if msg.Action.Type != "" {
|
||||
return
|
||||
}
|
||||
|
||||
if bool(msg.Out) {
|
||||
return
|
||||
}
|
||||
|
||||
peerID := msg.PeerID
|
||||
chatID := strconv.Itoa(peerID)
|
||||
|
||||
fromID := msg.FromID
|
||||
userID := strconv.Itoa(fromID)
|
||||
|
||||
platformID := userID
|
||||
sender := bus.SenderInfo{
|
||||
Platform: "vk",
|
||||
PlatformID: platformID,
|
||||
CanonicalID: identity.BuildCanonicalID("vk", platformID),
|
||||
DisplayName: c.getUserName(fromID),
|
||||
}
|
||||
|
||||
if !c.IsAllowedSender(sender) {
|
||||
logger.DebugCF("vk", "Message from unauthorized user", map[string]any{
|
||||
"peer_id": peerID,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
text := msg.Text
|
||||
if text == "" && len(msg.Attachments) > 0 {
|
||||
text = c.processAttachments(msg.Attachments)
|
||||
}
|
||||
|
||||
if text == "" {
|
||||
return
|
||||
}
|
||||
|
||||
groupTrigger := c.bc.GroupTrigger
|
||||
isGroupChat := peerID != fromID
|
||||
|
||||
if isGroupChat {
|
||||
isMentioned := c.isMentioned(msg)
|
||||
if isMentioned {
|
||||
text = c.stripBotMention(text)
|
||||
}
|
||||
respond, cleaned := c.ShouldRespondInGroup(isMentioned, text)
|
||||
if !respond {
|
||||
return
|
||||
}
|
||||
text = cleaned
|
||||
_ = groupTrigger
|
||||
}
|
||||
|
||||
chatType := "direct"
|
||||
if isGroupChat {
|
||||
chatType = "group"
|
||||
}
|
||||
|
||||
messageID := strconv.Itoa(msg.ConversationMessageID)
|
||||
|
||||
metadata := map[string]string{
|
||||
"user_id": userID,
|
||||
"is_group": fmt.Sprintf("%t", isGroupChat),
|
||||
}
|
||||
|
||||
c.HandleInboundContext(c.ctx, chatID, text, nil, bus.InboundContext{
|
||||
Channel: "vk",
|
||||
ChatID: chatID,
|
||||
ChatType: chatType,
|
||||
SenderID: userID,
|
||||
MessageID: messageID,
|
||||
Mentioned: isGroupChat && c.isMentioned(msg),
|
||||
Raw: metadata,
|
||||
}, sender)
|
||||
}
|
||||
|
||||
func (c *VKChannel) Send(ctx context.Context, msg bus.OutboundMessage) ([]string, error) {
|
||||
if !c.IsRunning() {
|
||||
return nil, channels.ErrNotRunning
|
||||
}
|
||||
|
||||
peerID, err := strconv.Atoi(msg.ChatID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid chat ID %s: %w", msg.ChatID, channels.ErrSendFailed)
|
||||
}
|
||||
|
||||
if msg.Content == "" {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
var messageIDs []string
|
||||
chunks := channels.SplitMessage(msg.Content, 4000)
|
||||
|
||||
for _, chunk := range chunks {
|
||||
if chunk == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
b := params.NewMessagesSendBuilder()
|
||||
b.Message(chunk)
|
||||
b.RandomID(0)
|
||||
b.PeerID(peerID)
|
||||
|
||||
if msg.ReplyToMessageID != "" {
|
||||
if replyID, err := strconv.Atoi(msg.ReplyToMessageID); err == nil {
|
||||
b.ReplyTo(replyID)
|
||||
}
|
||||
}
|
||||
|
||||
resp, err := c.vk.MessagesSend(b.Params)
|
||||
if err != nil {
|
||||
logger.ErrorCF("vk", "Failed to send message", map[string]any{
|
||||
"error": err.Error(),
|
||||
"peer_id": peerID,
|
||||
})
|
||||
return messageIDs, fmt.Errorf("failed to send message: %w", err)
|
||||
}
|
||||
|
||||
messageIDs = append(messageIDs, strconv.Itoa(resp))
|
||||
}
|
||||
|
||||
return messageIDs, nil
|
||||
}
|
||||
|
||||
func (c *VKChannel) isMentioned(msg object.MessagesMessage) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (c *VKChannel) stripBotMention(text string) string {
|
||||
return strings.TrimSpace(text)
|
||||
}
|
||||
|
||||
func (c *VKChannel) getUserName(userID int) string {
|
||||
users, err := c.vk.UsersGet(api.Params{
|
||||
"user_ids": userID,
|
||||
})
|
||||
if err != nil || len(users) == 0 {
|
||||
return strconv.Itoa(userID)
|
||||
}
|
||||
|
||||
user := users[0]
|
||||
return fmt.Sprintf("%s %s", user.FirstName, user.LastName)
|
||||
}
|
||||
|
||||
func (c *VKChannel) processAttachments(attachments []object.MessagesMessageAttachment) string {
|
||||
var parts []string
|
||||
|
||||
for _, att := range attachments {
|
||||
switch att.Type {
|
||||
case "photo":
|
||||
parts = append(parts, "[photo]")
|
||||
case "video":
|
||||
parts = append(parts, "[video]")
|
||||
case "audio":
|
||||
parts = append(parts, "[audio]")
|
||||
case "doc":
|
||||
if att.Doc.Title != "" {
|
||||
parts = append(parts, fmt.Sprintf("[document: %s]", att.Doc.Title))
|
||||
} else {
|
||||
parts = append(parts, "[document]")
|
||||
}
|
||||
case "audio_message":
|
||||
parts = append(parts, "[voice]")
|
||||
case "sticker":
|
||||
parts = append(parts, "[sticker]")
|
||||
}
|
||||
}
|
||||
|
||||
return strings.Join(parts, " ")
|
||||
}
|
||||
|
||||
func (c *VKChannel) VoiceCapabilities() channels.VoiceCapabilities {
|
||||
return channels.VoiceCapabilities{ASR: true, TTS: true}
|
||||
}
|
||||
@@ -1,252 +0,0 @@
|
||||
package vk
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/sipeed/picoclaw/pkg/bus"
|
||||
"github.com/sipeed/picoclaw/pkg/channels"
|
||||
"github.com/sipeed/picoclaw/pkg/config"
|
||||
)
|
||||
|
||||
func makeVKTestBaseChannel(vkCfg config.VKSettings) *config.Channel {
|
||||
settings, _ := json.Marshal(vkCfg)
|
||||
return &config.Channel{
|
||||
Enabled: true,
|
||||
Type: config.ChannelVK,
|
||||
Settings: settings,
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewVKChannel(t *testing.T) {
|
||||
msgBus := bus.NewMessageBus()
|
||||
|
||||
t.Run("missing group_id", func(t *testing.T) {
|
||||
bc := makeVKTestBaseChannel(config.VKSettings{
|
||||
Token: *config.NewSecureString("test_token"),
|
||||
})
|
||||
ch, err := NewVKChannel("vk", bc, msgBus)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error during creation: %v", err)
|
||||
}
|
||||
if ch.Name() != "vk" {
|
||||
t.Errorf("Name() = %q, want %q", ch.Name(), "vk")
|
||||
}
|
||||
if ch.IsRunning() {
|
||||
t.Error("new channel should not be running")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("valid config with group_id", func(t *testing.T) {
|
||||
bc := makeVKTestBaseChannel(config.VKSettings{
|
||||
Token: *config.NewSecureString("test_token"),
|
||||
GroupID: 123456789,
|
||||
})
|
||||
ch, err := NewVKChannel("vk", bc, msgBus)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if ch.Name() != "vk" {
|
||||
t.Errorf("Name() = %q, want %q", ch.Name(), "vk")
|
||||
}
|
||||
if ch.IsRunning() {
|
||||
t.Error("new channel should not be running")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("with allow_from", func(t *testing.T) {
|
||||
vkCfg := config.VKSettings{
|
||||
Token: *config.NewSecureString("test_token"),
|
||||
GroupID: 123456789,
|
||||
}
|
||||
settings, _ := json.Marshal(vkCfg)
|
||||
bc := &config.Channel{
|
||||
Enabled: true,
|
||||
Type: "vk",
|
||||
AllowFrom: []string{"123456789"},
|
||||
Settings: settings,
|
||||
}
|
||||
ch, err := NewVKChannel("vk", bc, msgBus)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !ch.IsAllowedSender(bus.SenderInfo{PlatformID: "123456789"}) {
|
||||
t.Error("user 123456789 should be allowed")
|
||||
}
|
||||
if ch.IsAllowedSender(bus.SenderInfo{PlatformID: "999999999"}) {
|
||||
t.Error("user 999999999 should not be allowed")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("with group_trigger", func(t *testing.T) {
|
||||
vkCfg := config.VKSettings{
|
||||
Token: *config.NewSecureString("test_token"),
|
||||
GroupID: 123456789,
|
||||
}
|
||||
settings, _ := json.Marshal(vkCfg)
|
||||
bc := &config.Channel{
|
||||
Enabled: true,
|
||||
Type: "vk",
|
||||
GroupTrigger: config.GroupTriggerConfig{
|
||||
MentionOnly: false,
|
||||
Prefixes: []string{"/bot", "!bot"},
|
||||
},
|
||||
Settings: settings,
|
||||
}
|
||||
ch, err := NewVKChannel("vk", bc, msgBus)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if ch.Name() != "vk" {
|
||||
t.Errorf("Name() = %q, want %q", ch.Name(), "vk")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestVKChannel_MaxMessageLength(t *testing.T) {
|
||||
msgBus := bus.NewMessageBus()
|
||||
bc := makeVKTestBaseChannel(config.VKSettings{
|
||||
Token: *config.NewSecureString("test_token"),
|
||||
GroupID: 123456789,
|
||||
})
|
||||
ch, err := NewVKChannel("vk", bc, msgBus)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
maxLen := ch.MaxMessageLength()
|
||||
if maxLen != 4000 {
|
||||
t.Errorf("MaxMessageLength() = %d, want 4000", maxLen)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVKChannel_SplitMessage(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
content string
|
||||
maxLen int
|
||||
want int
|
||||
}{
|
||||
{
|
||||
name: "short message",
|
||||
content: "hello",
|
||||
maxLen: 4000,
|
||||
want: 1,
|
||||
},
|
||||
{
|
||||
name: "exact length",
|
||||
content: string(make([]byte, 4000)),
|
||||
maxLen: 4000,
|
||||
want: 1,
|
||||
},
|
||||
{
|
||||
name: "needs split",
|
||||
content: string(make([]byte, 5000)),
|
||||
maxLen: 4000,
|
||||
want: 2,
|
||||
},
|
||||
{
|
||||
name: "empty message",
|
||||
content: "",
|
||||
maxLen: 4000,
|
||||
want: 0,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := channels.SplitMessage(tt.content, tt.maxLen)
|
||||
if len(got) != tt.want {
|
||||
t.Errorf("SplitMessage() got %d parts, want %d parts", len(got), tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestVKChannel_ProcessAttachments(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
attachments []string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "empty attachments",
|
||||
attachments: []string{},
|
||||
want: "",
|
||||
},
|
||||
{
|
||||
name: "photo attachment",
|
||||
attachments: []string{"photo"},
|
||||
want: "[photo]",
|
||||
},
|
||||
{
|
||||
name: "video attachment",
|
||||
attachments: []string{"video"},
|
||||
want: "[video]",
|
||||
},
|
||||
{
|
||||
name: "audio attachment",
|
||||
attachments: []string{"audio"},
|
||||
want: "[audio]",
|
||||
},
|
||||
{
|
||||
name: "document attachment",
|
||||
attachments: []string{"doc"},
|
||||
want: "[doc]",
|
||||
},
|
||||
{
|
||||
name: "sticker attachment",
|
||||
attachments: []string{"sticker"},
|
||||
want: "[sticker]",
|
||||
},
|
||||
{
|
||||
name: "audio_message attachment",
|
||||
attachments: []string{"audio_message"},
|
||||
want: "[voice]",
|
||||
},
|
||||
{
|
||||
name: "multiple attachments",
|
||||
attachments: []string{"photo", "video", "audio"},
|
||||
want: "[photo] [video] [audio]",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
var result string
|
||||
for i, att := range tt.attachments {
|
||||
if i > 0 {
|
||||
result += " "
|
||||
}
|
||||
if att == "audio_message" {
|
||||
result += "[voice]"
|
||||
} else {
|
||||
result += "[" + att + "]"
|
||||
}
|
||||
}
|
||||
if result != tt.want {
|
||||
t.Errorf("processAttachments() = %q, want %q", result, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestVKChannel_VoiceCapabilities(t *testing.T) {
|
||||
msgBus := bus.NewMessageBus()
|
||||
bc := makeVKTestBaseChannel(config.VKSettings{
|
||||
Token: *config.NewSecureString("test_token"),
|
||||
GroupID: 123456789,
|
||||
})
|
||||
ch, err := NewVKChannel("vk", bc, msgBus)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
caps := ch.VoiceCapabilities()
|
||||
if !caps.ASR {
|
||||
t.Error("VoiceCapabilities().ASR should be true")
|
||||
}
|
||||
if !caps.TTS {
|
||||
t.Error("VoiceCapabilities().TTS should be true")
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,6 @@ type VoiceCapabilityProvider interface {
|
||||
var asrCapableChannels = map[string]bool{
|
||||
"discord": true,
|
||||
"telegram": true,
|
||||
"matrix": true,
|
||||
"qq": true,
|
||||
"weixin": true,
|
||||
"line": true,
|
||||
|
||||
@@ -133,7 +133,7 @@ func TestBuiltinShowChannel_PreservesUserVisibleBehavior(t *testing.T) {
|
||||
func TestBuiltinListChannels_UsesGetEnabledChannels(t *testing.T) {
|
||||
rt := &Runtime{
|
||||
GetEnabledChannels: func() []string {
|
||||
return []string{"telegram", "slack"}
|
||||
return []string{"telegram", "discord"}
|
||||
},
|
||||
}
|
||||
defs := BuiltinDefinitions()
|
||||
@@ -150,8 +150,8 @@ func TestBuiltinListChannels_UsesGetEnabledChannels(t *testing.T) {
|
||||
if res.Outcome != OutcomeHandled {
|
||||
t.Fatalf("/list channels: outcome=%v, want=%v", res.Outcome, OutcomeHandled)
|
||||
}
|
||||
if !strings.Contains(reply, "telegram") || !strings.Contains(reply, "slack") {
|
||||
t.Fatalf("/list channels reply=%q, want telegram and slack", reply)
|
||||
if !strings.Contains(reply, "telegram") || !strings.Contains(reply, "discord") {
|
||||
t.Fatalf("/list channels reply=%q, want telegram and discord", reply)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -574,47 +574,6 @@ type DingTalkSettings struct {
|
||||
ClientSecret SecureString `json:"client_secret,omitzero" yaml:"client_secret,omitempty" env:"PICOCLAW_CHANNELS_DINGTALK_CLIENT_SECRET"`
|
||||
}
|
||||
|
||||
type SlackSettings struct {
|
||||
BotToken SecureString `json:"bot_token,omitzero" yaml:"bot_token,omitempty" env:"PICOCLAW_CHANNELS_SLACK_BOT_TOKEN"`
|
||||
AppToken SecureString `json:"app_token,omitzero" yaml:"app_token,omitempty" env:"PICOCLAW_CHANNELS_SLACK_APP_TOKEN"`
|
||||
}
|
||||
|
||||
type MatrixSettings struct {
|
||||
Homeserver string `json:"homeserver" yaml:"-" env:"PICOCLAW_CHANNELS_MATRIX_HOMESERVER"`
|
||||
UserID string `json:"user_id" yaml:"-" env:"PICOCLAW_CHANNELS_MATRIX_USER_ID"`
|
||||
AccessToken SecureString `json:"access_token,omitzero" yaml:"access_token,omitempty" env:"PICOCLAW_CHANNELS_MATRIX_ACCESS_TOKEN"`
|
||||
DeviceID string `json:"device_id,omitempty" yaml:"-"`
|
||||
JoinOnInvite bool `json:"join_on_invite" yaml:"-"`
|
||||
MessageFormat string `json:"message_format,omitempty" yaml:"-"`
|
||||
CryptoDatabasePath string `json:"crypto_database_path,omitempty" yaml:"-"`
|
||||
CryptoPassphrase string `json:"crypto_passphrase,omitempty" yaml:"-"`
|
||||
}
|
||||
|
||||
// DeltaChatSettings configures the Delta Chat channel. Delta Chat is an
|
||||
// email-based, end-to-end encrypted messenger; PicoClaw talks to a local
|
||||
// `deltachat-rpc-server` process over JSON-RPC (stdio).
|
||||
//
|
||||
// Email is the only required setting. A full address selects an already
|
||||
// configured account in DataDir; a first-run marker such as "@nine.testrun.org"
|
||||
// creates a chatmail account and tells the user which full email to save.
|
||||
// Mailbox credentials stay in the Delta Chat account store. DisplayName and
|
||||
// AvatarImage are optional profile settings applied on startup. Password remains
|
||||
// only for legacy PicoClaw-managed email configuration.
|
||||
type DeltaChatSettings struct {
|
||||
Email string `json:"email" yaml:"-" env:"PICOCLAW_CHANNELS_DELTACHAT_EMAIL"`
|
||||
Password SecureString `json:"password,omitzero" yaml:"password,omitempty" env:"PICOCLAW_CHANNELS_DELTACHAT_PASSWORD"`
|
||||
DisplayName string `json:"display_name,omitempty" yaml:"-" env:"PICOCLAW_CHANNELS_DELTACHAT_DISPLAY_NAME"`
|
||||
AvatarImage string `json:"avatar_image,omitempty" yaml:"-" env:"PICOCLAW_CHANNELS_DELTACHAT_AVATAR_IMAGE"`
|
||||
DataDir string `json:"data_dir,omitempty" yaml:"-" env:"PICOCLAW_CHANNELS_DELTACHAT_DATA_DIR"`
|
||||
RPCServerPath string `json:"rpc_server_path,omitempty" yaml:"-" env:"PICOCLAW_CHANNELS_DELTACHAT_RPC_SERVER_PATH"`
|
||||
InviteLink string `json:"invite_link,omitempty" yaml:"-" env:"PICOCLAW_CHANNELS_DELTACHAT_INVITE_LINK"`
|
||||
AllowCrosspost bool `json:"allow_crosspost,omitempty" yaml:"-" env:"PICOCLAW_CHANNELS_DELTACHAT_ALLOW_CROSSPOST"`
|
||||
IMAPServer string `json:"imap_server,omitempty" yaml:"-"`
|
||||
IMAPPort int `json:"imap_port,omitempty" yaml:"-"`
|
||||
SMTPServer string `json:"smtp_server,omitempty" yaml:"-"`
|
||||
SMTPPort int `json:"smtp_port,omitempty" yaml:"-"`
|
||||
}
|
||||
|
||||
type LINESettings struct {
|
||||
ChannelSecret SecureString `json:"channel_secret,omitzero" yaml:"channel_secret,omitempty" env:"PICOCLAW_CHANNELS_LINE_CHANNEL_SECRET"`
|
||||
ChannelAccessToken SecureString `json:"channel_access_token,omitzero" yaml:"channel_access_token,omitempty" env:"PICOCLAW_CHANNELS_LINE_CHANNEL_ACCESS_TOKEN"`
|
||||
@@ -659,41 +618,6 @@ func (c *WeixinSettings) SetToken(token string) {
|
||||
c.Token = *NewSecureString(token)
|
||||
}
|
||||
|
||||
type IRCSettings struct {
|
||||
Server string `json:"server" yaml:"-" env:"PICOCLAW_CHANNELS_IRC_SERVER"`
|
||||
TLS bool `json:"tls" yaml:"-" env:"PICOCLAW_CHANNELS_IRC_TLS"`
|
||||
Nick string `json:"nick" yaml:"-" env:"PICOCLAW_CHANNELS_IRC_NICK"`
|
||||
User string `json:"user,omitempty" yaml:"-" env:"PICOCLAW_CHANNELS_IRC_USER"`
|
||||
RealName string `json:"real_name,omitempty" yaml:"-"`
|
||||
Password SecureString `json:"password,omitzero" yaml:"password,omitempty" env:"PICOCLAW_CHANNELS_IRC_PASSWORD"`
|
||||
NickServPassword SecureString `json:"nickserv_password,omitzero" yaml:"nickserv_password,omitempty" env:"PICOCLAW_CHANNELS_IRC_NICKSERV_PASSWORD"`
|
||||
SASLUser string `json:"sasl_user" yaml:"-" env:"PICOCLAW_CHANNELS_IRC_SASL_USER"`
|
||||
SASLPassword SecureString `json:"sasl_password,omitzero" yaml:"sasl_password,omitempty" env:"PICOCLAW_CHANNELS_IRC_SASL_PASSWORD"`
|
||||
Channels FlexibleStringSlice `json:"channels" yaml:"-" env:"PICOCLAW_CHANNELS_IRC_CHANNELS"`
|
||||
RequestCaps FlexibleStringSlice `json:"request_caps,omitempty" yaml:"-"`
|
||||
}
|
||||
|
||||
type VKSettings struct {
|
||||
Token SecureString `json:"token,omitzero" yaml:"token,omitempty" env:"PICOCLAW_CHANNELS_VK_TOKEN"`
|
||||
GroupID int `json:"group_id" yaml:"-" env:"PICOCLAW_CHANNELS_VK_GROUP_ID"`
|
||||
}
|
||||
|
||||
func (c *VKSettings) SetToken(token string) {
|
||||
c.Token = *NewSecureString(token)
|
||||
}
|
||||
|
||||
// TeamsWebhookSettings configures the output-only Microsoft Teams webhook channel.
|
||||
// Multiple webhook targets can be configured and selected via ChatID at send time.
|
||||
type TeamsWebhookSettings struct {
|
||||
Webhooks map[string]TeamsWebhookTarget `json:"webhooks" yaml:"webhooks,omitempty"`
|
||||
}
|
||||
|
||||
// TeamsWebhookTarget represents a single Teams webhook destination.
|
||||
type TeamsWebhookTarget struct {
|
||||
WebhookURL SecureString `json:"webhook_url,omitzero" yaml:"webhook_url,omitempty"`
|
||||
Title string `json:"title,omitempty" yaml:"-"`
|
||||
}
|
||||
|
||||
type MQTTSettings struct {
|
||||
Broker string `json:"broker" yaml:"-" env:"PICOCLAW_CHANNELS_MQTT_BROKER"`
|
||||
AgentID string `json:"agent_id" yaml:"-" env:"PICOCLAW_CHANNELS_MQTT_AGENT_ID"`
|
||||
@@ -705,18 +629,6 @@ type MQTTSettings struct {
|
||||
QoS int `json:"qos,omitempty" yaml:"-" env:"PICOCLAW_CHANNELS_MQTT_QOS"`
|
||||
}
|
||||
|
||||
// SlackWebhookSettings configures the output-only Slack webhook channel.
|
||||
type SlackWebhookSettings struct {
|
||||
Webhooks map[string]SlackWebhookTarget `json:"webhooks" yaml:"webhooks,omitempty"`
|
||||
}
|
||||
|
||||
// SlackWebhookTarget represents a single Slack Incoming Webhook destination.
|
||||
type SlackWebhookTarget struct {
|
||||
WebhookURL SecureString `json:"webhook_url,omitzero" yaml:"webhook_url,omitempty"`
|
||||
Username string `json:"username,omitempty" yaml:"-"`
|
||||
IconEmoji string `json:"icon_emoji,omitempty" yaml:"-"`
|
||||
}
|
||||
|
||||
type HeartbeatConfig struct {
|
||||
Enabled bool `json:"enabled" env:"PICOCLAW_HEARTBEAT_ENABLED"`
|
||||
Interval int `json:"interval" env:"PICOCLAW_HEARTBEAT_INTERVAL"` // minutes, min 5
|
||||
|
||||
@@ -23,19 +23,12 @@ const (
|
||||
ChannelWeixin = "weixin"
|
||||
ChannelWeCom = "wecom"
|
||||
ChannelDingTalk = "dingtalk"
|
||||
ChannelSlack = "slack"
|
||||
ChannelMatrix = "matrix"
|
||||
ChannelDeltaChat = "deltachat"
|
||||
ChannelLINE = "line"
|
||||
ChannelOneBot = "onebot"
|
||||
ChannelQQ = "qq"
|
||||
ChannelIRC = "irc"
|
||||
ChannelVK = "vk"
|
||||
ChannelWhatsApp = "whatsapp"
|
||||
ChannelWhatsAppNative = "whatsapp_native"
|
||||
ChannelTeamsWebHook = "teams_webhook"
|
||||
ChannelMQTT = "mqtt"
|
||||
ChannelSlackWebHook = "slack_webhook"
|
||||
)
|
||||
|
||||
// RawNode stores raw configuration data as JSON bytes, supporting both JSON and YAML.
|
||||
@@ -611,19 +604,12 @@ var channelSettingsFactory = map[string]any{
|
||||
ChannelWeixin: (WeixinSettings{}),
|
||||
ChannelWeCom: (WeComSettings{}),
|
||||
ChannelDingTalk: (DingTalkSettings{}),
|
||||
ChannelSlack: (SlackSettings{}),
|
||||
ChannelMatrix: (MatrixSettings{}),
|
||||
ChannelDeltaChat: (DeltaChatSettings{}),
|
||||
ChannelLINE: (LINESettings{}),
|
||||
ChannelOneBot: (OneBotSettings{}),
|
||||
ChannelQQ: (QQSettings{}),
|
||||
ChannelIRC: (IRCSettings{}),
|
||||
ChannelVK: (VKSettings{}),
|
||||
ChannelWhatsApp: (WhatsAppSettings{}),
|
||||
ChannelWhatsAppNative: (WhatsAppSettings{}),
|
||||
ChannelTeamsWebHook: (TeamsWebhookSettings{}),
|
||||
ChannelMQTT: (MQTTSettings{}),
|
||||
ChannelSlackWebHook: (SlackWebhookSettings{}),
|
||||
}
|
||||
|
||||
// RegisterChannelSettings registers a settings struct prototype for a custom
|
||||
|
||||
@@ -720,7 +720,7 @@ func TestLoadConfig_MigratesLegacyBindingsToDispatchRules(t *testing.T) {
|
||||
{ "id": "main", "default": true },
|
||||
{ "id": "support" },
|
||||
{ "id": "ops" },
|
||||
{ "id": "slack" }
|
||||
{ "id": "discord" }
|
||||
]
|
||||
},
|
||||
"bindings": [
|
||||
@@ -739,9 +739,9 @@ func TestLoadConfig_MigratesLegacyBindingsToDispatchRules(t *testing.T) {
|
||||
}
|
||||
},
|
||||
{
|
||||
"agent_id": "slack",
|
||||
"agent_id": "discord",
|
||||
"match": {
|
||||
"channel": "slack",
|
||||
"channel": "discord",
|
||||
"account_id": "*"
|
||||
}
|
||||
}
|
||||
@@ -779,10 +779,10 @@ func TestLoadConfig_MigratesLegacyBindingsToDispatchRules(t *testing.T) {
|
||||
}
|
||||
|
||||
third := cfg.Agents.Dispatch.Rules[2]
|
||||
if third.Agent != "slack" {
|
||||
t.Fatalf("third.Agent = %q, want %q", third.Agent, "slack")
|
||||
if third.Agent != "discord" {
|
||||
t.Fatalf("third.Agent = %q, want %q", third.Agent, "discord")
|
||||
}
|
||||
if third.When.Channel != "slack" || third.When.Account != "" {
|
||||
if third.When.Channel != "discord" || third.When.Account != "" {
|
||||
t.Fatalf("third.When = %+v", third.When)
|
||||
}
|
||||
}
|
||||
@@ -1004,38 +1004,6 @@ func TestDefaultConfig_ChannelStreamingDisabled(t *testing.T) {
|
||||
|
||||
}
|
||||
|
||||
func TestDefaultConfig_DeltaChatExample(t *testing.T) {
|
||||
cfg := DefaultConfig()
|
||||
|
||||
deltachat := cfg.Channels.Get(ChannelDeltaChat)
|
||||
if deltachat == nil {
|
||||
t.Fatal("DefaultConfig() missing deltachat channel")
|
||||
}
|
||||
if deltachat.Enabled {
|
||||
t.Fatal("DefaultConfig().deltachat should be disabled")
|
||||
}
|
||||
if !deltachat.GroupTrigger.MentionOnly {
|
||||
t.Fatal("DefaultConfig().deltachat should use mention-only group trigger")
|
||||
}
|
||||
decoded, err := deltachat.GetDecoded()
|
||||
if err != nil {
|
||||
t.Fatalf("deltachat GetDecoded() error = %v", err)
|
||||
}
|
||||
settings, ok := decoded.(*DeltaChatSettings)
|
||||
if !ok {
|
||||
t.Fatalf("deltachat settings type = %T, want *DeltaChatSettings", decoded)
|
||||
}
|
||||
if settings.Email != "@nine.testrun.org" {
|
||||
t.Fatalf("DefaultConfig().deltachat.settings.email = %q, want @nine.testrun.org", settings.Email)
|
||||
}
|
||||
if settings.Password.String() != "" {
|
||||
t.Fatal("DefaultConfig().deltachat.settings.password should be empty")
|
||||
}
|
||||
if settings.DisplayName == "" {
|
||||
t.Fatal("DefaultConfig().deltachat.settings.display_name should be populated")
|
||||
}
|
||||
}
|
||||
|
||||
// TestDefaultConfig_WebTools verifies web tools config
|
||||
func TestDefaultConfig_WebTools(t *testing.T) {
|
||||
cfg := DefaultConfig()
|
||||
@@ -2909,16 +2877,6 @@ func TestFilterSensitiveData_AllTokenTypes(t *testing.T) {
|
||||
content: "Discord token: discord-bot-token-xyz789",
|
||||
want: "Discord token: [FILTERED]",
|
||||
},
|
||||
{
|
||||
name: "slack_tokens",
|
||||
content: "Slack bot: xoxb-slack-bot-token, app: xapp-slack-app-token",
|
||||
want: "Slack bot: [FILTERED], app: [FILTERED]",
|
||||
},
|
||||
{
|
||||
name: "matrix_token",
|
||||
content: "Matrix access token: matrix-access-token-abc",
|
||||
want: "Matrix access token: [FILTERED]",
|
||||
},
|
||||
{
|
||||
name: "brave_api_key",
|
||||
content: "Brave key: brave-api-key",
|
||||
@@ -2934,11 +2892,6 @@ func TestFilterSensitiveData_AllTokenTypes(t *testing.T) {
|
||||
content: "GitHub token: github-token-xyz",
|
||||
want: "GitHub token: [FILTERED]",
|
||||
},
|
||||
{
|
||||
name: "irc_passwords",
|
||||
content: "IRC password: irc-password, nickserv: nickserv-pass",
|
||||
want: "IRC password: [FILTERED], nickserv: [FILTERED]",
|
||||
},
|
||||
{
|
||||
name: "mixed_content",
|
||||
content: "Model key sk-model-key-12345 and Telegram token telegram-bot-token-abcdef",
|
||||
@@ -3129,14 +3082,6 @@ func testChannelsConfigWithTokens() ChannelsConfig {
|
||||
defs := []chDef{
|
||||
{"telegram", TelegramSettings{Token: *NewSecureString("telegram-bot-token-abcdef")}},
|
||||
{"discord", DiscordSettings{Token: *NewSecureString("discord-bot-token-xyz789")}},
|
||||
{
|
||||
"slack",
|
||||
SlackSettings{
|
||||
BotToken: *NewSecureString("xoxb-slack-bot-token"),
|
||||
AppToken: *NewSecureString("xapp-slack-app-token"),
|
||||
},
|
||||
},
|
||||
{"matrix", MatrixSettings{AccessToken: *NewSecureString("matrix-access-token-abc")}},
|
||||
{
|
||||
"feishu",
|
||||
FeishuSettings{
|
||||
@@ -3147,14 +3092,6 @@ func testChannelsConfigWithTokens() ChannelsConfig {
|
||||
{"dingtalk", DingTalkSettings{ClientSecret: *NewSecureString("dingtalk-client-secret")}},
|
||||
{"onebot", OneBotSettings{AccessToken: *NewSecureString("onebot-access-token")}},
|
||||
{"wecom", WeComSettings{Secret: *NewSecureString("wecom-secret")}},
|
||||
{
|
||||
"irc",
|
||||
IRCSettings{
|
||||
Password: *NewSecureString("irc-password"),
|
||||
NickServPassword: *NewSecureString("nickserv-pass"),
|
||||
SASLPassword: *NewSecureString("sasl-pass"),
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, def := range defs {
|
||||
// Create Channel directly with settings to preserve SecureString values
|
||||
|
||||
@@ -537,22 +537,6 @@ func defaultChannels() ChannelsConfig {
|
||||
"settings": map[string]any{"max_message_length": 2000},
|
||||
},
|
||||
"dingtalk": map[string]any{},
|
||||
"slack": map[string]any{},
|
||||
"matrix": map[string]any{
|
||||
"group_trigger": map[string]any{"mention_only": true},
|
||||
"placeholder": map[string]any{"enabled": true, "text": []string{"Thinking... 💭"}},
|
||||
"settings": map[string]any{
|
||||
"homeserver": "https://matrix.org",
|
||||
"join_on_invite": true,
|
||||
},
|
||||
},
|
||||
"deltachat": map[string]any{
|
||||
"group_trigger": map[string]any{"mention_only": true},
|
||||
"settings": map[string]any{
|
||||
"email": "@nine.testrun.org",
|
||||
"display_name": "PicoClaw Bot",
|
||||
},
|
||||
},
|
||||
"line": map[string]any{
|
||||
"group_trigger": map[string]any{"mention_only": true},
|
||||
"settings": map[string]any{
|
||||
@@ -579,14 +563,6 @@ func defaultChannels() ChannelsConfig {
|
||||
"cdn_base_url": "https://novac2c.cdn.weixin.qq.com/c2c",
|
||||
},
|
||||
},
|
||||
"irc": map[string]any{
|
||||
"settings": map[string]any{
|
||||
"server": "",
|
||||
"tls": true,
|
||||
"nick": "picoclaw",
|
||||
"channels": []string{},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
channels := make(ChannelsConfig, len(defs))
|
||||
|
||||
@@ -212,11 +212,6 @@ channels:
|
||||
app_secret: "value"
|
||||
dingtalk:
|
||||
client_secret: "value"
|
||||
slack:
|
||||
bot_token: "value"
|
||||
app_token: "value"
|
||||
matrix:
|
||||
access_token: "value"
|
||||
line:
|
||||
channel_secret: "value"
|
||||
channel_access_token: "value"
|
||||
@@ -233,12 +228,6 @@ channels:
|
||||
secret: "value"
|
||||
token: "value"
|
||||
encoding_aes_key: "value"
|
||||
pico:
|
||||
token: "value"
|
||||
irc:
|
||||
password: "value"
|
||||
nickserv_password: "value"
|
||||
sasl_password: "value"
|
||||
|
||||
## Web Tool API Keys
|
||||
|
||||
|
||||
@@ -228,14 +228,6 @@ func TestAllSecurityKeysAccessible(t *testing.T) {
|
||||
"enabled": true,
|
||||
"client_id": "test_client_id"
|
||||
},
|
||||
"slack": {
|
||||
"enabled": true
|
||||
},
|
||||
"matrix": {
|
||||
"enabled": true,
|
||||
"homeserver": "https://matrix.org",
|
||||
"user_id": "@test:matrix.org"
|
||||
},
|
||||
"line": {
|
||||
"enabled": true,
|
||||
"webhook_host": "localhost",
|
||||
@@ -250,11 +242,6 @@ func TestAllSecurityKeysAccessible(t *testing.T) {
|
||||
"enabled": true,
|
||||
"bot_id": "test_wecom_bot_id"
|
||||
},
|
||||
"irc": {
|
||||
"enabled": true,
|
||||
"server": "irc.example.com",
|
||||
"nick": "testbot"
|
||||
},
|
||||
"qq": {
|
||||
"enabled": true,
|
||||
"app_id": "test_qq_app_id"
|
||||
@@ -304,11 +291,6 @@ channels:
|
||||
token: "discord_test_bot_token_xyz"
|
||||
dingtalk:
|
||||
client_secret: "dingtalk_test_client_secret"
|
||||
slack:
|
||||
bot_token: "xoxb-slack-bot-token-123"
|
||||
app_token: "xapp-slack-app-token-456"
|
||||
matrix:
|
||||
access_token: "matrix_test_access_token"
|
||||
line:
|
||||
channel_secret: "line_test_channel_secret"
|
||||
channel_access_token: "line_test_channel_access_token"
|
||||
@@ -316,10 +298,6 @@ channels:
|
||||
access_token: "onebot_test_access_token"
|
||||
wecom:
|
||||
secret: "wecom_test_secret"
|
||||
irc:
|
||||
password: "irc_test_password"
|
||||
nickserv_password: "irc_test_nickserv_password"
|
||||
sasl_password: "irc_test_sasl_password"
|
||||
qq:
|
||||
app_secret: "qq_test_app_secret"
|
||||
|
||||
@@ -401,18 +379,6 @@ skills:
|
||||
assert.Equal(t, "dingtalk_test_client_secret", secureStr(dtSec.(*DingTalkSettings).ClientSecret))
|
||||
t.Logf("DingTalk ClientSecret(): %s", secureStr(dtSec.(*DingTalkSettings).ClientSecret))
|
||||
|
||||
// Slack
|
||||
slSec := decodeChannel("slack")
|
||||
assert.Equal(t, "xoxb-slack-bot-token-123", secureStr(slSec.(*SlackSettings).BotToken))
|
||||
assert.Equal(t, "xapp-slack-app-token-456", secureStr(slSec.(*SlackSettings).AppToken))
|
||||
t.Logf("Slack BotToken(): %s", secureStr(slSec.(*SlackSettings).BotToken))
|
||||
t.Logf("Slack AppToken(): %s", secureStr(slSec.(*SlackSettings).AppToken))
|
||||
|
||||
// Matrix
|
||||
matSec := decodeChannel("matrix")
|
||||
assert.Equal(t, "matrix_test_access_token", secureStr(matSec.(*MatrixSettings).AccessToken))
|
||||
t.Logf("Matrix AccessToken(): %s", secureStr(matSec.(*MatrixSettings).AccessToken))
|
||||
|
||||
// LINE
|
||||
lineSec := decodeChannel("line")
|
||||
assert.Equal(t, "line_test_channel_secret", secureStr(lineSec.(*LINESettings).ChannelSecret))
|
||||
@@ -432,15 +398,6 @@ skills:
|
||||
t.Logf("WeCom BotID: %s", wcSec.(*WeComSettings).BotID)
|
||||
t.Logf("WeCom Secret(): %s", secureStr(wcSec.(*WeComSettings).Secret))
|
||||
|
||||
// IRC
|
||||
ircSec := decodeChannel("irc")
|
||||
assert.Equal(t, "irc_test_password", secureStr(ircSec.(*IRCSettings).Password))
|
||||
assert.Equal(t, "irc_test_nickserv_password", secureStr(ircSec.(*IRCSettings).NickServPassword))
|
||||
assert.Equal(t, "irc_test_sasl_password", secureStr(ircSec.(*IRCSettings).SASLPassword))
|
||||
t.Logf("IRC Password(): %s", secureStr(ircSec.(*IRCSettings).Password))
|
||||
t.Logf("IRC NickServPassword(): %s", secureStr(ircSec.(*IRCSettings).NickServPassword))
|
||||
t.Logf("IRC SASLPassword(): %s", secureStr(ircSec.(*IRCSettings).SASLPassword))
|
||||
|
||||
// QQ
|
||||
qqSec := decodeChannel("qq")
|
||||
assert.Equal(t, "qq_test_app_secret", secureStr(qqSec.(*QQSettings).AppSecret))
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
//go:build !mipsle && !netbsd && !(freebsd && arm) && !android
|
||||
|
||||
package gateway
|
||||
|
||||
import (
|
||||
// Matrix currently pulls in mautrix crypto and modernc sqlite transitively.
|
||||
//
|
||||
// We exclude it on:
|
||||
// - linux/mipsle: mautrix crypto falls back to libolm when the `goolm` build
|
||||
// tag is unavailable, and modernc.org/sqlite/modernc.org/libc also lacks a
|
||||
// working build path for our mipsle + softfloat target.
|
||||
// - netbsd/*: modernc.org/sqlite v1.46.1 fails to compile due to broken
|
||||
// generated mutex code on NetBSD (for example sqlite_netbsd_amd64.go calls
|
||||
// mu.enter/mu.leave, but the generated mutex type does not define them).
|
||||
// - freebsd/arm: modernc.org/libc v1.67.6 fails to compile due to broken
|
||||
// generated 32-bit FreeBSD code (size_t/uint64 and int32/int64 mismatches
|
||||
// in libc_freebsd.go).
|
||||
//
|
||||
// This means Matrix is currently unavailable on those targets. The proper
|
||||
// long-term fix is to split Matrix basic support from its E2EE/sqlite-backed
|
||||
// crypto path, or to upgrade/replace the upstream sqlite dependency once the
|
||||
// affected targets are supported.
|
||||
_ "github.com/sipeed/picoclaw/pkg/channels/matrix"
|
||||
)
|
||||
@@ -19,20 +19,14 @@ 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/channels/deltachat"
|
||||
_ "github.com/sipeed/picoclaw/pkg/channels/dingtalk"
|
||||
_ "github.com/sipeed/picoclaw/pkg/channels/discord"
|
||||
_ "github.com/sipeed/picoclaw/pkg/channels/feishu"
|
||||
_ "github.com/sipeed/picoclaw/pkg/channels/irc"
|
||||
_ "github.com/sipeed/picoclaw/pkg/channels/line"
|
||||
_ "github.com/sipeed/picoclaw/pkg/channels/mqtt"
|
||||
_ "github.com/sipeed/picoclaw/pkg/channels/onebot"
|
||||
_ "github.com/sipeed/picoclaw/pkg/channels/qq"
|
||||
_ "github.com/sipeed/picoclaw/pkg/channels/slack"
|
||||
_ "github.com/sipeed/picoclaw/pkg/channels/slack_webhook"
|
||||
_ "github.com/sipeed/picoclaw/pkg/channels/teams_webhook"
|
||||
_ "github.com/sipeed/picoclaw/pkg/channels/telegram"
|
||||
_ "github.com/sipeed/picoclaw/pkg/channels/vk"
|
||||
_ "github.com/sipeed/picoclaw/pkg/channels/wecom"
|
||||
_ "github.com/sipeed/picoclaw/pkg/channels/weixin"
|
||||
_ "github.com/sipeed/picoclaw/pkg/channels/whatsapp"
|
||||
|
||||
@@ -14,7 +14,7 @@ func TestBuildCanonicalID(t *testing.T) {
|
||||
}{
|
||||
{"telegram", "123456", "telegram:123456"},
|
||||
{"Discord", "98765432", "discord:98765432"},
|
||||
{"SLACK", "U123ABC", "slack:U123ABC"},
|
||||
{"DISCORD", "U123ABC", "discord:U123ABC"},
|
||||
{"", "123", ""},
|
||||
{"telegram", "", ""},
|
||||
{" telegram ", " 123 ", "telegram:123"},
|
||||
@@ -38,7 +38,7 @@ func TestParseCanonicalID(t *testing.T) {
|
||||
}{
|
||||
{"telegram:123456", "telegram", "123456", true},
|
||||
{"discord:98765432", "discord", "98765432", true},
|
||||
{"slack:U123ABC", "slack", "U123ABC", true},
|
||||
{"discord:U123ABC", "discord", "U123ABC", true},
|
||||
{"nocolon", "", "", false},
|
||||
{"", "", "", false},
|
||||
{":missing", "", "", false},
|
||||
|
||||
Loaded 100 of 112 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user