whatsapp_service.py 2.1 KB

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