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.
Daniel Kliewer
Author, Sovereign AI


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:
venvorconda. - 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:
bash1mkdir CrossPlatformContentGenerator2cd CrossPlatformContentGenerator
1.2 Initialize a Git Repository (Optional)
bash1git init
1.3 Create a Virtual Environment
bash1python3 -m venv venv
Activate the virtual environment:
-
On Linux/macOS:
bash1source venv/bin/activate -
On Windows:
bash1venv\Scripts\activate
1.4 Upgrade pip and Install Required Python Packages
bash1pip install --upgrade pip2pip install openai praw python-dotenv requests requests_oauthlib langchain
Install additional packages for specific platforms:
bash1pip 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:
bash1touch .env
Add .env to .gitignore to prevent it from being tracked by git:
bash1echo ".env" >> .gitignore
1.6 Install FFmpeg (Required by moviepy)
-
On Linux:
bash1sudo apt-get install ffmpeg -
On macOS (using Homebrew):
bash1brew 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:
ini1OPENAI_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)
ini1INSTAGRAM_APP_ID=your_instagram_app_id2INSTAGRAM_APP_SECRET=your_instagram_app_secret3INSTAGRAM_ACCESS_TOKEN=your_instagram_access_token
ini1REDDIT_CLIENT_ID=your_reddit_client_id2REDDIT_CLIENT_SECRET=your_reddit_client_secret3REDDIT_USERNAME=your_reddit_username4REDDIT_PASSWORD=your_reddit_password5REDDIT_USER_AGENT=your_reddit_user_agent
ini1TWITTER_API_KEY=your_twitter_api_key2TWITTER_API_SECRET=your_twitter_api_secret3TWITTER_ACCESS_TOKEN=your_twitter_access_token4TWITTER_ACCESS_TOKEN_SECRET=your_twitter_access_token_secret
ini1FACEBOOK_APP_ID=your_facebook_app_id2FACEBOOK_APP_SECRET=your_facebook_app_secret3FACEBOOK_ACCESS_TOKEN=your_facebook_access_token
Step 3: Implement the Input Listener Agent
3.1 Create the agents Directory
bash1mkdir agents
3.2 Implement input_listener.py
Create a file agents/input_listener.py:
python1# agents/input_listener.py23import time4import os5import praw6import tweepy7from dotenv import load_dotenv89load_dotenv()1011class InputListener:12 def __init__(self):13 self.init_reddit_client()14 self.init_twitter_client()15 # Add other platforms as needed1617 # Load last seen IDs18 self.last_seen = {'reddit': None, 'twitter': None}1920 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()2930 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_name3940 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 break46 post_data = {47 'platform': 'reddit',48 'content_type': 'text',49 'content': submission.selftext,50 'title': submission.title,51 'url': submission.url,52 'id': submission.id53 }54 new_posts.append(post_data)55 if submissions:56 self.last_seen['reddit'] = submissions[0].id57 return new_posts5859 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 break65 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_posts7576 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 needed81 return new_posts
Step 4: Implement the Content Analysis Agent
4.1 Implement content_analysis.py
Create a file agents/content_analysis.py:
python1# agents/content_analysis.py23import openai4import os5from dotenv import load_dotenv67load_dotenv()89class ContentAnalysisAgent:10 def __init__(self):11 openai.api_key = os.getenv("OPENAI_API_KEY")1213 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:
python1# agents/text_generation_agent.py23import openai4import os5from dotenv import load_dotenv67load_dotenv()89class TextGenerationAgent:10 def __init__(self):11 openai.api_key = os.getenv("OPENAI_API_KEY")1213 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:
python1# agents/image_generation_agent.py23import openai4import os5from dotenv import load_dotenv67load_dotenv()89class ImageGenerationAgent:10 def __init__(self):11 openai.api_key = os.getenv("OPENAI_API_KEY")1213 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:
python1# agents/publishing_agent.py23import os4import requests5import tweepy6from dotenv import load_dotenv78load_dotenv()910class PublishingAgent:11 def __init__(self):12 self.init_twitter_client()13 # Initialize other platforms as needed1415 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)2324 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}")3031 def post_to_instagram(self, image_path, caption):32 # Implement Instagram posting logic33 pass3435 def post_to_facebook(self, message):36 # Implement Facebook posting logic37 pass3839 # Add methods for other platforms
Step 7: Implement the Agent Coordinator
7.1 Implement coordinator.py
Create a file coordinator.py:
python1# coordinator.py23from agents.input_listener import InputListener4from agents.content_analysis import ContentAnalysisAgent5from agents.text_generation_agent import TextGenerationAgent6from agents.image_generation_agent import ImageGenerationAgent7from agents.publishing_agent import PublishingAgent89class 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()1617 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 Instagram23 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 image26 image_data = requests.get(image_url).content27 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 Facebook34 text = self.text_generation_agent.generate_text(analysis, 'Facebook')35 self.publishing_agent.post_to_facebook(text)36 # Add other platform logic as needed3738if __name__ == "__main__":39 coordinator = AgentCoordinator()40 coordinator.coordinate()
7.2 Create Temporary Directory for Images
bash1mkdir temp_images
Step 8: Automate the Workflow
8.1 Install Celery and Redis
bash1pip install celery redis
Ensure Redis is installed and running:
-
On Linux:
bash1sudo apt-get install redis-server2sudo service redis-server start -
On macOS (using Homebrew):
bash1brew install redis2brew services start redis
8.2 Set Up Celery Tasks
Create a file tasks.py:
python1# tasks.py23from celery import Celery4from coordinator import AgentCoordinator56app = Celery('tasks', broker='redis://localhost:6379/0')78@app.task9def run_coordinator():10 coordinator = AgentCoordinator()11 coordinator.coordinate()
8.3 Schedule the Task
Create a file celeryconfig.py:
python1# celeryconfig.py23from celery.schedules import crontab45beat_schedule = {6 'run-every-5-minutes': {7 'task': 'tasks.run_coordinator',8 'schedule': crontab(minute='*/5'), # Every 5 minutes9 },10}1112timezone = 'UTC'
Update your tasks.py to include the configuration:
python1app.config_from_object('celeryconfig')
8.4 Start Celery Worker and Beat Scheduler
In separate terminal windows, run:
Start the Celery worker:
bash1celery -A tasks worker --loglevel=info
Start the Celery beat scheduler:
bash1celery -A tasks beat --loglevel=info
Step 9: Implement Webhooks for Real-Time Triggers (Optional)
9.1 Install Flask
bash1pip install flask
9.2 Create webhook_server.py
python1# webhook_server.py23from flask import Flask, request4from tasks import run_coordinator56app = Flask(__name__)78@app.route('/webhook', methods=['POST'])9def webhook():10 data = request.json11 # Process the webhook data if necessary12 run_coordinator.delay()13 return '', 2001415if __name__ == "__main__":16 app.run(port=5000)
9.3 Expose Your Server (During Development)
Use ngrok to expose your local server to the internet:
bash1ngrok 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: 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.