### MilkyBot Framework Quick Start (Python) Source: https://github.com/notnotype/milky-python-sdk/blob/master/README_EN.md Example demonstrating how to initialize and run a bot using the MilkyBot framework. It showcases event handling for mentions and commands using decorators. ```python from milky import MilkyBot # Initialize bot with API endpoint and token bot = MilkyBot("http://localhost:3010", "your_token") @bot.on_mention() async def handle_mention(event): await bot.reply(event, "Hello!") @bot.on_command("echo") async def echo_command(event, args): if args: await bot.reply(event, args, at_sender=False) if __name__ == "__main__": bot.run() ``` -------------------------------- ### AsyncMilkyClient Quick Start (Python) Source: https://github.com/notnotype/milky-python-sdk/blob/master/README_EN.md Example showing how to use the AsyncMilkyClient for more direct integration into asynchronous Python applications. It demonstrates connecting and fetching login information. ```python import asyncio from milky import AsyncMilkyClient async def main(): async with AsyncMilkyClient("http://localhost:3010", "your_token") as client: info = await client.get_login_info() print(f"Logged in as: {info.nickname}") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Complex State Management (Conversation) with MilkyBot Source: https://github.com/notnotype/milky-python-sdk/blob/master/docs/AGENT.md Demonstrates how to manage conversational state using a defaultdict and bot decorators for command and message handling. This example is suitable for multi-step interactions. ```python from milky import MilkyBot from collections import defaultdict bot = MilkyBot("http://localhost:3010", "token") # Simple in-memory state: user_id -> step user_state = defaultdict(int) @bot.on_command("survey") async def start_survey(event, args): """Start a multi-step survey""" user_id = event["data"]["sender_id"] user_state[user_id] = 1 await bot.reply(event, "Step 1: What is your favorite color?") @bot.on_message("friend") async def handle_survey_response(event): user_id = event["data"]["sender_id"] state = user_state[user_id] if state == 1: color = bot._get_text(event) await bot.reply(event, f"You liked {color}. Step 2: What is your quest?") user_state[user_id] = 2 elif state == 2: quest = bot._get_text(event) await bot.reply(event, f"Quest: {quest}. Survey complete!") del user_state[user_id] ``` -------------------------------- ### MilkyBot Framework Example Source: https://context7.com/notnotype/milky-python-sdk/llms.txt Demonstrates the high-level MilkyBot framework for building QQ bots. It uses decorators to handle various events like mentions, commands, and messages. The bot is initialized with an API endpoint and an access token. ```python from milky import MilkyBot bot = MilkyBot("http://localhost:3010", "your_access_token") @bot.on_mention() async def handle_mention(event): """Triggered when bot is mentioned with @""" await bot.reply(event, "Hello! You mentioned me!") @bot.on_command("help") async def help_command(event, args): """Triggered by /help command""" await bot.reply(event, "Available commands: /help, /echo, /status", at_sender=False) @bot.on_command("echo") async def echo_command(event, args): """Echo user input back""" if args: await bot.reply(event, f"You said: {args}", at_sender=False) else: await bot.reply(event, "Usage: /echo ") @bot.on_message("group") async def log_group_messages(event): """Log all group messages""" data = event["data"] print(f"Group {data['peer_id']}: {data['segments']}") @bot.on_message("friend") async def handle_private(event): """Handle private messages""" text = bot._get_text(event) if "hello" in text.lower(): await bot.reply(event, "Hi there!") bot.run() # Start the bot (blocking) ``` -------------------------------- ### Install Milky Python SDK Source: https://github.com/notnotype/milky-python-sdk/blob/master/README_EN.md Command to install the Milky Python SDK using pip. This is the first step to using the SDK in your Python project. ```bash pip install milky-python-sdk ``` -------------------------------- ### Event Receiving via WebSocket Source: https://context7.com/notnotype/milky-python-sdk/llms.txt This code example shows how to receive events using a WebSocket connection, which requires the 'websockets' library. It sets up an event handler and an error handler, then starts a blocking WebSocket event listener. ```python from milky import MilkyClient client = MilkyClient("http://localhost:3010", "your_access_token") def handle_event(event): """Event handler callback""" event_type = event.get("event_type") print(f"Received: {event_type}") if event_type == "message_receive": data = event["data"] print(f"Message: {data['segments']}") def handle_error(error): """Error handler callback""" print(f"WebSocket error: {error}") # Start WebSocket event listener (blocking) client.events_ws(on_event=handle_event, on_error=handle_error) ``` -------------------------------- ### Dynamic API Usage and Error Handling with AsyncMilkyClient Source: https://github.com/notnotype/milky-python-sdk/blob/master/docs/AGENT.md Shows how to safely make dynamic API calls using `AsyncMilkyClient`, specifically demonstrating error handling for `MilkyHttpError` (like 404 Not Found) and general `MilkyError`. ```python from milky import AsyncMilkyClient, MilkyHttpError, MilkyError async def safe_get_info(client: AsyncMilkyClient, group_id: int): try: group_info = await client.get_group_info(group_id) print(f"Group Name: {group_info.group_name}") except MilkyHttpError as e: if e.status_code == 404: print("Group not found") else: print(f"Network error: {e}") except MilkyError as e: print(f"API logic error: {e.message}") ``` -------------------------------- ### Handling Image Uploads and Sending Images with MilkyBot Source: https://github.com/notnotype/milky-python-sdk/blob/master/docs/AGENT.md Illustrates how to process incoming image messages and send images back using `OutgoingImageSegment`. It assumes the server supports image URIs for sending. ```python from milky import MilkyBot from milky.models import OutgoingImageSegment, OutgoingImageSegmentData bot = MilkyBot("http://localhost:3010", "token") @bot.on_message("friend") async def echo_image(event): data = event["data"] for seg in data["segments"]: if seg["type"] == "image": image_id = seg["data"]["image_id"] # To send an image back, we can use the file_id if the server supports it, # or upload a new one. Here we demonstrate constructing an outgoing segment. # Assuming we have a URL or file path: message = [ OutgoingImageSegment( data=OutgoingImageSegmentData(image_uri="https://example.com/image.png") ) ] await bot.client.send_private_message(data["sender_id"], message) ``` -------------------------------- ### Manage Friends with Milky Python SDK Source: https://context7.com/notnotype/milky-python-sdk/llms.txt This snippet demonstrates how to manage friend requests, retrieve friend lists, get specific friend information, and send profile likes and nudges using the AsyncMilkyClient. It requires the 'milky' library and 'asyncio'. ```python from milky import AsyncMilkyClient import asyncio async def main(): async with AsyncMilkyClient("http://localhost:3010", "token") as client: # Get friend requests requests = await client.get_friend_requests(limit=20) for req in requests: print(f"Friend request from {req.requester_uin}: {req.message}") # Accept request await client.accept_friend_request( initiator_uid=req.initiator_uid, is_filtered=False ) # Get friend list friends = await client.get_friend_list(no_cache=False) for friend in friends: print(f"{friend.nickname} ({friend.user_id}) - {friend.remark}") # Get specific friend info friend_info = await client.get_friend_info(user_id=123456) print(f"Friend: {friend_info.nickname}, QID: {friend_info.qid}") # Send profile like await client.send_profile_like(user_id=123456, count=1) # Send friend nudge (poke) await client.send_friend_nudge(user_id=123456, is_self=False) asyncio.run(main()) ``` -------------------------------- ### Error Handling for API and HTTP Errors Source: https://context7.com/notnotype/milky-python-sdk/llms.txt This example provides comprehensive exception handling for potential errors when interacting with the Milky API. It specifically catches `MilkyHttpError` for issues like authentication failures or connection problems, and `MilkyError` for API-level errors such as invalid parameters or permission issues. A general `Exception` catch is included for unexpected errors. ```python from milky import AsyncMilkyClient from milky.async_client import MilkyError, MilkyHttpError import asyncio async def main(): async with AsyncMilkyClient("http://localhost:3010", "token") as client: try: # Attempt to send message message = [OutgoingTextSegment(data=TextSegmentData(text="Test"))] await client.send_group_message(group_id=123456, message=message) except MilkyHttpError as e: # HTTP-level errors (connection, timeout, 401, 404, etc.) if e.status_code == 401: print("Authentication failed: Invalid access token") elif e.status_code == 404: print(f"API endpoint not found") elif e.status_code == 0: print(f"Connection/timeout error: {e.message}") else: print(f"HTTP {e.status_code}: {e.message}") except MilkyError as e: # API-level errors (invalid parameters, permission denied, etc.) print(f"API Error [{e.retcode}]: {e.message}") if e.retcode == 10001: print("Invalid parameter provided") elif e.retcode == 10002: print("Permission denied") except Exception as e: print(f"Unexpected error: {e}") asyncio.run(main()) ``` -------------------------------- ### Async SSE Event Stream Processing Source: https://context7.com/notnotype/milky-python-sdk/llms.txt This snippet demonstrates asynchronous event stream processing using Server-Sent Events (SSE). It uses `AsyncMilkyClient` and iterates over events asynchronously. The example includes logic to detect if the bot is mentioned in a message and send a reply. ```python from milky import AsyncMilkyClient from milky.models import OutgoingTextSegment, TextSegmentData import asyncio async def main(): async with AsyncMilkyClient("http://localhost:3010", "your_access_token") as client: async for event in client.events_sse(): event_type = event.get("event_type") if event_type == "message_receive": data = event["data"] # Check if bot is mentioned bot_mentioned = False for seg in data["segments"]: if seg["type"] == "mention" and seg["data"]["user_id"] == 12345: bot_mentioned = True break if bot_mentioned: reply = [OutgoingTextSegment(data=TextSegmentData(text="You called?"))] if data["message_scene"] == "group": await client.send_group_message(data["peer_id"], reply) asyncio.run(main()) ``` -------------------------------- ### Retrieve Message History with Milky Python SDK Source: https://context7.com/notnotype/milky-python-sdk/llms.txt This snippet shows how to retrieve and paginate through message history for a group, including getting specific messages and marking them as read. It utilizes the AsyncMilkyClient and requires the 'milky' library and 'asyncio'. ```python from milky import AsyncMilkyClient from milky.models import MessageScene import asyncio async def main(): async with AsyncMilkyClient("http://localhost:3010", "token") as client: group_id = 123456 # Get first page of history messages, next_seq = await client.get_history_messages( message_scene=MessageScene.GROUP, peer_id=group_id, limit=20 ) print(f"Retrieved {len(messages)} messages") for msg in messages: print(f"Message {msg.get('message_seq')}: {msg.get('segments')}") # Paginate through history while next_seq is not None: messages, next_seq = await client.get_history_messages( message_scene=MessageScene.GROUP, peer_id=group_id, start_message_seq=next_seq, limit=20 ) print(f"Retrieved {len(messages)} more messages") # Get specific message message = await client.get_message( message_scene=MessageScene.GROUP, peer_id=group_id, message_seq=12345 ) print(f"Specific message: {message}") # Mark message as read await client.mark_message_as_read( message_scene=MessageScene.GROUP, peer_id=group_id, message_seq=12345 ) asyncio.run(main()) ``` -------------------------------- ### AsyncMilkyClient Usage Source: https://context7.com/notnotype/milky-python-sdk/llms.txt Shows how to use the AsyncMilkyClient for asynchronous operations. It demonstrates fetching login information, listing friends and groups, sending messages, retrieving group members, and muting users. Requires an active asyncio event loop. ```python from milky import AsyncMilkyClient from milky.models import OutgoingTextSegment, TextSegmentData import asyncio async def main(): async with AsyncMilkyClient("http://localhost:3010", "your_access_token") as client: # Get bot login info info = await client.get_login_info() print(f"Bot: {info.nickname} ({info.uin})") # Get friend and group lists friends = await client.get_friend_list() groups = await client.get_group_list() print(f"Friends: {len(friends)}, Groups: {len(groups)}") # Send a text message to a group message = [OutgoingTextSegment(data=TextSegmentData(text="Hello from async!"))] result = await client.send_group_message(group_id=123456, message=message) print(f"Message sent: {result.message_id}") # Get group member list members = await client.get_group_member_list(group_id=123456) for member in members[:5]: print(f"- {member.nickname} ({member.user_id})") # Mute a user for 60 seconds await client.set_group_member_mute( group_id=123456, user_id=789012, duration=60 ) asyncio.run(main()) ``` -------------------------------- ### Event Receiving via SSE Source: https://context7.com/notnotype/milky-python-sdk/llms.txt Illustrates how to initialize a MilkyClient to receive real-time events using Server-Sent Events (SSE). This is a foundational step for setting up event-driven communication. ```python from milky import MilkyClient client = MilkyClient("http://localhost:3010", "your_access_token") ``` -------------------------------- ### Manage Group Members and Settings Source: https://context7.com/notnotype/milky-python-sdk/llms.txt Perform comprehensive group administration tasks, including setting admin privileges, muting/unmuting members, kicking members, setting nicknames, sending announcements, and nudging users. This function utilizes the `AsyncMilkyClient` and requires group and user IDs. ```python from milky import AsyncMilkyClient import asyncio async def main(): async with AsyncMilkyClient("http://localhost:3010", "token") as client: group_id = 123456 user_id = 789012 # Set group member as admin await client.set_group_member_admin(group_id, user_id, is_set=True) # Mute user for 5 minutes (300 seconds) await client.set_group_member_mute(group_id, user_id, duration=300) # Unmute user await client.set_group_member_mute(group_id, user_id, duration=0) # Set group whole mute (all members muted except admins) await client.set_group_whole_mute(group_id, is_mute=True) # Kick member with rejection of future requests await client.kick_group_member( group_id=group_id, user_id=user_id, reject_add_request=True ) # Set member card (nickname in group) await client.set_group_member_card( group_id=group_id, user_id=user_id, card="New Nickname" ) # Set special title await client.set_group_member_special_title( group_id=group_id, user_id=user_id, special_title="Elite Member" ) # Send group nudge (poke) await client.send_group_nudge(group_id, user_id) # Get group announcements announcements = await client.get_group_announcements(group_id) for ann in announcements: print(f"Announcement: {ann.content}") # Create new announcement await client.send_group_announcement( group_id=group_id, content="Important: Meeting at 3PM tomorrow!" ) asyncio.run(main()) ``` -------------------------------- ### File Operations API Source: https://context7.com/notnotype/milky-python-sdk/llms.txt APIs for uploading, downloading, listing, organizing, and managing files and folders within groups. ```APIDOC ## Upload Group File ### Description Uploads a file to a specified group and folder. ### Method POST ### Endpoint /api/groups/{group_id}/files/upload ### Parameters #### Path Parameters - **group_id** (integer) - Required - The ID of the group. #### Request Body - **file_uri** (string) - Required - The URI of the file to upload (e.g., `file:///path/to/document.pdf`). - **file_name** (string) - Required - The desired name for the file in the group. - **parent_folder_id** (string) - Required - The ID of the parent folder where the file should be uploaded. Use `/` for the root. ### Response #### Success Response (200) - **file_id** (string) - The unique identifier of the uploaded file. #### Response Example ```json { "file_id": "file_xyz789abc" } ``` ``` ```APIDOC ## List Group Files and Folders ### Description Lists files and subfolders within a specified group folder. ### Method GET ### Endpoint /api/groups/{group_id}/files ### Parameters #### Path Parameters - **group_id** (integer) - Required - The ID of the group. #### Query Parameters - **parent_folder_id** (string) - Required - The ID of the folder to list contents from. Use `/` for the root. ### Response #### Success Response (200) - **files** (array) - A list of file objects. - **file_name** (string) - The name of the file. - **file_size** (integer) - The size of the file in bytes. - **file_id** (string) - The unique identifier of the file. - **folders** (array) - A list of folder objects. - **folder_name** (string) - The name of the folder. - **folder_id** (string) - The unique identifier of the folder. #### Response Example ```json { "files": [ {"file_name": "important_document.pdf", "file_size": 102400, "file_id": "file_xyz789abc"} ], "folders": [ {"folder_name": "Shared Documents", "folder_id": "folder_uvw456def"} ] } ``` ``` ```APIDOC ## Create Group Folder ### Description Creates a new folder within a specified group. ### Method POST ### Endpoint /api/groups/{group_id}/folders ### Parameters #### Path Parameters - **group_id** (integer) - Required - The ID of the group. #### Request Body - **folder_name** (string) - Required - The name for the new folder. - **parent_folder_id** (string) - Required - The ID of the parent folder. Use `/` for the root. ### Response #### Success Response (200) - **folder_id** (string) - The unique identifier of the created folder. #### Response Example ```json { "folder_id": "folder_uvw456def" } ``` ``` ```APIDOC ## Move Group File ### Description Moves a file from one folder to another within the same group. ### Method PUT ### Endpoint /api/groups/{group_id}/files/{file_id}/move ### Parameters #### Path Parameters - **group_id** (integer) - Required - The ID of the group. - **file_id** (string) - Required - The ID of the file to move. #### Request Body - **parent_folder_id** (string) - Required - The current folder ID of the file. - **target_folder_id** (string) - Required - The ID of the destination folder. ### Response #### Success Response (200) Empty response body on success. ``` ```APIDOC ## Get Group File Download URL ### Description Retrieves a temporary download URL for a group file. ### Method GET ### Endpoint /api/groups/{group_id}/files/{file_id}/download-url ### Parameters #### Path Parameters - **group_id** (integer) - Required - The ID of the group. - **file_id** (string) - Required - The ID of the file. ### Response #### Success Response (200) - **url** (string) - The temporary URL to download the file. #### Response Example ```json { "url": "https://example.com/download/path/to/file.pdf?token=..." } ``` ``` ```APIDOC ## Rename Group File ### Description Renames a file within a group. ### Method PUT ### Endpoint /api/groups/{group_id}/files/{file_id}/rename ### Parameters #### Path Parameters - **group_id** (integer) - Required - The ID of the group. - **file_id** (string) - Required - The ID of the file to rename. #### Request Body - **new_file_name** (string) - Required - The new name for the file. - **parent_folder_id** (string) - Required - The ID of the folder containing the file. ### Response #### Success Response (200) Empty response body on success. ``` ```APIDOC ## Delete Group File ### Description Deletes a file from a group. ### Method DELETE ### Endpoint /api/groups/{group_id}/files/{file_id} ### Parameters #### Path Parameters - **group_id** (integer) - Required - The ID of the group. - **file_id** (string) - Required - The ID of the file to delete. ### Response #### Success Response (200) Empty response body on success. ``` -------------------------------- ### MilkyClient Usage Source: https://context7.com/notnotype/milky-python-sdk/llms.txt Demonstrates the synchronous MilkyClient for traditional blocking operations. It covers sending text and mention messages to groups, retrieving group information, recalling messages, and utilizing the client as a context manager. Ensure to close the client when done if not using a context manager. ```python from milky import MilkyClient from milky.models import ( OutgoingTextSegment, TextSegmentData, OutgoingMentionSegment, MentionSegmentData ) # Initialize client client = MilkyClient("http://localhost:3010", "your_access_token") # Get login information info = client.get_login_info() print(f"Logged in as: {info.nickname}") # Send text message to group message = [OutgoingTextSegment(data=TextSegmentData(text="Hello World!"))] result = client.send_group_message(group_id=123456, message=message) # Send mention + text message mention_message = [ OutgoingMentionSegment(data=MentionSegmentData(user_id=789012)), OutgoingTextSegment(data=TextSegmentData(text=" Check this out!")) ] client.send_group_message(group_id=123456, message=mention_message) # Get group information group = client.get_group_info(group_id=123456) print(f"Group: {group.group_name}, Members: {group.member_count}/{group.max_member_count}") # Recall a message client.recall_group_message(group_id=123456, message_seq=12345) # Context manager support with MilkyClient("http://localhost:3010", "token") as client: friends = client.get_friend_list() print(f"Total friends: {len(friends)}") client.close() ``` -------------------------------- ### Group Management API Source: https://context7.com/notnotype/milky-python-sdk/llms.txt Comprehensive group administration functions including member management, muting, and announcements. ```APIDOC ## Set Group Member Admin ### Description Sets or unsets a group member's administrative privileges. ### Method PUT ### Endpoint /api/groups/{group_id}/members/{user_id}/admin ### Parameters #### Path Parameters - **group_id** (integer) - Required - The ID of the group. - **user_id** (integer) - Required - The ID of the user to modify. #### Query Parameters - **is_set** (boolean) - Required - Set to `true` to make the user an admin, `false` to remove admin privileges. ### Response #### Success Response (200) Empty response body on success. ``` ```APIDOC ## Set Group Member Mute ### Description Mutes or unmutes a specific group member. ### Method PUT ### Endpoint /api/groups/{group_id}/members/{user_id}/mute ### Parameters #### Path Parameters - **group_id** (integer) - Required - The ID of the group. - **user_id** (integer) - Required - The ID of the user to mute/unmute. #### Query Parameters - **duration** (integer) - Required - The duration of the mute in seconds. Set to `0` to unmute. ### Response #### Success Response (200) Empty response body on success. ``` ```APIDOC ## Set Group Whole Mute ### Description Mutes or unmutes all members in a group (except admins). ### Method PUT ### Endpoint /api/groups/{group_id}/mute ### Parameters #### Path Parameters - **group_id** (integer) - Required - The ID of the group. #### Query Parameters - **is_mute** (boolean) - Required - Set to `true` to mute all members, `false` to unmute. ### Response #### Success Response (200) Empty response body on success. ``` ```APIDOC ## Kick Group Member ### Description Removes a member from a group, optionally rejecting future join requests from them. ### Method DELETE ### Endpoint /api/groups/{group_id}/members/{user_id} ### Parameters #### Path Parameters - **group_id** (integer) - Required - The ID of the group. - **user_id** (integer) - Required - The ID of the user to kick. #### Query Parameters - **reject_add_request** (boolean) - Optional - If `true`, the user will be rejected from future join requests. ### Response #### Success Response (200) Empty response body on success. ``` ```APIDOC ## Set Group Member Card ### Description Sets a custom nickname (card) for a group member. ### Method PUT ### Endpoint /api/groups/{group_id}/members/{user_id}/card ### Parameters #### Path Parameters - **group_id** (integer) - Required - The ID of the group. - **user_id** (integer) - Required - The ID of the user whose card to set. #### Request Body - **card** (string) - Required - The new nickname for the group member. ### Response #### Success Response (200) Empty response body on success. ``` ```APIDOC ## Set Group Member Special Title ### Description Assigns a special title to a group member. ### Method PUT ### Endpoint /api/groups/{group_id}/members/{user_id}/special-title ### Parameters #### Path Parameters - **group_id** (integer) - Required - The ID of the group. - **user_id** (integer) - Required - The ID of the user to assign the title to. #### Request Body - **special_title** (string) - Required - The special title to assign. ### Response #### Success Response (200) Empty response body on success. ``` ```APIDOC ## Send Group Nudge ### Description Sends a nudge (poke) to a specific member within a group. ### Method POST ### Endpoint /api/groups/{group_id}/members/{user_id}/nudge ### Parameters #### Path Parameters - **group_id** (integer) - Required - The ID of the group. - **user_id** (integer) - Required - The ID of the user to nudge. ### Response #### Success Response (200) Empty response body on success. ``` ```APIDOC ## Get Group Announcements ### Description Retrieves a list of announcements for a group. ### Method GET ### Endpoint /api/groups/{group_id}/announcements ### Parameters #### Path Parameters - **group_id** (integer) - Required - The ID of the group. ### Response #### Success Response (200) - **announcements** (array) - A list of announcement objects. - **content** (string) - The content of the announcement. #### Response Example ```json { "announcements": [ {"content": "Meeting at 3PM tomorrow!"} ] } ``` ``` ```APIDOC ## Send Group Announcement ### Description Creates a new announcement for a group. ### Method POST ### Endpoint /api/groups/{group_id}/announcements ### Parameters #### Path Parameters - **group_id** (integer) - Required - The ID of the group. #### Request Body - **content** (string) - Required - The content of the announcement. ### Response #### Success Response (200) Empty response body on success. ``` -------------------------------- ### Manage Group Files Source: https://context7.com/notnotype/milky-python-sdk/llms.txt Perform file operations within groups, including uploading, listing, creating folders, moving, renaming, and deleting files. This function requires the `AsyncMilkyClient` and group/file identifiers. It supports operations on files and folders. ```python from milky import AsyncMilkyClient import asyncio async def main(): async with AsyncMilkyClient("http://localhost:3010", "token") as client: group_id = 123456 # Upload file to group upload_result = await client.upload_group_file( group_id=group_id, file_uri="file:///path/to/document.pdf", file_name="important_document.pdf", parent_folder_id="/" ) print(f"File uploaded: {upload_result.file_id}") # List group files and folders files, folders = await client.get_group_files( group_id=group_id, parent_folder_id="/" ) print("Files:") for file in files: print(f" - {file.file_name} ({file.file_size} bytes)") print("Folders:") for folder in folders: print(f" - {folder.folder_name}") # Create new folder folder_result = await client.create_group_folder( group_id=group_id, folder_name="Shared Documents" ) # Move file to folder await client.move_group_file( group_id=group_id, file_id=upload_result.file_id, parent_folder_id="/", target_folder_id=folder_result.folder_id ) # Get download URL for a file download_url = await client.get_group_file_download_url( group_id=group_id, file_id=upload_result.file_id ) print(f"Download URL: {download_url.url}") # Rename file await client.rename_group_file( group_id=group_id, file_id=upload_result.file_id, new_file_name="renamed_document.pdf", parent_folder_id=folder_result.folder_id ) # Delete file await client.delete_group_file(group_id=group_id, file_id=upload_result.file_id) asyncio.run(main()) ``` -------------------------------- ### Advanced Message Composition Source: https://context7.com/notnotype/milky-python-sdk/llms.txt Send complex messages with multiple segment types, including mentions, text, and images. ```APIDOC ## Send Group Message ### Description Sends a message to a group, allowing for rich content with multiple segment types. ### Method POST ### Endpoint /api/groups/{group_id}/messages ### Parameters #### Path Parameters - **group_id** (integer) - Required - The ID of the group to send the message to. #### Request Body - **message** (array) - Required - An array of message segments, each defining a part of the message (e.g., text, mention, image). - **type** (string) - Required - The type of the segment (e.g., `text`, `mention`, `image`). - **data** (object) - Required - The data for the segment, varying by type. - For `mention` type: **user_id** (integer) - Required. - For `text` type: **text** (string) - Required. - For `image` type: **file_uri** (string) - Required, **sub_type** (string, enum: `NORMAL`, `THUMBNAIL`) - Required. ### Request Example ```json { "message": [ { "type": "mention", "data": {"user_id": 123456} }, { "type": "text", "data": {"text": "Check this out:\n"} }, { "type": "image", "data": {"file_uri": "file:///path/to/image.jpg", "sub_type": "NORMAL"} } ] } ``` ### Response #### Success Response (200) - **message_id** (string) - The unique identifier of the sent message. #### Response Example ```json { "message_id": "msg_abc123xyz" } ``` ``` -------------------------------- ### Synchronous SSE Event Stream Processing Source: https://context7.com/notnotype/milky-python-sdk/llms.txt This snippet demonstrates how to process events from a synchronous Server-Sent Events (SSE) stream. It iterates over incoming events, extracts message data, and conditionally replies to messages containing 'hello'. It handles different event types like 'message_receive', 'friend_request', and 'group_member_increase'. ```python for event in client.events_sse(): event_type = event.get("event_type") if event_type == "message_receive": data = event["data"] print(f"Message from {data['sender_id']}: {data['segments']}") # Extract text from segments text_parts = [] for seg in data["segments"]: if seg["type"] == "text": text_parts.append(seg["data"]["text"]) message_text = "".join(text_parts) # Reply to messages containing "hello" if "hello" in message_text.lower(): reply = [OutgoingTextSegment(data=TextSegmentData(text="Hi!"))] if data["message_scene"] == "group": client.send_group_message(data["peer_id"], reply) elif data["message_scene"] == "friend": client.send_private_message(data["sender_id"], reply) elif event_type == "friend_request": print(f"Friend request from {event['data']['requester_uin']}") elif event_type == "group_member_increase": print(f"New member joined group {event['data']['group_id']}") ``` -------------------------------- ### Compose Advanced Messages with Multiple Segments Source: https://context7.com/notnotype/milky-python-sdk/llms.txt Send messages containing various elements like mentions, text, and images. This function requires the `AsyncMilkyClient` and specific model classes for message segments. It returns the ID of the sent message. ```python from milky import AsyncMilkyClient from milky.models import ( OutgoingTextSegment, OutgoingMentionSegment, OutgoingImageSegment, TextSegmentData, MentionSegmentData, OutgoingImageSegmentData, ImageSubType ) import asyncio async def main(): async with AsyncMilkyClient("http://localhost:3010", "token") as client: # Complex message: mention + text + image message = [ OutgoingMentionSegment(data=MentionSegmentData(user_id=123456)), OutgoingTextSegment(data=TextSegmentData(text=" Check this out:\n")), OutgoingImageSegment(data=OutgoingImageSegmentData( file_uri="file:///path/to/image.jpg", sub_type=ImageSubType.NORMAL )) ] result = await client.send_group_message(group_id=789012, message=message) print(f"Sent message ID: {result.message_id}") asyncio.run(main()) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.