fix fb issue
Browse files- app/facebook.py +37 -12
- requirements.txt +2 -1
app/facebook.py
CHANGED
|
@@ -1,10 +1,12 @@
|
|
| 1 |
import hmac
|
| 2 |
import hashlib
|
| 3 |
import json
|
|
|
|
| 4 |
from typing import Any, Dict, Optional
|
| 5 |
import httpx
|
| 6 |
from fastapi import HTTPException, Request
|
| 7 |
from loguru import logger
|
|
|
|
| 8 |
|
| 9 |
from .utils import timing_decorator_async, timing_decorator_sync
|
| 10 |
|
|
@@ -97,32 +99,55 @@ class FacebookClient:
|
|
| 97 |
messages.append(current.rstrip())
|
| 98 |
return messages
|
| 99 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
@timing_decorator_async
|
| 101 |
async def send_message(self, page_access_token: Optional[str] = None, recipient_id: Optional[str] = None, message: str = "") -> dict:
|
| 102 |
page_access_token = page_access_token or self.page_token
|
| 103 |
recipient_id = recipient_id or self.sender_id
|
| 104 |
if not page_access_token or not recipient_id:
|
| 105 |
raise ValueError("FacebookClient: page_access_token and recipient_id must not be None when sending a message.")
|
|
|
|
| 106 |
# Format message
|
| 107 |
response_to_send = self.format_message(message.replace('**', '*')) if isinstance(message, str) else message
|
|
|
|
| 108 |
# Chia nhỏ nếu quá dài
|
| 109 |
messages = self.split_message(response_to_send)
|
| 110 |
results = []
|
|
|
|
| 111 |
for msg in messages:
|
| 112 |
if len(msg) > 2000:
|
| 113 |
msg = msg[:2000] # fallback cắt cứng
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
return results[0] if results else {}
|
| 127 |
|
| 128 |
@timing_decorator_sync
|
|
|
|
| 1 |
import hmac
|
| 2 |
import hashlib
|
| 3 |
import json
|
| 4 |
+
import asyncio
|
| 5 |
from typing import Any, Dict, Optional
|
| 6 |
import httpx
|
| 7 |
from fastapi import HTTPException, Request
|
| 8 |
from loguru import logger
|
| 9 |
+
import facebook
|
| 10 |
|
| 11 |
from .utils import timing_decorator_async, timing_decorator_sync
|
| 12 |
|
|
|
|
| 99 |
messages.append(current.rstrip())
|
| 100 |
return messages
|
| 101 |
|
| 102 |
+
def _send_message_sync(self, page_access_token: str, recipient_id: str, message: str) -> dict:
|
| 103 |
+
"""
|
| 104 |
+
Gửi tin nhắn sử dụng facebook-sdk (sync).
|
| 105 |
+
"""
|
| 106 |
+
try:
|
| 107 |
+
graph = facebook.GraphAPI(access_token=page_access_token, version="18.0")
|
| 108 |
+
result = graph.put_object(
|
| 109 |
+
parent_object='me',
|
| 110 |
+
connection_name='messages',
|
| 111 |
+
recipient={'id': recipient_id},
|
| 112 |
+
message={'text': message}
|
| 113 |
+
)
|
| 114 |
+
return result
|
| 115 |
+
except facebook.GraphAPIError as e:
|
| 116 |
+
logger.error(f"Facebook GraphAPI Error: {e}")
|
| 117 |
+
raise HTTPException(status_code=500, detail=f"Failed to send message to Facebook: {e}")
|
| 118 |
+
except Exception as e:
|
| 119 |
+
logger.error(f"Unexpected error sending message to Facebook: {e}")
|
| 120 |
+
raise HTTPException(status_code=500, detail="Failed to send message to Facebook")
|
| 121 |
+
|
| 122 |
@timing_decorator_async
|
| 123 |
async def send_message(self, page_access_token: Optional[str] = None, recipient_id: Optional[str] = None, message: str = "") -> dict:
|
| 124 |
page_access_token = page_access_token or self.page_token
|
| 125 |
recipient_id = recipient_id or self.sender_id
|
| 126 |
if not page_access_token or not recipient_id:
|
| 127 |
raise ValueError("FacebookClient: page_access_token and recipient_id must not be None when sending a message.")
|
| 128 |
+
|
| 129 |
# Format message
|
| 130 |
response_to_send = self.format_message(message.replace('**', '*')) if isinstance(message, str) else message
|
| 131 |
+
|
| 132 |
# Chia nhỏ nếu quá dài
|
| 133 |
messages = self.split_message(response_to_send)
|
| 134 |
results = []
|
| 135 |
+
|
| 136 |
for msg in messages:
|
| 137 |
if len(msg) > 2000:
|
| 138 |
msg = msg[:2000] # fallback cắt cứng
|
| 139 |
+
|
| 140 |
+
# Wrap sync SDK call in thread executor để giữ async
|
| 141 |
+
loop = asyncio.get_event_loop()
|
| 142 |
+
result = await loop.run_in_executor(
|
| 143 |
+
None,
|
| 144 |
+
self._send_message_sync,
|
| 145 |
+
page_access_token,
|
| 146 |
+
recipient_id,
|
| 147 |
+
msg
|
| 148 |
+
)
|
| 149 |
+
results.append(result)
|
| 150 |
+
|
| 151 |
return results[0] if results else {}
|
| 152 |
|
| 153 |
@timing_decorator_sync
|
requirements.txt
CHANGED
|
@@ -12,4 +12,5 @@ numpy==1.26.2
|
|
| 12 |
python-multipart==0.0.6
|
| 13 |
tenacity==8.2.3
|
| 14 |
pydantic-settings
|
| 15 |
-
google-generativeai>=0.3.0
|
|
|
|
|
|
| 12 |
python-multipart==0.0.6
|
| 13 |
tenacity==8.2.3
|
| 14 |
pydantic-settings
|
| 15 |
+
google-generativeai>=0.3.0
|
| 16 |
+
facebook-sdk>=3.1.0
|