From 15186846bea51ec959f5f9cc098deb4ebde8c547 Mon Sep 17 00:00:00 2001 From: Shane Date: Wed, 30 Apr 2025 08:51:38 +1000 Subject: [PATCH] add enguagement tweet & fix filtered words --- foodie_automator_reddit.py | 7 +- foodie_engagement_tweet.py | 61 +++++++++++++++++ foodie_hooks.py | 36 ++++++---- foodie_utils.py | 52 ++++++++------- foodie_weekly_thread.py | 130 +++++++++++++++++++++++++++++++++++++ 5 files changed, 245 insertions(+), 41 deletions(-) create mode 100644 foodie_engagement_tweet.py create mode 100644 foodie_weekly_thread.py diff --git a/foodie_automator_reddit.py b/foodie_automator_reddit.py index ab34ba0..50ff5d6 100644 --- a/foodie_automator_reddit.py +++ b/foodie_automator_reddit.py @@ -240,7 +240,8 @@ def curate_from_reddit(): logging.info(f"Trying Reddit Post: {title} from {source_name}") image_query, relevance_keywords, skip = smart_image_and_filter(title, summary) - if skip or any(keyword in title.lower() or keyword in summary.lower() for keyword in RECIPE_KEYWORDS + ["homemade"]): + # Check both raw_title and title for keywords + if skip or any(keyword in title.lower() or keyword in raw_title.lower() for keyword in RECIPE_KEYWORDS + ["homemade"]): print(f"Skipping filtered Reddit post: {title}") logging.info(f"Skipping filtered Reddit post: {title}") attempts += 1 @@ -316,7 +317,7 @@ def curate_from_reddit(): uploader=uploader, pixabay_url=pixabay_url, interest_score=interest_score, - should_post_tweet=True # Post the X tweet on the first call + should_post_tweet=True ) finally: is_posting = False @@ -338,7 +339,7 @@ def curate_from_reddit(): pixabay_url=pixabay_url, interest_score=interest_score, post_id=post_id, - should_post_tweet=False # Skip X tweet on the update call + should_post_tweet=False ) finally: is_posting = False diff --git a/foodie_engagement_tweet.py b/foodie_engagement_tweet.py new file mode 100644 index 0000000..b5eb56a --- /dev/null +++ b/foodie_engagement_tweet.py @@ -0,0 +1,61 @@ +import random +import logging +from datetime import datetime +import openai +from foodie_utils import post_tweet, AUTHORS + +# Setup logging +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') + +def generate_engagement_tweet(author): + author_handle = author["handle"] + prompt = ( + f"Generate a concise tweet (under 280 characters) for {author_handle}. " + f"Create an engaging food-related question or statement to spark interaction. " + f"Include a call to action to follow {author_handle} or like the tweet, and mention InsiderFoodie.com with a link to https://insiderfoodie.com. " + f"Avoid using the word 'elevate'—use more humanized language like 'level up' or 'bring to life'. " + f"Do not include emojis, hashtags, or reward-driven incentives (e.g., giveaways)." + ) + + try: + response = openai.ChatCompletion.create( + model="gpt-4o", + messages=[ + {"role": "system", "content": "You are a social media expert crafting engaging tweets."}, + {"role": "user", "content": prompt} + ], + max_tokens=100, + temperature=0.7 + ) + tweet = response.choices[0].message.content.strip() + if len(tweet) > 280: + tweet = tweet[:277] + "..." + return tweet + except Exception as e: + logging.warning(f"Failed to generate engagement tweet for {author['username']}: {e}") + # Fallback templates + engagement_templates = [ + "Whats the most mouthwatering dish youve seen this week Share below and follow {handle} for more foodie ideas on InsiderFoodie.com Link: https://insiderfoodie.com", + "Food lovers unite Whats your go to comfort food Tell us and like this tweet for more tasty ideas from {handle} on InsiderFoodie.com Link: https://insiderfoodie.com", + "Ever tried a dish that looked too good to eat Share your favorites and follow {handle} for more culinary trends on InsiderFoodie.com Link: https://insiderfoodie.com", + "What food trend are you loving right now Let us know and like this tweet to keep up with {handle} on InsiderFoodie.com Link: https://insiderfoodie.com" + ] + template = random.choice(engagement_templates) + return template.format(handle=author_handle) + +def post_engagement_tweet(): + for author in AUTHORS: + tweet = generate_engagement_tweet(author) + + logging.info(f"Posting engagement tweet for {author['username']}: {tweet}") + if post_tweet(author, tweet): + logging.info(f"Successfully posted engagement tweet for {author['username']}") + else: + logging.warning(f"Failed to post engagement tweet for {author['username']}") + +if __name__ == "__main__": + # Run only on Mondays + if datetime.now(timezone.utc).weekday() == 0: # Monday (0 = Monday) + post_engagement_tweet() + else: + logging.info("Not Monday - skipping engagement tweet posting") \ No newline at end of file diff --git a/foodie_hooks.py b/foodie_hooks.py index 662f652..94981f1 100644 --- a/foodie_hooks.py +++ b/foodie_hooks.py @@ -28,17 +28,27 @@ def get_dynamic_hook(article_title): logging.error(f"Dynamic hook generation failed: {e}") return "This food scoop will blow your mind!" -def select_best_cta(article_title, article_summary, post_url): - # Use the provided post_url if available, otherwise a placeholder to be updated later - share_url_base = post_url if post_url else "https://insiderfoodie.com/placeholder" - share_url = f"https://x.com/intent/tweet?url={quote(share_url_base)}&text={quote(get_dynamic_hook(article_title))}" - cta_options = [ - f"Can’t Get Enough? Share This Now On !", - f"Obsessed Yet? Spread the Word On !", - f"This Blew Your Mind, Right? Tweet It On !", - f"Ready to Spill the Tea? Share On !", - f"Too Wild to Keep Quiet? Post It On !" +def select_best_cta(title, content, post_url=None): + cta_templates = [ + # Share-focused CTAs + "Cant Get Enough Share This Now On ", + "This Blew Your Mind Right Tweet It On ", + "Ready to Spill the Tea Share On ", + "Too Wild to Keep Quiet Post It On ", + # Like-focused CTAs + "Love This Foodie Find Hit That Like Button", + "Think This Dish Is a Game Changer Show Some Love With a Like", + # Follow-focused CTAs + "Hungry for More Foodie Insights Follow Us for the Latest Trends", + "Dont Miss Out on Foodie Updates Follow Us Today" ] - selected_cta = random.choice(cta_options) - logging.info(f"Selected random CTA: {selected_cta}") - return selected_cta \ No newline at end of file + + hook = get_dynamic_hook(title).strip() + hook = urllib.parse.quote(hook) + url = post_url if post_url else "https://insiderfoodie.com/placeholder" + url = urllib.parse.quote(url) + + cta = random.choice(cta_templates) + if "https://x.com/intent/tweet" in cta: + cta = cta.format(url=url, text=hook) + return cta \ No newline at end of file diff --git a/foodie_utils.py b/foodie_utils.py index 8abec9e..2cbbec5 100644 --- a/foodie_utils.py +++ b/foodie_utils.py @@ -122,33 +122,35 @@ def save_post_counts(counts): logging.info("Saved post counts to x_post_counts.json") def generate_article_tweet(author, post, persona): - persona_config = PERSONA_CONFIGS[persona] - base_prompt = persona_config["x_prompt"].format( - description=persona_config["description"], - tone=persona_config["tone"] + title = post["title"] + url = post["url"] + author_handle = f"@{author['username']}" + + # Base tweet content + prompt = ( + f"Generate a concise tweet (under 280 characters) for {author_handle} using the persona '{persona}'. " + f"Summarize the article '{title}' and include the link '{url}'. " + f"Highlight the article's appeal, make it engaging, and encourage interaction. " + f"Always mention 'InsiderFoodie.com' in the tweet. " + f"Avoid using the word 'elevate'—use more humanized language like 'level up' or 'bring to life'. " + f"Do not include hashtags or emojis." ) - prompt = base_prompt.replace( - "For article tweets, include the article title, a quirky hook, and the URL.", - f"Generate an article tweet including the title '{post['title']}', a quirky hook, and the URL '{post['url']}'." + + response = openai.ChatCompletion.create( + model=SUMMARY_MODEL, + messages=[ + {"role": "system", "content": "You are a social media expert crafting engaging tweets."}, + {"role": "user", "content": prompt} + ], + max_tokens=100, + temperature=0.7 ) - try: - response = client.chat.completions.create( - model=LIGHT_TASK_MODEL, - messages=[ - {"role": "system", "content": prompt}, - {"role": "user", "content": f"Generate tweet for {post['title']}."} - ], - max_tokens=100, - temperature=0.9 - ) - tweet = response.choices[0].message.content.strip() - if len(tweet) > 280: - tweet = tweet[:277] + "..." - logging.info(f"Generated article tweet for {author['username']}: {tweet}") - return tweet - except Exception as e: - logging.error(f"Failed to generate article tweet for {author['username']}: {e}") - return f"This trend is fire! Check out {post['title']} at {post['url']} #Foodie" + + tweet = response.choices[0].message.content.strip() + if len(tweet) > 280: + tweet = tweet[:277] + "..." + + return tweet def post_tweet(author, tweet): credentials = next((cred for cred in X_API_CREDENTIALS if cred["username"] == author["username"]), None) diff --git a/foodie_weekly_thread.py b/foodie_weekly_thread.py new file mode 100644 index 0000000..f576f54 --- /dev/null +++ b/foodie_weekly_thread.py @@ -0,0 +1,130 @@ +import json +from datetime import datetime, timedelta +import logging +import random +import openai +from foodie_utils import post_tweet, AUTHORS + +# Setup logging +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') + +RECENT_POSTS_FILE = "/home/shane/foodie_automator/recent_posts.json" + +def load_recent_posts(): + posts = [] + if not os.path.exists(RECENT_POSTS_FILE): + return posts + + with open(RECENT_POSTS_FILE, 'r') as f: + for line in f: + if line.strip(): + try: + entry = json.loads(line.strip()) + posts.append(entry) + except json.JSONDecodeError as e: + logging.warning(f"Skipping invalid JSON line in {RECENT_POSTS_FILE}: {e}") + + return posts + +def filter_posts_for_week(posts, start_date, end_date): + filtered_posts = [] + for post in posts: + timestamp = datetime.fromisoformat(post["timestamp"]) + if start_date <= timestamp <= end_date: + filtered_posts.append(post) + return filtered_posts + +def generate_intro_tweet(author): + author_handle = author["handle"] + prompt = ( + f"Generate a concise tweet (under 280 characters) for {author_handle}. " + f"Introduce a thread of their top 10 foodie posts of the week on InsiderFoodie.com. " + f"Make it engaging, create curiosity, and include a call to action to visit InsiderFoodie.com, follow {author_handle}, or like the thread. " + f"Avoid using the word 'elevate'—use more humanized language like 'level up' or 'bring to life'. " + f"Do not include emojis, hashtags, or reward-driven incentives (e.g., giveaways)." + ) + + try: + response = openai.ChatCompletion.create( + model="gpt-4o", + messages=[ + {"role": "system", "content": "You are a social media expert crafting engaging tweets."}, + {"role": "user", "content": prompt} + ], + max_tokens=100, + temperature=0.7 + ) + tweet = response.choices[0].message.content.strip() + if len(tweet) > 280: + tweet = tweet[:277] + "..." + return tweet + except Exception as e: + logging.warning(f"Failed to generate intro tweet for {author['username']}: {e}") + # Fallback template + return ( + f"This weeks top 10 foodie finds by {author_handle} Check out the best on InsiderFoodie.com " + f"Follow {author_handle} for more and like this thread to stay in the loop Visit us at https://insiderfoodie.com" + ) + +def post_weekly_thread(): + # Determine the date range (Monday to Sunday of the past week) + today = datetime.now(timezone.utc) + days_since_monday = (today.weekday() + 1) % 7 + 7 # Go back to previous Monday + start_date = (today - timedelta(days=days_since_monday)).replace(hour=0, minute=0, second=0, microsecond=0) + end_date = start_date + timedelta(days=6, hours=23, minutes=59, seconds=59) + + logging.info(f"Fetching posts from {start_date} to {end_date}") + + # Load and filter posts + all_posts = load_recent_posts() + weekly_posts = filter_posts_for_week(all_posts, start_date, end_date) + + # Group posts by author + posts_by_author = {} + for post in weekly_posts: + author = post["author"] + if author not in posts_by_author: + posts_by_author[author] = [] + posts_by_author[author].append(post) + + # For each author, post a thread + for author in AUTHORS: + author_posts = posts_by_author.get(author["username"], []) + if not author_posts: + logging.info(f"No posts found for {author['username']} this week") + continue + + # Sort by interest score and take top 10 + author_posts.sort(key=lambda x: x.get("interest_score", 0), reverse=True) + top_posts = author_posts[:10] + + if not top_posts: + continue + + # First tweet: Intro with CTA (generated by GPT) + intro_tweet = generate_intro_tweet(author) + + logging.info(f"Posting intro tweet for {author['username']}: {intro_tweet}") + intro_response = post_tweet(author, intro_tweet) + if not intro_response: + logging.warning(f"Failed to post intro tweet for {author['username']}") + continue + + intro_tweet_id = intro_response.get("id") + + # Post each top post as a reply in the thread + for i, post in enumerate(top_posts, 1): + post_tweet_content = ( + f"{i}. {post['title']} Link: {post['url']}" + ) + logging.info(f"Posting thread reply {i} for {author['username']}: {post_tweet_content}") + post_tweet(author, post_tweet_content, reply_to_id=intro_tweet_id) + + logging.info(f"Successfully posted weekly thread for {author['username']}") + +if __name__ == "__main__": + # Run only on Sundays + if datetime.now(timezone.utc).weekday() == 6: # Sunday (0 = Monday, 6 = Sunday) + post_weekly_thread() + else: + logging.info("Not Sunday - skipping weekly thread posting") \ No newline at end of file