File size: 15,995 Bytes
d086025 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 | # wx-cli
> Turn WeChat into a data source that Agents can read, search, and subscribe to in real time.
wx-cli reads WeChat's local data on macOS directly, giving you and your Agents access to chat history, contacts, group chats, and media messages. Data stays on the machine by default — no chat database upload, no cloud export required.
*Note: the upstream documentation is written in Chinese; command syntax is unchanged.*
## What it can do
- **Read the local WeChat database**: query history by contact, group, time range, and message type.
- **Search all chat history**: keyword search across all conversations.
- **Cross-conversation timeline in one call**: fetch new messages from all conversations in a time range (memory backfill, archiving, daily reports).
- **Real-time subscription**: listen from the CLI, or push new messages via SSE.
- **Export and process content**: export conversations as JSON or text; read images, voice, and video media.
- **Agent-ready**: ships an Agent Skill so Claude Code, Codex, Cursor, etc. know how to query and subscribe after install.
- **Stable local service**: REST API for assistants, automation, workflows, and multiple Agents.
- **Privacy controls**: hide specific contacts, groups, tags, or group members from queries and subscriptions.
## Supported scope
- **Platform**: macOS (arm64 / Apple Silicon)
- **WeChat version**: 4.1.7.x / 4.1.8.x
## Prerequisites
Key extraction **requires SIP disabled** (with SIP enabled, `task_for_pid` is rejected by the kernel even as root); sudo is usually not needed. If you already have a key, skip SIP and use `key set` manually.
`key extract` (LLDB method) also needs:
1. `sudo DevToolsSecurity -enable`
2. `sudo dscl . append /Groups/_developer GroupMembership $USER`
3. `xcode-select --install` (provides `lldb` and `python3`)
Check SIP status: `csrutil status`. Disabling requires Recovery Mode: `csrutil disable`.
## Installation
### From Release (recommended)
Download the prebuilt binary (macOS arm64) from the upstream Releases page, or:
```bash
# Download latest release
curl -fSL "$(curl -fsSL https://api.github.com/repos/pandorafuture/wx-cli/releases/latest \
| grep -o '"browser_download_url": "[^"]*macos-arm64[^"]*"' \
| cut -d'"' -f4)" -o wx-cli.tar.gz
tar xzf wx-cli.tar.gz
# Install to PATH
mkdir -p ~/.local/bin
mv wx-cli ~/.local/bin/
chmod +x ~/.local/bin/wx-cli
wx-cli --version
```
### From source
```bash
# Requires a Rust toolchain (install via rustup)
cargo build --release
```
The binary is at `target/release/wx-cli`; copy it to `~/.local/bin/` and `chmod +x` it.
### Let Agents use it directly
```bash
npx skills add pandorafuture/wx-cli
```
## Usage walkthrough
### 1. Check the environment
```bash
wx-cli doctor # checks SIP, DevToolsSecurity, _developer group, LLDB/python3
wx-cli doctor --fix # prints fix commands for FAIL items
wx-cli status # WeChat running state and per-account key/cache status
```
### 2. Extract keys
```bash
# LLDB hook extraction — restarts WeChat, usually no sudo needed
wx-cli key extract --timeout 120
# List saved keys (`raw=yes` means the full database key is saved)
wx-cli key list
```
`key extract` captures the raw key via an LLDB hook on the PBKDF2 call; it covers **all** databases. With the full database key saved, `query`/`sessions`/`search`/`contacts`/`server run`/`watch` can read encrypted databases directly — `decrypt` is not required first.
Manual key entry:
```bash
wx-cli key set <account> <64-hex-key> # database key (32 bytes hex)
wx-cli key set-image <account> <image-key> # image AES key (16 bytes, V2 format)
```
### 3. Decrypt databases (optional, for plaintext export)
```bash
wx-cli decrypt # decrypt into the cache directory
wx-cli decrypt --incremental # only process changed files
# Manual paths and key
wx-cli decrypt -k <64-hex-key> -d /path/to/xwechat_files/<account_dir> -o /tmp/decrypted
```
### 4. Query chat history
```bash
wx-cli sessions --limit 10 # recent conversations
wx-cli contacts --search 张三 # search contacts (nickname, remark, wxid, alias, phone)
wx-cli query 张三 --limit 20 # messages from one person
wx-cli search 周末 --limit 20 # global keyword search
wx-cli query 张三 --type text # filter by type: text/image/voice/video/emoji/app/system/revoke
wx-cli query 张三 --since 1772600000 --until 1772700000 # time range (Unix seconds)
wx-cli query 周末爬山群 # group chat by name
wx-cli query 18819405230@chatroom --limit 10 # group chat by ID
wx-cli export 张三 -o /tmp/export --all --format json # export a conversation
wx-cli watch --poll --poll-ms 3000 # real-time monitoring
```
Anchor/context queries:
```bash
wx-cli query 张三 --around-sort-seq 1773421188000 --context 10 # context around a sort_seq
wx-cli query 张三 --around-server-id 5455993825313690274 --context 10 # context around a server_id
wx-cli query 张三 --after-sort-seq 1773421188000 --limit 20 # incremental fetch
```
Rules: anchor queries always return ascending (`--order desc` ignored); `--context` defaults to 50 and only applies to `around-*`; `around-*` is mutually exclusive with `--since`/`--until`/`--all`; the three anchor parameters are mutually exclusive.
If `server run` is already running locally, query commands automatically reuse the REST API (probing `http://127.0.0.1:9100` by default). Use `--no-server` to force local queries or `--server-only` to force remote. Related flags: `--server-url <url>`, `--server-token <token>`.
### 5. Media
```bash
wx-cli decode-image input.dat -d <account_data_dir> -o output.png # decrypt image (V2 key auto-derived)
wx-cli decode-image /path/to/dat_dir/ -d <account_data_dir> -o /tmp/ # batch decrypt a directory
wx-cli media decrypt-dat input.dat --v2-key <key> -o output.png # pass V2 AES key explicitly
wx-cli media extract-voice --media-dir <dir> <svr_id> -o voice.mp3 # voice → MP3 (needs ffmpeg)
wx-cli media extract-voice --media-dir <dir> <svr_id> --raw # raw SILK
wx-cli media resolve-path --db <hardlink.db> <md5_key> # hardlink path lookup (image)
wx-cli media resolve-path --db <hardlink.db> --media-type video <key> # ... for video
wx-cli media resolve-path --db <hardlink.db> --media-type file <key> # ... for files
wx-cli media decrypt-video encrypted.bin --seed 2105122989 -o video.mp4 # decimal seed
wx-cli media decrypt-video encrypted.bin --seed 0x7d844e8d -o video.mp4 # hex seed
```
If ffmpeg is missing: `brew install ffmpeg`, or set `FFMPEG_PATH=/path/to/ffmpeg`.
### 6. Export
```bash
wx-cli export 张三 -o /tmp/export/ --all # TXT, all messages (parallel by default)
wx-cli export 张三 -o /tmp/export/ --all --format json # JSON
wx-cli export 张三 -o /tmp/export/ --all --no-media # skip media files
wx-cli export 张三 -o /tmp/export/ --all --show-emoji # show emoji details
```
Export sorts ascending (oldest first) by default — opposite of `query`, which defaults to descending.
### 7. HTTP API service
```bash
wx-cli server run # start (default 127.0.0.1:9100)
wx-cli server run --host 0.0.0.0 --token mysecret # remote access (token required)
wx-cli server status # status
wx-cli server stop # stop
wx-cli server restart # restart
```
REST endpoints (read-only; no send/reply/webhook write APIs):
| Endpoint | Purpose | Key parameters |
|------|---------|----------------|
| `GET /api/v1/health` | health probe | none |
| `GET /api/v1/sessions` | conversation list | `limit`, `offset`, `order`, `show_hidden` |
| `GET /api/v1/contacts` | contact list | `limit`, `offset`, `search`, `show_hidden` |
| `GET /api/v1/messages` | message query | `contact` (required), `limit`, `offset`, `since`, `until`, `type`, `order`, `around_sort_seq`, `around_server_id`, `after_sort_seq`, `context`, `show_hidden` |
| `GET /api/v1/timeline` | cross-conversation batch read | `since` (required), `until` (required), `limit`, `offset`, `type`, `order`, `show_hidden` |
| `GET /api/v1/media` | media content | `server_id` (required), `talker` (required), `format=ogg\|mp3` (voice only) |
| `GET /api/v1/search` | full-text search | `q` (required), `limit`, `offset` |
| `GET /api/v1/events` | SSE event stream | none |
Auth: when started with `--token`, send `Authorization: Bearer <token>`. `--token` is mandatory when `--host` is not a loopback address.
### 8. Real-time monitoring
```bash
wx-cli watch # default
wx-cli watch --poll --poll-ms 5000 # polling with custom interval
wx-cli watch --fsnotify # file-event mode
wx-cli watch --format json # one JSON object per line
wx-cli watch --show-hidden # ignore hide rules
```
### 9. Search semantics
- Chinese is tokenized per character; English supports Porter stemming.
- Multi-word searches use AND logic.
- `stats.scanned=0` means WeChat's built-in full-text index was used; `stats.scanned>0` means it fell back to a full scan.
## JSON output
All query commands accept `--format json` and return a uniform envelope:
```json
{
"items": [...],
"paging": { "offset": 0, "limit": 20, "returned": 20, "total": 103, "has_more": true },
"stats": { "scanned": 103, "skipped": 0, "elapsed_ms": 3 }
}
```
| Command | Key item fields |
|---------|-----------------|
| sessions | `username`, `display_name`, `summary`, `sort_timestamp`, `direction?` |
| query | `sort_seq`, `server_id`, `msg_type`, `sender`, `content`, `direction` |
| timeline API | `sort_seq`, `server_id`, `msg_type`, `sender`, `talker`, `talker_display_name`, `create_time`, `direction`, `snippet` |
| contacts | `user_name`, `alias`, `remark`, `nick_name`, `phone`, `labels` |
| search | `server_id`, `talker`, `sender`, `snippet`, `hit_type` |
Gotchas:
- contacts use `user_name` (underscore); sessions use `username` (no underscore).
- The message-level `sender` field is what determines self vs. other.
- `/api/v1/health`'s `current_account.wxid` is the source of truth for "messages I sent".
- JSON goes to stdout, diagnostics to stderr — capture stdout only when parsing.
Paging and ordering:
```bash
wx-cli query 张三 --format json --limit 10 --offset 0 # page 1
wx-cli query 张三 --format json --limit 10 --offset 10 # page 2
wx-cli query 张三 --order asc # oldest first
wx-cli query 张三 --all # all messages (cap 20,000)
```
`--all` overrides `--limit` (current cap 20,000); `--limit 0` falls back to the command default.
Structured type-49 message labels (JSON `content` is a tagged union keyed by variant):
| Variant | sub_type | Output |
|---------|----------|--------|
| Link | 4, 5, 7, 92 | `[链接] <title>` |
| File | 6 | `[文件] <filename>` |
| MiniProgram | 33, 36 | `[小程序] <name>` |
| MergedMessages | 19 | `[聊天记录] <title>` |
| Quote | 57 | `[引用 @sender: original] reply` |
| Transfer | 2000 | `[转账] ¥amount` |
| RedEnvelope | 2001, 2003 | `[红包] <title>` |
| ChannelVideo | 51, 63 | `[视频号] <title>` |
| Pat | 62 | `[拍一拍]` |
## Command reference
| Command | Description |
|---------|-------------|
| `wx-cli status` | WeChat running state |
| `wx-cli doctor [--fix]` | environment checks (SIP etc.) |
| `wx-cli key extract --timeout <s>` | LLDB hook key extraction |
| `wx-cli key list` | list saved keys |
| `wx-cli key set <account> <key>` | set database key manually |
| `wx-cli key set-image <account> <image-key>` | set image key manually |
| `wx-cli decrypt [--incremental]` | decrypt databases |
| `wx-cli sessions [--limit N] [--show-hidden]` | recent conversations |
| `wx-cli contacts --search <name> [--show-hidden]` | search contacts |
| `wx-cli query <contact> [...]` | query messages |
| `wx-cli search <keyword>` | global search |
| `wx-cli export <contact> -o <dir> [--all] [--format json] [--no-media] [--show-emoji] [--show-hidden]` | export a conversation |
| `wx-cli watch [--poll --poll-ms N] [--fsnotify] [--format json] [--show-hidden]` | real-time monitoring |
| `wx-cli decode-image <path> -d <data_dir> -o <out>` | decrypt images |
| `wx-cli media decrypt-dat <path> --v2-key <key>` | decrypt image with explicit V2 key |
| `wx-cli media extract-voice --media-dir <dir> <svr_id> [--raw]` | extract voice |
| `wx-cli media resolve-path --db <hardlink.db> <key> [--media-type ...]` | hardlink path lookup |
| `wx-cli media decrypt-video <file> --seed <seed>` | decrypt Channels video |
| `wx-cli server run [--host H] [--token T]` | start HTTP API |
| `wx-cli server status/stop/restart` | manage the service |
| `wx-cli paths [--json]` | show all data paths |
| `wx-cli info <db>` | database encryption status |
| `wx-cli --version` | version |
## Contact hiding
Hide contacts, group chats, or tagged contacts per account. Once enabled, query/export/watch commands apply the rules by default (global search excepted).
Config file: `~/Library/Application Support/wx-cli/config/settings.toml`
```toml
[accounts."<account_id>"]
ignore_contacts = ["wxid_xxx", "12345@chatroom"]
ignore_tags = ["同事", "客户"]
```
Local commands accept `--show-hidden` to bypass the rules and see full results. `search` currently does not apply hide rules and has no `--show-hidden`. Privacy first: if output contains `[消息已隐藏]` ("message hidden"), do not add `--show-hidden` unless the user explicitly asks.
## File paths
| Category | Path (macOS) | Purpose | Deletable? |
|----------|--------------|---------|------------|
| Config | `~/Library/Application Support/wx-cli/config/` | keys, settings | No (back up first) |
| Cache | `~/Library/Caches/wx-cli/` | decrypted databases | Yes (re-run decrypt) |
| State | `~/Library/Application Support/wx-cli/state/` | service runtime metadata | Yes |
| Logs | `~/Library/Logs/wx-cli/` | service logs | Yes |
| Temp | `$TMPDIR/wx-cli/` | key-extraction temp files | Yes |
Run `wx-cli paths` to list all paths. Clear the cache with `rm -rf ~/Library/Caches/wx-cli/`.
## Troubleshooting
### `key extract` times out
- Make sure WeChat shows the login screen and login completes.
- Increase the timeout: `--timeout 300`.
- Check the log: `$TMPDIR/wx-cli/lldb/wx_cli_lldb_output.txt`.
### SIP / DevToolsSecurity errors
Key extraction requires SIP disabled. Reboot into Recovery Mode, run `csrutil disable`, then re-check with `wx-cli doctor`.
### Decrypted database won't open
- `wx-cli key list` — verify the key.
- `wx-cli info <db>` — check whether the file is still encrypted.
- Confirm the WeChat version is 4.1.7.x / 4.1.8.x.
### `error: no key for account <account_id>`
```bash
wx-cli status # 1. confirm WeChat state
wx-cli key extract --timeout 120 # 2. extract key
wx-cli key list # 3. verify
wx-cli sessions # 4. retry
```
### `task_for_pid failed (kern_return=5)`
SIP is enabled; disable it from Recovery Mode with `csrutil disable`.
## Empty-result diagnosis
When a query returns nothing, don't randomly retry parameters:
```bash
# 1. Check stats.skipped
wx-cli query <contact> --all --format json 2>/dev/null | \
python3 -c "import json,sys; d=json.load(sys.stdin); print(f'items={len(d[\"items\"])}, skipped={d[\"stats\"][\"skipped\"]}')"
# 2. skipped > 0 → re-decrypt
wx-cli decrypt
# 3. items=0 and skipped=0 → check the contact
wx-cli contacts --search <name> --format json
```
## Notes
- All commands auto-detect the account and keys; `--account`/`--key` are usually unnecessary.
- `query` accepts wxid, chatroom IDs, `filehelper`, and fuzzy Chinese names.
- `search` queries WeChat's own `message_fts.db`; no separate index build needed.
- `server run` automatically refreshes the decryption cache incrementally after startup.
|