·8 min

Complete Guide: Building AI Agent-Based Cross-Platform Content Generator for Automated Social Media Distribution

Step-by-step tutorial for creating intelligent AI agents that automatically generate and distribute platform-optimized content across multiple social media networks using Python, APIs, and automation.

DK

Daniel Kliewer

Author, Sovereign AI

AI AgentsContent GenerationSocial MediaPythonAPI IntegrationAutomationTutorialSocial Media MarketingMulti-PlatformContent DistributionAI Automation
Sovereign AI book cover

From the Book

This is from Sovereign AI: Building Local-First Intelligent Systems.

Get the Book — $88
Complete Guide: Building AI Agent-Based Cross-Platform Content Generator for Automated Social Media Distribution

Image

Guide to Building an AI Agent-Based Cross-Platform Content Generator and Distributor

This guide will walk you through building an application that automates content creation and posting across multiple social media platforms by generating unique, platform-specific content based on a single post. We'll focus on terminal commands, instructions, and code to help you implement this system step by step.


Prerequisites

  • Programming Knowledge: Intermediate proficiency in Python.
  • Python Environment: Python 3.8 or later installed on your machine.
  • API Access: Developer accounts and API credentials for the social media platforms you plan to use.
  • OpenAI API Key: Access to OpenAI's API for GPT-4 and DALL·E (or equivalents).
  • Virtual Environment Tool: venv or conda.
  • Additional Tools: git, ffmpeg (for video processing).

Step 1: Set Up the Project Environment

1.1 Create a Project Directory

Open your terminal and create a new directory for your project:

bash
1mkdir CrossPlatformContentGenerator
2cd CrossPlatformContentGenerator

1.2 Initialize a Git Repository (Optional)

bash
1git init

1.3 Create a Virtual Environment

bash
1python3 -m venv venv

Activate the virtual environment:

  • On Linux/macOS:

    bash
    1source venv/bin/activate
  • On Windows:

    bash
    1venv\Scripts\activate

1.4 Upgrade pip and Install Required Python Packages

bash
1pip install --upgrade pip
2pip install openai praw python-dotenv requests requests_oauthlib langchain

Install additional packages for specific platforms:

bash
1pip install facebook-sdk google-api-python-client tweepy moviepy

1.5 Create a .env File for Environment Variables

Create a file named .env in your project directory to store your API keys and credentials:

bash
1touch .env

Add .env to .gitignore to prevent it from being tracked by git:

bash
1echo ".env" >> .gitignore

1.6 Install FFmpeg (Required by moviepy)

  • On Linux:

    bash
    1sudo apt-get install ffmpeg
  • On macOS (using Homebrew):

    bash
    1brew install ffmpeg
  • On Windows:

    Download FFmpeg from the official website and add it to your system PATH.


Step 2: Obtain API Credentials

2.1 OpenAI API Key

Sign up for an OpenAI account and obtain your API key. Add it to your .env file:

ini
1OPENAI_API_KEY=your_openai_api_key_here

2.2 Social Media API Credentials

For each platform, obtain the necessary API credentials and add them to your .env file.

Instagram (Facebook Graph API)

ini
1INSTAGRAM_APP_ID=your_instagram_app_id
2INSTAGRAM_APP_SECRET=your_instagram_app_secret
3INSTAGRAM_ACCESS_TOKEN=your_instagram_access_token

Reddit

ini
1REDDIT_CLIENT_ID=your_reddit_client_id
2REDDIT_CLIENT_SECRET=your_reddit_client_secret
3REDDIT_USERNAME=your_reddit_username
4REDDIT_PASSWORD=your_reddit_password
5REDDIT_USER_AGENT=your_reddit_user_agent

Twitter

ini
1TWITTER_API_KEY=your_twitter_api_key
2TWITTER_API_SECRET=your_twitter_api_secret
3TWITTER_ACCESS_TOKEN=your_twitter_access_token
4TWITTER_ACCESS_TOKEN_SECRET=your_twitter_access_token_secret

