ForcePilot/backend/package/yuxi/channel/extensions/wecom/media.py
Kris 7215418610 feat(channel): 添加企业微信、微博、WhatsApp 和 Workplace 渠道扩展
新增企业微信、微博、WhatsApp、Workplace 四个渠道扩展。

企业微信渠道扩展主要模块:config, gateway, webhook, webhook_bot, outbound, streaming, pairing, security, crypto, dedupe, persistent_dedupe, card, directory, events, externalcontact, media, mentions, menu, message, oauth, status

微博渠道扩展主要模块:config, gateway, webhook, outbound, streaming, pairing, security, dedupe, passive_reply, broadcast, message, menu, media, subscription, template, status

WhatsApp 渠道扩展主要模块:config, gateway, webhook, outbound, streaming, pairing, security, dedupe, actions, monitor, status

Workplace 渠道扩展主要模块:config, gateway, webhook, outbound, streaming, pairing, security, dedupe, actions, challenge, groups, media, mentions, menu, monitor, persona, quick_reply, signature, subscriptions, template, threading, users, status
2026-05-21 12:01:56 +08:00

64 lines
1.9 KiB
Python

import logging
import httpx
logger = logging.getLogger(__name__)
MEDIA_UPLOAD_URL = "https://qyapi.weixin.qq.com/cgi-bin/media/upload"
MEDIA_GET_URL = "https://qyapi.weixin.qq.com/cgi-bin/media/get"
MEDIA_UPLOAD_IMG_URL = "https://qyapi.weixin.qq.com/cgi-bin/media/uploadimg"
class WeComMedia:
def __init__(self, gateway):
self._gateway = gateway
self._http: httpx.AsyncClient | None = None
async def upload(self, media_type: str, file_path: str) -> str | None:
token = self._gateway.access_token
if not token:
return None
url = f"{MEDIA_UPLOAD_URL}?access_token={token}&type={media_type}"
if self._http is None:
self._http = httpx.AsyncClient(timeout=30.0)
try:
with open(file_path, "rb") as f:
files = {"media": f}
resp = await self._http.post(url, files=files)
data = resp.json()
if data.get("errcode") == 0:
return data.get("media_id")
logger.error("WeCom media upload failed: %s", data)
return None
except Exception:
logger.exception("WeCom media upload error")
return None
async def download(self, media_id: str, save_path: str) -> bool:
token = self._gateway.access_token
if not token:
return False
url = f"{MEDIA_GET_URL}?access_token={token}&media_id={media_id}"
if self._http is None:
self._http = httpx.AsyncClient(timeout=30.0)
try:
resp = await self._http.get(url)
with open(save_path, "wb") as f:
f.write(resp.content)
return True
except Exception:
logger.exception("WeCom media download error")
return False
async def close(self):
if self._http:
await self._http.aclose()
self._http = None