Files
XijiaX/wp_publisher.py
2025-07-15 10:52:00 +08:00

105 lines
4.2 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods.posts import NewPost
from wordpress_xmlrpc.methods import media
from wordpress_xmlrpc.compat import xmlrpc_client
from config import Config
import os
class WordPressPublisher:
def __init__(self):
self.client = Client(
Config.WORDPRESS_URL,
Config.WORDPRESS_USERNAME,
Config.WORDPRESS_PASSWORD
)
async def publish_post(self, item, ai_content):
print(f"\n开始发布文章:{ai_content['title']}")
post = WordPressPost()
post.title = ai_content['title']
# 构建文章内容
content = []
if item.get('local_image'):
print("正在上传文章配图...")
# 上传图片到WordPress
with open(item['local_image'], 'rb') as img:
data = {}
data['name'] = os.path.basename(item['local_image'])
data['type'] = 'image/jpeg'
data['bits'] = xmlrpc_client.Binary(img.read())
response = self.client.call(media.UploadFile(data))
image_url = response['url']
print(f"图片上传成功:{image_url}")
content.append(f'<img src="{image_url}" alt="{ai_content["title"]}" />')
print("正在构建文章内容...")
content.append(f'<p>{ai_content["review"]}</p>')
if item['free_time']:
content.append(f'<hr /> <p><strong>限免时间:</strong><span style="color: #339966;">{item["free_time"]}</span></p>')
if item['serial_key']:
content.append(f'<hr /> <p><strong>序列号/注册码:</strong><span style="color: #339966;">{item["serial_key"]}</span></p>')
if item['download_urls']:
content.append('<hr /> <p><strong>喜加X地址</strong></p>')
for url in item['download_urls']:
content.append(f'<p><a href="{url}" target="_blank">{ai_content["title"]}</a></p>')
post.content = '\n'.join(content)
# 设置文章分类,处理父子分类关系
print(f"\n设置文章分类信息:")
print(f"- AI分析的分类类型{ai_content['type']}")
print(f"- 设置分类ID{ai_content['category_id']}")
# 分类ID到名称的映射
category_map = {
1: "游戏",
2: "软件",
3: "Apps",
57: "Android",
56: "APP游戏",
434: "IOS"
}
# 使用分类名称设置分类
categories = []
# 如果是Android、APP游戏或IOS分类同时添加Apps分类
if ai_content['category_id'] in [57, 56, 434]:
categories.append(category_map[3]) # 添加Apps分类名称
# 添加文章主分类名称
if ai_content['category_id'] and ai_content['category_id'] in category_map:
categories.append(category_map[ai_content['category_id']])
post.terms_names = {'category': categories} # 使用terms_names属性设置分类名称
print(f"- 最终分类设置:{categories}")
post.post_status = 'publish'
print("\n正在发布文章...")
try:
# 发布文章
post_id = self.client.call(NewPost(post))
print(f"文章发布成功文章ID{post_id}")
# 更新数据库中的文章状态
await item['db_manager'].mark_article_published(item['url'])
print("文章状态已更新!")
# 删除本地图片文件
if item.get('local_image') and os.path.exists(item['local_image']):
try:
os.remove(item['local_image'])
print(f"本地图片已删除:{item['local_image']}")
except Exception as e:
print(f"删除本地图片失败:{str(e)}")
except Exception as e:
error_msg = f"文章发布失败: {str(e)}"
print(f"错误:{error_msg}")
raise Exception(error_msg)