Facebook

ini
1FACEBOOK_APP_ID=your_facebook_app_id
2FACEBOOK_APP_SECRET=your_facebook_app_secret
3FACEBOOK_ACCESS_TOKEN=your_facebook_access_token

Step 3: Implement the Input Listener Agent

3.1 Create the agents Directory

bash
1mkdir agents

3.2 Implement input_listener.py

Create a file agents/input_listener.py:

python
1# agents/input_listener.py
2
3import time
4import os
5import praw
6import tweepy
7from dotenv import load_dotenv
8
9load_dotenv()
10
11class InputListener:
12 def __init__(self):
13 self.init_reddit_client()
14 self.init_twitter_client()
15 # Add other platforms as needed
16
17 # Load last seen IDs
18 self.last_seen = {'reddit': None, 'twitter': None}
19
20 def init_reddit_client(self):
21 self.reddit = praw.Reddit(
22 client_id=os.getenv("REDDIT_CLIENT_ID"),
23 client_secret=os.getenv("REDDIT_CLIENT_SECRET"),
24 user_agent=os.getenv("REDDIT_USER_AGENT"),
25 username=os.getenv("REDDIT_USERNAME"),
26 password=os.getenv("REDDIT_PASSWORD")
27 )
28 self.reddit_user = self.reddit.user.me()
29
30 def init_twitter_client(self):
31 auth = tweepy.OAuth1UserHandler(
32 os.getenv("TWITTER_API_KEY"),
33 os.getenv("TWITTER_API_SECRET"),
34 os.getenv("TWITTER_ACCESS_TOKEN"),
35 os.getenv("TWITTER_ACCESS_TOKEN_SECRET")
36 )
37 self.twitter_api = tweepy.API(auth)
38 self.twitter_username = self.twitter_api.me().screen_name
39
40 def monitor_reddit(self):
41 new_posts = []
42 submissions = list(self.reddit_user.submissions.new(limit=5))
43 for submission in submissions:
44 if submission.id == self.last_seen.get('reddit'):
45 break
46 post_data = {
47 'platform': 'reddit',
48 'content_type': 'text',
49 'content': submission.selftext,
50 'title': submission.title,
51 'url': submission.url,
52 'id': submission.id
53 }
54 new_posts.append(post_data)
55 if submissions:
56 self.last_seen['reddit'] = submissions[0].id
57 return new_posts
58
59 def monitor_twitter(self):
60 new_posts = []
61 tweets = self.twitter_api.user_timeline(screen_name=self.twitter_username, count=5, tweet_mode='extended')
62 for tweet in tweets:
63 if str(tweet.id) == self.last_seen.get('twitter'):
64 break
65 post_data = {
66 'platform': 'twitter',
67 'content_type': 'text',
68 'content': tweet.full_text,
69 'id': str(tweet.id)
70 }
71 new_posts.append(post_data)
72 if tweets:
73 self.last_seen['twitter'] = str(tweets[0].id)
74 return new_posts
75
76 def monitor_platforms(self):
77 new_posts = []
78 new_posts.extend(self.monitor_reddit())
79 new_posts.extend(self.monitor_twitter())
80 # Add other platforms as needed
81 return new_posts

Step 4: Implement the Content Analysis Agent

4.1 Implement content_analysis.py

Create a file agents/content_analysis.py:

python
1# agents/content_analysis.py
2
3import openai
4import os
5from dotenv import load_dotenv
6
7load_dotenv()
8
9class ContentAnalysisAgent:
10 def __init__(self):
11 openai.api_key = os.getenv("OPENAI_API_KEY")
12
13 def analyze_content(self, content):
14 prompt = f"Analyze the following content and provide key themes, tone, and intent:\n\n{content}"
15 response = openai.ChatCompletion.create(
16 model="gpt-4",
17 messages=[{"role": "user", "content": prompt}]
18 )
19 analysis = response.choices[0].message.content.strip()
20 return analysis

