wechat-message-content-format.md 7.79 KB

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 <img> + CDN metadata THUMBNAIL_DIRPATH://th_<hash>
34 Voice XML with <voicemsg> + CDN metadata Voice filename hash (no extension)
43 Video XML with <videomsg> Video hash
47 Emoji XML with <emoji> NULL
49 Article/Link/Mini-program XML with <appmsg> containing <url>, <title> NULL
10000 System Plain text NULL
754974769 Unsupported (newer client message) "当前微信版本不支持展示该内容" NULL
822083633 Referenced appmsg (reply with quote) XML with <appmsg> containing <refermsg> + <title> NULL

Type 822083633: This is a "reply with reference" message. The XML structure contains <refermsg> pointing to the original message being quoted, embedded inside an <appmsg>. Extract <title> from the outer appmsg for display. Example:\n> xml\n> <msg><appmsg><title>原来是你</title>...<refermsg><type>3</type><displayname>发条猴子</displayname>...\n>\n> Display as: [引用发条猴子的消息] 原来是你 or just the title.\n\n> Type 754974769 (Finder/视频号): Although title says \"当前微信版本不支持展示该内容\", the XML contains a full <finderFeed> block with usable metadata. CRITICAL: All text fields inside finderFeed are wrapped in <![CDATA[...]]> — you MUST strip CDATA before regex extraction:\n> python\n> cdata_clean = re.sub(r\"<!\\[CDATA\\[(.*?)\\]\\]>\", r\"\\1\", content)\n> nick = re.search(r\"<nickname>(.*?)</nickname>\", cdata_clean)\n>\n> Extractable fields: <nickname> (账号名), <desc> (视频描述), <avatar> (CDN头像), <coverUrl> (封面图, HTTP可直接访问), <media><url> (视频下载链接), <videoPlayDuration> (秒), <width>/<height> (分辨率).

XML Message Parsing Patterns

Pattern 1: Clean text (type=1)

display_text = content.split("\n", 1)[-1]  # strip sender prefix
if "<msg>" not in display_text:
    return display_text.strip()  # plain text, done

Pattern 2: appmsg with title (types 49, 822083633, and others)

title = re.search(r"<title>(.*?)</title>", content)
url = re.search(r"<url>(.*?)</url>", content)
if title:
    if url:
        return {"articles": [{"url": url, "title": title}]}
    return title  # text only

Pattern 3: refermsg (quoted reply)

if "<refermsg>" in content:
    ref_from = re.search(r"<displayname>(.*?)</displayname>", content)
    title = re.search(r"<title>(.*?)</title>", 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)

# Step 1: strip CDATA wrappers (ESSENTIAL — regex won't match otherwise)
cdata_clean = re.sub(r"<!\[CDATA\[(.*?)\]\]>", r"\1", content)

# Step 2: extract fields
nick = re.search(r"<nickname>(.*?)</nickname>", cdata_clean)
desc = re.search(r"<desc>(.*?)</desc>", cdata_clean)
cover = re.search(r"<coverUrl>(.*?)</coverUrl>", cdata_clean)
avatar = re.search(r"<avatar>(.*?)</avatar>", cdata_clean)
video_url = re.search(r"<media>.*?<url>(.*?)</url>", cdata_clean, re.DOTALL)
duration = int(re.search(r"<videoPlayDuration>(\d+)</videoPlayDuration>", 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<?xml version=\"1.0\"?>..."
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:      <WECHAT_DATA_ROOT>/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: <WECHAT_DATA_ROOT>/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 <path> && echo yes"
  • Copying files to a readable location: su -c "cp <src> <dst> && chmod 644 <dst>"
  • Finding files: su -c "find <dir> -name '*<pattern>*'"

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:

su -c "find <WECHAT_DATA_ROOT>/voice2 -name '*<imgPath>*' 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:

# Must copy to temp first (permission issue)
su -c "cp <voice_path> /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:

    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:

    PRAGMA key=<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:

    cmd = ["su", "-c", " ".join([
       "/path/to/sqlcipher", db_path,
       '-cmd "PRAGMA key=<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:

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.