Python scripts companion to the book 'Automating Social Media Interactions for Organic Growth using Python.' Covers API, frontend, spreadsheet, and simple automation patterns.
git clone https://github.com/The-School-of-Automation/automation-book-scripts.gitautomation-book-scripts is the official code companion to 'Automating Social Media Interactions for Organic Growth using Python' by The School of Automation. The repository is organized into five focused modules: simple automations, API automations, API reverse automations, frontend automations, and spreadsheet automations. Each folder contains scripts and test data designed to illustrate the techniques taught in the book. Marketers and developers learning social media automation with Python can use these ready-made examples to follow along with the book's lessons and adapt the patterns to their own workflows.
1. **Install Dependencies**: Run `pip install tweepy pandas python-dotenv` to install required packages. 2. **Configure API Keys**: Create a `.env` file with your platform API credentials (e.g., Twitter API keys). 3. **Prepare Input Files**: - For Twitter: Create `post_schedule.csv` with columns for post time, text, and optional image paths - For other platforms: Follow the book's companion scripts structure for your specific platform 4. **Customize Script**: Modify the script template to include your specific automation logic (e.g., post formatting, additional API parameters). 5. **Run and Monitor**: Execute the script with `python automate_[platform]_posting.py` and check the generated log file for errors or confirmations. **Tips for Better Results**: - Start with small batches of scheduled posts to test the script - Use the book's error handling patterns for your specific platform - Implement rate limiting to avoid API bans - Add validation for your input files before processing
Follow along with book exercises using provided Python scripts and test data
Automate social media interactions via platform APIs
Automate browser-based social media tasks using frontend automation scripts
Manage and process social media data using spreadsheet automation
No install command available. Check the GitHub repository for manual installation instructions.
git clone https://github.com/The-School-of-Automation/automation-book-scriptsCopy the install command above and run it in your terminal.
Launch Claude Code, Cursor, or your preferred AI coding agent.
Use the prompt template or examples below to test the skill.
Adapt the skill to your specific use case and workflow.
Generate a Python script to automate [TASK] for [PLATFORM] using the 'automation-book-scripts' companion. The script should include error handling, logging, and follow the patterns from the book. Use [API_KEY] for authentication if required. Include a README.md file with setup instructions and usage examples.
```python
# Script: automate_twitter_posting.py
# Purpose: Automate scheduled Twitter posts with image uploads
# Companion to 'Automating Social Media Interactions for Organic Growth using Python'
import tweepy
import logging
from datetime import datetime
import os
# Configuration
CONSUMER_KEY = os.getenv('TWITTER_CONSUMER_KEY')
CONSUMER_SECRET = os.getenv('TWITTER_CONSUMER_SECRET')
ACCESS_TOKEN = os.getenv('TWITTER_ACCESS_TOKEN')
ACCESS_TOKEN_SECRET = os.getenv('TWITTER_ACCESS_TOKEN_SECRET')
SCHEDULE_FILE = 'post_schedule.csv'
LOG_FILE = 'automation.log'
# Setup logging
logging.basicConfig(
filename=LOG_FILE,
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
class TwitterAutomation:
def __init__(self):
try:
self.client = tweepy.Client(
consumer_key=CONSUMER_KEY,
consumer_secret=CONSUMER_SECRET,
access_token=ACCESS_TOKEN,
access_token_secret=ACCESS_TOKEN_SECRET
)
self.auth = tweepy.OAuth1UserHandler(
CONSUMER_KEY, CONSUMER_SECRET,
ACCESS_TOKEN, ACCESS_TOKEN_SECRET
)
self.api = tweepy.API(self.auth)
logging.info("Twitter API client initialized successfully")
except Exception as e:
logging.error(f"Failed to initialize Twitter client: {str(e)}")
raise
def load_schedule(self):
"""Load post schedule from CSV file"""
try:
import pandas as pd
schedule = pd.read_csv(SCHEDULE_FILE)
schedule['post_time'] = pd.to_datetime(schedule['post_time'])
return schedule
except FileNotFoundError:
logging.error(f"Schedule file {SCHEDULE_FILE} not found")
return None
except Exception as e:
logging.error(f"Error loading schedule: {str(e)}")
return None
def post_tweet(self, text, image_path=None):
"""Post a tweet with optional image"""
try:
if image_path:
with open(image_path, 'rb') as image:
media = self.api.media_upload(image_path)
response = self.client.create_tweet(text=text, media_ids=[media.media_id])
else:
response = self.client.create_tweet(text=text)
logging.info(f"Posted tweet: {text[:20]}... (ID: {response.data['id']})")
return response
except tweepy.TweepyException as e:
logging.error(f"Twitter API error: {str(e)}")
return None
except Exception as e:
logging.error(f"Error posting tweet: {str(e)}")
return None
def run_scheduled_posts(self):
"""Check schedule and post tweets at scheduled times"""
schedule = self.load_schedule()
if not schedule:
logging.warning("No schedule loaded. Exiting.")
return
while True:
now = datetime.now()
due_posts = schedule[schedule['post_time'] <= now]
if not due_posts.empty:
for _, post in due_posts.iterrows():
result = self.post_tweet(post['text'], post.get('image_path'))
if result:
schedule = schedule[schedule['post_time'] > now]
schedule.to_csv(SCHEDULE_FILE, index=False)
logging.info(f"Processed scheduled post: {post['text'][:20]}...")
time.sleep(60) # Check every minute
if __name__ == "__main__":
try:
bot = TwitterAutomation()
bot.run_scheduled_posts()
except KeyboardInterrupt:
logging.info("Script stopped by user")
```
```markdown
# README.md
## Twitter Automation Script
This script automates scheduled Twitter posting based on a CSV schedule file.
### Setup
1. Install dependencies:
```bash
pip install tweepy pandas python-dotenv
```
2. Create a `.env` file with your Twitter API keys:
```
TWITTER_CONSUMER_KEY=your_consumer_key
TWITTER_CONSUMER_SECRET=your_consumer_secret
TWITTER_ACCESS_TOKEN=your_access_token
TWITTER_ACCESS_TOKEN_SECRET=your_access_token_secret
```
3. Create a `post_schedule.csv` file with columns:
- `post_time` (datetime)
- `text` (tweet content)
- `image_path` (optional image path)
### Usage
Run the script:
```bash
python automate_twitter_posting.py
```
The script will:
- Load the schedule from `post_schedule.csv`
- Post tweets at scheduled times
- Remove posted items from the schedule
- Log all actions to `automation.log`
### Error Handling
The script includes:
- API error handling
- Logging for all operations
- Graceful shutdown on keyboard interrupt
- Validation of schedule file
### Example Schedule
```csv
post_time,text,image_path
2023-11-15 09:00:00,Good morning! Here's our latest blog post: https://example.com/blog,
2023-11-15 14:30:00,Check out our new product video!,
2023-11-15 18:00:00,End of day wrap-up: https://example.com/updates
```
```Automate your browser workflows effortlessly
Improve ML models with better datasets
ML deployment platform for industrial robots
mobile operating system for higher education
Predictive student analytics
AI-driven math platform
Take a free 3-minute scan and get personalized AI skill recommendations.
Take free scan