78 lines
2.4 KiB
Python
78 lines
2.4 KiB
Python
"""WeCom messaging/test endpoints."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from ...core.database import get_db
|
|
from ...dependencies.auth import get_current_user
|
|
from ...dependencies.tenant import get_tenant_id
|
|
from ...models import User
|
|
from ...services.integrations.wecom import get_wecom_service
|
|
from .schemas import WeComSendMessageRequest
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@router.post("/send-message")
|
|
async def send_wecom_message(
|
|
request: WeComSendMessageRequest,
|
|
current_user: User = Depends(get_current_user),
|
|
db: AsyncSession = Depends(get_db),
|
|
tenant_id: int = Depends(get_tenant_id),
|
|
):
|
|
"""发送文本消息到企业微信群。"""
|
|
try:
|
|
service = get_wecom_service(db)
|
|
await service.load_config(tenant_id)
|
|
|
|
result = await service.send_message_to_group(
|
|
chat_id=request.chat_id,
|
|
message=request.message,
|
|
)
|
|
|
|
return {
|
|
"status": "success",
|
|
"result": result,
|
|
}
|
|
except ValueError as exc:
|
|
raise HTTPException(status_code=400, detail=str(exc))
|
|
except Exception as exc:
|
|
raise HTTPException(status_code=500, detail=f"发送消息失败: {str(exc)}")
|
|
|
|
|
|
@router.post("/test-connection")
|
|
async def test_wecom_connection(
|
|
current_user: User = Depends(get_current_user),
|
|
db: AsyncSession = Depends(get_db),
|
|
tenant_id: int = Depends(get_tenant_id),
|
|
):
|
|
"""测试企业微信连接是否正常。"""
|
|
try:
|
|
service = get_wecom_service(db)
|
|
await service.load_config(tenant_id)
|
|
|
|
if not service.is_configured():
|
|
return {
|
|
"status": "error",
|
|
"message": "企业微信未配置",
|
|
}
|
|
|
|
try:
|
|
access_token = await service._get_access_token()
|
|
return {
|
|
"status": "success",
|
|
"message": "企业微信连接正常",
|
|
"has_token": bool(access_token),
|
|
}
|
|
except Exception as token_error:
|
|
return {
|
|
"status": "error",
|
|
"message": f"获取 Token 失败: {str(token_error)}",
|
|
"hint": "请检查 Corp ID、Agent ID 和 App Secret 是否正确",
|
|
}
|
|
|
|
except Exception as exc:
|
|
raise HTTPException(status_code=500, detail=f"测试连接失败: {str(exc)}")
|