Files
tw/services/service_wecom_bot.py

52 lines
1.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import logging
import os
import httpx
from dotenv import load_dotenv
load_dotenv()
logger = logging.getLogger("cs_agent")
WECOM_BOT_WEBHOOK = os.getenv(
"WECOM_BOT_WEBHOOK",
"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=cc88bdef-a13f-4d7e-bdb6-ee51b68b8205",
).strip()
class WecomBotService:
def __init__(self, webhook_url: str = WECOM_BOT_WEBHOOK):
self.webhook_url = str(webhook_url or "").strip()
async def send_text(self, content: str) -> bool:
text = str(content or "").strip()
if not text:
return False
if not self.webhook_url:
logger.warning("[WeComBot] 未配置 webhook跳过发送")
return False
payload = {
"msgtype": "text",
"text": {
"content": text[:3500],
},
}
try:
async with httpx.AsyncClient(timeout=10.0) as client:
response = await client.post(self.webhook_url, json=payload)
if response.status_code != 200:
logger.warning(f"[WeComBot] 发送失败 HTTP {response.status_code}: {response.text}")
return False
data = response.json()
ok = int(data.get("errcode", -1)) == 0
if not ok:
logger.warning(f"[WeComBot] 发送失败: {data}")
return ok
except Exception as e:
logger.warning(f"[WeComBot] 发送异常: {e}")
return False
wecom_bot_service = WecomBotService()