如何通过WordPress REST API将OpenAI响应发布为草稿文章?
问题:无法将OpenAI响应同步为WordPress草稿文章
尝试通过Python代码将OpenAI生成的内容创建为WordPress草稿文章,但WordPress相关逻辑始终无法正常工作,无法生成草稿。以下是使用的代码:
import openai import requests import json from requests.auth import HTTPBasicAuth import random import base64 # Array holding wordpress author IDs authorList = ["1", "2"] # Randomly choose a number from authorList array randomAuthor = random.choice(authorList) # Set OpenAI API key openai.api_key = "" # Then, you can call the "gpt-3.5-turbo" model modelEngine = "gpt-3.5-turbo" # set your input text inputText = "Write a 500 word tweet on {} stock" inputTitle = "Test analyst on {}" # Array of keywords to generate article on keywords = ["Nio (NIO)", "Apple (AAPL)", "Microsoft (MSFT)", "Tesla (TSLA)", "Meta (META)", "Amazon (AMZN)"] # WordPress information wp_base_url = "" #auth = HTTPBasicAuth("", "") wp_username = "" wp_password = "" auth = wp_username + ':' + wp_password token = base64.b64encode(auth.encode()) # Post creator function def create_post(title, content, authorList): post_status = "draft" headers = { "Authorization": "Basic" + token.decode('utf-8') #"Accept": "application/json", #"Content-Type": "application/json" } post = json.dumps({ "title": title, "content": content, "status": post_status, "author": authorList }) url = wp_base_url + "/wp-json/wp/v2/posts" response = requests.post(url, json=post, headers=headers) return response # Switches and injects keywords into API request for keyword in keywords: # set input text with the current keyword inputSent = inputText.format(keyword) inputTitleSent = inputTitle.format(keyword) # Send an API request and get a response, note that the interface and parameters have changed compared to the old model response = openai.ChatCompletion.create( model=modelEngine, messages=[{"role": "user", "content": inputSent }], n = 1 ) print("ChatGPT API replies for", keyword, "stock:\n") for choice in response.choices: outputText = choice.message print(outputText) print("------") # Create the WordPress post using the OpenAI response create_post(inputTitleSent, choice.message, randomAuthor) print("\n")
问题分析与修复方案
代码中存在多个导致WordPress API调用失败的问题,逐一修正如下:
1. 授权头格式错误
Authorization头中Basic和token之间缺少空格,WordPress无法识别正确的授权信息:
# 原代码 "Authorization": "Basic" + token.decode('utf-8') # 修改后 "Authorization": "Basic " + token.decode('utf-8')
2. OpenAI响应内容提取错误
choice.message是包含role和content的字典,直接传入会导致JSON序列化错误,需提取content字段:
# 原调用 create_post(inputTitleSent, choice.message, randomAuthor) # 修改后 create_post(inputTitleSent, choice.message['content'], randomAuthor)
3. 请求头缺失必要字段
注释掉的Accept和Content-Type头是WordPress API要求的格式声明,必须添加:
headers = { "Authorization": "Basic " + token.decode('utf-8'), "Accept": "application/json", "Content-Type": "application/json" }
4. 请求参数传递错误
requests.post的json参数接受字典类型,无需提前用json.dumps序列化,否则会导致格式错误;同时作者ID需转为整数(WordPress API要求数字类型):
# 原代码 post = json.dumps({...}) response = requests.post(url, json=post, headers=headers) # 修改后 post_data = { "title": title, "content": content, "status": post_status, "author": int(author_id) } response = requests.post(url, json=post_data, headers=headers)
5. 添加错误排查日志
在create_post函数中打印响应状态码和内容,方便定位问题:
print(f"WordPress API响应状态码: {response.status_code}") print(f"响应内容: {response.text}")
修正后的完整代码
import openai import requests import random import base64 # WordPress作者ID列表 author_list = ["1", "2"] # 随机选择作者ID random_author = random.choice(author_list) # 设置OpenAI API密钥 openai.api_key = "你的OpenAI API密钥" # 使用的模型 model_engine = "gpt-3.5-turbo" # 输入模板 input_text = "写一篇500字关于{}股票的分析内容" input_title = "{}股票分析师报告" # 目标股票列表 keywords = ["蔚来(NIO)", "苹果(AAPL)", "微软(MSFT)", "特斯拉(TSLA)", "Meta(META)", "亚马逊(AMZN)"] # WordPress配置 wp_base_url = "你的WordPress站点地址" wp_username = "你的WordPress用户名" wp_password = "你的WordPress应用密码" # 生成授权token auth_str = f"{wp_username}:{wp_password}" token = base64.b64encode(auth_str.encode()).decode('utf-8') # 创建WordPress草稿文章函数 def create_post(title, content, author_id): post_status = "draft" headers = { "Authorization": f"Basic {token}", "Accept": "application/json", "Content-Type": "application/json" } post_data = { "title": title, "content": content, "status": post_status, "author": int(author_id) } url = f"{wp_base_url}/wp-json/wp/v2/posts" response = requests.post(url, json=post_data, headers=headers) # 打印响应信息用于排查 print(f"文章创建响应状态码: {response.status_code}") if response.status_code != 201: print(f"错误详情: {response.text}") return response # 遍历股票生成内容并创建文章 for keyword in keywords: current_input = input_text.format(keyword) current_title = input_title.format(keyword) # 调用OpenAI生成内容 ai_response = openai.ChatCompletion.create( model=model_engine, messages=[{"role": "user", "content": current_input}], n=1 ) print(f"=== {keyword} 生成内容 ===") for choice in ai_response.choices: content = choice.message['content'] print(content) # 创建WordPress草稿 create_post(current_title, content, random_author) print("\n")
额外注意事项
- 确保WordPress站点启用了REST API(默认已启用)
- 使用应用密码而非普通密码进行授权(需开启两步验证后在WordPress后台生成)
- 检查WordPress用户是否有创建文章的权限
- 确认
wp_base_url格式正确,例如https://your-site.com,不要带末尾的斜杠
内容的提问来源于stack exchange,提问作者overdeveloping
相关产品推荐
相关产品推荐

