### Get Login Token with XianyuApis Source: https://context7.com/jeanmoumou/xianyuapis/llms.txt Use this method to request an access token from the Xianyu server, which is necessary for establishing WebSocket connections. It requires user cookies and a device ID. ```python from XianyuApis import XianyuApis from utils.xianyu_utils import trans_cookies, generate_device_id # Initialize API client xianyu = XianyuApis() # User cookies string (obtained from browser) cookies_str = r'_m_h5_tk=cd69ceb8b218792aaa87a25520ac2e42_1741675519283; unb=3888777108; ...' # Convert cookies to dictionary format cookies = trans_cookies(cookies_str) # Get user ID and generate device ID user_id = cookies['unb'] device_id = generate_device_id(user_id) # Get access token response = xianyu.get_token(cookies, device_id) # Response example: # { # "api": "mtop.taobao.idlemessage.pc.login.token", # "data": { # "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." # }, # "ret": ["SUCCESS::调用成功"] # } access_token = response['data']['accessToken'] print(f"Obtained token: {access_token}") ``` -------------------------------- ### XianyuApis.get_token - Get Login Token Source: https://context7.com/jeanmoumou/xianyuapis/llms.txt Obtains an access token required for establishing WebSocket connections. It takes user cookies and a device ID as input and returns the access token upon successful authentication. ```APIDOC ## POST /api/token ### Description Requests an access token (Access Token) from the Xianyu server. This token is necessary for establishing a WebSocket connection. The method accepts user cookies and a device ID, and returns response data containing the accessToken after signature verification. ### Method POST ### Endpoint /api/token ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **cookies** (dict) - Required - Dictionary of user cookies. - **device_id** (str) - Required - Generated device ID for the user. ### Request Example ```python from XianyuApis import XianyuApis from utils.xianyu_utils import trans_cookies, generate_device_id xianyu = XianyuApis() cookies_str = r'_m_h5_tk=cd69ceb8b218792aaa87a25520ac2e42_1741675519283; unb=3888777108; ...' cookies = trans_cookies(cookies_str) user_id = cookies['unb'] device_id = generate_device_id(user_id) response = xianyu.get_token(cookies, device_id) ``` ### Response #### Success Response (200) - **api** (str) - The API endpoint called. - **data** (object) - Contains the access token. - **accessToken** (str) - The obtained access token. - **ret** (list) - Status of the API call. #### Response Example ```json { "api": "mtop.taobao.idlemessage.pc.login.token", "data": { "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." }, "ret": ["SUCCESS::调用成功"] } ``` ``` -------------------------------- ### Build and Run Docker Image Source: https://github.com/jeanmoumou/xianyuapis/blob/master/README.md Use these commands to build the Docker image for the XianYuApis project and then run it in interactive mode. ```bash docker build -t xianyuapp . docker run -it xianyuapp bash ``` -------------------------------- ### XianyuLive.create_chat - Create Chat Session Source: https://context7.com/jeanmoumou/xianyuapis/llms.txt Initiates a chat session with a specified user for a given item. It requires the target user ID and item ID to establish the session and returns a unique chat ID (cid). ```APIDOC ## POST /chat/create ### Description Creates a chat session with a specified user via WebSocket. Requires the target user ID and the associated item ID. Upon successful session creation, it returns a session ID (cid) for subsequent message sending. ### Method POST (via WebSocket message) ### Endpoint `wss://wss-goofish.dingtalk.com/` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body (Sent as a WebSocket message payload) - **toid** (str) - Required - The ID of the target user. - **item_id** (str) - Required - The ID of the associated item. ### Request Example ```python import asyncio import json import websockets from XianyuAutoAsync import XianyuLive cookies_str = r'your_cookies_here' xianyu_live = XianyuLive(cookies_str) async def create_chat_example(): headers = { "Cookie": cookies_str, "Host": "wss-goofish.dingtalk.com", "Origin": "https://www.goofish.com", } async with websockets.connect( 'wss://wss-goofish.dingtalk.com/', extra_headers=headers ) as ws: await xianyu_live.init(ws) await xianyu_live.create_chat(ws, '2202640918079', '897742748011') async for message in ws: msg = json.loads(message) if 'body' in msg and 'singleChatConversation' in msg['body']: cid = msg['body']['singleChatConversation']['cid'] cid = cid.split('@')[0] print(f"会话创建成功,会话 ID: {cid}") break asyncio.run(create_chat_example()) ``` ### Response #### Success Response (200 OK via WebSocket) - **body.singleChatConversation.cid** (str) - The unique chat session ID. #### Response Example ```json { "body": { "singleChatConversation": { "cid": "1234567890@XXXX" } } } ``` ``` -------------------------------- ### Create Chat Session with XianyuLive Source: https://context7.com/jeanmoumou/xianyuapis/llms.txt Use this method to create a chat session with a specified user via WebSocket. It requires the target user ID and an associated item ID. Upon successful creation, a conversation ID (cid) is returned for subsequent message sending. ```python import asyncio import json import websockets from XianyuAutoAsync import XianyuLive cookies_str = r'your_cookies_here' xianyu_live = XianyuLive(cookies_str) async def create_chat_example(): headers = { "Cookie": cookies_str, "Host": "wss-goofish.dingtalk.com", "Origin": "https://www.goofish.com", } async with websockets.connect( 'wss://wss-goofish.dingtalk.com/', extra_headers=headers ) as ws: # Initialize connection await xianyu_live.init(ws) # Create chat session # Parameters: ws (WebSocket), toid (target user ID), item_id (item ID) await xianyu_live.create_chat(ws, '2202640918079', '897742748011') # Listen for response to get session ID async for message in ws: msg = json.loads(message) if 'body' in msg and 'singleChatConversation' in msg['body']: cid = msg['body']['singleChatConversation']['cid'] cid = cid.split('@')[0] print(f"Chat created successfully, conversation ID: {cid}") break asyncio.run(create_chat_example()) ``` -------------------------------- ### XianyuLive WebSocket Real-time Messaging Client Source: https://context7.com/jeanmoumou/xianyuapis/llms.txt This class provides WebSocket real-time connection capabilities with the Xianyu messaging service. It supports initializing connections, creating chat sessions, sending messages, and listening for incoming messages using an asynchronous architecture. ```python import asyncio from XianyuAutoAsync import XianyuLive # User cookies string cookies_str = r'cna=xxx; t=xxx; unb=3888777108; _m_h5_tk=xxx; ...' # Create XianyuLive instance xianyu_live = XianyuLive(cookies_str) # Method 1: Send a single message and disconnect async def send_single_message(): to_id = '2202640918079' # Target user ID item_id = '897742748011' # Item ID text = 'Hello, this is an automated message!' await xianyu_live.send_msg_once(to_id, item_id, text) print("Message sent successfully") # Method 2: Persistent process, listen and auto-reply messages async def auto_reply_daemon(): to_id = '2202640918079' item_id = '897742748011' text = 'Hello, World!' # Start persistent process to automatically listen and reply to messages await xianyu_live.main(to_id, item_id, text) # Run examples asyncio.run(send_single_message()) # Or run the persistent process # asyncio.run(auto_reply_daemon()) ``` -------------------------------- ### Generate MD5 Signature for API Requests Source: https://context7.com/jeanmoumou/xianyuapis/llms.txt Creates an MD5 signature for API requests, essential for authentication. The signature is composed of a timestamp, token, appKey, and request data. ```python from utils.xianyu_utils import generate_sign timestamp = '1741667630548' token = 'b7e897bf9767618a32b439c6103fe1cb' data = '{"appKey":"444e9908a51d1cb236a27862abc769c9","deviceId":"ED4CBA2C-5DA0-4154-A902-BF5CB52409E2-3888777108"}' sign = generate_sign(timestamp, token, data) print(f"签名: {sign}") ``` -------------------------------- ### XianyuLive - WebSocket Real-time Message Client Source: https://context7.com/jeanmoumou/xianyuapis/llms.txt Manages WebSocket connections for real-time messaging with the Xianyu platform. It supports initializing connections, creating chat sessions, sending messages, and listening for incoming messages. ```APIDOC ## WebSocket /wss-goofish.dingtalk.com/ ### Description Provides WebSocket real-time connection capabilities with the Xianyu message service. Supports initializing connections, creating chat sessions, sending messages, and listening for received messages. It utilizes an asynchronous architecture for efficient message processing. ### Method WebSocket ### Endpoint wss://wss-goofish.dingtalk.com/ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (Connection is established via WebSocket handshake with headers) ### Request Example ```python import asyncio from XianyuAutoAsync import XianyuLive cookies_str = r'cna=xxx; t=xxx; unb=3888777108; _m_h5_tk=xxx; ...' xianyu_live = XianyuLive(cookies_str) async def send_single_message(): to_id = '2202640918079' item_id = '897742748011' text = 'Hello, 这是一条自动消息!' await xianyu_live.send_msg_once(to_id, item_id, text) print("消息发送成功") async def auto_reply_daemon(): to_id = '2202640918079' item_id = '897742748011' text = 'Hello, World!' await xianyu_live.main(to_id, item_id, text) # asyncio.run(send_single_message()) # asyncio.run(auto_reply_daemon()) ``` ### Response None (This is a client-side representation of a WebSocket connection. Server responses are handled within the message loop.) ``` -------------------------------- ### Generate Device ID for Xianyu API Source: https://context7.com/jeanmoumou/xianyuapis/llms.txt Generates a unique device identifier by combining a UUID with a user ID. This is required for device authentication with Xianyu APIs. ```python from utils.xianyu_utils import generate_device_id user_id = '3888777108' device_id = generate_device_id(user_id) print(f"设备 ID: {device_id}") ``` -------------------------------- ### Transform Cookie String to Dictionary Source: https://context7.com/jeanmoumou/xianyuapis/llms.txt Converts a browser-copied cookie string into a Python dictionary for easier access to individual cookie values. Useful for initializing API clients with existing session data. ```python cookies_str = r'cna=aKpWII3TuhYCAXAC; unb=3888777108; _m_h5_tk=cd69ceb8b218792aaa87a25520ac2e42_1741675519283; sgcookie=E100lZr6TdR%2F%2BM8eOe%2FYNfKSzRbSpMCf4UIc3o1d%2F7W8mC4HM1DrJ%2F5OtlUg0oBOx00QqwiqNvs72HeWdtbEsXHkRezIHmW30%2BxeGtEBSUKRDa0%3D' cookies = trans_cookies(cookies_str) print(f"用户 ID: {cookies['unb']}") print(f"Token: {cookies['_m_h5_tk'].split('_')[0]}") ``` -------------------------------- ### Send Message with XianyuLive Source: https://context7.com/jeanmoumou/xianyuapis/llms.txt This method is used to send text messages within an established chat session. The message content is Base64 encoded before being sent over WebSocket. It requires the conversation ID, target user ID, and the message text. ```python import asyncio import json import websockets from XianyuAutoAsync import XianyuLive cookies_str = r'your_cookies_here' xianyu_live = XianyuLive(cookies_str) async def send_message_example(): headers = { "Cookie": cookies_str, "Host": "wss-goofish.dingtalk.com", "Origin": "https://www.goofish.com", } async with websockets.connect( 'wss://wss-goofish.dingtalk.com/', extra_headers=headers ) as ws: await xianyu_live.init(ws) await xianyu_live.create_chat(ws, '2202640918079', '897742748011') async for message in ws: msg = json.loads(message) if 'body' in msg and 'singleChatConversation' in msg['body']: cid = msg['body']['singleChatConversation']['cid'].split('@')[0] # Send message # Parameters: ws, cid (conversation ID), toid (target user), text (message content) await xianyu_live.send_msg( ws, cid, '2202640918079', 'Hello! Thank you for your inquiry. The item is still available. Please proceed to purchase if interested~' ) print("Message sent successfully") break asyncio.run(send_message_example()) ``` -------------------------------- ### Convert Cookie String to Dictionary Source: https://context7.com/jeanmoumou/xianyuapis/llms.txt The `trans_cookies` utility function converts a cookie string copied from a browser into a Python dictionary format, suitable for subsequent HTTP requests. It correctly handles cases where cookie values contain equal signs. ```python from utils.xianyu_utils import trans_cookies ``` -------------------------------- ### Generate Message ID and UUID Source: https://context7.com/jeanmoumou/xianyuapis/llms.txt Generates a message ID for WebSocket communication and a unique UUID for message deduplication. These are crucial for managing real-time message exchanges. ```python from utils.xianyu_utils import generate_mid, generate_uuid mid = generate_mid() print(f"消息 ID: {mid}") uuid = generate_uuid() print(f"UUID: {uuid}") ``` -------------------------------- ### trans_cookies - Cookie String Conversion Source: https://context7.com/jeanmoumou/xianyuapis/llms.txt A utility function to convert a cookie string copied from a browser into a Python dictionary format, suitable for use in HTTP requests. ```APIDOC ## Utility Function: trans_cookies ### Description Converts a cookie string, typically copied from a browser, into a Python dictionary format. This function correctly handles cookie values that may contain equals signs, making it easier to use cookies in subsequent HTTP requests. ### Method Function Call ### Endpoint N/A (Local utility function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from utils.xianyu_utils import trans_cookies cookies_str = r'_m_h5_tk=cd69ceb8b218792aaa87a25520ac2e42_1741675519283; unb=3888777108; ...' cookies_dict = trans_cookies(cookies_str) print(cookies_dict) ``` ### Response #### Success Response - **cookies_dict** (dict) - A dictionary representing the cookies, where keys are cookie names and values are cookie values. #### Response Example ```json { "_m_h5_tk": "cd69ceb8b218792aaa87a25520ac2e42_1741675519283", "unb": "3888777108" } ``` ``` -------------------------------- ### Decrypt WebSocket Messages Source: https://context7.com/jeanmoumou/xianyuapis/llms.txt Decrypts MessagePack encoded messages received from Xianyu's WebSocket. It decodes Base64 data and parses the content into a JSON format. Requires the `json` library for parsing. ```python from utils.xianyu_utils import decrypt import json encrypted_msg = "ggGLAYEBtTIyMDI2NDA5MTgwNzlAZ29vZmlzaAKzNDc4MTI4NzAwMDBAZ29vZmlzaAOxMzQwMzIwNTY4OTU4MS5QTk0EAAXPAAABlYXRFx8GggFlA4UBoAKkMTExMQOgBAEF2gA1eyJhdFVzZXJzIjpbXSwiY29udGVudFR5cGUiOjEsInRleHQiOnsidGV4dCI6IjExMTEifX0HAggBCQA..." decrypted = decrypt(encrypted_msg) message = json.loads(decrypted) print(f"发送者: {message['1']['10']['reminderTitle']}") print(f"消息内容: {message['1']['10']['reminderContent']}") ``` -------------------------------- ### XianyuLive.send_msg - Send Message Source: https://context7.com/jeanmoumou/xianyuapis/llms.txt Sends a text message within an established chat session. The message content is Base64 encoded before transmission via WebSocket. ```APIDOC ## POST /message/send ### Description Sends a text message within an established chat session. The message content is Base64 encoded before being sent via WebSocket. Requires the session ID, target user ID, and the message text. ### Method POST (via WebSocket message) ### Endpoint `wss://wss-goofish.dingtalk.com/` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body (Sent as a WebSocket message payload) - **cid** (str) - Required - The chat session ID. - **toid** (str) - Required - The ID of the target user. - **text** (str) - Required - The content of the message to send. ### Request Example ```python import asyncio import json import websockets from XianyuAutoAsync import XianyuLive cookies_str = r'your_cookies_here' xianyu_live = XianyuLive(cookies_str) async def send_message_example(): headers = { "Cookie": cookies_str, "Host": "wss-goofish.dingtalk.com", "Origin": "https://www.goofish.com", } async with websockets.connect( 'wss://wss-goofish.dingtalk.com/', extra_headers=headers ) as ws: await xianyu_live.init(ws) await xianyu_live.create_chat(ws, '2202640918079', '897742748011') async for message in ws: msg = json.loads(message) if 'body' in msg and 'singleChatConversation' in msg['body']: cid = msg['body']['singleChatConversation']['cid'].split('@')[0] await xianyu_live.send_msg( ws, cid, '2202640918079', '您好!感谢您的咨询,商品仍在售,有意请拍下~' ) print("消息发送成功") break asyncio.run(send_message_example()) ``` ### Response None (Success is typically indicated by the absence of an error message in the WebSocket stream after sending.) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.