diff --git a/pxy_meta_pages/services.py b/pxy_meta_pages/services.py index 796c16e..7522763 100644 --- a/pxy_meta_pages/services.py +++ b/pxy_meta_pages/services.py @@ -73,7 +73,7 @@ class FacebookService: description = post_details.get("description", "") parent_id = post_details.get("parent_id", None) - author_page_id = post_details.get("from_id", None) + author_page_id = post_details.get("parent_from_id", None) # Fetch the appropriate OpenAI assistant for the page try: @@ -141,8 +141,13 @@ class FacebookService: def get_post_details(self, post_id, access_token): """ - Retrieves details of a post, including description, parent_id, and author Page ID (from_id). + Retrieves details of a post, including: + - description (from attachments) + - parent_id (if it’s a share) + - from_id (author of THIS post) + - parent_from_id (author of the ORIGINAL post, if shared) """ + # 1st call: get this post’s description, parent_id, and its own from() url = ( f"{self.base_url}/{post_id}" "?fields=attachments.limit(10){description,media,media_type,target,url}," @@ -155,20 +160,38 @@ class FacebookService: data = response.json() attachments = data.get("attachments", {}).get("data", [{}]) - description = attachments[0].get("description", "") if attachments else "" - parent_id = data.get("parent_id", None) - from_id = data.get("from", {}).get("id") + description = attachments[0].get("description", "") if attachments else "" + parent_id = data.get("parent_id") + from_id = data.get("from", {}).get("id") + + # default if there is no parent + parent_from_id = None + + # If this is a share, fetch the ORIGINAL post’s author + if parent_id: + parent_url = ( + f"{self.base_url}/{parent_id}" + "?fields=from" + f"&access_token={access_token}" + ) + p_resp = requests.get(parent_url) + p_resp.raise_for_status() + p_data = p_resp.json() + parent_from_id = p_data.get("from", {}).get("id") return { - "description": description, - "parent_id": parent_id, - "from_id": from_id + "description": description, + "parent_id": parent_id, + "from_id": from_id, + "parent_from_id": parent_from_id } + except requests.exceptions.RequestException as e: logger.error(f"Failed to fetch post details for {post_id}. Error: {e}") return {} + def _post_facebook_comment(self, post_id, message, access_token, sender_id=None): """ Helper function to post a comment to a specific post.