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", "")
source_name = trend.get("source", "Google Trends")
original_source = f'<a href="{link}">{source_name}</a>'
original_url = link # Store for fallback
if title in posted_titles:
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
)
if not post_id:
logging.warning(f"Failed to post to WordPress for '{title}'")
attempts += 1
continue
logging.warning(f"Failed to post to WordPress for '{title}', using original URL: {original_url}")
post_url = original_url # Fallback to original trend URL
else:
logging.info(f"Posted to WordPress for {author_username}: {post_url}")
# Update post with actual post_url
post_url_encoded = quote(post_url)
share_links = share_links_template.format(post_url=post_url_encoded)
post_data["content"] = f"{final_summary}\n\n{share_links}"
post_data["post_id"] = post_id
post_to_wp(
post_data=post_data,
category=category,
link=link,
author=author,
image_url=None, # Skip image re-upload
original_source=original_source,
image_source=image_source,
uploader=uploader,
page_url=page_url,
interest_score=interest_score,
post_id=post_id,
should_post_tweet=False
)
if post_id:
post_to_wp(
post_data=post_data,
category=category,
link=link,
author=author,
image_url=None, # Skip image re-upload
original_source=original_source,
image_source=image_source,
uploader=uploader,
page_url=page_url,
interest_score=interest_score,
post_id=post_id,
should_post_tweet=False
)
except Exception as e:
logging.error(f"Failed to post to WordPress for '{title}': {e}", exc_info=True)
attempts += 1
continue
post_url = original_url # Fallback to original trend URL
finally:
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)
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
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", "")
source_name = post.get("source", "Reddit")
original_source = f'<a href="{link}">{source_name}</a>'
original_url = link # Store for fallback
if title in posted_titles:
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
)
if not post_id:
logging.warning(f"Failed to post to WordPress for '{title}'")
attempts += 1
continue
logging.warning(f"Failed to post to WordPress for '{title}', using original URL: {original_url}")
post_url = original_url # Fallback to original Reddit post URL
else:
logging.info(f"Posted to WordPress for {author_username}: {post_url}")
# Update post with actual post_url
post_url_encoded = quote(post_url)
share_links = share_links_template.format(post_url=post_url_encoded)
post_data["content"] = f"{final_summary}\n\n{share_links}"
post_data["post_id"] = post_id
post_to_wp(
post_data=post_data,
category=category,
link=link,
author=author,
image_url=None, # Skip image re-upload
original_source=original_source,
image_source=image_source,
uploader=uploader,
page_url=page_url,
interest_score=interest_score,
post_id=post_id,
should_post_tweet=False
)
if post_id:
post_to_wp(
post_data=post_data,
category=category,
link=link,
author=author,
image_url=None, # Skip image re-upload
original_source=original_source,
image_source=image_source,
uploader=uploader,
page_url=page_url,
interest_score=interest_score,
post_id=post_id,
should_post_tweet=False
)
except Exception as e:
logging.error(f"Failed to post to WordPress for '{title}': {e}", exc_info=True)
attempts += 1
continue
post_url = original_url # Fallback to original Reddit post URL
finally:
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)
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
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", "")
source_name = article.get("feed_title", "Unknown Source")
original_source = f'<a href="{link}">{source_name}</a>'
original_url = link # Store for fallback
if title in posted_titles:
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
)
if not post_id:
logging.warning(f"Failed to post to WordPress for '{title}'")
attempts += 1
continue
logging.warning(f"Failed to post to WordPress for '{title}', using original URL: {original_url}")
post_url = original_url # Fallback to original article URL
else:
logging.info(f"Posted to WordPress for {author_username}: {post_url}")
# Update post with actual post_url
post_url_encoded = quote(post_url)
share_links = share_links_template.format(post_url=post_url_encoded)
post_data["content"] = f"{final_summary}\n\n{share_links}"
post_data["post_id"] = post_id
post_to_wp(
post_data=post_data,
category=category,
link=link,
author=author,
image_url=None, # Skip image re-upload
original_source=original_source,
image_source=image_source,
uploader=uploader,
page_url=page_url,
interest_score=interest_score,
post_id=post_id,
should_post_tweet=False
)
if post_id:
post_to_wp(
post_data=post_data,
category=category,
link=link,
author=author,
image_url=None, # Skip image re-upload
original_source=original_source,
image_source=image_source,
uploader=uploader,
page_url=page_url,
interest_score=interest_score,
post_id=post_id,
should_post_tweet=False
)
except Exception as e:
logging.error(f"Failed to post to WordPress for '{title}': {e}", exc_info=True)
attempts += 1
continue
post_url = original_url # Fallback to original article URL
finally:
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)
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)
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 requests
from foodie_config import WP_CREDENTIALS, X_API_CREDENTIALS
from foodie_config import X_API_CREDENTIALS # Removed WP_CREDENTIALS
logger = logging.getLogger(__name__)
wp_username = WP_CREDENTIALS["username"]
wp_password = WP_CREDENTIALS["password"]
endpoint = f"{WP_CREDENTIALS['url']}/wp-json/wp/v2/posts"
# Extract WordPress credentials from author dictionary
wp_url = author.get("url")
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:
endpoint += f"/{post_id}"
headers = {
"Authorization": "Basic " + base64.b64encode(f"{wp_username}:{wp_password}".encode()).decode(),
"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 = {
"title": post_data["title"],
"content": post_data["content"],
"status": post_data["status"],
"author": WP_CREDENTIALS["authors"].get(post_data["author"], 1),
"categories": [category]
"author": wp_username, # Use username directly
"categories": [category_id]
}
try:
response = requests.post(endpoint, headers=headers, json=payload)
response.raise_for_status()
post_id = response.json().get("id")
post_url = response.json().get("link")
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
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:
requests.post(
f"{WP_CREDENTIALS['url']}/wp-json/wp/v2/posts/{post_id}",
f"{wp_base_url}/posts/{post_id}",
headers=headers,
json={"featured_media": media_id}
)
logger.info(f"Set featured image (Media ID: {media_id}) for post {post_id}")
if should_post_tweet and post_url:
credentials = X_API_CREDENTIALS.get(post_data["author"])
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']}")
else:
logger.warning(f"Failed to tweet for post: {post_data['title']}")
return post_id, post_url
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)

Loading…
Cancel
Save