import requests import json def upload_article_draft(access_token, title, content, cover_media_id, author, digest=None, show_cover_pic=1): """ 上传文章草稿到微信公众号草稿箱 参数: access_token (str): 公众号的access_token title (str): 文章标题 content (str): 文章内容(HTML格式) cover_media_id (str): 封面图片的media_id author (str): 作者 digest (str, optional): 文章摘要,默认为None show_cover_pic (int, optional): 是否显示封面,0不显示,1显示,默认为1 返回: str: 成功时返回草稿的media_id None: 失败时返回None """ # 验证必填参数 if not all([access_token, title, content, cover_media_id, author]): return None # 微信上传草稿接口 url = f"https://api.weixin.qq.com/cgi-bin/draft/add?access_token={access_token}" # 构造请求数据 article_data = { "articles": [ { "title": title, "content": content, "thumb_media_id": cover_media_id, "author": author, "show_cover_pic": show_cover_pic } ] } # 添加可选参数 if digest: article_data["articles"][0]["digest"] = digest try: # 发送POST请求 response = requests.post( url, data=json.dumps(article_data, ensure_ascii=False).encode('utf-8'), headers={'Content-Type': 'application/json'}, timeout=15 ) # 解析响应结果 result = json.loads(response.text) # 检查是否有错误 if "errcode" in result and result["errcode"] != 0: return None # 返回草稿的media_id media_id = result.get("media_id") if media_id: return media_id else: return None except requests.exceptions.RequestException: return None except json.JSONDecodeError: return None except Exception: return None