一、准备工作

1. 注册微信公众号并获取接口权限

• 登录微信公众平台,进入 开发 > 基本配置
• 获取 AppIDAppSecret
• 开启 IP白名单(需配置服务器IP)。

2. 安装依赖库

使用 requests 发送 HTTP 请求:

pip install requests

二、核心流程

1. 获取 Access Token
import requests

def get_access_token(appid, appsecret):
    url = "https://api.weixin.qq.com/cgi-bin/token"
    params = {
        "grant_type": "client_credential",
        "appid": appid,
        "secret": appsecret
    }
    response = requests.get(url, params=params).json()
    return response.get("access_token")
2. 上传素材(如图片/缩略图)

图文消息需先上传图片获取 media_id

def upload_image(access_token, image_path):
    url = "https://api.weixin.qq.com/cgi-bin/media/upload"
    params = {"access_token": access_token, "type": "image"}
    with open(image_path, "rb") as file:
        files = {"media": file}
        response = requests.post(url, params=params, files=files).json()
    return response.get("media_id")
3. 构造图文消息内容
def create_article(title, content, thumb_media_id):
    return {
        "title": title,
        "thumb_media_id": thumb_media_id,  # 封面图片 media_id
        "author": "作者名称",
        "content": content,
        "content_source_url": "https://example.com",  # 原文链接
        "digest": "文章摘要",
        "show_cover_pic": 1  # 是否显示封面图(0/1)
    }
4. 发布图文消息
def publish_article(access_token, articles):
    url = "https://api.weixin.qq.com/cgi-bin/draft/add"
    headers = {"Content-Type": "application/json"}
    data = {
        "articles": articles  # 支持多图文(列表格式)
    }
    response = requests.post(
        url,
        params={"access_token": access_token},
        headers=headers,
        json=data
    )
    return response.json()

三、完整代码示例

import requests

# 配置信息
APPID = "YOUR_APPID"
APPSECRET = "YOUR_APPSECRET"
IMAGE_PATH = "cover.jpg"  # 封面图片路径

def main():
    # 1. 获取 Access Token
    access_token = get_access_token(APPID, APPSECRET)
    if not access_token:
        print("获取 Access Token 失败!")
        return

    # 2. 上传封面图片
    thumb_media_id = upload_image(access_token, IMAGE_PATH)
    if not thumb_media_id:
        print("上传封面图片失败!")
        return

    # 3. 构造文章内容
    article_content = """
    <p>这里是文章正文,支持HTML格式。</p>
    <p><img src="https://example.com/image.jpg" /></p>
    """
    article = create_article(
        title="测试文章标题",
        content=article_content,
        thumb_media_id=thumb_media_id
    )

    # 4. 发布草稿(需转为正式文章后发布)
    result = publish_article(access_token, [article])
    if result.get("errcode") == 0:
        print("草稿创建成功!媒体ID:", result.get("media_id"))
    else:
        print("发布失败:", result.get("errmsg"))

if __name__ == "__main__":
    main()

四、注意事项

  1. 从草稿到正式发布
    • 上述代码仅创建草稿,需通过微信公众平台手动 群发 或调用 submit 接口 完成发布。

  2. 内容安全审核
    • 微信会自动审核内容,涉及敏感词可能导致发布失败。

  3. 频率限制
    • 图文消息每日最多发布 1 次,草稿无限制但需谨慎操作。

  4. 错误处理
    • 检查返回的 errcode,常见错误:
    40001: Access Token 失效(需重新获取)
    45009: API 调用频率超限


五、扩展功能

1. 自动发布定时任务

结合 APScheduler 定时触发:

from apscheduler.schedulers.blocking import BlockingScheduler

scheduler = BlockingScheduler()
@scheduler.scheduled_job('cron', hour=8)
def auto_publish():
    main()
scheduler.start()
2. Markdown 转微信 HTML

使用 markdown 库生成内容:

import markdown
content_md = "# 标题\n正文内容"
article_content = markdown.markdown(content_md)

六、官方文档

微信公众号开发文档
图文消息接口文档

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