### Install and Configure Xianyu AutoAgent Source: https://github.com/shaxiu/xianyuautoagent/blob/main/README.md Commands to clone the repository, install dependencies, and set up the required environment variables. ```bash 1. 克隆仓库 git clone https://github.com/shaxiu/XianyuAutoAgent.git cd XianyuAutoAgent 2. 安装依赖 pip install -r requirements.txt 3. 配置环境变量 创建一个 `.env` 文件,包含以下内容,也可直接重命名 `.env.example` : #必配配置 API_KEY=apikey通过模型平台获取 COOKIES_STR=填写网页端获取的cookie MODEL_BASE_URL=模型地址 MODEL_NAME=模型名称 #可选配置 TOGGLE_KEYWORDS=接管模式切换关键词,默认为句号(输入句号切换为人工接管,再次输入则切换AI接管) SIMULATE_HUMAN_TYPING=True/False #模拟人工回复延迟 注意:默认使用的模型是通义千问,如需使用其他API,请自行修改.env文件中的模型地址和模型名称; COOKIES_STR自行在闲鱼网页端获取cookies(网页端F12打开控制台,选择Network,点击Fetch/XHR,点击一个请求,查看cookies) 4. 创建提示词文件prompts/*_prompt.txt(也可以直接将模板名称中的_example去掉),否则默认读取四个提示词模板中的内容 ``` -------------------------------- ### Run the Main Program Source: https://github.com/shaxiu/xianyuautoagent/blob/main/README.md Command to start the Xianyu AutoAgent service. ```bash python main.py ``` -------------------------------- ### Configure Environment Variables Source: https://context7.com/shaxiu/xianyuautoagent/llms.txt Define system configuration including API keys, model settings, and heartbeat intervals in a .env file. ```bash # .env 配置文件示例 # 必需配置 API_KEY=sk-xxxxxxxxxxxxx # 通义千问API密钥(百炼平台获取) COOKIES_STR=unb=123;cookie2=xxx;... # 闲鱼登录Cookie # 模型配置 MODEL_BASE_URL=https://dashscope.aliyuncs.com/compatible-mode/v1 MODEL_NAME=qwen-max # 可选: qwen-plus, qwen-turbo # 心跳配置 HEARTBEAT_INTERVAL=15 # 心跳间隔(秒) HEARTBEAT_TIMEOUT=5 # 心跳超时(秒) # Token刷新配置 TOKEN_REFRESH_INTERVAL=3600 # Token刷新间隔(秒,默认1小时) TOKEN_RETRY_INTERVAL=300 # Token重试间隔(秒,默认5分钟) # 人工接管配置 TOGGLE_KEYWORDS=。 # 切换人工/自动模式的关键词 MANUAL_MODE_TIMEOUT=3600 # 人工模式超时时间(秒) MESSAGE_EXPIRE_TIME=300000 # 消息过期时间(毫秒,默认5分钟) # 其他配置 LOG_LEVEL=INFO # 日志级别: DEBUG, INFO, WARNING, ERROR SIMULATE_HUMAN_TYPING=False # 是否模拟人工输入延迟 ``` -------------------------------- ### Initialize XianyuLive WebSocket Listener Source: https://context7.com/shaxiu/xianyuautoagent/llms.txt The main entry point for establishing WebSocket connections, managing heartbeats, and handling token refreshes. ```python import asyncio import os from dotenv import load_dotenv from XianyuAgent import XianyuReplyBot # 加载环境变量 load_dotenv() class XianyuLive: def __init__(self, cookies_str): self.xianyu = XianyuApis() self.base_url = 'wss://wss-goofish.dingtalk.com/' self.cookies_str = cookies_str self.cookies = trans_cookies(cookies_str) self.xianyu.session.cookies.update(self.cookies) self.myid = self.cookies['unb'] self.device_id = generate_device_id(self.myid) self.context_manager = ChatContextManager() # 心跳配置 self.heartbeat_interval = int(os.getenv("HEARTBEAT_INTERVAL", "15")) self.heartbeat_timeout = int(os.getenv("HEARTBEAT_TIMEOUT", "5")) # Token刷新配置 self.token_refresh_interval = int(os.getenv("TOKEN_REFRESH_INTERVAL", "3600")) # 人工接管配置 self.manual_mode_timeout = int(os.getenv("MANUAL_MODE_TIMEOUT", "3600")) self.toggle_keywords = os.getenv("TOGGLE_KEYWORDS", "。") # 启动机器人 cookies_str = os.getenv("COOKIES_STR") bot = XianyuReplyBot() xianyu_live = XianyuLive(cookies_str) asyncio.run(xianyu_live.main()) ``` -------------------------------- ### Deploy with Docker Source: https://context7.com/shaxiu/xianyuautoagent/llms.txt Use Docker Compose to manage the service container and persistent volumes. ```yaml # docker-compose.yml version: '3.8' services: xianyu-agent: build: . container_name: xianyu-autoagent restart: unless-stopped volumes: - ./data:/app/data # 持久化数据库 - ./.env:/app/.env # 环境变量配置 - ./prompts:/app/prompts # 自定义提示词 environment: - TZ=Asia/Shanghai ``` ```bash # 启动服务 docker-compose up -d # 查看日志 docker-compose logs -f # 停止服务 docker-compose down ``` -------------------------------- ### Provide Technical Support with TechAgent Source: https://context7.com/shaxiu/xianyuautoagent/llms.txt Handles product specifications and comparisons, supporting web search integration for up-to-date information. ```python from XianyuAgent import TechAgent tech_prompt = """ 你是一位专业的产品技术顾问,擅长回答产品规格、参数、适配性等技术问题。 回答要简洁专业,突出产品优势。 """ tech_agent = TechAgent(client, tech_prompt, safety_filter) # 技术咨询示例 - 启用联网搜索 reply = tech_agent.generate( user_msg="这个耳机的降噪效果怎么样,和Bose QC45比呢", item_desc='{"title": "索尼WH-1000XM5", "desc": "头戴式主动降噪耳机"}', context="" ) # TechAgent 会通过 enable_search=True 联网获取最新对比信息 print(reply) # 输出示例: "XM5降噪业界顶级,比QC45低频降噪更强,佩戴也更舒适" ``` -------------------------------- ### Utilize Xianyu Utility Functions Source: https://context7.com/shaxiu/xianyuautoagent/llms.txt Provides helper functions for cookie parsing, ID generation, API signing, and message decryption. ```python from utils.xianyu_utils import ( trans_cookies, generate_mid, generate_uuid, generate_device_id, generate_sign, decrypt ) # 解析Cookie字符串为字典 cookie_str = "unb=123456; cookie2=abcdef; _m_h5_tk=token_12345" cookies = trans_cookies(cookie_str) print(cookies) # {'unb': '123456', 'cookie2': 'abcdef', '_m_h5_tk': 'token_12345'} # 生成消息ID(用于WebSocket通信) mid = generate_mid() print(mid) # "1234561234567890123 0" # 生成UUID(用于消息唯一标识) uuid = generate_uuid() print(uuid) # "-16234567890121" # 生成设备ID(基于用户ID) device_id = generate_device_id("123456") print(device_id) # "a1b2c3d4-e5f6-4789-abcd-ef0123456789-123456" # 生成API签名 timestamp = "1234567890123" token = "abcdef123456" data = '{"itemId":"123456"}' sign = generate_sign(timestamp, token, data) print(sign) # "e10adc3949ba59abbe56e057f20f883e" (MD5签名) # 解密WebSocket消息(MessagePack格式) encrypted_data = "gqExo..." # Base64编码的MessagePack数据 decrypted = decrypt(encrypted_data) print(decrypted) # JSON格式的消息内容 ``` -------------------------------- ### Generate AI Replies with XianyuReplyBot Source: https://context7.com/shaxiu/xianyuautoagent/llms.txt Core class for initializing agents, loading prompts, and generating context-aware responses. ```python from XianyuAgent import XianyuReplyBot # 初始化机器人(自动从环境变量读取API配置) bot = XianyuReplyBot() # 商品信息 item_desc = '''当前商品的信息如下:{ "title": "索尼WH-1000XM5头戴式降噪耳机", "desc": "99新,仅拆封试听,支持LDAC", "price_range": "¥1800", "total_stock": 1, "sku_details": [{"spec": "黑色", "price": 1800.0, "stock": 1}] }''' # 对话历史上下文 context = [ {"role": "user", "content": "你好,这个耳机还在吗"}, {"role": "assistant", "content": "在的亲,随时可拍"} ] # 生成回复 user_message = "能便宜点吗,1500行不行" reply = bot.generate_reply(user_message, item_desc, context) print(f"机器人回复: {reply}") # 输出示例: "亲,这个价格已经很实惠了,诚心要可以小刀" # 检查最后识别的意图 print(f"识别意图: {bot.last_intent}") # 输出: price # 重新加载提示词(热更新) bot.reload_prompts() ``` -------------------------------- ### Configure IntentRouter for Message Classification Source: https://context7.com/shaxiu/xianyuautoagent/llms.txt Implements a three-level routing strategy using keywords, regex patterns, and LLM fallback. ```python from XianyuAgent import IntentRouter, ClassifyAgent from openai import OpenAI import os # 创建分类Agent client = OpenAI( api_key=os.getenv("API_KEY"), base_url=os.getenv("MODEL_BASE_URL", "https://dashscope.aliyuncs.com/compatible-mode/v1") ) # 意图路由器的规则配置 router_rules = { 'tech': { 'keywords': ['参数', '规格', '型号', '连接', '对比'], 'patterns': [r'和.+比'] }, 'price': { 'keywords': ['便宜', '价', '砍价', '少点'], 'patterns': [r'\d+元', r'能少\d+'] } } # 意图检测示例 user_messages = [ "这个耳机支持什么蓝牙版本", # -> tech (技术类关键词) "能便宜200吗", # -> price (价格类关键词 + 正则) "你好在吗", # -> default (大模型兜底) "和AirPods Pro比怎么样", # -> tech (正则匹配) ] for msg in user_messages: # 路由器会自动判断意图 intent = router.detect(msg, item_desc, context_str) print(f"消息: {msg} -> 意图: {intent}") ``` -------------------------------- ### Handle Bargaining with PriceAgent Source: https://context7.com/shaxiu/xianyuautoagent/llms.txt Specialized agent for price negotiations using dynamic temperature settings and safety filters. ```python from XianyuAgent import PriceAgent from openai import OpenAI client = OpenAI( api_key=os.getenv("API_KEY"), base_url="https://dashscope.aliyuncs.com/compatible-mode/v1" ) # 议价提示词 price_prompt = """ 【核心策略】 1. 优惠上限:设定明确的优惠上限(如100元或商品价格的10%) 2. 梯度让步:根据议价次数逐步增加优惠幅度 3. 价值强调:突出产品品质和价值 """ def safety_filter(text): blocked = ["微信", "QQ", "支付宝", "银行卡", "线下"] return "[安全提醒]请通过平台沟通" if any(p in text for p in blocked) else text price_agent = PriceAgent(client, price_prompt, safety_filter) # 根据议价次数动态调整温度 # 第1次议价: temperature = 0.3 + 1*0.15 = 0.45 (较保守) # 第3次议价: temperature = 0.3 + 3*0.15 = 0.75 (更灵活) # 第5次议价: temperature = min(0.3 + 5*0.15, 0.9) = 0.9 (最大值) reply = price_agent.generate( user_msg="1600能出吗", item_desc='{"title": "耳机", "price_range": "¥1800"}', context="user: 能便宜吗\nassistant: 诚心要可以小刀", bargain_count=2 # 第二次议价 ) print(reply) # 输出示例: "1700最低了,真的没利润了" ``` -------------------------------- ### Interact with Xianyu APIs Source: https://context7.com/shaxiu/xianyuautoagent/llms.txt XianyuApis handles authentication, token retrieval, and item information queries with automatic signature and cookie management. ```python from XianyuApis import XianyuApis from utils.xianyu_utils import trans_cookies, generate_device_id # 初始化API客户端 api = XianyuApis() # 设置Cookie cookies_str = "unb=123456; cookie2=xxxxx; _m_h5_tk=token_xxxxx; ..." cookies = trans_cookies(cookies_str) api.session.cookies.update(cookies) # 检查登录状态 is_logged_in = api.hasLogin() if is_logged_in: print("登录状态有效") # 获取WebSocket连接Token user_id = cookies['unb'] device_id = generate_device_id(user_id) token_result = api.get_token(device_id) if 'data' in token_result: access_token = token_result['data']['accessToken'] print(f"Token获取成功: {access_token[:20]}...") # 获取商品详情 item_id = "123456789" item_result = api.get_item_info(item_id) if 'data' in item_result and 'itemDO' in item_result['data']: item = item_result['data']['itemDO'] print(f"商品标题: {item.get('title')}") print(f"商品价格: {item.get('soldPrice') / 100}元") print(f"商品描述: {item.get('desc')}") ``` -------------------------------- ### Manage Conversation Context with ChatContextManager Source: https://context7.com/shaxiu/xianyuautoagent/llms.txt Use ChatContextManager to persist conversation history, item details, and bargain counts in a SQLite database. ```python from context_manager import ChatContextManager # 初始化上下文管理器 context_mgr = ChatContextManager( max_history=100, # 每个对话最多保留100条消息 db_path="data/chat_history.db" ) # 保存商品信息 item_info = { "title": "索尼降噪耳机", "soldPrice": 180000, # 单位:分 "desc": "99新头戴式降噪耳机", "quantity": 1, "skuList": [ {"propertyList": [{"valueText": "黑色"}], "price": 180000, "quantity": 1} ] } context_mgr.save_item_info("item_123456", item_info) # 获取商品信息 cached_item = context_mgr.get_item_info("item_123456") print(cached_item["title"]) # 索尼降噪耳机 # 添加对话消息(基于会话ID) chat_id = "conv_789" context_mgr.add_message_by_chat( chat_id=chat_id, user_id="buyer_001", item_id="item_123456", role="user", content="这个耳机还在吗" ) context_mgr.add_message_by_chat( chat_id=chat_id, user_id="seller_001", item_id="item_123456", role="assistant", content="在的亲,随时可拍" ) # 获取对话历史 history = context_mgr.get_context_by_chat(chat_id) print(history) # [ # {"role": "user", "content": "这个耳机还在吗"}, # {"role": "assistant", "content": "在的亲,随时可拍"} # ] # 增加并获取议价次数 context_mgr.increment_bargain_count_by_chat(chat_id) context_mgr.increment_bargain_count_by_chat(chat_id) bargain_count = context_mgr.get_bargain_count_by_chat(chat_id) print(f"议价次数: {bargain_count}") # 议价次数: 2 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.