Automate Tweeting New Blog Posts in Python

A mock script that fetches new blog posts from a CMS and tweets them via a simulated Twitter API, outputting JSON results.

Easy Python 3.9+ Aug 9, 2026 Automation & scripting 16 views 0 copies

Python code

43 lines
Python 3.9+
import json
import time
from datetime import datetime


def fetch_new_blog_posts():
    """Mock function to simulate fetching latest blog posts from a CMS."""
    return [
        {
            "id": 1,
            "title": "Getting Started with Python",
            "url": "https://blog.example.com/python-start",
            "published_at": datetime.now().isoformat(),
        },
        {
            "id": 2,
            "title": "Advanced Django Patterns",
            "url": "https://blog.example.com/django-patterns",
            "published_at": datetime.now().isoformat(),
        },
    ]


def post_tweet(post):
    """Mock function to simulate posting a tweet via Twitter API."""
    tweet_text = f"New blog post: {post['title']} - {post['url']}"
    # In a real implementation, this would use tweepy or requests to call Twitter API
    return {"status": "success", "tweet": tweet_text, "posted_at": time.time()}


def publish_new_posts():
    """Fetch blog posts and tweet them (simulated)."""
    posts = fetch_new_blog_posts()
    results = []
    for post in posts:
        response = post_tweet(post)
        results.append({"post_id": post["id"], "tweet_response": response})
    return json.dumps(results, indent=2)


if __name__ == "__main__":
    output = publish_new_posts()
    print(output)

Output

stdout
Run the snippet in the editor to inspect the return value or side effect.

How it works

The script defines two mock functions to simulate external services: fetch_new_blog_posts returns a list of post dicts with recent timestamps, and post_tweet constructs a tweet string and returns a success response with the current Unix timestamp. The publish_new_posts function iterates over the posts, calls the tweet function for each, and builds a list of results with post IDs and tweet responses. Finally, it serializes the results to a JSON string with indent=2 for readability, which is printed when the script runs as the main module. In production, the mock functions would be replaced with real CMS API calls and Twitter API requests (e.g., via tweepy).

Common mistakes

  • Forgetting to replace mock functions with real API calls before deploying
  • Hardcoding tweet text if the post title contains special characters needing handling
  • Missing error handling for API timeouts or rate limits
  • Not sleeping between tweets to stay within API rate limits

Variations

  1. Use scheduling (e.g., cron or APScheduler) to run `publish_new_posts` automatically
  2. Send tweets in batches with a small delay between each post

Real-world use cases

  • Automatically announce new content to followers when a company blog publishes a post.
  • Notify a development team of new release notes or documentation updates via Twitter.
  • Share curated industry news from multiple sources by tweeting each new article.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.