
基于大语言模型(LLM)全自动生成文章、内容清洗、格式优化,并自动发布至公众号、小红书、知乎、WordPress、自建 CMS等平台的端到端自动化系统,本文参照汇创鸭AI工具技术文档编写。
requests、openai、python-dotenv、selenium、schedule统一管理 API 密钥、发布平台参数、生成规则。
bash
运行
pip install openai python-dotenv requests schedule seleniumenv
# AI大模型配置
OPENAI_API_KEY=你的OpenAI API密钥
OPENAI_BASE_URL=https://api.openai.com/v1
# 发布平台配置(以WordPress为例)
WP_URL=https://你的域名/wp-json/wp/v2
WP_USER=用户名
WP_APP_PASSWORD=应用密码
# 文章配置
ARTICLE_COUNT=1
ARTICLE_WORDS=800
ARTICLE_TOPIC=AI技术、职场效率、生活科普python
运行
import os
import json
import time
import requests
from dotenv import load_dotenv
from openai import OpenAI
import schedule
# 加载环境变量
load_dotenv()
# ======================
# 1. AI文章生成模块
# ======================
class AIContentGenerator:
def __init__(self):
self.client = OpenAI(
api_key=os.getenv("OPENAI_API_KEY"),
base_url=os.getenv("OPENAI_BASE_URL")
)
def generate_article(self, topic, words=800):
"""AI生成文章(标题+正文+标签)"""
prompt = f"""
你是专业自媒体作者,请围绕主题【{topic}】撰写一篇约{words}字的原创文章。
要求:
1. 结构清晰:标题+引言+分段内容+总结
2. 语言流畅、无废话、适合自媒体阅读
3. 输出纯文本,不要markdown、不要特殊符号
4. 最后一行输出标签,格式:标签1,标签2,标签3
"""
try:
response = self.client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": prompt}],
temperature=0.7,
)
content = response.choices[0].message.content.strip()
# 拆分正文和标签
lines = content.split("\n")
tags = lines[-1].replace("标签:", "").strip()
article = "\n".join(lines[:-1])
return article, tags
except Exception as e:
print(f"生成失败:{e}")
return None, None
# ======================
# 2. 自动发布模块(WordPress示例)
# ======================
class WordPressPublisher:
def __init__(self):
self.url = os.getenv("WP_URL")
self.auth = (os.getenv("WP_USER"), os.getenv("WP_APP_PASSWORD"))
def publish(self, title, content, tags="AI,自动化"):
"""自动发布文章到WordPress"""
data = {
"title": title,
"content": content,
"status": "publish", # publish=发布 draft=草稿
"tags": tags.split(",")
}
try:
res = requests.post(
f"{self.url}/posts",
json=data,
auth=self.auth,
timeout=30
)
if res.status_code in [200, 201]:
print(f"✅ 发布成功!文章ID:{res.json()['id']}")
return True
else:
print(f"❌ 发布失败:{res.text}")
return False
except Exception as e:
print(f"发布异常:{e}")
return False
# ======================
# 3. 自动化任务主流程
# ======================
def auto_write_and_publish():
print("===== 开始执行自动写作+发布任务 =====")
# 1. 初始化
generator = AIContentGenerator()
publisher = WordPressPublisher()
topic = os.getenv("ARTICLE_TOPIC")
words = int(os.getenv("ARTICLE_WORDS"))
# 2. AI生成文章
article_content, tags = generator.generate_article(topic, words)
if not article_content:
print("生成失败,任务终止")
return
# 3. 提取标题(取第一段)
title = article_content.split("\n")[0][:50]
content = "\n".join(article_content.split("\n")[1:])
# 4. 自动发布
publisher.publish(title, content, tags)
# ======================
# 4. 定时任务(每天9点自动运行)
# ======================
def start_schedule():
schedule.every().day.at("09:00").do(auto_write_and_publish)
print("⏰ 定时任务已启动,每日09:00自动发文")
while True:
schedule.run_pending()
time.sleep(60)
# ======================
# 启动程序
# ======================
if __name__ == "__main__":
# 立即执行一次
auto_write_and_publish()
# 启动定时任务
# start_schedule()适用于无开放 API的平台,使用 Selenium 模拟人工发布:
python
运行
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
class XiaohongshuPublisher:
def __init__(self):
self.driver = webdriver.Chrome()
def publish(self, title, content):
driver = self.driver
driver.get("https://creator.xiaohongshu.com/")
time.sleep(3)
# 登录(需手动扫码一次)
input("请扫码登录后按回车继续...")
# 进入发布页
driver.get("https://creator.xiaohongshu.com/publish")
time.sleep(2)
# 输入标题
driver.find_element(By.XPATH, '//input[@placeholder="写个标题"]').send_keys(title)
time.sleep(1)
# 输入内容
driver.find_element(By.XPATH, '//div[@role="textbox"]').send_keys(content)
time.sleep(2)
# 点击发布
driver.find_element(By.XPATH, '//button[text()="发布"]').click()
print("✅ 小红书发布完成")
time.sleep(5)
driver.quit().env中填入 API 密钥、发布平台信息python auto_article_publisher.pystart_schedule()即可 7×24 小时自动运行log.txt日志文件原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。