Shane 7 months ago
parent c97425f5e2
commit ae194b502f
  1. 42
      foodie_automator_google.py
  2. 42
      foodie_automator_reddit.py
  3. 42
      foodie_automator_rss.py
  4. 51
      foodie_utils.py

@ -266,6 +266,7 @@ def curate_from_google_trends(posted_titles_data, posted_titles, used_images_dat
summary = trend.get("summary", "") summary = trend.get("summary", "")
source_name = trend.get("source", "Google Trends") source_name = trend.get("source", "Google Trends")
original_source = f'<a href="{link}">{source_name}</a>' original_source = f'<a href="{link}">{source_name}</a>'
original_url = link # Store for fallback
if title in posted_titles: if title in posted_titles:
logging.info(f"Skipping already posted trend: {title}") logging.info(f"Skipping already posted trend: {title}")
@ -375,33 +376,34 @@ def curate_from_google_trends(posted_titles_data, posted_titles, used_images_dat
should_post_tweet=True should_post_tweet=True
) )
if not post_id: if not post_id:
logging.warning(f"Failed to post to WordPress for '{title}'") logging.warning(f"Failed to post to WordPress for '{title}', using original URL: {original_url}")
attempts += 1 post_url = original_url # Fallback to original trend URL
continue else:
logging.info(f"Posted to WordPress for {author_username}: {post_url}")
# Update post with actual post_url # Update post with actual post_url
post_url_encoded = quote(post_url) post_url_encoded = quote(post_url)
share_links = share_links_template.format(post_url=post_url_encoded) share_links = share_links_template.format(post_url=post_url_encoded)
post_data["content"] = f"{final_summary}\n\n{share_links}" post_data["content"] = f"{final_summary}\n\n{share_links}"
post_data["post_id"] = post_id post_data["post_id"] = post_id
post_to_wp( if post_id:
post_data=post_data, post_to_wp(
category=category, post_data=post_data,
link=link, category=category,
author=author, link=link,
image_url=None, # Skip image re-upload author=author,
original_source=original_source, image_url=None, # Skip image re-upload
image_source=image_source, original_source=original_source,
uploader=uploader, image_source=image_source,
page_url=page_url, uploader=uploader,
interest_score=interest_score, page_url=page_url,
post_id=post_id, interest_score=interest_score,
should_post_tweet=False post_id=post_id,
) should_post_tweet=False
)
except Exception as e: except Exception as e:
logging.error(f"Failed to post to WordPress for '{title}': {e}", exc_info=True) logging.error(f"Failed to post to WordPress for '{title}': {e}", exc_info=True)
attempts += 1 post_url = original_url # Fallback to original trend URL
continue
finally: finally:
is_posting = False is_posting = False
@ -415,7 +417,7 @@ def curate_from_google_trends(posted_titles_data, posted_titles, used_images_dat
used_images.add(image_url) used_images.add(image_url)
logging.info(f"Saved image '{image_url}' to {USED_IMAGES_FILE}") logging.info(f"Saved image '{image_url}' to {USED_IMAGES_FILE}")
logging.info(f"***** SUCCESS: Posted '{post_data['title']}' (ID: {post_id}) from Google Trends *****") logging.info(f"***** SUCCESS: Posted '{post_data['title']}' (ID: {post_id or 'N/A'}) from Google Trends *****")
return post_data, category, True return post_data, category, True
logging.info("No interesting Google Trend found after attempts") logging.info("No interesting Google Trend found after attempts")

@ -286,6 +286,7 @@ def curate_from_reddit(posted_titles_data, posted_titles, used_images_data, used
summary = post.get("summary", "") summary = post.get("summary", "")
source_name = post.get("source", "Reddit") source_name = post.get("source", "Reddit")
original_source = f'<a href="{link}">{source_name}</a>' original_source = f'<a href="{link}">{source_name}</a>'
original_url = link # Store for fallback
if title in posted_titles: if title in posted_titles:
logging.info(f"Skipping already posted Reddit post: {title}") logging.info(f"Skipping already posted Reddit post: {title}")
@ -395,33 +396,34 @@ def curate_from_reddit(posted_titles_data, posted_titles, used_images_data, used
should_post_tweet=True should_post_tweet=True
) )
if not post_id: if not post_id:
logging.warning(f"Failed to post to WordPress for '{title}'") logging.warning(f"Failed to post to WordPress for '{title}', using original URL: {original_url}")
attempts += 1 post_url = original_url # Fallback to original Reddit post URL
continue else:
logging.info(f"Posted to WordPress for {author_username}: {post_url}")
# Update post with actual post_url # Update post with actual post_url
post_url_encoded = quote(post_url) post_url_encoded = quote(post_url)
share_links = share_links_template.format(post_url=post_url_encoded) share_links = share_links_template.format(post_url=post_url_encoded)
post_data["content"] = f"{final_summary}\n\n{share_links}" post_data["content"] = f"{final_summary}\n\n{share_links}"
post_data["post_id"] = post_id post_data["post_id"] = post_id
post_to_wp( if post_id:
post_data=post_data, post_to_wp(
category=category, post_data=post_data,
link=link, category=category,
author=author, link=link,
image_url=None, # Skip image re-upload author=author,
original_source=original_source, image_url=None, # Skip image re-upload
image_source=image_source, original_source=original_source,
uploader=uploader, image_source=image_source,
page_url=page_url, uploader=uploader,
interest_score=interest_score, page_url=page_url,
post_id=post_id, interest_score=interest_score,
should_post_tweet=False post_id=post_id,
) should_post_tweet=False
)
except Exception as e: except Exception as e:
logging.error(f"Failed to post to WordPress for '{title}': {e}", exc_info=True) logging.error(f"Failed to post to WordPress for '{title}': {e}", exc_info=True)
attempts += 1 post_url = original_url # Fallback to original Reddit post URL
continue
finally: finally:
is_posting = False is_posting = False
@ -435,7 +437,7 @@ def curate_from_reddit(posted_titles_data, posted_titles, used_images_data, used
used_images.add(image_url) used_images.add(image_url)
logging.info(f"Saved image '{image_url}' to {USED_IMAGES_FILE}") logging.info(f"Saved image '{image_url}' to {USED_IMAGES_FILE}")
logging.info(f"***** SUCCESS: Posted '{post_data['title']}' (ID: {post_id}) from Reddit *****") logging.info(f"***** SUCCESS: Posted '{post_data['title']}' (ID: {post_id or 'N/A'}) from Reddit *****")
return post_data, category, True return post_data, category, True
logging.info("No interesting Reddit post found after attempts") logging.info("No interesting Reddit post found after attempts")

@ -271,6 +271,7 @@ def curate_from_rss(posted_titles_data, posted_titles, used_images_data, used_im
summary = article.get("summary", "") summary = article.get("summary", "")
source_name = article.get("feed_title", "Unknown Source") source_name = article.get("feed_title", "Unknown Source")
original_source = f'<a href="{link}">{source_name}</a>' original_source = f'<a href="{link}">{source_name}</a>'
original_url = link # Store for fallback
if title in posted_titles: if title in posted_titles:
logging.info(f"Skipping already posted article: {title}") logging.info(f"Skipping already posted article: {title}")
@ -380,33 +381,34 @@ def curate_from_rss(posted_titles_data, posted_titles, used_images_data, used_im
should_post_tweet=True should_post_tweet=True
) )
if not post_id: if not post_id:
logging.warning(f"Failed to post to WordPress for '{title}'") logging.warning(f"Failed to post to WordPress for '{title}', using original URL: {original_url}")
attempts += 1 post_url = original_url # Fallback to original article URL
continue else:
logging.info(f"Posted to WordPress for {author_username}: {post_url}")
# Update post with actual post_url # Update post with actual post_url
post_url_encoded = quote(post_url) post_url_encoded = quote(post_url)
share_links = share_links_template.format(post_url=post_url_encoded) share_links = share_links_template.format(post_url=post_url_encoded)
post_data["content"] = f"{final_summary}\n\n{share_links}" post_data["content"] = f"{final_summary}\n\n{share_links}"
post_data["post_id"] = post_id post_data["post_id"] = post_id
post_to_wp( if post_id:
post_data=post_data, post_to_wp(
category=category, post_data=post_data,
link=link, category=category,
author=author, link=link,
image_url=None, # Skip image re-upload author=author,
original_source=original_source, image_url=None, # Skip image re-upload
image_source=image_source, original_source=original_source,
uploader=uploader, image_source=image_source,
page_url=page_url, uploader=uploader,
interest_score=interest_score, page_url=page_url,
post_id=post_id, interest_score=interest_score,
should_post_tweet=False post_id=post_id,
) should_post_tweet=False
)
except Exception as e: except Exception as e:
logging.error(f"Failed to post to WordPress for '{title}': {e}", exc_info=True) logging.error(f"Failed to post to WordPress for '{title}': {e}", exc_info=True)
attempts += 1 post_url = original_url # Fallback to original article URL
continue
finally: finally:
is_posting = False is_posting = False
@ -420,7 +422,7 @@ def curate_from_rss(posted_titles_data, posted_titles, used_images_data, used_im
used_images.add(image_url) used_images.add(image_url)
logging.info(f"Saved image '{image_url}' to {USED_IMAGES_FILE}") logging.info(f"Saved image '{image_url}' to {USED_IMAGES_FILE}")
logging.info(f"***** SUCCESS: Posted '{post_data['title']}' (ID: {post_id}) from RSS *****") logging.info(f"***** SUCCESS: Posted '{post_data['title']}' (ID: {post_id or 'N/A'}) from RSS *****")
return post_data, category, random.randint(0, 1800) return post_data, category, random.randint(0, 1800)
logging.info("No interesting RSS article found after attempts") logging.info("No interesting RSS article found after attempts")

@ -718,46 +718,67 @@ def post_to_wp(post_data, category, link, author, image_url, original_source, im
""" """
import logging import logging
import requests import requests
from foodie_config import WP_CREDENTIALS, X_API_CREDENTIALS from foodie_config import X_API_CREDENTIALS # Removed WP_CREDENTIALS
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
wp_username = WP_CREDENTIALS["username"]
wp_password = WP_CREDENTIALS["password"] # Extract WordPress credentials from author dictionary
wp_url = author.get("url")
endpoint = f"{WP_CREDENTIALS['url']}/wp-json/wp/v2/posts" wp_username = author.get("username")
wp_password = author.get("password")
if not all([wp_url, wp_username, wp_password]):
logger.error(f"Missing WordPress credentials for author: {author.get('username', 'unknown')}")
return None, None
# Ensure wp_url ends with '/wp-json/wp/v2'
if not wp_url.endswith('/wp-json/wp/v2'):
wp_base_url = f"{wp_url.rstrip('/')}/wp-json/wp/v2"
else:
wp_base_url = wp_url
endpoint = f"{wp_base_url}/posts"
if post_id: if post_id:
endpoint += f"/{post_id}" endpoint += f"/{post_id}"
headers = { headers = {
"Authorization": "Basic " + base64.b64encode(f"{wp_username}:{wp_password}".encode()).decode(), "Authorization": "Basic " + base64.b64encode(f"{wp_username}:{wp_password}".encode()).decode(),
"Content-Type": "application/json" "Content-Type": "application/json"
} }
# Get or create category ID
category_id = get_wp_category_id(category, wp_base_url, wp_username, wp_password)
if not category_id:
category_id = create_wp_category(category, wp_base_url, wp_username, wp_password)
if not category_id:
logger.warning(f"Failed to get or create category '{category}', using default")
category_id = 1 # Fallback to default category
payload = { payload = {
"title": post_data["title"], "title": post_data["title"],
"content": post_data["content"], "content": post_data["content"],
"status": post_data["status"], "status": post_data["status"],
"author": WP_CREDENTIALS["authors"].get(post_data["author"], 1), "author": wp_username, # Use username directly
"categories": [category] "categories": [category_id]
} }
try: try:
response = requests.post(endpoint, headers=headers, json=payload) response = requests.post(endpoint, headers=headers, json=payload)
response.raise_for_status() response.raise_for_status()
post_id = response.json().get("id") post_id = response.json().get("id")
post_url = response.json().get("link") post_url = response.json().get("link")
logger.info(f"{'Updated' if post_id else 'Posted'} WordPress post: {post_data['title']} (ID: {post_id})") logger.info(f"{'Updated' if post_id else 'Posted'} WordPress post: {post_data['title']} (ID: {post_id})")
if image_url and not post_id: # Only upload image for new posts if image_url and not post_id: # Only upload image for new posts
media_id = upload_image_to_wp(image_url, post_data["title"], image_source, uploader, page_url) media_id = upload_image_to_wp(image_url, post_data["title"], wp_base_url, wp_username, wp_password, image_source, uploader, page_url)
if media_id: if media_id:
requests.post( requests.post(
f"{WP_CREDENTIALS['url']}/wp-json/wp/v2/posts/{post_id}", f"{wp_base_url}/posts/{post_id}",
headers=headers, headers=headers,
json={"featured_media": media_id} json={"featured_media": media_id}
) )
logger.info(f"Set featured image (Media ID: {media_id}) for post {post_id}") logger.info(f"Set featured image (Media ID: {media_id}) for post {post_id}")
if should_post_tweet and post_url: if should_post_tweet and post_url:
credentials = X_API_CREDENTIALS.get(post_data["author"]) credentials = X_API_CREDENTIALS.get(post_data["author"])
if credentials: if credentials:
@ -766,7 +787,7 @@ def post_to_wp(post_data, category, link, author, image_url, original_source, im
logger.info(f"Successfully tweeted for post: {post_data['title']}") logger.info(f"Successfully tweeted for post: {post_data['title']}")
else: else:
logger.warning(f"Failed to tweet for post: {post_data['title']}") logger.warning(f"Failed to tweet for post: {post_data['title']}")
return post_id, post_url return post_id, post_url
except requests.exceptions.RequestException as e: except requests.exceptions.RequestException as e:
logger.error(f"Failed to {'update' if post_id else 'post'} WordPress post: {post_data['title']}: {e}", exc_info=True) logger.error(f"Failed to {'update' if post_id else 'post'} WordPress post: {post_data['title']}: {e}", exc_info=True)

Loading…
Cancel
Save