This commit is contained in:
yumoqing 2026-03-03 16:31:38 +08:00
parent 97ef9067d3
commit 54b41c7160

View File

@ -91,34 +91,40 @@ class WeChatMediaManager:
else: else:
url = f"https://api.weixin.qq.com/cgi-bin/media/upload?access_token={token}&type={media_type}" url = f"https://api.weixin.qq.com/cgi-bin/media/upload?access_token={token}&type={media_type}"
# 构建 multipart/form-data form = aiohttp.FormData()
form = aiohttp.FormData() f = open(file_path, 'rb') # 不用 with
with open(file_path, 'rb') as f: try:
# 微信要求的字段名必须是 'media' form.add_field(
form.add_field('media', f, filename=os.path.basename(file_path)) 'media',
f,
filename=os.path.basename(file_path),
content_type='application/octet-stream'
)
# 永久视频需要额外的 description 字段 (JSON 格式) if is_permanent and media_type == 'video':
if is_permanent and media_type == 'video': if not title:
if not title: title = os.path.basename(file_path)
title = os.path.basename(file_path)
desc_json = json.dumps({
"title": title,
"introduction": description or ""
}, ensure_ascii=False)
form.add_field('description', desc_json)
timeout = aiohttp.ClientTimeout(total=120) # 大文件上传需要更长超时 desc_json = json.dumps({
"title": title,
"introduction": description or ""
}, ensure_ascii=False)
async with aiohttp.ClientSession(timeout=timeout) as session: form.add_field('description', desc_json)
async with session.post(url, data=form) as resp:
result = await resp.json()
if resp.status == 200 and ('media_id' in result or 'url' in result): timeout = aiohttp.ClientTimeout(total=120)
debug(f"上传成功 ({'永久' if is_permanent else '临时'}): {result.get('media_id')}")
return result async with aiohttp.ClientSession(timeout=timeout) as session:
else: async with session.post(url, data=form) as resp:
error(f"上传失败: {result}") result = await resp.json()
raise Exception(f"WeChat Upload Error: {result}")
if resp.status == 200 and ('media_id' in result or 'url' in result):
return result['media_id']
else:
raise Exception(f"WeChat Upload Error: {result}")
finally:
f.close() # 手动关闭
# ================= 3. 下载媒体文件 ================= # ================= 3. 下载媒体文件 =================
async def download_media( async def download_media(