#!/usr/bin/env python3 """ 使用新仓库代码创建并发布小红书笔记 """ import os import sys import json import subprocess import tempfile from datetime import datetime def create_xiaohongshu_content(): """创建小红书内容""" # 使用新仓库的humanizer工具 sys.path.append('/home/ubuntu/nanocode/it_automation/scripts') try: from humanizer_cn import HumanizerCN # 原始内容(可能包含AI痕迹) original_content = """今天测试nanobot的新仓库代码发布功能! 经过安全迁移和测试验证,我们的IT资讯自动化系统已经成功迁移到Git仓库。 🎯 主要功能: • 网页抓取 - 自动获取最新技术资讯 • 内容处理 - 翻译和格式转换 • 去AI化 - 让文章更自然 • 小红书发布 - 自动分享有价值的内容 🔧 技术亮点: 1. 模块化设计,易于维护 2. 配置与代码分离,安全可靠 3. 完整的自动化流程 这次发布是为了验证新仓库代码的实际运行效果。一切顺利! 🚀 #技术分享 #自动化 #AI助手 #Git管理 #小红书测试""" print("📝 原始内容创建完成") print(f"📏 长度: {len(original_content)} 字符") # 使用humanizer处理(可选) humanizer = HumanizerCN() ai_detection = humanizer.detect_ai_patterns(original_content) if ai_detection.get('total_patterns', 0) > 0: print(f"🔍 检测到 {ai_detection['total_patterns']} 个AI模式") # 可以选择进行去AI化处理 # humanized_content = humanizer.humanize_text(original_content) # content = humanized_content content = original_content print("⚠️ 检测到AI痕迹,但为了测试保持原样") else: content = original_content print("✅ 内容自然,无需去AI化") return content except Exception as e: print(f"❌ 创建内容失败: {e}") # 使用简单内容作为备选 simple_content = """测试nanobot新仓库代码的小红书发布功能! ✅ 验证通过: • 代码迁移成功 • 功能测试完成 • 发布流程正常 这是使用新仓库代码的第一次实际发布! 🎉 #技术测试 #自动化 #小红书发布""" return simple_content def publish_to_xiaohongshu(title, content, tags=None): """发布到小红书""" if tags is None: tags = ["技术测试", "自动化", "AI助手", "Git管理"] print(f"\n📱 准备发布小红书笔记") print(f"📌 标题: {title}") print(f"📄 内容长度: {len(content)} 字符") print(f"🏷️ 标签: {', '.join(tags)}") # 构建xhs命令 cmd = ['xhs', 'publish', '--title', title, '--content', content] # 添加标签 for tag in tags: cmd.extend(['--tags', tag]) print(f"\n🔧 执行命令: {' '.join(cmd[:8])}...") try: # 执行发布命令 print("⏳ 正在发布...") result = subprocess.run(cmd, capture_output=True, text=True, timeout=60) print(f"\n📊 命令返回码: {result.returncode}") if result.stdout: print(f"📄 标准输出:\n{result.stdout[:500]}...") if result.stderr: print(f"⚠️ 标准错误:\n{result.stderr[:500]}...") # 尝试解析输出 output_text = result.stdout or result.stderr # 检查是否包含笔记ID import re note_id_match = re.search(r'note[id|ID][\s:]*([a-f0-9]+)', output_text, re.IGNORECASE) if result.returncode == 0: 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]} else: print("✅ 发布命令执行成功(可能需要手动确认笔记ID)") return {"success": True, "output": output_text[:200]} else: print("❌ 发布失败") 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)} 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"publish_{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": "新仓库代码测试", "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("🚀 新仓库代码小红书发布测试") 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) # 1. 创建内容 print("\n1️⃣ 创建小红书内容...") content = create_xiaohongshu_content() # 2. 设置标题 title = "测试nanobot新仓库代码发布功能" # 3. 设置标签 tags = ["技术测试", "自动化", "AI助手", "Git管理", "小红书发布", "代码迁移"] # 4. 发布 print("\n2️⃣ 发布到小红书...") result = publish_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']}") print(f"📁 记录文件: {record_file}") # 建议下一步 print("\n💡 建议:") print("1. 在小红书App中查看发布的笔记") print("2. 检查笔记内容和格式是否正确") print("3. 验证新仓库代码的发布功能") else: print("⚠️ 发布测试遇到问题") print(f"❌ 错误: {result.get('error', '未知错误')}") # 故障排除建议 print("\n🔧 故障排除:") print("1. 检查Cookie是否过期: cat /home/ubuntu/xiaohongshu_cookies.txt") print("2. 测试xhs命令: xhs --help") print("3. 检查网络连接") 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)