Step 5: Implement the Content Generation Agents

5.1 Implement Text Generation Agent

Create a file agents/text_generation_agent.py:

python
1# agents/text_generation_agent.py
2
3import openai
4import os
5from dotenv import load_dotenv
6
7load_dotenv()
8
9class TextGenerationAgent:
10 def __init__(self):
11 openai.api_key = os.getenv("OPENAI_API_KEY")
12
13 def generate_text(self, analysis, platform):
14 prompt = f"Based on the analysis:\n\n{analysis}\n\nCreate a {platform}-appropriate post that is engaging and follows the platform's style."
15 response = openai.ChatCompletion.create(
16 model="gpt-4",
17 messages=[{"role": "user", "content": prompt}]
18 )
19 text_content = response.choices[0].message.content.strip()
20 return text_content

5.2 Implement Image Generation Agent

Create a file agents/image_generation_agent.py:

python
1# agents/image_generation_agent.py
2
3import openai
4import os
5from dotenv import load_dotenv
6
7load_dotenv()
8
9class ImageGenerationAgent:
10 def __init__(self):
11 openai.api_key = os.getenv("OPENAI_API_KEY")
12
13 def generate_image(self, prompt):
14 response = openai.Image.create(
15 prompt=prompt,
16 n=1,
17 size="1024x1024"
18 )
19 image_url = response['data'][0]['url']
20 return image_url

Step 6: Implement the Publishing Agents

6.1 Implement publishing_agent.py

Create a file agents/publishing_agent.py:

python
1# agents/publishing_agent.py
2
3import os
4import requests
5import tweepy
6from dotenv import load_dotenv
7
8load_dotenv()
9
10class PublishingAgent:
11 def __init__(self):
12 self.init_twitter_client()
13 # Initialize other platforms as needed
14
15 def init_twitter_client(self):
16 auth = tweepy.OAuth1UserHandler(
17 os.getenv("TWITTER_API_KEY"),
18 os.getenv("TWITTER_API_SECRET"),
19 os.getenv("TWITTER_ACCESS_TOKEN"),
20 os.getenv("TWITTER_ACCESS_TOKEN_SECRET")
21 )
22 self.twitter_api = tweepy.API(auth)
23
24 def post_to_twitter(self, text):
25 try:
26 self.twitter_api.update_status(status=text)
27 print("Posted to Twitter.")
28 except Exception as e:
29 print(f"Error posting to Twitter: {e}")
30
31 def post_to_instagram(self, image_path, caption):
32 # Implement Instagram posting logic
33 pass
34
35 def post_to_facebook(self, message):
36 # Implement Facebook posting logic
37 pass
38
39 # Add methods for other platforms

Step 7: Implement the Agent Coordinator

7.1 Implement coordinator.py

Create a file coordinator.py:

python
1# coordinator.py
2
3from agents.input_listener import InputListener
4from agents.content_analysis import ContentAnalysisAgent
5from agents.text_generation_agent import TextGenerationAgent
6from agents.image_generation_agent import ImageGenerationAgent
7from agents.publishing_agent import PublishingAgent
8
9class AgentCoordinator:
10 def __init__(self):
11 self.input_listener = InputListener()
12 self.content_analysis_agent = ContentAnalysisAgent()
13 self.text_generation_agent = TextGenerationAgent()
14 self.image_generation_agent = ImageGenerationAgent()
15 self.publishing_agent = PublishingAgent()
16
17 def coordinate(self):
18 new_posts = self.input_listener.monitor_platforms()
19 for post in new_posts:
20 analysis = self.content_analysis_agent.analyze_content(post['content'])
21 if post['platform'] == 'reddit':
22 # Generate image for Instagram
23 image_prompt = f"Create an image that represents the following:\n\n{analysis}"
24 image_url = self.image_generation_agent.generate_image(image_prompt)
25 # Download the image
26 image_data = requests.get(image_url).content
27 image_path = f"temp_images/{post['id']}.png"
28 with open(image_path, 'wb') as handler:
29 handler.write(image_data)
30 caption = post.get('title', '')
31 self.publishing_agent.post_to_instagram(image_path, caption)
32 elif post['platform'] == 'twitter':
33 # Generate text for Facebook
34 text = self.text_generation_agent.generate_text(analysis, 'Facebook')
35 self.publishing_agent.post_to_facebook(text)
36 # Add other platform logic as needed
37
38if __name__ == "__main__":
39 coordinator = AgentCoordinator()
40 coordinator.coordinate()

