whatsapp_service.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import aiohttp
  2. from typing import Optional
  3. from app.core.biz_exception import BizLogicError
  4. class WhatsappService:
  5. @staticmethod
  6. async def send_text(
  7. api_base_url: str,
  8. session: str,
  9. chat_id: str,
  10. message: str,
  11. api_key: Optional[str] = None,
  12. ):
  13. if not api_base_url:
  14. raise BizLogicError("Whatsapp api_base_url not configured")
  15. if not chat_id:
  16. raise BizLogicError("Whatsapp chat_id missing")
  17. headers = {}
  18. if api_key:
  19. headers["X-Api-Key"] = api_key
  20. read_url = f"{api_base_url}/api/{session}/chats/{chat_id}/messages/read"
  21. send_url = f"{api_base_url}/api/sendText"
  22. timeout = aiohttp.ClientTimeout(total=10)
  23. try:
  24. async with aiohttp.ClientSession(timeout=timeout) as session_client:
  25. async with session_client.post(read_url, json={}, headers=headers) as read_resp:
  26. if read_resp.status >= 300:
  27. raise BizLogicError(f"Whatsapp read failed, http_status={read_resp.status}")
  28. payload = {
  29. "session": session,
  30. "chatId": chat_id,
  31. "text": message,
  32. }
  33. async with session_client.post(send_url, json=payload, headers=headers) as send_resp:
  34. if send_resp.status >= 300:
  35. raise BizLogicError(f"Whatsapp push failed, http_status={send_resp.status}")
  36. except aiohttp.ClientError as e:
  37. raise BizLogicError(f"Whatsapp push request error: {e}")
  38. return True