
Wechat Article Publisher
- 2.5k installs
- 152 repo stars
- Updated January 16, 2026
- iamzifei/wechat-article-publisher-skill
wechat-article-publisher publishes Markdown or HTML articles to WeChat Official Account drafts via the wx.limyai.com OpenAPI.
About
The wechat-article-publisher skill publishes Markdown or HTML content to WeChat Official Account drafts through direct API calls to wx.limyai.com, avoiding browser automation for reliability and speed. It requires WECHAT_API_KEY in the environment, Python 3.9 plus, and an authorized WeChat account on wx.limyai.com. The workflow checks the API key, lists authorized accounts with wechat_api.py, detects file format, and calls the publish endpoint to create a draft. Supported formats include .md files converted by the API and .html files with preserved formatting, plus newspic image-text mode with up to twenty images. Critical rules forbid auto-publishing to live feeds, require listing accounts first, and preserve original content. Error codes cover missing keys, unauthorized accounts, expired tokens, and WeChat API failures. After success the agent reminds users to review and publish manually in the WeChat admin panel.
- API-first publishing to WeChat drafts via wx.limyai.com with X-API-Key auth.
- Supports Markdown, HTML, and newspic image-text article types.
- NEVER auto-publishes live; drafts only for manual WeChat admin review.
- wechat_api.py scripts for list-accounts and publish from markdown or HTML.
- Images in markdown or HTML are auto-uploaded to WeChat when referenced.
Wechat Article Publisher by the numbers
- 2,528 all-time installs (skills.sh)
- +25 installs in the week ending Aug 5, 2026 (Skillselion tracking)
- Ranked #232 of 1,879 Marketing & SEO skills by installs in the Skillselion catalog
- Security screen: MEDIUM risk (skills.sh audit)
- Data as of Aug 5, 2026 (Skillselion catalog sync)
wechat-article-publisher capabilities & compatibility
- Capabilities
- list authorized wechat accounts via openapi · publish markdown or html to draft endpoint · newspic image text mode with image extraction · api key validation and structured error handling · format detection and title extraction from h1 or
- Use cases
- copywriting · marketing · email
- Pricing
- Bring your own API key
What wechat-article-publisher says it does
Unlike browser-based publishing, this skill uses direct API calls for reliable, fast publishing.
npx skills add https://github.com/iamzifei/wechat-article-publisher-skill --skill wechat-article-publisherAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 2.5k |
|---|---|
| repo stars | ★ 152 |
| Security audit | 2 / 3 scanners passed |
| Last updated | January 16, 2026 |
| Repository | iamzifei/wechat-article-publisher-skill ↗ |
How do I send a Markdown or HTML article to a WeChat Official Account draft box reliably without browser UI automation?
Publish Markdown or HTML articles to WeChat Official Account drafts via wx.limyai.com API without browser automation.
Who is it for?
Teams with WECHAT_API_KEY and authorized wx.limyai.com accounts publishing articles to WeChat drafts.
Skip if: Skip when the user needs live auto-publish, multi-platform syndication, or has no API key or authorized account.
When should I use this skill?
User asks to publish Markdown or HTML to WeChat Official Account, WeChat drafts, or 微信公众号.
What you get
A draft created in WeChat with publicationId, mediaId, and status returned from the publish API.
- wechat json payload
- stripped html article
Files
WeChat Article Publisher
Publish Markdown or HTML content to WeChat Official Account drafts via API, with automatic format conversion.
Prerequisites
- WECHAT_API_KEY environment variable set (from .env file)
- Python 3.9+
- Authorized WeChat Official Account on wx.limyai.com
Scripts
Located in ~/.claude/skills/wechat-article-publisher/scripts/:
wechat_api.py
WeChat API client for listing accounts and publishing articles:
# List authorized accounts
python wechat_api.py list-accounts
# Publish from markdown file
python wechat_api.py publish --appid <wechat_appid> --markdown /path/to/article.md
# Publish from HTML file (preserves formatting)
python wechat_api.py publish --appid <wechat_appid> --html /path/to/article.html
# Publish with custom options
python wechat_api.py publish --appid <appid> --markdown /path/to/article.md --type newspicparse_markdown.py
Parse Markdown and extract structured data (optional, for advanced use):
python parse_markdown.py <markdown_file> [--output json|html]Workflow
Strategy: "API-First Publishing"
Unlike browser-based publishing, this skill uses direct API calls for reliable, fast publishing.
1. Load WECHAT_API_KEY from environment 2. List available WeChat accounts (if user hasn't specified) 3. Detect file format (Markdown or HTML) and parse accordingly 4. Call publish API to create draft in WeChat 5. Report success with draft details
Supported File Formats:
.mdfiles → Parsed as Markdown, converted by WeChat API.htmlfiles → Sent as HTML, formatting preserved
Step-by-Step Guide
Step 1: Check API Key
Before any operation, verify the API key is available:
# Check if .env file exists and contains WECHAT_API_KEY
cat .env | grep WECHAT_API_KEYIf not set, remind user to: 1. Copy .env.example to .env 2. Set their WECHAT_API_KEY value
Step 2: List Available Accounts
Get the list of authorized WeChat accounts:
python ~/.claude/skills/wechat-article-publisher/scripts/wechat_api.py list-accountsOutput example:
{
"success": true,
"data": {
"accounts": [
{
"name": "我的公众号",
"wechatAppid": "wx1234567890",
"username": "gh_abc123",
"type": "subscription",
"verified": true,
"status": "active"
}
],
"total": 1
}
}Important:
- If only one account, use it automatically
- If multiple accounts, ask user to choose
- Note the
wechatAppidfor publishing
Step 3: Publish Article
For Markdown files:
python ~/.claude/skills/wechat-article-publisher/scripts/wechat_api.py publish \
--appid <wechatAppid> \
--markdown /path/to/article.mdFor HTML files (preserves formatting):
python ~/.claude/skills/wechat-article-publisher/scripts/wechat_api.py publish \
--appid <wechatAppid> \
--html /path/to/article.htmlFor 小绿书 (image-text mode):
python ~/.claude/skills/wechat-article-publisher/scripts/wechat_api.py publish \
--appid <wechatAppid> \
--markdown /path/to/article.md \
--type newspicSuccess response:
{
"success": true,
"data": {
"publicationId": "uuid-here",
"materialId": "uuid-here",
"mediaId": "wechat-media-id",
"status": "published",
"message": "文章已成功发布到公众号草稿箱"
}
}Step 4: Report Result
After successful publishing:
- Confirm the draft was created
- Remind user to review and publish manually in WeChat admin panel
- Provide any relevant IDs for reference
API Reference
Authentication
All API requests require the X-API-Key header:
X-API-Key: WECHAT_API_KEYGet Accounts List
POST https://wx.limyai.com/api/openapi/wechat-accountsPublish Article
POST https://wx.limyai.com/api/openapi/wechat-publishParameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
| wechatAppid | string | Yes | WeChat AppID |
| title | string | Yes | Article title (max 64 chars) |
| content | string | Yes | Article content (Markdown/HTML) |
| summary | string | No | Article summary (max 120 chars) |
| coverImage | string | No | Cover image URL |
| author | string | No | Author name |
| contentFormat | string | No | 'markdown' (default) or 'html' |
| articleType | string | No | 'news' (default) or 'newspic' |
Error Codes
| Code | Description |
|---|---|
| API_KEY_MISSING | API key not provided |
| API_KEY_INVALID | API key invalid |
| ACCOUNT_NOT_FOUND | Account not found or unauthorized |
| ACCOUNT_TOKEN_EXPIRED | Account authorization expired |
| INVALID_PARAMETER | Invalid parameter |
| WECHAT_API_ERROR | WeChat API call failed |
| INTERNAL_ERROR | Server error |
Critical Rules
1. NEVER auto-publish - Only save to drafts, user publishes manually 2. Check API key first - Fail fast if not configured 3. List accounts first - User may have multiple accounts 4. Handle errors gracefully - Show clear error messages 5. Preserve original content - Don't modify user's markdown unnecessarily
Supported Formats
Markdown Files (.md)
- H1 header (# ) → Article title
- H2/H3 headers (##, ###) → Section headers
- Bold (text)
- Italic (text)
- Links text
- Blockquotes (> )
- Code blocks (``
...``) - Lists (- or 1.)
- Images !alt → Auto-uploaded to WeChat
HTML Files (.html)
<title>or<h1>→ Article title- All HTML formatting preserved (styles, tables, etc.)
<img>tags → Images auto-uploaded to WeChat- First
<p>→ Auto-extracted as summary - Supports inline styles and rich formatting
HTML Title Extraction Priority: 1. <title> tag content 2. First <h1> tag content 3. "Untitled" as fallback
HTML Content Extraction:
- If
<body>exists, uses body content - Otherwise, strips
<html>,<head>,<!DOCTYPE>and uses remaining content
Article Types
news (普通文章)
- Standard WeChat article format
- Full Markdown/HTML support
- Rich text with images
newspic (小绿书/图文消息)
- Image-focused format (like Instagram posts)
- Maximum 20 images extracted from content
- Text content limited to 1000 characters
- Images auto-uploaded to WeChat
Example Flow
Markdown File
User: "把 ~/articles/ai-tools.md 发布到微信公众号"
# Step 1: Verify API key
cat .env | grep WECHAT_API_KEY
# Step 2: List accounts
python ~/.claude/skills/wechat-article-publisher/scripts/wechat_api.py list-accounts
# Step 3: Publish (assuming single account with appid wx1234567890)
python ~/.claude/skills/wechat-article-publisher/scripts/wechat_api.py publish \
--appid wx1234567890 \
--markdown ~/articles/ai-tools.md
# Step 4: Report
# "文章已成功发布到公众号草稿箱!请登录微信公众平台预览并发布。"HTML File
User: "把这个HTML文章发布到公众号:~/articles/newsletter.html"
# Step 1: Verify API key
cat .env | grep WECHAT_API_KEY
# Step 2: List accounts
python ~/.claude/skills/wechat-article-publisher/scripts/wechat_api.py list-accounts
# Step 3: Publish HTML (auto-detects format)
python ~/.claude/skills/wechat-article-publisher/scripts/wechat_api.py publish \
--appid wx1234567890 \
--html ~/articles/newsletter.html
# Step 4: Report
# "文章已成功发布到公众号草稿箱!HTML格式已保留。请登录微信公众平台预览并发布。"Error Handling
API Key Not Found
Error: WECHAT_API_KEY environment variable not set.Solution: Ask user to set up .env file with their API key.
Account Not Found
Error: ACCOUNT_NOT_FOUND - 公众号不存在或未授权Solution: Ask user to authorize their account on wx.limyai.com.
Token Expired
Error: ACCOUNT_TOKEN_EXPIRED - 公众号授权已过期Solution: Ask user to re-authorize on wx.limyai.com.
WeChat API Error
Error: WECHAT_API_ERROR - 微信接口调用失败Solution: May be temporary issue, retry or check WeChat service status.
Best Practices
Why use API instead of browser automation?
1. Reliability: Direct API calls are more stable than browser automation 2. Speed: No browser startup, page loading, or UI interactions 3. Simplicity: Single command to publish 4. Portability: Works on any system with Python (no macOS-only dependencies)
Content Guidelines
1. Images: Use public URLs when possible; local images will be uploaded 2. Title: Keep under 64 characters 3. Summary: Auto-extracted from first paragraph if not provided 4. Cover: First image in markdown becomes cover if not specified
Workflow Efficiency
Minimal workflow (1 command):
- list-accounts → get appid → publish → done
Full workflow (with verification):
1. Check .env → list accounts → confirm with user
2. Publish with options → report resultTroubleshooting
Q: How do I get a WECHAT_API_KEY?
A: Register and authorize your WeChat account at wx.limyai.com to get your API key.
Q: Can I publish to multiple accounts?
A: Yes, use list-accounts to see all authorized accounts, then specify the target --appid.
Q: Images not showing in WeChat?
A: Ensure images are accessible URLs. Local images are auto-uploaded but may fail if path is incorrect.
Q: Title is too long?
A: WeChat limits titles to 64 characters. The script will use the first 64 chars of H1.
Q: What's the difference between news and newspic?
A: news is standard article format; newspic (小绿书) is image-focused with limited text.
#!/usr/bin/env python3
"""
Parse Markdown for WeChat Official Account article publishing.
Extracts:
- Title (from first H1/H2 or first line)
- Cover image (first image)
- Content images with block index for precise positioning
- HTML content (images stripped)
Usage:
python parse_markdown.py <markdown_file> [--output json|html]
Output (JSON):
{
"title": "Article Title",
"cover_image": "/path/to/cover.jpg",
"content_images": [
{"path": "/path/to/img.jpg", "block_index": 3, "after_text": "context..."},
...
],
"html": "<p>Content...</p><h2>Section</h2>...",
"total_blocks": 25
}
The block_index indicates which block element (0-indexed) the image should follow.
This allows precise positioning without relying on text matching.
"""
import argparse
import json
import os
import re
import sys
from pathlib import Path
def split_into_blocks(markdown: str) -> list[str]:
"""Split markdown into logical blocks (paragraphs, headers, quotes, code blocks, etc.)."""
blocks = []
current_block = []
in_code_block = False
code_block_lines = []
lines = markdown.split('\n')
for line in lines:
stripped = line.strip()
# Handle code block boundaries
if stripped.startswith('```'):
if in_code_block:
# End of code block
in_code_block = False
if code_block_lines:
# Mark as code block with special prefix for later processing
# Use ___CODE_BLOCK_START___ and ___CODE_BLOCK_END___ to preserve content
blocks.append('___CODE_BLOCK_START___' + '\n'.join(code_block_lines) + '___CODE_BLOCK_END___')
code_block_lines = []
else:
# Start of code block
if current_block:
blocks.append('\n'.join(current_block))
current_block = []
in_code_block = True
continue
# If inside code block, collect ALL lines (including empty lines)
if in_code_block:
code_block_lines.append(line)
continue
# Empty line signals end of block
if not stripped:
if current_block:
blocks.append('\n'.join(current_block))
current_block = []
continue
# Headers, blockquotes are their own blocks
if stripped.startswith(('#', '>')):
if current_block:
blocks.append('\n'.join(current_block))
current_block = []
blocks.append(stripped)
continue
# Image on its own line is its own block
if re.match(r'^!\[.*\]\(.*\)$', stripped):
if current_block:
blocks.append('\n'.join(current_block))
current_block = []
blocks.append(stripped)
continue
current_block.append(line)
if current_block:
blocks.append('\n'.join(current_block))
# Handle unclosed code block
if code_block_lines:
blocks.append('___CODE_BLOCK_START___' + '\n'.join(code_block_lines) + '___CODE_BLOCK_END___')
return blocks
def extract_images_with_block_index(markdown: str, base_path: Path) -> tuple[list[dict], str, int]:
"""Extract images with their block index position.
Returns:
(image_list, markdown_without_images, total_blocks)
"""
blocks = split_into_blocks(markdown)
images = []
clean_blocks = []
img_pattern = re.compile(r'^!\[([^\]]*)\]\(([^)]+)\)$')
for i, block in enumerate(blocks):
match = img_pattern.match(block.strip())
if match:
alt_text = match.group(1)
img_path = match.group(2)
# Resolve relative paths
if not os.path.isabs(img_path):
full_path = str(base_path / img_path)
else:
full_path = img_path
# block_index is the index in clean_blocks (without images)
# i.e., this image should be inserted after clean_blocks[block_index-1]
block_index = len(clean_blocks)
# Get context from previous block for reference
after_text = ""
if clean_blocks:
prev_block = clean_blocks[-1].strip()
# Get last line of previous block
lines = [l for l in prev_block.split('\n') if l.strip()]
after_text = lines[-1][:80] if lines else ""
images.append({
"path": full_path,
"alt": alt_text,
"block_index": block_index,
"after_text": after_text # Keep for reference/debugging
})
else:
clean_blocks.append(block)
clean_markdown = '\n\n'.join(clean_blocks)
return images, clean_markdown, len(clean_blocks)
def extract_title(markdown: str) -> tuple[str, str]:
"""Extract title from first H1, H2, or first non-empty line.
Returns:
(title, markdown_without_title): Title string and markdown with H1 title removed.
If title is from H1, it's removed from markdown to avoid duplication.
"""
lines = markdown.strip().split('\n')
title = "Untitled"
title_line_idx = None
for idx, line in enumerate(lines):
stripped = line.strip()
if not stripped:
continue
# H1 - use as title and mark for removal
if stripped.startswith('# '):
title = stripped[2:].strip()
title_line_idx = idx
break
# H2 - use as title but don't remove (it's a section header)
if stripped.startswith('## '):
title = stripped[3:].strip()
break
# First non-empty, non-image line
if not stripped.startswith('!['):
title = stripped[:100]
break
# Remove H1 title line from markdown to avoid duplication
if title_line_idx is not None:
lines.pop(title_line_idx)
markdown = '\n'.join(lines)
return title, markdown
def markdown_to_html(markdown: str) -> str:
"""Convert markdown to HTML for WeChat article publishing."""
html = markdown
# Process code blocks first (marked with ___CODE_BLOCK_START___ and ___CODE_BLOCK_END___)
# Convert to blockquote format for better compatibility
def convert_code_block(match):
code_content = match.group(1)
lines = code_content.strip().split('\n')
# Join non-empty lines with <br> for display
formatted = '<br>'.join(line for line in lines if line.strip())
return f'<blockquote>{formatted}</blockquote>'
html = re.sub(r'___CODE_BLOCK_START___(.*?)___CODE_BLOCK_END___', convert_code_block, html, flags=re.DOTALL)
# Headers (H2 only, H1 is title)
html = re.sub(r'^## (.+)$', r'<h2>\1</h2>', html, flags=re.MULTILINE)
html = re.sub(r'^### (.+)$', r'<h3>\1</h3>', html, flags=re.MULTILINE)
# Bold
html = re.sub(r'\*\*(.+?)\*\*', r'<strong>\1</strong>', html)
# Italic
html = re.sub(r'\*([^*]+)\*', r'<em>\1</em>', html)
# Links
html = re.sub(r'\[([^\]]+)\]\(([^)]+)\)', r'<a href="\2">\1</a>', html)
# Blockquotes (regular markdown blockquotes, not code blocks)
html = re.sub(r'^> (.+)$', r'<blockquote>\1</blockquote>', html, flags=re.MULTILINE)
# Unordered lists
html = re.sub(r'^- (.+)$', r'<li>\1</li>', html, flags=re.MULTILINE)
# Ordered lists
html = re.sub(r'^\d+\. (.+)$', r'<li>\1</li>', html, flags=re.MULTILINE)
# Wrap consecutive <li> in <ul>
html = re.sub(r'((?:<li>.*?</li>\n?)+)', r'<ul>\1</ul>', html)
# Paragraphs - split by double newlines
parts = html.split('\n\n')
processed_parts = []
for part in parts:
part = part.strip()
if not part:
continue
# Skip if already a block element
if part.startswith(('<h2>', '<h3>', '<blockquote>', '<ul>', '<ol>')):
processed_parts.append(part)
else:
# Wrap in paragraph, convert single newlines to <br>
part = part.replace('\n', '<br>')
processed_parts.append(f'<p>{part}</p>')
return ''.join(processed_parts)
def parse_markdown_file(filepath: str) -> dict:
"""Parse a markdown file and return structured data."""
path = Path(filepath)
base_path = path.parent
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
# Extract title first (and remove H1 from markdown)
title, content = extract_title(content)
# Extract images with block indices
images, clean_markdown, total_blocks = extract_images_with_block_index(content, base_path)
# Convert to HTML
html = markdown_to_html(clean_markdown)
# Separate cover image from content images
cover_image = images[0]["path"] if images else None
content_images = images[1:] if len(images) > 1 else []
# Adjust block_index for content images (subtract 1 since cover image is removed)
# The first content image's block_index was calculated including cover image's position
return {
"title": title,
"cover_image": cover_image,
"content_images": content_images,
"html": html,
"total_blocks": total_blocks,
"source_file": str(path.absolute())
}
def main():
parser = argparse.ArgumentParser(description='Parse Markdown for WeChat article publishing')
parser.add_argument('file', help='Markdown file to parse')
parser.add_argument('--output', choices=['json', 'html'], default='json',
help='Output format (default: json)')
parser.add_argument('--html-only', action='store_true',
help='Output only HTML content')
args = parser.parse_args()
if not os.path.exists(args.file):
print(f"Error: File not found: {args.file}", file=sys.stderr)
sys.exit(1)
result = parse_markdown_file(args.file)
if args.html_only:
print(result['html'])
elif args.output == 'json':
print(json.dumps(result, ensure_ascii=False, indent=2))
else:
print(result['html'])
if __name__ == '__main__':
main()
#!/usr/bin/env python3
"""
WeChat Official Account API client for publishing articles.
This script provides functions to interact with the WeChat API:
- List authorized WeChat official accounts
- Publish articles to WeChat drafts
Authentication:
The API key is read from the WECHAT_API_KEY environment variable.
You can set it in a .env file in the project root.
Usage:
# List accounts
python wechat_api.py list-accounts
# Publish article
python wechat_api.py publish --appid <wechat_appid> --title "Title" --content "Content"
# Publish from markdown file
python wechat_api.py publish --appid <wechat_appid> --markdown /path/to/article.md
# Publish from HTML file (with formatting preserved)
python wechat_api.py publish --appid <wechat_appid> --html /path/to/article.html
# Publish as "小绿书" (image-text mode)
python wechat_api.py publish --appid <wechat_appid> --markdown /path/to/article.md --type newspic
API Documentation:
Base URL: https://wx.limyai.com/api/openapi
Authentication: X-API-Key header
"""
import argparse
import json
import os
import sys
from pathlib import Path
from typing import Optional
from urllib.request import Request, urlopen
from urllib.error import HTTPError, URLError
# API configuration
API_BASE_URL = "https://wx.limyai.com/api/openapi"
def load_env_file(env_path: Optional[str] = None) -> None:
"""
Load environment variables from .env file.
Args:
env_path: Optional path to .env file. If not provided, searches in
current directory and parent directories.
"""
if env_path:
env_file = Path(env_path)
else:
# Search for .env file in current and parent directories
current = Path.cwd()
env_file = None
for _ in range(5): # Search up to 5 levels
candidate = current / ".env"
if candidate.exists():
env_file = candidate
break
current = current.parent
if env_file and env_file.exists():
with open(env_file, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if line and not line.startswith("#") and "=" in line:
key, value = line.split("=", 1)
key = key.strip()
value = value.strip().strip('"').strip("'")
if key and value:
os.environ.setdefault(key, value)
def get_api_key() -> str:
"""
Get the WeChat API key from environment variable.
Returns:
The API key string.
Raises:
SystemExit: If API key is not found.
"""
# Try to load from .env file first
load_env_file()
api_key = os.environ.get("WECHAT_API_KEY")
if not api_key:
print("Error: WECHAT_API_KEY environment variable not set.", file=sys.stderr)
print("Please set it in your .env file or environment.", file=sys.stderr)
sys.exit(1)
return api_key
def make_api_request(endpoint: str, data: Optional[dict] = None) -> dict:
"""
Make a POST request to the WeChat API.
Args:
endpoint: API endpoint path (e.g., '/wechat-accounts')
data: Optional JSON data to send in request body
Returns:
JSON response as dictionary
Raises:
SystemExit: On API errors
"""
url = f"{API_BASE_URL}{endpoint}"
api_key = get_api_key()
headers = {
"X-API-Key": api_key,
"Content-Type": "application/json",
}
body = json.dumps(data).encode("utf-8") if data else b"{}"
try:
request = Request(url, data=body, headers=headers, method="POST")
with urlopen(request, timeout=60) as response:
response_data = json.loads(response.read().decode("utf-8"))
return response_data
except HTTPError as e:
error_body = e.read().decode("utf-8") if e.fp else ""
try:
error_json = json.loads(error_body)
error_msg = error_json.get("error", error_body)
error_code = error_json.get("code", "UNKNOWN")
print(f"API Error ({error_code}): {error_msg}", file=sys.stderr)
except json.JSONDecodeError:
print(f"HTTP Error {e.code}: {error_body or e.reason}", file=sys.stderr)
sys.exit(1)
except URLError as e:
print(f"Network Error: {e.reason}", file=sys.stderr)
sys.exit(1)
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)
def list_accounts() -> dict:
"""
Get list of authorized WeChat official accounts.
Returns:
API response containing accounts list
Response format:
{
"success": true,
"data": {
"accounts": [
{
"name": "公众号名称",
"wechatAppid": "wx1234567890",
"username": "gh_abc123",
"avatar": "https://...",
"type": "subscription",
"verified": true,
"status": "active",
"lastAuthTime": "2024-01-01T00:00:00.000Z",
"createdAt": "2024-01-01T00:00:00.000Z"
}
],
"total": 1
}
}
"""
return make_api_request("/wechat-accounts")
def publish_article(
wechat_appid: str,
title: str,
content: str,
summary: Optional[str] = None,
cover_image: Optional[str] = None,
author: Optional[str] = None,
content_format: str = "markdown",
article_type: str = "news",
) -> dict:
"""
Publish an article to WeChat official account drafts.
Args:
wechat_appid: WeChat AppID of the target account
title: Article title (max 64 characters)
content: Article content (Markdown or HTML)
summary: Article summary (max 120 characters, optional)
cover_image: Cover image URL (optional)
author: Author name (optional)
content_format: Content format - 'markdown' (default) or 'html'
article_type: Article type - 'news' (default) or 'newspic' (小绿书)
Returns:
API response containing publication result
Response format (success):
{
"success": true,
"data": {
"publicationId": "uuid-here",
"materialId": "uuid-here",
"mediaId": "wechat-media-id",
"status": "published",
"message": "文章已成功发布到公众号草稿箱"
}
}
Response format (failure):
{
"success": false,
"error": "错误信息",
"code": "ERROR_CODE"
}
"""
data = {
"wechatAppid": wechat_appid,
"title": title,
"content": content,
"contentFormat": content_format,
"articleType": article_type,
}
if summary:
data["summary"] = summary
if cover_image:
data["coverImage"] = cover_image
if author:
data["author"] = author
return make_api_request("/wechat-publish", data)
def parse_markdown_for_wechat(filepath: str) -> dict:
"""
Parse a markdown file and extract data for WeChat publishing.
Args:
filepath: Path to the markdown file
Returns:
Dictionary containing:
- title: Article title
- content: Article content (markdown)
- cover_image: First image URL/path (if any)
- summary: First paragraph as summary (truncated to 120 chars)
"""
path = Path(filepath)
if not path.exists():
print(f"Error: File not found: {filepath}", file=sys.stderr)
sys.exit(1)
with open(filepath, "r", encoding="utf-8") as f:
content = f.read()
# Extract title from H1
title = "Untitled"
lines = content.strip().split("\n")
content_start = 0
for idx, line in enumerate(lines):
stripped = line.strip()
if not stripped:
continue
if stripped.startswith("# "):
title = stripped[2:].strip()
content_start = idx + 1
break
elif stripped.startswith("## "):
title = stripped[3:].strip()
break
elif not stripped.startswith("!["):
title = stripped[:64]
break
# Get content without H1 title
content_lines = lines[content_start:]
markdown_content = "\n".join(content_lines).strip()
# Extract first image as cover
import re
cover_image = None
img_pattern = re.compile(r"!\[[^\]]*\]\(([^)]+)\)")
img_match = img_pattern.search(markdown_content)
if img_match:
cover_image = img_match.group(1)
# If relative path, make absolute
if cover_image and not cover_image.startswith(("http://", "https://")):
cover_path = path.parent / cover_image
if cover_path.exists():
cover_image = str(cover_path.absolute())
# Extract summary from first paragraph
summary = None
for line in content_lines:
stripped = line.strip()
if stripped and not stripped.startswith(("#", "!", ">", "-", "*", "`")):
summary = stripped[:120]
break
return {
"title": title,
"content": markdown_content,
"cover_image": cover_image,
"summary": summary,
"source_file": str(path.absolute()),
}
def parse_html_for_wechat(filepath: str) -> dict:
"""
Parse an HTML file and extract data for WeChat publishing.
Extracts title from <title> tag, <h1> tag, or first heading.
Uses <body> content or full content if no body tag.
Args:
filepath: Path to the HTML file
Returns:
Dictionary containing:
- title: Article title
- content: Article content (HTML)
- cover_image: First image URL/path (if any)
- summary: Text from first paragraph (truncated to 120 chars)
"""
import re
path = Path(filepath)
if not path.exists():
print(f"Error: File not found: {filepath}", file=sys.stderr)
sys.exit(1)
with open(filepath, "r", encoding="utf-8") as f:
content = f.read()
# Extract title from <title> tag first
title = "Untitled"
title_match = re.search(r"<title[^>]*>([^<]+)</title>", content, re.IGNORECASE)
if title_match:
title = title_match.group(1).strip()
else:
# Try <h1> tag
h1_match = re.search(r"<h1[^>]*>([^<]+)</h1>", content, re.IGNORECASE)
if h1_match:
title = h1_match.group(1).strip()
# Truncate title to 64 characters (WeChat limit)
title = title[:64]
# Extract body content if present
body_match = re.search(r"<body[^>]*>(.*?)</body>", content, re.IGNORECASE | re.DOTALL)
if body_match:
html_content = body_match.group(1).strip()
else:
# Use full content, but try to remove html/head tags
html_content = re.sub(r"<html[^>]*>|</html>", "", content, flags=re.IGNORECASE)
html_content = re.sub(r"<head[^>]*>.*?</head>", "", html_content, flags=re.IGNORECASE | re.DOTALL)
html_content = re.sub(r"<!DOCTYPE[^>]*>", "", html_content, flags=re.IGNORECASE)
html_content = html_content.strip()
# Extract first image as cover
cover_image = None
img_match = re.search(r'<img[^>]+src=["\']([^"\']+)["\']', html_content, re.IGNORECASE)
if img_match:
cover_image = img_match.group(1)
# If relative path, make absolute
if cover_image and not cover_image.startswith(("http://", "https://", "data:")):
cover_path = path.parent / cover_image
if cover_path.exists():
cover_image = str(cover_path.absolute())
# Extract summary from first <p> tag
summary = None
p_match = re.search(r"<p[^>]*>([^<]+)", html_content, re.IGNORECASE)
if p_match:
# Remove HTML tags and get plain text
summary_text = re.sub(r"<[^>]+>", "", p_match.group(1))
summary = summary_text.strip()[:120]
return {
"title": title,
"content": html_content,
"cover_image": cover_image,
"summary": summary,
"source_file": str(path.absolute()),
}
def main():
"""Main entry point for CLI."""
parser = argparse.ArgumentParser(
description="WeChat Official Account API Client"
)
subparsers = parser.add_subparsers(dest="command", required=True)
# List accounts command
list_parser = subparsers.add_parser(
"list-accounts",
help="List authorized WeChat official accounts"
)
# Publish command
publish_parser = subparsers.add_parser(
"publish",
help="Publish article to WeChat drafts"
)
publish_parser.add_argument(
"--appid",
required=True,
help="WeChat AppID of target account"
)
publish_parser.add_argument(
"--title",
help="Article title (max 64 characters)"
)
publish_parser.add_argument(
"--content",
help="Article content (Markdown or HTML)"
)
publish_parser.add_argument(
"--markdown",
help="Path to markdown file (alternative to --title and --content)"
)
publish_parser.add_argument(
"--html",
help="Path to HTML file (alternative to --markdown, auto-sets format to html)"
)
publish_parser.add_argument(
"--summary",
help="Article summary (max 120 characters)"
)
publish_parser.add_argument(
"--cover",
help="Cover image URL"
)
publish_parser.add_argument(
"--author",
help="Author name"
)
publish_parser.add_argument(
"--format",
choices=["markdown", "html"],
default="markdown",
help="Content format (default: markdown)"
)
publish_parser.add_argument(
"--type",
choices=["news", "newspic"],
default="news",
help="Article type: news (default) or newspic (小绿书)"
)
args = parser.parse_args()
if args.command == "list-accounts":
result = list_accounts()
print(json.dumps(result, ensure_ascii=False, indent=2))
elif args.command == "publish":
# Determine content format based on input
content_format = args.format
# Get content from file or direct input
if args.html:
# HTML file takes precedence, auto-set format to html
parsed = parse_html_for_wechat(args.html)
title = args.title or parsed["title"]
content = parsed["content"]
summary = args.summary or parsed["summary"]
cover = args.cover or parsed["cover_image"]
content_format = "html" # Always use html format for HTML files
elif args.markdown:
parsed = parse_markdown_for_wechat(args.markdown)
title = args.title or parsed["title"]
content = parsed["content"]
summary = args.summary or parsed["summary"]
cover = args.cover or parsed["cover_image"]
else:
if not args.title or not args.content:
print(
"Error: Either --markdown, --html, or both --title and --content required",
file=sys.stderr
)
sys.exit(1)
title = args.title
content = args.content
summary = args.summary
cover = args.cover
result = publish_article(
wechat_appid=args.appid,
title=title,
content=content,
summary=summary,
cover_image=cover,
author=args.author,
content_format=content_format,
article_type=args.type,
)
print(json.dumps(result, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
Related skills
How it compares
Use wechat-article-publisher for WeChat-specific Markdown-to-structured-data conversion; use generic static-site or RSS skills for non-WeChat content distribution.
FAQ
Does this skill publish articles live automatically?
No. It only saves to drafts; the user must review and publish manually in the WeChat admin panel.
What API key is required?
WECHAT_API_KEY must be set in the environment and sent as X-API-Key to wx.limyai.com endpoints.
What is the difference between news and newspic?
news is standard article format; newspic is image-focused with up to 20 images and 1000 character text limit.
Is Wechat Article Publisher safe to install?
skills.sh reports 2 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.