add-wechat
Add WeChat (personal) channel integration via Tencent's official iLink Bot API. Uses long-polling and QR scan — no webhook, no ToS risk, no paid token.
Install
npx skills add https://github.com/nanocoai/nanoclaw/tree/main/.claude/skills/add-wechat
claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install nanocoai-nanoclaw@llmmart
git clone https://github.com/nanocoai/nanoclaw.git
The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole nanocoai/nanoclaw collection as a plugin from our marketplace. Git is the plain clone.
Skill manifest
Add WeChat Channel
Adds WeChat support via iLink Bot API — the first-party Tencent API for personal WeChat bots (different from WeCom / Official Account).
Why this is different from wechaty/PadLocal:
- Official Tencent API — no ToS violation, no ban risk
- Free — no PadLocal token required
- No public webhook URL needed — uses long-poll
- Works with any personal WeChat account
Prerequisites
- A personal WeChat account with the mobile app installed
- A phone to scan the QR code for login
- Node.js >= 20 (already required by NanoClaw)
Install
NanoClaw doesn't ship channels in trunk. This skill copies the WeChat adapter in from the channels branch.
1. Copy the adapter and its registration test
Fetch the channels branch from the configured remote that carries it, then
overwrite the skill-owned files with the canonical registry copies:
src/channels/wechat.ts
src/channels/wechat-registration.test.ts
2. Append the self-registration import
Append to src/channels/index.ts (skip if the line is already present):
import './wechat.js';
3. Install the library (pinned)
wechat-ilink-client@0.1.0
4. Build and validate
pnpm run build
pnpm exec vitest run src/channels/wechat-registration.test.ts
Both must be clean before proceeding. wechat-registration.test.ts is the one integration test: it imports the real channel barrel and asserts the registry contains wechat. It goes red if the import './wechat.js'; line is deleted or drifts, if the barrel fails to evaluate (so the channel genuinely would not register), or if wechat-ilink-client isn't installed (the import throws) — so it also implicitly verifies the dependency from step 4. Importing is safe: the adapter opens its long-poll connection only in setup() (at host startup), never at import.
End-to-end message delivery against a real WeChat account is verified manually once the service is running — see Credentials and Wire your first DM above.
Credentials
Unlike most channels, WeChat requires no pre-configured API keys. Auth happens via QR code scan from your phone.
1. Enable the channel
Add to .env:
WECHAT_ENABLED=true
2. Start the service and scan the QR
Restart NanoClaw.
Run from your NanoClaw project root:
source setup/lib/install-slug.sh
systemctl --user restart $(systemd_unit) # Linux
# or
launchctl kickstart -k gui/$(id -u)/$(launchd_label) # macOS
The adapter will print a QR URL to the logs and save it to data/wechat/qr.txt:
tail -f logs/nanoclaw.log | grep WeChat
# or
cat data/wechat/qr.txt
Open the URL in a browser (it renders a QR code), then:
- Open WeChat on your phone
- Use its built-in QR scanner (top-right "+" → Scan)
- Approve the authorization on your phone
- Auth credentials are saved to
data/wechat/auth.json— do not commit this file
The bot is now connected as your WeChat account.
Wire your first DM
A successful QR login alone isn't enough — the adapter still needs to be wired to an agent group before it can respond.
Prerequisite: the host service must be running. The wire script creates the wiring through ncl, which talks to the running host over a Unix socket — there is no offline mode.
1. Trigger the first inbound message
Have a different WeChat account send a message to the bot account. This auto-creates a messaging_groups row with the sender's platform_id and the unknown_sender_policy the WeChat adapter declares.
2. Run the wire script
pnpm exec tsx .claude/skills/add-wechat/scripts/wire-dm.ts
Interactive flow: the script lists all unwired WeChat messaging groups, asks which agent group to wire it to, and runs ncl wirings create — engage mode/pattern and priority come from the WeChat adapter's declared channel defaults, so a wiring created here matches one created by /manage-channels or the approval-card flow.
With request_approval as the sender policy, the next DM from a stranger fires an approval card to the admin — admin taps Approve/Deny, approved users are added as members and their queued message replays through the agent.
Non-interactive:
pnpm exec tsx .claude/skills/add-wechat/scripts/wire-dm.ts \
--platform-id wechat:wxid_xxxxx \
--agent-group ag-xxxxx \
--non-interactive
Flags:
--platform-id <id>— wire a specific messaging group (default: most recent unwired)--agent-group <id>— target agent group (default: prompt; auto-picked when only one exists)--sender-policy public|strict|request_approval— override the messaging group'sunknown_sender_policy(default: leave whatever the WeChat adapter declared when the row was auto-created)--session-mode shared|per-thread— defaultshared
Equivalent raw ncl invocation (host must be running):
ncl wirings create --messaging-group-id <mg-id> --agent-group-id <ag-id> --session-mode shared
3. Test
Have the sender message the bot again — the agent should respond.
Operational notes
- Only one instance can use a given token at a time. Don't run multiple NanoClaw instances pointing to the same
data/wechat/auth.json. - Re-login on session expiry: if you see
WeChat: session expiredin logs, deletedata/wechat/auth.jsonand restart — you'll be asked to re-scan. - Sync cursor persistence:
data/wechat/sync-buf.txtholds the long-poll cursor. Deleting it replays recent history on next start; don't delete it in normal operation. - Account safety: this uses the official Tencent API, so account bans for bot automation aren't a risk. That said, don't spam — normal rate limits still apply.
Next Steps
If you're in the middle of /setup, return to the setup flow now.
Otherwise, restart the service to pick up the new channel and wiring.
Channel Info
- type:
wechat - terminology: WeChat has "contacts" (DMs) and "group chats" (rooms). Each DM or group is a separate messaging group.
- how-to-find-id: Send a message to the bot from the target account; the adapter auto-creates a messaging group and logs
WeChat inbound platformId=wechat:<id>. Usewechat:<user_id>for DMs,wechat:<group_id>for rooms. - admin-user-id: The operator's WeChat user_id (for
init-first-agent.ts --admin-user-id) is saved todata/wechat/auth.jsonasoperatorUserIdafter the QR scan. Read it withcat data/wechat/auth.json | jq -r .operatorUserIdand prefix withwechat:(i.e.wechat:<operatorUserId>). - supports-threads: no (WeChat has no reply threads)
- typical-use: Long-poll — the adapter holds a persistent connection to Tencent's iLink API and receives messages in real time. No webhook URL needed.
- default-isolation:
sharedsession mode per messaging group (DM or room). Usestrictsender policy if you want only specific users to reach the agent;publicopens it to anyone who messages the bot. - post-install-wiring: Use the
wire-dm.tshelper (see the "Wire your first DM" section above) if running this skill standalone. If running as part ofbash nanoclaw.sh,init-first-agent.tshandles wiring — just pass theplatform-idandadmin-user-idcaptured above.
Files (nanoclaw)
-
scripts
-
wire-dm.ts 8.1 KB
#!/usr/bin/env pnpm exec tsx /** * Wire a WeChat DM (or group) to an agent group. * * After /add-wechat installs the adapter and the user scans the QR login, * the first inbound message from another WeChat account auto-creates a * `messaging_groups` row. This script finds that row, asks the operator * which agent group to wire it to, and creates the wiring via * `ncl wirings create` — engage mode/pattern and priority come from the * WeChat adapter's declared channel defaults, not from SQL baked into this * script, so it can't drift against schema migrations. * * PREREQUISITE: the NanoClaw host service must be RUNNING — `ncl` talks to * it over a Unix socket and has no offline mode. * * Usage (from the project root): * pnpm exec tsx .claude/skills/add-wechat/scripts/wire-dm.ts * * Flags: * --platform-id <id> Wire a specific messaging group (default: most recent unwired) * --agent-group <id> Target agent group (default: interactive pick; auto-picked when only one exists) * --sender-policy <p> public | strict | request_approval — overrides the * channel-declared unknown_sender_policy on the * messaging group (default: leave as the adapter declared) * --session-mode <m> shared | per-thread (default: shared) * --non-interactive Fail instead of prompting */ import { spawnSync } from 'node:child_process'; import path from 'node:path'; import readline from 'node:readline'; import { fileURLToPath } from 'node:url'; // <root>/.claude/skills/add-wechat/scripts/wire-dm.ts → <root> const PROJECT_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../..'); type SenderPolicy = 'public' | 'strict' | 'request_approval'; interface Args { platformId?: string; agentGroupId?: string; senderPolicy?: SenderPolicy; sessionMode: 'shared' | 'per-thread'; interactive: boolean; } function parseArgs(argv: string[]): Args { const args: Args = { // No --sender-policy default: the router already stamped the policy the // WeChat adapter declares when it auto-created the messaging group. // Only an explicit flag overrides it. sessionMode: 'shared', interactive: true, }; for (let i = 0; i < argv.length; i++) { const flag = argv[i]; const val = argv[i + 1]; switch (flag) { case '--platform-id': args.platformId = val; i++; break; case '--agent-group': args.agentGroupId = val; i++; break; case '--sender-policy': if (val !== 'public' && val !== 'strict' && val !== 'request_approval') { throw new Error(`bad --sender-policy: ${val} (use public | strict | request_approval)`); } args.senderPolicy = val; i++; break; case '--session-mode': if (val !== 'shared' && val !== 'per-thread') throw new Error(`bad --session-mode: ${val}`); args.sessionMode = val; i++; break; case '--non-interactive': args.interactive = false; break; case '--help': case '-h': console.log('See .claude/skills/add-wechat/scripts/wire-dm.ts header for usage.'); process.exit(0); } } return args; } /** Run one ncl command against the running host and return its parsed data. */ function ncl(...cliArgs: string[]): unknown { const res = spawnSync('pnpm', ['exec', 'tsx', 'src/cli/client.ts', ...cliArgs, '--json'], { cwd: PROJECT_ROOT, encoding: 'utf-8', }); if (res.error) throw res.error; let frame: { ok: boolean; data?: unknown; error?: { message: string } } | undefined; try { frame = JSON.parse(res.stdout); } catch { // No frame — transport-level failure (host not running), reported on stderr. } if (frame && !frame.ok) throw new Error(`ncl ${cliArgs.join(' ')} failed: ${frame.error?.message}`); if (!frame || res.status !== 0) { const detail = (res.stderr || res.stdout || '').trim(); throw new Error( `ncl ${cliArgs.join(' ')} failed:\n${detail}\n\n` + 'Is the NanoClaw host service running? ncl connects to it over a Unix socket.', ); } return frame.data; } async function prompt(q: string): Promise<string> { const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); return new Promise((resolve) => rl.question(q, (a) => { rl.close(); resolve(a.trim()); })); } interface MgRow { id: string; platform_id: string; name: string | null; is_group: number; created_at: string } interface AgRow { id: string; name: string; created_at: string } async function main(): Promise<void> { const args = parseArgs(process.argv.slice(2)); const mgs = ncl('messaging-groups', 'list', '--channel-type', 'wechat') as MgRow[]; const wirings = ncl('wirings', 'list', '--limit', '10000') as Array<{ messaging_group_id: string }>; const wiredMgIds = new Set(wirings.map((w) => w.messaging_group_id)); // 1. Pick the messaging group let mg: MgRow | undefined; if (args.platformId) { mg = mgs.find((r) => r.platform_id === args.platformId); if (!mg) throw new Error(`no wechat messaging_group with platform_id = ${args.platformId}`); } else { const unwired = mgs .filter((r) => !wiredMgIds.has(r.id)) .sort((a, b) => b.created_at.localeCompare(a.created_at)); if (unwired.length === 0) { console.error('No unwired WeChat messaging groups found.'); console.error('Send a message to the bot first (from another WeChat account), then re-run.'); process.exit(1); } if (unwired.length === 1 || !args.interactive) { mg = unwired[0]; console.log(`Using most recent unwired group: ${mg.platform_id} (${mg.is_group ? 'group' : 'DM'})`); } else { console.log('Unwired WeChat messaging groups:'); unwired.forEach((r, i) => { console.log(` ${i + 1}. ${r.platform_id} (${r.is_group ? 'group' : 'DM'}, ${r.created_at})`); }); const pick = await prompt('Pick one [1]: '); const idx = pick === '' ? 0 : parseInt(pick, 10) - 1; if (Number.isNaN(idx) || idx < 0 || idx >= unwired.length) throw new Error('invalid choice'); mg = unwired[idx]; } } // 2. Pick the agent group let agentGroupId = args.agentGroupId; if (!agentGroupId) { const agents = (ncl('groups', 'list') as AgRow[]) .sort((a, b) => a.created_at.localeCompare(b.created_at)); if (agents.length === 0) throw new Error('no agent groups exist — create one first'); if (agents.length === 1) { agentGroupId = agents[0].id; console.log(`Auto-selected sole agent group: ${agents[0].name} (${agentGroupId})`); } else if (args.interactive) { console.log('Agent groups:'); agents.forEach((a, i) => { console.log(` ${i + 1}. ${a.name} (${a.id})`); }); const pick = await prompt('Pick one [1]: '); const idx = pick === '' ? 0 : parseInt(pick, 10) - 1; if (Number.isNaN(idx) || idx < 0 || idx >= agents.length) throw new Error('invalid choice'); agentGroupId = agents[idx].id; } else { throw new Error('multiple agent groups exist; pass --agent-group <id>'); } } const ag = (ncl('groups', 'list') as AgRow[]).find((a) => a.id === agentGroupId); if (!ag) throw new Error(`no agent_group with id = ${agentGroupId}`); // 3. Wire, then apply the optional policy override. Engage mode/pattern and // priority are filled by the wirings resolveDefaults hook from the WeChat // adapter's declared channel defaults. Policy update runs second so a // failed create (e.g. already wired) leaves the mg row untouched. const wiring = ncl( 'wirings', 'create', '--messaging-group-id', mg.id, '--agent-group-id', ag.id, '--session-mode', args.sessionMode, ) as { engage_mode: string; engage_pattern: string | null }; if (args.senderPolicy) { ncl('messaging-groups', 'update', mg.id, '--unknown-sender-policy', args.senderPolicy); } console.log(''); console.log( `WIRED platform_id=${mg.platform_id} agent_group=${ag.name} ` + `engage=${wiring.engage_mode}${wiring.engage_pattern ? `(${wiring.engage_pattern})` : ''} ` + `policy=${args.senderPolicy ?? '(channel default)'} mode=${args.sessionMode}`, ); } main().catch((err) => { console.error('FAILED:', err.message); process.exit(1); });
-
-
REMOVE.md 1.1 KB
# Remove WeChat Channel Every step is idempotent — safe to re-run. ## 1. Remove the adapter Delete the self-registration import from `src/channels/index.ts` (skip if already gone): ```typescript import './wechat.js'; ``` Then delete the copied adapter and its registration test: ```bash rm -f src/channels/wechat.ts src/channels/wechat-registration.test.ts ``` ## 2. Remove credentials Remove `WECHAT_ENABLED` from `.env`. ## 3. Remove the package ```bash pnpm uninstall wechat-ilink-client ``` ## 4. Remove saved auth + sync state ```bash rm -rf data/wechat ``` The channel's messaging groups, wirings, and conversation history are **left intact** — you created those at runtime (wiring + use), not this skill's install, so removal doesn't touch them. To purge them deliberately, delete them yourself with `ncl messaging-groups delete <id>`. ## 5. Rebuild and restart Run from your NanoClaw project root: ```bash pnpm run build source setup/lib/install-slug.sh launchctl kickstart -k gui/$(id -u)/$(launchd_label) # macOS # Linux: systemctl --user restart $(systemd_unit) ``` -
SKILL.md 7.4 KB
--- name: add-wechat description: Add WeChat (personal) channel integration via Tencent's official iLink Bot API. Uses long-polling and QR scan — no webhook, no ToS risk, no paid token. --- # Add WeChat Channel Adds WeChat support via **iLink Bot API** — the first-party Tencent API for personal WeChat bots (different from WeCom / Official Account). **Why this is different from wechaty/PadLocal:** - Official Tencent API — no ToS violation, no ban risk - Free — no PadLocal token required - No public webhook URL needed — uses long-poll - Works with any personal WeChat account ## Prerequisites - A **personal WeChat account** with the mobile app installed - A phone to scan the QR code for login - Node.js >= 20 (already required by NanoClaw) ## Install NanoClaw doesn't ship channels in trunk. This skill copies the WeChat adapter in from the `channels` branch. ### 1. Copy the adapter and its registration test Fetch the `channels` branch from the configured remote that carries it, then overwrite the skill-owned files with the canonical registry copies: ```nc:copy from-branch:channels src/channels/wechat.ts src/channels/wechat-registration.test.ts ``` ### 2. Append the self-registration import Append to `src/channels/index.ts` (skip if the line is already present): ```nc:append to:src/channels/index.ts import './wechat.js'; ``` ### 3. Install the library (pinned) ```nc:dep wechat-ilink-client@0.1.0 ``` ### 4. Build and validate ```nc:run effect:build pnpm run build ``` ```nc:run effect:test pnpm exec vitest run src/channels/wechat-registration.test.ts ``` Both must be clean before proceeding. `wechat-registration.test.ts` is the one integration test: it imports the real channel barrel and asserts the registry contains `wechat`. It goes red if the `import './wechat.js';` line is deleted or drifts, if the barrel fails to evaluate (so the channel genuinely would not register), or if `wechat-ilink-client` isn't installed (the import throws) — so it also implicitly verifies the dependency from step 4. Importing is safe: the adapter opens its long-poll connection only in `setup()` (at host startup), never at import. End-to-end message delivery against a real WeChat account is verified manually once the service is running — see Credentials and Wire your first DM above. ## Credentials Unlike most channels, WeChat requires **no pre-configured API keys**. Auth happens via QR code scan from your phone. ### 1. Enable the channel Add to `.env`: ```bash WECHAT_ENABLED=true ``` ### 2. Start the service and scan the QR Restart NanoClaw. Run from your NanoClaw project root: ```bash source setup/lib/install-slug.sh systemctl --user restart $(systemd_unit) # Linux # or launchctl kickstart -k gui/$(id -u)/$(launchd_label) # macOS ``` The adapter will print a **QR URL** to the logs and save it to `data/wechat/qr.txt`: ```bash tail -f logs/nanoclaw.log | grep WeChat # or cat data/wechat/qr.txt ``` Open the URL in a browser (it renders a QR code), then: 1. Open WeChat on your phone 2. Use its built-in QR scanner (top-right "+" → Scan) 3. Approve the authorization on your phone 4. Auth credentials are saved to `data/wechat/auth.json` — do not commit this file The bot is now connected as your WeChat account. ## Wire your first DM A successful QR login alone isn't enough — the adapter still needs to be wired to an agent group before it can respond. **Prerequisite: the host service must be running.** The wire script creates the wiring through `ncl`, which talks to the running host over a Unix socket — there is no offline mode. ### 1. Trigger the first inbound message Have a different WeChat account send a message to the bot account. This auto-creates a `messaging_groups` row with the sender's `platform_id` and the `unknown_sender_policy` the WeChat adapter declares. ### 2. Run the wire script ```bash pnpm exec tsx .claude/skills/add-wechat/scripts/wire-dm.ts ``` Interactive flow: the script lists all unwired WeChat messaging groups, asks which agent group to wire it to, and runs `ncl wirings create` — engage mode/pattern and priority come from the WeChat adapter's declared channel defaults, so a wiring created here matches one created by `/manage-channels` or the approval-card flow. With `request_approval` as the sender policy, the next DM from a stranger fires an approval card to the admin — admin taps Approve/Deny, approved users are added as members and their queued message replays through the agent. Non-interactive: ```bash pnpm exec tsx .claude/skills/add-wechat/scripts/wire-dm.ts \ --platform-id wechat:wxid_xxxxx \ --agent-group ag-xxxxx \ --non-interactive ``` Flags: - `--platform-id <id>` — wire a specific messaging group (default: most recent unwired) - `--agent-group <id>` — target agent group (default: prompt; auto-picked when only one exists) - `--sender-policy public|strict|request_approval` — override the messaging group's `unknown_sender_policy` (default: leave whatever the WeChat adapter declared when the row was auto-created) - `--session-mode shared|per-thread` — default `shared` Equivalent raw `ncl` invocation (host must be running): ```bash ncl wirings create --messaging-group-id <mg-id> --agent-group-id <ag-id> --session-mode shared ``` ### 3. Test Have the sender message the bot again — the agent should respond. ## Operational notes - **Only one instance can use a given token at a time.** Don't run multiple NanoClaw instances pointing to the same `data/wechat/auth.json`. - **Re-login on session expiry:** if you see `WeChat: session expired` in logs, delete `data/wechat/auth.json` and restart — you'll be asked to re-scan. - **Sync cursor persistence:** `data/wechat/sync-buf.txt` holds the long-poll cursor. Deleting it replays recent history on next start; don't delete it in normal operation. - **Account safety:** this uses the official Tencent API, so account bans for bot automation aren't a risk. That said, don't spam — normal rate limits still apply. ## Next Steps If you're in the middle of `/setup`, return to the setup flow now. Otherwise, restart the service to pick up the new channel and wiring. ## Channel Info - **type**: `wechat` - **terminology**: WeChat has "contacts" (DMs) and "group chats" (rooms). Each DM or group is a separate messaging group. - **how-to-find-id**: Send a message to the bot from the target account; the adapter auto-creates a messaging group and logs `WeChat inbound platformId=wechat:<id>`. Use `wechat:<user_id>` for DMs, `wechat:<group_id>` for rooms. - **admin-user-id**: The operator's WeChat user_id (for `init-first-agent.ts --admin-user-id`) is saved to `data/wechat/auth.json` as `operatorUserId` after the QR scan. Read it with `cat data/wechat/auth.json | jq -r .operatorUserId` and prefix with `wechat:` (i.e. `wechat:<operatorUserId>`). - **supports-threads**: no (WeChat has no reply threads) - **typical-use**: Long-poll — the adapter holds a persistent connection to Tencent's iLink API and receives messages in real time. No webhook URL needed. - **default-isolation**: `shared` session mode per messaging group (DM or room). Use `strict` sender policy if you want only specific users to reach the agent; `public` opens it to anyone who messages the bot. - **post-install-wiring**: Use the `wire-dm.ts` helper (see the "Wire your first DM" section above) if running this skill standalone. If running as part of `bash nanoclaw.sh`, `init-first-agent.ts` handles wiring — just pass the `platform-id` and `admin-user-id` captured above.
Comments (0)
Sign in to join the conversation.
Reviews (0)
No reviews yet.
No comments yet.