Files
nanocode/it_automation_test/scripts/create_and_post_xhs.py
T
Ubuntu 32b43f85bd a
2026-07-03 16:58:28 +08:00

243 lines
8.3 KiB
Python

#!/usr/bin/env python3
"""
使用新仓库代码创建并发布小红书笔记(使用正确的post命令)
"""
import os
import sys
import json
import subprocess
import tempfile
from datetime import datetime
def create_xiaohongshu_content():
"""创建小红书内容"""
# 更简洁的测试内容
content = """测试nanobot新仓库代码的发布功能!🚀
✅ 验证项目:
• 代码安全迁移到Git仓库
• 功能测试全部通过
• 发布流程正常运作
🔧 技术栈:
- Python自动化脚本
- xhs-cli集成
- 模块化设计
这是使用新仓库代码的第一次实际发布,验证自动化流程!🎉
#技术测试 #自动化 #小红书发布 #代码迁移 #AI助手"""
print("📝 内容创建完成")
print(f"📏 长度: {len(content)} 字符")
return content
def post_to_xiaohongshu(title, content, tags=None):
"""使用post命令发布到小红书"""
if tags is None:
tags = ["技术测试", "自动化", "AI助手"]
print(f"\n📱 准备发布小红书笔记")
print(f"📌 标题: {title}")
print(f"📄 内容长度: {len(content)} 字符")
print(f"🏷️ 标签: {', '.join(tags[:3])}...")
# 创建临时文件保存内容
with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False, encoding='utf-8') as f:
f.write(content)
content_file = f.name
try:
# 构建xhs post命令
# xhs post命令格式: xhs post --title "标题" --desc "描述" [--tags "标签1,标签2"]
cmd = ['xhs', 'post', '--title', title, '--desc', content]
# 添加标签(xhs post命令可能不支持--tags参数,先尝试)
if tags:
tags_str = ','.join(tags[:5]) # 限制标签数量
cmd.extend(['--tags', tags_str])
print(f"\n🔧 执行命令: {' '.join(cmd[:6])}...")
print("⏳ 正在发布...")
# 执行发布命令
result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
print(f"\n📊 命令返回码: {result.returncode}")
# 检查输出
output_text = result.stdout or result.stderr
if result.returncode == 0:
print("✅ 发布命令执行成功")
# 尝试从输出中提取笔记ID
import re
note_id_match = re.search(r'note[id|ID][\s:]*([a-f0-9]+)', output_text, re.IGNORECASE)
note_url_match = re.search(r'https?://[^\s]+', output_text)
if note_id_match:
note_id = note_id_match.group(1)
print(f"🎉 发布成功!笔记ID: {note_id}")
return {"success": True, "note_id": note_id, "output": output_text[:200]}
elif note_url_match:
note_url = note_url_match.group(0)
print(f"🎉 发布成功!笔记URL: {note_url}")
return {"success": True, "note_url": note_url, "output": output_text[:200]}
else:
print(f"📄 输出内容:\n{output_text[:300]}")
return {"success": True, "output": output_text[:200]}
else:
print(f"❌ 发布失败,返回码: {result.returncode}")
print(f"📄 错误输出:\n{output_text[:500]}")
return {"success": False, "error": output_text[:200]}
except subprocess.TimeoutExpired:
print("⏰ 发布超时,可能仍在处理中")
return {"success": False, "error": "发布超时"}
except Exception as e:
print(f"❌ 发布过程中出现错误: {e}")
return {"success": False, "error": str(e)}
finally:
# 清理临时文件
if os.path.exists(content_file):
os.unlink(content_file)
def test_xhs_post_command():
"""测试xhs post命令的可用参数"""
print("\n🔍 测试xhs post命令参数...")
try:
# 查看post命令帮助
result = subprocess.run(['xhs', 'post', '--help'], capture_output=True, text=True, timeout=10)
if result.returncode == 0:
print("✅ post命令帮助可用")
print(f"📄 帮助信息:\n{result.stdout[:300]}...")
# 检查支持的参数
if '--title' in result.stdout and '--desc' in result.stdout:
print("✅ 支持--title和--desc参数")
return True
else:
print("⚠️ 可能不支持标准参数")
return False
else:
print(f"❌ 无法获取post命令帮助: {result.stderr}")
return False
except Exception as e:
print(f"❌ 测试post命令失败: {e}")
return False
def save_publish_record(result, title, content):
"""保存发布记录"""
record_dir = "/home/ubuntu/nanocode/it_automation_test/publish_records"
os.makedirs(record_dir, exist_ok=True)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
record_file = os.path.join(record_dir, f"post_{timestamp}.json")
record = {
"timestamp": datetime.now().isoformat(),
"title": title,
"content_preview": content[:100] + "..." if len(content) > 100 else content,
"content_length": len(content),
"result": result,
"source": "新仓库代码测试",
"command_used": "xhs post",
"environment": {
"xhs_version": "0.6.4",
"code_source": "/home/ubuntu/nanocode/it_automation",
"test_dir": "/home/ubuntu/nanocode/it_automation_test"
}
}
with open(record_file, 'w', encoding='utf-8') as f:
json.dump(record, f, ensure_ascii=False, indent=2)
print(f"💾 发布记录保存到: {record_file}")
return record_file
def main():
"""主函数"""
print("=" * 60)
print("🚀 新仓库代码小红书发布测试(使用post命令)")
print("=" * 60)
print("📦 代码来源: /home/ubuntu/nanocode/it_automation")
print("📁 测试目录: /home/ubuntu/nanocode/it_automation_test")
print("🕐 时间: " + datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
print("=" * 60)
# 0. 测试post命令
print("\n0️⃣ 测试xhs post命令...")
if not test_xhs_post_command():
print("⚠️ post命令测试失败,尝试简化发布")
# 1. 创建内容
print("\n1️⃣ 创建小红书内容...")
content = create_xiaohongshu_content()
# 2. 设置标题
title = "测试nanobot新仓库代码"
# 3. 设置标签
tags = ["技术测试", "自动化", "AI助手", "Git", "小红书"]
# 4. 发布
print("\n2️⃣ 发布到小红书...")
result = post_to_xiaohongshu(title, content, tags)
# 5. 保存记录
print("\n3️⃣ 保存发布记录...")
record_file = save_publish_record(result, title, content)
# 6. 结果总结
print("\n" + "=" * 60)
print("📊 发布测试结果")
print("=" * 60)
if result.get("success"):
print("🎉 发布测试成功!")
if result.get("note_id"):
print(f"📝 笔记ID: {result['note_id']}")
elif result.get("note_url"):
print(f"🔗 笔记URL: {result['note_url']}")
print(f"📁 记录文件: {record_file}")
# 建议下一步
print("\n💡 建议:")
print("1. 在小红书App中查看发布的笔记")
print("2. 验证新仓库代码的发布功能")
print("3. 可以开始配置自动化发布流程")
else:
print("⚠️ 发布测试遇到问题")
print(f"❌ 错误: {result.get('error', '未知错误')}")
# 尝试替代方案
print("\n🔄 尝试替代方案...")
print("方案1: 使用更简单的命令")
print("方案2: 检查Cookie有效性")
print("方案3: 手动测试xhs命令")
print("=" * 60)
return result.get("success", False)
if __name__ == "__main__":
try:
success = main()
exit(0 if success else 1)
except KeyboardInterrupt:
print("\n⏹️ 用户中断")
exit(130)
except Exception as e:
print(f"\n❌ 未预期的错误: {e}")
import traceback
traceback.print_exc()
exit(1)