7.2 Create Temporary Directory for Images

bash
1mkdir temp_images

Step 8: Automate the Workflow

8.1 Install Celery and Redis

bash
1pip install celery redis

Ensure Redis is installed and running:

  • On Linux:

    bash
    1sudo apt-get install redis-server
    2sudo service redis-server start
  • On macOS (using Homebrew):

    bash
    1brew install redis
    2brew services start redis

8.2 Set Up Celery Tasks

Create a file tasks.py:

python
1# tasks.py
2
3from celery import Celery
4from coordinator import AgentCoordinator
5
6app = Celery('tasks', broker='redis://localhost:6379/0')
7
8@app.task
9def run_coordinator():
10 coordinator = AgentCoordinator()
11 coordinator.coordinate()

8.3 Schedule the Task

Create a file celeryconfig.py:

python
1# celeryconfig.py
2
3from celery.schedules import crontab
4
5beat_schedule = {
6 'run-every-5-minutes': {
7 'task': 'tasks.run_coordinator',
8 'schedule': crontab(minute='*/5'), # Every 5 minutes
9 },
10}
11
12timezone = 'UTC'

Update your tasks.py to include the configuration:

python
1app.config_from_object('celeryconfig')

8.4 Start Celery Worker and Beat Scheduler

In separate terminal windows, run:

Start the Celery worker:

bash
1celery -A tasks worker --loglevel=info

Start the Celery beat scheduler:

bash
1celery -A tasks beat --loglevel=info

Step 9: Implement Webhooks for Real-Time Triggers (Optional)

9.1 Install Flask

bash
1pip install flask

9.2 Create webhook_server.py

python
1# webhook_server.py
2
3from flask import Flask, request
4from tasks import run_coordinator
5
6app = Flask(__name__)
7
8@app.route('/webhook', methods=['POST'])
9def webhook():
10 data = request.json
11 # Process the webhook data if necessary
12 run_coordinator.delay()
13 return '', 200
14
15if __name__ == "__main__":
16 app.run(port=5000)

9.3 Expose Your Server (During Development)

Use ngrok to expose your local server to the internet:

bash
1ngrok http 5000

Set up the webhook URL in your platform's developer settings to point to the ngrok URL.


Step 10: Additional Notes and Considerations

  • API Limitations: Be aware of the rate limits and usage policies of each platform's API.
  • Content Moderation: Implement checks to ensure generated content complies with platform policies.
  • Error Handling: Add robust error handling and logging to your application.
  • Security: Secure your API keys and credentials. Do not expose them in your code or logs.
  • Cleanup: Delete temporary files (like downloaded images) after use to save space.

Conclusion

By following the terminal commands, instructions, and code provided in this guide, you can build an AI agent-based application that automates content creation and distribution across multiple social media platforms. This system will help you maintain an active presence online without the need to manually create and post content on each platform.


Note: This guide assumes familiarity with Python programming and working with APIs. Some steps may require adaptation based on updates to APIs or libraries. Always refer to the official documentation of the APIs and libraries used.

Happy Coding!

Sovereign AI book cover

Sovereign AI: Building Local-First Intelligent Systems

by Daniel Kliewer · Paperback · 72 pages

The hands-on guide to building AI that runs on your hardware, keeps your data private, and eliminates cloud dependence. Working code included.