ForcePilot/backend/package/yuxi/channel/extensions/messenger/notification.py

70 lines
2.3 KiB
Python
Raw Normal View History

import logging
import httpx
logger = logging.getLogger(__name__)
MESSENGER_API_BASE = "https://graph.facebook.com/v22.0"
class MessengerOneTimeNotification:
def __init__(self, page_id: str, access_token: str):
self._page_id = page_id
self._access_token = access_token
async def request_otn(self, psid: str, title: str, payload: str) -> dict | None:
url = f"{MESSENGER_API_BASE}/{self._page_id}/messages"
body = {
"recipient": {"id": psid},
"message": {
"attachment": {
"type": "template",
"payload": {
"template_type": "one_time_notif_req",
"title": title,
"payload": payload,
},
}
},
}
try:
async with httpx.AsyncClient(timeout=httpx.Timeout(30.0)) as client:
resp = await client.post(
url,
params={"access_token": self._access_token},
json=body,
)
if resp.status_code == 200:
return resp.json()
logger.error(f"messenger OTN request failed: {resp.status_code} {resp.text}")
return None
except Exception:
logger.exception("messenger OTN request error")
return None
async def send_otn_message(
self,
psid: str,
text: str,
one_time_notif_token: str,
) -> dict | None:
url = f"{MESSENGER_API_BASE}/{self._page_id}/messages"
body = {
"recipient": {"one_time_notif_token": one_time_notif_token},
"message": {"text": text},
}
try:
async with httpx.AsyncClient(timeout=httpx.Timeout(30.0)) as client:
resp = await client.post(
url,
params={"access_token": self._access_token},
json=body,
)
if resp.status_code == 200:
return resp.json()
logger.error(f"messenger OTN send failed: {resp.status_code} {resp.text}")
return None
except Exception:
logger.exception("messenger OTN send error")
return None