# WeChat Message Content Format Reference
## Message Type Codes (Complete)
| Type | Meaning | Content Field | imgPath Field |
|------|---------|--------------|---------------|
| 1 | Text | Plain text, XML, or special format | NULL |
| 3 | Image | XML with `
` + CDN metadata | `THUMBNAIL_DIRPATH://th_` |
| 34 | Voice | XML with `` + CDN metadata | Voice filename hash (no extension) |
| 43 | Video | XML with `` | Video hash |
| 47 | Emoji | XML with `` | NULL |
| 49 | Article/Link/Mini-program | XML with `` containing ``, `` | NULL |
| 10000 | System | Plain text | NULL |
| 754974769 | Unsupported (newer client message) | "当前微信版本不支持展示该内容" | NULL |
| 822083633 | Referenced appmsg (reply with quote) | XML with `` containing `` + `` | NULL |
> **Type 822083633**: This is a "reply with reference" message. The XML structure contains `` pointing to the original message being quoted, embedded inside an ``. Extract `` from the outer appmsg for display. Example:\n> ```xml\n> 原来是你...3发条猴子...\n> ```\n> Display as: `[引用发条猴子的消息] 原来是你` or just the title.\n\n> **Type 754974769 (Finder/视频号)**: Although title says \"当前微信版本不支持展示该内容\", the XML contains a full `` block with usable metadata. **CRITICAL**: All text fields inside finderFeed are wrapped in `` — you MUST strip CDATA before regex extraction:\n> ```python\n> cdata_clean = re.sub(r\"\", r\"\\1\", content)\n> nick = re.search(r\"(.*?)\", cdata_clean)\n> ```\n> Extractable fields: `` (账号名), `` (视频描述), `` (CDN头像), `` (封面图, HTTP可直接访问), `` (视频下载链接), `` (秒), ``/`` (分辨率).
## XML Message Parsing Patterns
### Pattern 1: Clean text (type=1)
```python
display_text = content.split("\n", 1)[-1] # strip sender prefix
if "" not in display_text:
return display_text.strip() # plain text, done
```
### Pattern 2: appmsg with title (types 49, 822083633, and others)
```python
title = re.search(r"(.*?)", content)
url = re.search(r"(.*?)", content)
if title:
if url:
return {"articles": [{"url": url, "title": title}]}
return title # text only
```
### Pattern 3: refermsg (quoted reply)
```python
if "" in content:
ref_from = re.search(r"(.*?)", content)
title = re.search(r"(.*?)", content)
if title:
return f"[引用{ref_from}的消息] {title}"
return "[引用消息]"
```
### Pattern 4: Garbage suppression
After stripping XML tags (`re.sub(r"<[^>]+>", "")`), if the remaining text is >200 chars, it's likely metadata garbage — truncate to 150 chars + "...".
### Pattern 5: finderFeed with CDATA (type=754974769)
```python
# Step 1: strip CDATA wrappers (ESSENTIAL — regex won't match otherwise)
cdata_clean = re.sub(r"", r"\1", content)
# Step 2: extract fields
nick = re.search(r"(.*?)", cdata_clean)
desc = re.search(r"(.*?)", cdata_clean)
cover = re.search(r"(.*?)", cdata_clean)
avatar = re.search(r"(.*?)", cdata_clean)
video_url = re.search(r".*?(.*?)", cdata_clean, re.DOTALL)
duration = int(re.search(r"(\d+)", cdata_clean).group(1))
# The cover URL is an HTTP CDN URL — directly accessible from browser
# e.g. http://wxapp.tc.qq.com/251/20304/stodownload?encfilekey=...
```
## Chatroom Message Content Format
Chatroom messages have a `sender:\n` prefix that MUST be stripped before display:
```
Raw content: "yibooo:\nok 我来也整一个 快速看齐"
Display text: "ok 我来也整一个 快速看齐"
Raw content: "hw090909:\n..."
Display text: stripped XML content
```
**Parsing rule**: split on first `\n`. If the first segment contains `:`, it's the sender prefix — drop it.
## Image Path Resolution
The `imgPath` field for type=3 messages stores a thumbnail path:
```
Raw imgPath: THUMBNAIL_DIRPATH://th_505c5070300c2473cdd5c672ee08d581
Stripped: th_505c5070300c2473cdd5c672ee08d581
Hash: 505c5070300c2473cdd5c672ee08d581
Actual path: /image2/50/5c/th_505c5070300c2473cdd5c672ee08d581
```
**Path construction rule**:
1. Strip `THUMBNAIL_DIRPATH://` or `THUMBNAIL_DIR_PATH://` prefix
2. Remove `th_` prefix to get the hash
3. Subdirectory: `{hash[0:2]}/{hash[2:4]}`
4. Try both `th_{hash}` and `{hash}` (original may not exist locally)
5. Full path: `/image2/{sub1}/{sub2}/{filename}`
**Permissions**: The WeChat data directory (`/data/data/com.tencent.mm/MicroMsg/`) is owned by the WeChat UID (u0_a336), NOT Termux. Direct file access from Flask/Python running as Termux user will raise `PermissionError: [Errno 13]`. Use `su -c` for:
- Checking file existence: `su -c "test -f && echo yes"`
- Copying files to a readable location: `su -c "cp && chmod 644 "`
- Finding files: `su -c "find -name '**'"`
**Serving pattern for Flask**: Copy the file to `/tmp/` via `su`, then serve from `/tmp/`.
## Voice Path Resolution
Voice files have a complex directory structure NOT based on simple hash prefix:
```
imgPath from DB: 05142107062628ef8e19f29104
Actual file: voice2/66/33/msg_05142107062628ef8e19f29104.amr
^^^^^^ — subdirs 66/33 do NOT match hash prefix 05/14
```
**Resolution method**: Use `find` via `su` because the subdirectory pattern is non-trivial:
```bash
su -c "find /voice2 -name '**' 2>/dev/null | head -1"
```
Files are named `msg_{hash}.amr`, stored in `voice2/{XX}/{YY}/` subdirectories.
**Playback in browser**: AMR is not browser-supported. Convert to MP3 via ffmpeg:
```bash
# Must copy to temp first (permission issue)
su -c "cp /tmp/voice_src && chmod 644 /tmp/voice_src"
ffmpeg -y -i /tmp/voice_src -acodec libmp3lame -ar 22050 -ac 1 /tmp/voice.mp3
```
## SQLCipher CLI Quirks
When using sqlcipher CLI from Python subprocess:
1. **"ok\n" prefix**: sqlcipher prints `ok\n` before JSON output in some versions. Strip it:
```python
if output.startswith("ok"):
output = output[2:].strip()
```
2. **Multi-line JSON arrays**: `.mode json` produces pretty-printed arrays with line breaks inside the array. `json.loads()` handles this fine AFTER stripping "ok\n".
3. **Required pragmas** for WeChat EnMicroMsg.db:
```bash
PRAGMA key=;
PRAGMA cipher_compatibility=1;
PRAGMA cipher_page_size=1024;
PRAGMA query_only=true; # Recommended for read-only access
```
4. **Command construction**: Must use `su -c` wrapper since DB is root-owned:
```python
cmd = ["su", "-c", " ".join([
"/path/to/sqlcipher", db_path,
'-cmd "PRAGMA key=;"',
'-cmd "PRAGMA cipher_compatibility=1;"',
...
])]
```
## Group Name Resolution
For `@chatroom` talkers, the custom group name lives in `rcontact.nickname`, NOT in `chatroom.displayname`:
```
rcontact.nickname → "宜创AI全员群" (custom name if set, else empty)
chatroom.displayname → "火星人、丁鹏、小伙子..." (member nickname list)
```
**SQL pattern for session list**:
```sql
CASE
WHEN m.talker LIKE '%@chatroom' THEN
COALESCE(NULLIF(r.nickname, ''), c.displayname, m.talker)
ELSE
COALESCE(NULLIF(r.conRemark, ''), r.nickname, m.talker)
END AS display_name
```
**For personal contacts**, prefer `rcontact.conRemark` (remark name) over `rcontact.nickname`.