33 lines
1.0 KiB
Python
33 lines
1.0 KiB
Python
import logging
|
|
import json
|
|
from urllib import request
|
|
|
|
from app.core.config import settings
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
def send_wecom_text(content: str) -> bool:
|
|
text = str(content or "").strip()
|
|
webhook = str(getattr(settings, "WECOM_BOT_WEBHOOK", "") or "").strip()
|
|
if not text or not webhook:
|
|
return False
|
|
try:
|
|
payload = json.dumps({"msgtype": "text", "text": {"content": text[:3500]}}).encode("utf-8")
|
|
req = request.Request(
|
|
webhook,
|
|
data=payload,
|
|
headers={"Content-Type": "application/json"},
|
|
method="POST",
|
|
)
|
|
with request.urlopen(req, timeout=10) as resp:
|
|
body = resp.read().decode("utf-8", errors="ignore")
|
|
data = json.loads(body or "{}")
|
|
ok = int(data.get("errcode", -1)) == 0
|
|
if not ok:
|
|
logger.warning(f"WeCom bot send failed: {data}")
|
|
return ok
|
|
except Exception as e:
|
|
logger.warning(f"WeCom bot send exception: {e}")
|
|
return False
|