167 lines
		
	
	
		
			5.1 KiB
		
	
	
	
		
			Python
		
	
	
	
			
		
		
	
	
			167 lines
		
	
	
		
			5.1 KiB
		
	
	
	
		
			Python
		
	
	
	
#!/usr/bin/env python3
 | 
						|
# -*- coding: utf-8 -*-
 | 
						|
"""
 | 
						|
WordPress 内容发布工具
 | 
						|
简化的内容发布脚本
 | 
						|
"""
 | 
						|
 | 
						|
import os
 | 
						|
import requests
 | 
						|
from requests.auth import HTTPBasicAuth
 | 
						|
from dotenv import load_dotenv
 | 
						|
from datetime import datetime
 | 
						|
 | 
						|
# 加载环境变量
 | 
						|
load_dotenv()
 | 
						|
 | 
						|
class WordPressPublisher:
 | 
						|
    def __init__(self):
 | 
						|
        self.wp_url = os.getenv('WORDPRESS_URL')
 | 
						|
        self.wp_user = os.getenv('WORDPRESS_USERNAME')
 | 
						|
        self.wp_password = os.getenv('WORDPRESS_APP_PASSWORD')
 | 
						|
        
 | 
						|
        if self.wp_password:
 | 
						|
            self.wp_password = self.wp_password.replace(" ", "")
 | 
						|
        
 | 
						|
        if not all([self.wp_url, self.wp_user, self.wp_password]):
 | 
						|
            raise ValueError("请在 .env 文件中配置 WORDPRESS_URL, WORDPRESS_USERNAME, WORDPRESS_APP_PASSWORD")
 | 
						|
        
 | 
						|
        self.api_url = f"{self.wp_url.rstrip('/')}/wp-json/wp/v2"
 | 
						|
        self.auth = HTTPBasicAuth(self.wp_user, self.wp_password)
 | 
						|
    
 | 
						|
    def publish_post(self, title, content, excerpt="", categories=None, tags=None, status="publish"):
 | 
						|
        """
 | 
						|
        发布文章
 | 
						|
        
 | 
						|
        Args:
 | 
						|
            title (str): 文章标题
 | 
						|
            content (str): 文章内容 (HTML)
 | 
						|
            excerpt (str): 文章摘要
 | 
						|
            categories (list): 分类ID列表
 | 
						|
            tags (list): 标签ID列表
 | 
						|
            status (str): 文章状态 (draft, publish, private)
 | 
						|
        
 | 
						|
        Returns:
 | 
						|
            dict: 创建的文章信息
 | 
						|
        """
 | 
						|
        post_data = {
 | 
						|
            'title': title,
 | 
						|
            'content': content,
 | 
						|
            'excerpt': excerpt,
 | 
						|
            'status': status
 | 
						|
        }
 | 
						|
        
 | 
						|
        if categories:
 | 
						|
            post_data['categories'] = categories
 | 
						|
        if tags:
 | 
						|
            post_data['tags'] = tags
 | 
						|
        
 | 
						|
        response = requests.post(
 | 
						|
            f"{self.api_url}/posts",
 | 
						|
            json=post_data,
 | 
						|
            auth=self.auth
 | 
						|
        )
 | 
						|
        
 | 
						|
        if response.status_code == 201:
 | 
						|
            post = response.json()
 | 
						|
            print(f"✅ 文章发布成功!")
 | 
						|
            print(f"   标题: {post['title']['rendered']}")
 | 
						|
            print(f"   链接: {post['link']}")
 | 
						|
            print(f"   状态: {post['status']}")
 | 
						|
            return post
 | 
						|
        else:
 | 
						|
            print(f"❌ 文章发布失败: {response.status_code}")
 | 
						|
            print(f"   错误信息: {response.text}")
 | 
						|
            return None
 | 
						|
    
 | 
						|
    def get_categories(self):
 | 
						|
        """获取所有分类"""
 | 
						|
        response = requests.get(f"{self.api_url}/categories")
 | 
						|
        if response.status_code == 200:
 | 
						|
            return response.json()
 | 
						|
        return []
 | 
						|
    
 | 
						|
    def get_tags(self):
 | 
						|
        """获取所有标签"""
 | 
						|
        response = requests.get(f"{self.api_url}/tags")
 | 
						|
        if response.status_code == 200:
 | 
						|
            return response.json()
 | 
						|
        return []
 | 
						|
    
 | 
						|
    def create_category(self, name, description=""):
 | 
						|
        """创建新分类"""
 | 
						|
        category_data = {
 | 
						|
            'name': name,
 | 
						|
            'description': description
 | 
						|
        }
 | 
						|
        
 | 
						|
        response = requests.post(
 | 
						|
            f"{self.api_url}/categories",
 | 
						|
            json=category_data,
 | 
						|
            auth=self.auth
 | 
						|
        )
 | 
						|
        
 | 
						|
        if response.status_code == 201:
 | 
						|
            category = response.json()
 | 
						|
            print(f"✅ 分类创建成功: {category['name']} (ID: {category['id']})")
 | 
						|
            return category
 | 
						|
        else:
 | 
						|
            print(f"❌ 分类创建失败: {response.status_code}")
 | 
						|
            return None
 | 
						|
    
 | 
						|
    def create_tag(self, name, description=""):
 | 
						|
        """创建新标签"""
 | 
						|
        tag_data = {
 | 
						|
            'name': name,
 | 
						|
            'description': description
 | 
						|
        }
 | 
						|
        
 | 
						|
        response = requests.post(
 | 
						|
            f"{self.api_url}/tags",
 | 
						|
            json=tag_data,
 | 
						|
            auth=self.auth
 | 
						|
        )
 | 
						|
        
 | 
						|
        if response.status_code == 201:
 | 
						|
            tag = response.json()
 | 
						|
            print(f"✅ 标签创建成功: {tag['name']} (ID: {tag['id']})")
 | 
						|
            return tag
 | 
						|
        else:
 | 
						|
            print(f"❌ 标签创建失败: {response.status_code}")
 | 
						|
            return None
 | 
						|
 | 
						|
def main():
 | 
						|
    """示例用法"""
 | 
						|
    try:
 | 
						|
        wp = WordPressPublisher()
 | 
						|
        
 | 
						|
        # 示例:发布一篇文章
 | 
						|
        title = f"测试文章 - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
 | 
						|
        content = """
 | 
						|
        <h2>这是一个测试文章</h2>
 | 
						|
        <p>这是文章的内容。你可以使用 HTML 标签来格式化内容。</p>
 | 
						|
        <ul>
 | 
						|
            <li>支持列表</li>
 | 
						|
            <li>支持链接和图片</li>
 | 
						|
            <li>支持各种 HTML 元素</li>
 | 
						|
        </ul>
 | 
						|
        """
 | 
						|
        excerpt = "这是一个通过 API 发布的测试文章"
 | 
						|
        
 | 
						|
        # 发布为草稿,避免直接发布到生产环境
 | 
						|
        result = wp.publish_post(
 | 
						|
            title=title,
 | 
						|
            content=content,
 | 
						|
            excerpt=excerpt,
 | 
						|
            status="draft"  # 使用 "publish" 来直接发布
 | 
						|
        )
 | 
						|
        
 | 
						|
        if result:
 | 
						|
            print(f"\n📝 文章ID: {result['id']}")
 | 
						|
            print(f"🔗 编辑链接: {result['link'].replace('?preview=true', '')}")
 | 
						|
        
 | 
						|
    except Exception as e:
 | 
						|
        print(f"❌ 错误: {e}")
 | 
						|
 | 
						|
if __name__ == "__main__":
 | 
						|
    main() |