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