CLAUDE
import requests
import json
from datetime import datetime
import time
import logging
from typing import Dict, List, Optional
class ClaudeWordPressPoster:
def __init__(self,
claude_api_key: str,
wordpress_url: str,
wp_username: str,
wp_password: str):
“””
Initialize the auto poster with API credentials
Args:
claude_api_key: Your Anthropic API key
wordpress_url: Your WordPress site URL (e.g., ‘https://yoursite.com’)
wp_username: WordPress username
wp_password: WordPress application password (not regular password)
“””
self.claude_api_key = claude_api_key
self.wordpress_url = wordpress_url.rstrip(‘/’)
self.wp_auth = (wp_username, wp_password)
self.claude_api_url = “https://api.anthropic.com/v1/messages”
# Setup logging
logging.basicConfig(level=logging.INFO)
self.logger = logging.getLogger(__name__)
def generate_blog_post(self, topic: str, keywords: List[str] = None) -> Dict[str, str]:
“””
Generate a blog post using Claude AI
Args:
topic: The main topic for the blog post
keywords: Optional list of keywords to include
Returns:
Dictionary with ‘title’ and ‘content’ keys
“””
keywords_text = f” Include these keywords naturally: {‘, ‘.join(keywords)}” if keywords else “”
prompt = f”””Write a comprehensive, engaging blog post about: {topic}
Requirements:
– Create an attention-grabbing title
– Write 800-1200 words
– Use proper headings and subheadings
– Include an introduction, main content, and conclusion
– Make it SEO-friendly and reader-engaging
– Use HTML formatting (h2, h3, p, ul, li tags)
{keywords_text}
Format your response as:
TITLE: [Your title here]
CONTENT:
[Your HTML-formatted blog post content here]”””
headers = {
“Content-Type”: “application/json”,
“x-api-key”: self.claude_api_key,
“anthropic-version”: “2023-06-01”
}
data = {
“model”: “claude-sonnet-4-20250514”,
“max_tokens”: 4000,
“messages”: [
{
“role”: “user”,
“content”: prompt
}
]
}
try:
response = requests.post(self.claude_api_url, headers=headers, json=data)
response.raise_for_status()
content = response.json()[‘content’][0][‘text’]
# Parse title and content
lines = content.split(‘\n’)
title = “”
content_start = 0
for i, line in enumerate(lines):
if line.startswith(“TITLE:”):
title = line.replace(“TITLE:”, “”).strip()
elif line.startswith(“CONTENT:”):
content_start = i + 1
break
if not title:
title = f”Blog Post About {topic}”
blog_content = ‘\n’.join(lines[content_start:]).strip()
return {
“title”: title,
“content”: blog_content
}
except requests.exceptions.RequestException as e:
self.logger.error(f”Error generating content with Claude: {e}”)
raise
except KeyError as e:
self.logger.error(f”Unexpected API response format: {e}”)
raise
def post_to_wordpress(self, title: str, content: str, status: str = “draft”) -> Dict:
“””
Post content to WordPress using REST API
Args:
title: Post title
content: Post content (HTML)
status: Post status (‘draft’, ‘publish’, ‘private’)
Returns:
WordPress API response
“””
wp_api_url = f”{self.wordpress_url}/wp-json/wp/v2/posts”
post_data = {
“title”: title,
“content”: content,
“status”: status,
“format”: “standard”
}
headers = {
“Content-Type”: “application/json”
}
try:
response = requests.post(
wp_api_url,
json=post_data,
auth=self.wp_auth,
headers=headers
)
response.raise_for_status()
result = response.json()
self.logger.info(f”Successfully posted: {result.get(‘link’, ‘No link available’)}”)
return result
except requests.exceptions.RequestException as e:
self.logger.error(f”Error posting to WordPress: {e}”)
if hasattr(e.response, ‘text’):
self.logger.error(f”Response: {e.response.text}”)
raise
def auto_post(self, topics: List[str], keywords_per_topic: Dict[str, List[str]] = None,
delay_hours: int = 24, post_status: str = “draft”):
“””
Automatically generate and post multiple blog posts
Args:
topics: List of topics to write about
keywords_per_topic: Dictionary mapping topics to keyword lists
delay_hours: Hours to wait between posts
post_status: WordPress post status
“””
keywords_per_topic = keywords_per_topic or {}
for i, topic in enumerate(topics):
try:
self.logger.info(f”Generating post {i+1}/{len(topics)} for topic: {topic}”)
# Generate content
keywords = keywords_per_topic.get(topic, [])
blog_post = self.generate_blog_post(topic, keywords)
# Post to WordPress
wp_response = self.post_to_wordpress(
blog_post[“title”],
blog_post[“content”],
post_status
)
self.logger.info(f”Posted: {blog_post[‘title’]}”)
# Wait before next post (except for last post)
if i < len(topics) - 1:
self.logger.info(f"Waiting {delay_hours} hours before next post...")
time.sleep(delay_hours * 3600) # Convert hours to seconds
except Exception as e:
self.logger.error(f"Failed to process topic '{topic}': {e}")
continue
# Example usage
if __name__ == "__main__":
# Configuration
CLAUDE_API_KEY = "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" \
WORDPRESS_URL = "https://yourwordpresssite.com"
WP_USERNAME = "Application"
WP_PASSWORD = "ea)0IG2N8w8(jZD*MVD6daAu" # Generate in WP Admin -> Users -> Application Passwords
# Initialize the poster
poster = ClaudeWordPressPoster(
claude_api_key=CLAUDE_API_KEY,
wordpress_url=WORDPRESS_URL,
wp_username=WP_USERNAME,
wp_password=WP_PASSWORD,
)
# Define topics and keywords
topics = [
“The Future of Artificial Intelligence in Fintech”,
“Sustainable finace Tips for Modern Families”,
“Remote Work Best Practices in 2025”,
“Digital coinbase Marketing Trends to Watch”
]
keywords_map = {
“The Future of Artificial Intelligence in Healthcare”: [“AI”, “healthcare”, “medical technology”, “patient care”],
“Sustainable Living Tips for Modern Families”: [“sustainability”, “eco-friendly”, “green living”, “environment”],
“Remote Work Best Practices in 2025”: [“remote work”, “productivity”, “work from home”, “collaboration”],
“Digital Marketing Trends to Watch”: [“digital marketing”, “SEO”, “social media”, “online advertising”]
}
# Option 1: Generate and post one article
try:
single_post = poster.generate_blog_post(topics[0], keywords_map[topics[0]])
wp_response = poster.post_to_wordpress(
single_post[“title”],
single_post[“content”],
“draft” # Change to “publish” to publish immediately
)
print(f”Successfully posted: {single_post[‘title’]}”)
except Exception as e:
print(f”Error: {e}”)
# Option 2: Auto-post multiple articles with delays
# poster.auto_post(
# topics=topics,
# keywords_per_topic=keywords_map,
# delay_hours=24, # Post one per day
# post_status=”draft” # Change to “publish” for immediate publishing
# )
