### Admin Command Example (V11) Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/README.md An example of creating an admin-only command using the V11 adapter's GROUP_ADMIN permission. ```python from nonebot import on_command from nonebot.adapters.onebot.v11 import GROUP_ADMIN matcher = on_command("admin_cmd", permission=GROUP_ADMIN) @matcher.handle() async def handle(event): await matcher.finish("Admin action completed!") ``` -------------------------------- ### Install Nonebot Adapter Onebot Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/README.md Install the adapter using pip. ```bash pip install nonebot-adapter-onebot ``` -------------------------------- ### OneBot V12 Msgpack Configuration Examples Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/types.md Examples demonstrating how to enable msgpack encoding globally or for specific implementations within the OneBot v12 adapter configuration. ```python # Enable msgpack globally ONEBOT_USE_MSGPACK=true # Enable msgpack for specific implementation ONEBOT_USE_MSGPACK={"qq": true, "telegram": false} ``` -------------------------------- ### Basic WebSocket Setup Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/configuration.md Minimal configuration for establishing a WebSocket connection to the OneBot API. ```env ONEBOT_WS_URLS=["ws://127.0.0.1:5700"] ``` -------------------------------- ### Bot send Method Examples Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/v12-bot.md Examples demonstrating how to use the send method to send a simple text message or a message with additional options like mentioning the sender and quoting. ```python await bot.send(event, "Hello world!") await bot.send(event, "Thanks!", at_sender=True, reply_message=True) ``` -------------------------------- ### Configuration Priority Example Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/configuration.md Demonstrates how generic and version-specific environment variables are prioritized. Version-specific variables override generic ones for their respective OneBot versions. ```env ONEBOT_ACCESS_TOKEN=shared_token ONEBOT_V11_ACCESS_TOKEN=v11_specific_token # Only used by V11 ONEBOT_V12_ACCESS_TOKEN=v12_specific_token # Only used by V12 ``` -------------------------------- ### Echo Bot Example (V11) Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/README.md A simple echo bot using the V11 adapter that replies to messages with the same content. ```python from nonebot import on_message from nonebot.adapters.onebot.v11 import MessageEvent matcher = on_message() @matcher.handle() async def handle(event: MessageEvent): await bot.send(event, event.message) ``` -------------------------------- ### V11 Configuration Example Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/README.md Configuration parameters for the OneBot V11 adapter, including access token, secret, WebSocket URLs, and API roots. ```python ONEBOT_ACCESS_TOKEN=token # Authorization token ONEBOT_SECRET=secret # HMAC-SHA1 secret ONEBOT_WS_URLS=["ws://..."] # WebSocket URLs ONEBOT_API_ROOTS={"id": "http://..."} # HTTP API endpoints ``` -------------------------------- ### Example: Creating and Combining Message Segments Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/v12-message.md Demonstrates creating a location segment and a text segment, then combining them into a single message. ```python seg = MessageSegment.location(39.9, 116.4, "Beijing", "China") msg = MessageSegment.reply("msg_123") + MessageSegment.text("Good point!") ``` -------------------------------- ### HTTP-Only Setup Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/configuration.md Configure the adapter to use HTTP polling instead of WebSocket, including API roots and an access token. ```env ONEBOT_API_ROOTS={"123456789": "http://127.0.0.1:5700"} ONEBOT_ACCESS_TOKEN=my_token ``` -------------------------------- ### V12 Configuration Example Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/README.md Configuration parameters for the OneBot V12 adapter, including access token, WebSocket URLs, API roots, and MessagePack enablement. ```python ONEBOT_ACCESS_TOKEN=token # Authorization token ONEBOT_WS_URLS=["ws://..."] # WebSocket URLs ONEBOT_API_ROOTS={"id": "http://..."} # HTTP API endpoints ONEBOT_USE_MSGPACK=true # Enable MessagePack ``` -------------------------------- ### Single Permission Matcher Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/permissions.md Example of creating a message matcher that triggers only for group admins. ```python from nonebot import on_message from nonebot.adapters.onebot.v11 import GROUP_ADMIN # Only group admins can trigger matcher = on_message(permission=GROUP_ADMIN) ``` -------------------------------- ### Secure HTTP Setup with Signature Verification Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/configuration.md Set up an HTTP connection with enhanced security using an access token and HMAC secret key for signature verification. ```env ONEBOT_API_ROOTS={"123456789": "http://127.0.0.1:5700"} ONEBOT_ACCESS_TOKEN=my_token ONEBOT_SECRET=hmac_secret_key ``` -------------------------------- ### OneBot V12 HTTP API Request Example Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/endpoints.md Example of an HTTP POST request to a OneBot V12 API endpoint for sending a message. ```http POST http://127.0.0.1:5700/send_message ``` -------------------------------- ### API Error Response Example (JSON) Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/endpoints.md This is an example of an API error response from the OneBot adapter. It indicates a failed request with a specific retcode and message. ```json { "status": "failed", "retcode": 1102, "msg": "Invalid action", "echo": "1" } ``` -------------------------------- ### Image Processing Example (V11) Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/README.md Extracts image URLs from messages using the V11 adapter's helper function for further processing. ```python from nonebot.adapters.onebot.v11.helpers import extract_image_urls matcher = on_message() @matcher.handle() async def handle(event: MessageEvent): urls = extract_image_urls(event.message) for url in urls: # Process image pass ``` -------------------------------- ### Basic Message Handler (V11) Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/README.md Example of a basic message handler for Onebot V11 that responds to messages from superusers. ```python from nonebot import on_message from nonebot.adapters.onebot.v11 import MessageEvent from nonebot.permission import SUPERUSER matcher = on_message(permission=SUPERUSER) @matcher.handle() async def handle(event: MessageEvent): await bot.send(event, "Hello!") ``` -------------------------------- ### Valid Configuration Data Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/configuration.md Example of a valid configuration dictionary that passes Pydantic validation. Note that 'onebot_ws_urls' is converted to a set. ```python config_data = { "onebot_access_token": "token123", "onebot_ws_urls": ["ws://127.0.0.1:5700"], # Converted to set "onebot_api_roots": {"123": "http://127.0.0.1:5700"}, } ``` -------------------------------- ### Basic Message Handler (V12) Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/README.md Example of a basic message handler for Onebot V12 that responds to messages from superusers. ```python from nonebot import on_message from nonebot.adapters.onebot.v12 import MessageEvent from nonebot.permission import SUPERUSER matcher = on_message(permission=SUPERUSER) @matcher.handle() async def handle(event: MessageEvent): await bot.send(event, "Hello!") ``` -------------------------------- ### Combine Permissions with AND Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/permissions.md Use the bitwise AND operator to combine permissions, requiring all specified conditions to be met for a matcher to trigger. This example requires the message to be from an allowed group AND a trusted user. ```python from nonebot.permission import Permission from nonebot.adapters.onebot.v11 import GroupMessageEvent async def is_allowed_group(event: GroupMessageEvent) -> bool: allowed_groups = {123456789, 987654321} return event.group_id in allowed_groups async def is_trusted_user(event: GroupMessageEvent) -> bool: trusted_users = {111, 222, 333} return event.user_id in trusted_users permission = Permission(is_allowed_group) & Permission(is_trusted_user) matcher = on_message(permission=permission) ``` -------------------------------- ### Example: Define InvalidAction with Retcode Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/errors.md Example of subclassing ActionFailedWithRetcode to handle specific API retcodes. This class triggers on retcode '10001'. ```python # Subclasses define their retcode values class InvalidAction(ActionFailedWithRetcode): __retcode__ = ("10001",) # Triggered when API returns retcode 10001 ``` -------------------------------- ### Example OneBot V11 WebSocket URL Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/endpoints.md The URL format for establishing a WebSocket connection to the OneBot V11 server endpoint. Ensure the host and port are correct. ```text ws://localhost:8080/onebot/v11/ws ``` -------------------------------- ### Example OneBot V11 HTTP POST Request Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/endpoints.md Demonstrates how to send an event to the OneBot V11 HTTP endpoint using curl. Requires specific headers and a JSON body. ```bash curl -X POST http://localhost:8080/onebot/v11/http \ -H "x-self-id: 123456789" \ -H "content-type: application/json" \ -d '{ "time": 1234567890, "self_id": 123456789, "post_type": "message", "message_type": "private", "sub_type": "friend", "message_id": 1, "user_id": 987654321, "message": "Hello" }' ``` -------------------------------- ### Bot Send Function Examples Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/v12-bot.md Illustrates how to use the bot's send function for private messages, group messages with sender mentions, and messages that reply to a specific event. ```python # Private message await bot.send(private_event, "Hi!") ``` ```python # Group with mention await bot.send(group_event, "Thanks!", at_sender=True) ``` ```python # With reply await bot.send(event, "Good point!", reply_message=True) ``` -------------------------------- ### Example OneBot HTTP API POST Request Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/endpoints.md Demonstrates an HTTP POST request to a OneBot implementation's API endpoint for sending a message. Requires specific headers and a JSON body. ```http POST http://127.0.0.1:5700/send_msg Content-Type: application/json Authorization: Bearer my_token { "message_type": "private", "user_id": 987654321, "message": "Hello" } ``` -------------------------------- ### Implement and Register Custom Send Handler Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/v12-bot.md Provides an example of a custom send function that preprocesses messages and registers it with the OneBot V12 adapter for a specific platform. Requires importing Adapter. ```python async def custom_send(bot: Bot, event: Event, message): # Custom logic before sending if isinstance(message, str): message = Message.text(message) # Add custom attributes response = await bot.call_api( "send_message", detail_type="private", user_id=event.user_id, message=message, custom_field="value" # Implementation-specific ) return response # Register custom handler from nonebot.adapters.onebot.v12 import Adapter Adapter.custom_send(custom_send, impl="qq") ``` -------------------------------- ### Combine Permissions with OR Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/permissions.md Use the bitwise OR operator to combine permissions, allowing a matcher to trigger if any of the specified conditions are met. This example allows messages from group members or private messages from friends. ```python from nonebot.permission import Permission from nonebot.adapters.onebot.v11 import ( GROUP_MEMBER, GROUP_ADMIN, GROUP_OWNER, PRIVATE_FRIEND, PrivateMessageEvent, GroupMessageEvent ) # Member in group OR friend private permission = (GROUP_MEMBER) | (PRIVATE_FRIEND) matcher = on_message(permission=permission) ``` -------------------------------- ### Test WebSocket Connection and API Call Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/endpoints.md This Python script demonstrates how to connect to the WebSocket endpoint, send an API call to get self information, and receive the response. The 'x-self-id' header is required for authentication. ```python import asyncio import json import websockets async def test(): uri = "ws://localhost:8080/onebot/v11/ws" async with websockets.connect( uri, extra_headers={"x-self-id": "123456789"} ) as websocket: # Send API call await websocket.send(json.dumps({ "action": "get_self_info", "params": {}, "echo": "1" })) # Receive response response = await websocket.recv() print(response) asyncio.run(test()) ``` -------------------------------- ### Multi-Platform Bot Logic (V12) Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/README.md Demonstrates how to implement platform-specific logic within a V12 adapter bot. ```python from nonebot.adapters.onebot.v12 import Bot, MessageEvent async def handle(bot: Bot, event: MessageEvent): if bot.platform == "qq": # QQ-specific pass elif bot.platform == "telegram": # Telegram-specific pass ``` -------------------------------- ### Get Segment Class Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/v12-message.md Retrieve the MessageSegment class associated with the Message class. ```python @classmethod def get_segment_class(cls) -> type[MessageSegment]: pass ``` -------------------------------- ### Extract Image URLs from Message Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/README.md Use extract_image_urls helper to get a list of image URLs from a message. ```python from nonebot.adapters.onebot.v11.helpers import extract_image_urls urls = extract_image_urls(event.message) ``` -------------------------------- ### Extract Plain Text from Message Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/README.md Get the plain text content of a message by using the extract_plain_text method. ```python # Plain text text = event.message.extract_plain_text() ``` -------------------------------- ### V12 Message Structure Example Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/v12-message.md A V12 message is a JSON array of segment objects, each with a 'type' and 'data' field. ```json [{"type": "text", "data": {"text": "Hello "}}, {"type": "mention", "data": {"user_id": "12345"}}, {"type": "text", "data": {"text": "!"}}] ``` -------------------------------- ### V12 with MessagePack Optimization Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/configuration.md Configure the adapter for v12 compatibility and optimize communication by enabling MessagePack serialization. ```env ONEBOT_WS_URLS=["ws://127.0.0.1:5700"] ONEBOT_USE_MSGPACK=true ONEBOT_ACCESS_TOKEN=my_token ``` -------------------------------- ### Documentation File Structure Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/COMPLETION_REPORT.md This structure shows the organization of documentation files within the project, including the main navigation, API references, and configuration details. ```text /workspace/home/output/ ├── INDEX.md (Complete navigation guide) ├── README.md (Getting started) ├── configuration.md (Configuration reference) ├── endpoints.md (HTTP/WebSocket routes) ├── errors.md (Error handling) ├── types.md (Type definitions) └── api-reference/ ├── v11-adapter.md (V11 Adapter API) ├── v11-bot.md (V11 Bot API) ├── v11-message.md (V11 Message API) ├── v11-event.md (V11 Event types) ├── v12-adapter.md (V12 Adapter API) ├── v12-bot.md (V12 Bot API) ├── v12-message.md (V12 Message API) ├── utilities.md (Helper functions) └── permissions.md (Permission system) ``` -------------------------------- ### Multiple Permissions (AND) Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/permissions.md Demonstrates the syntax for combining permissions using the AND operator. Note that combining GROUP and PRIVATE permissions is contradictory and will never match. ```python from nonebot.permission import Permission from nonebot.adapters.onebot.v11 import GROUP, PRIVATE # This example doesn't make practical sense but shows syntax # permission = GROUP & PRIVATE # Never matches (contradictory) ``` -------------------------------- ### get_auth_bearer Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/utilities.md Extracts the bearer token from an Authorization header string. Returns None if the header is not present or does not start with 'Bearer '. ```APIDOC ## get_auth_bearer ### Description Extract bearer token from Authorization header. ### Signature ```python def get_auth_bearer(authorization: Optional[str]) -> Optional[str] ``` ### Parameters #### Path Parameters - **authorization** (Optional[str]) - Authorization header value ### Returns Bearer token or None ### Example ```python token = get_auth_bearer("Bearer my_token_123") # Result: "my_token_123" token = get_auth_bearer("Basic xyz") # Result: None ``` ``` -------------------------------- ### Adapter Instance Methods Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/v12-adapter.md Methods for interacting with a specific instance of the OneBot V12 adapter, primarily for calling OneBot APIs. ```APIDOC ## _call_api ### Description Calls a OneBot API action with automatic encoding detection (MessagePack or JSON) for requests and responses. ### Method `async def _call_api(self, bot: Bot, api: str, **data: Any) -> Any` ### Parameters #### Path Parameters - **bot** (`Bot`) - Required - The Bot instance to use for the API call. - **api** (`str`) - Required - The name of the API action to call. - **data** (`Any`) - Optional - Additional parameters for the API action. ### Returns - `Any` - The data returned by the API call. ### Raises - `NetworkError` - If the connection fails or times out. - `ApiNotAvailable` - If no active connection is available. - `ActionMissingField` - If the API response is missing required fields. - `ActionFailedWithRetcode` - If the API returns an error, with the specific exception type depending on the retcode. ### Encoding - Uses MessagePack if `onebot_use_msgpack` is enabled. - Falls back to JSON if MessagePack is not enabled. - Handles both request and response encoding automatically. ### Example ```python result = await adapter._call_api(bot, 'send_message', detail_type='private', user_id='123', message=[...]) ``` ``` -------------------------------- ### Load OneBot Configuration Dynamically Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/configuration.md Retrieve the OneBot adapter configuration at runtime using `get_plugin_config`. Access properties like `onebot_access_token` and `onebot_ws_urls` to customize behavior. ```python from nonebot import get_plugin_config from nonebot.adapters.onebot.v11 import Config async def my_handler(): config = get_plugin_config(Config) # Use config if config.onebot_access_token: print("Authentication enabled") for url in config.onebot_ws_urls: print(f"Connecting to {url}") ``` -------------------------------- ### Enable MessagePack Encoding Globally Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/v12-adapter.md Configure the adapter to use MessagePack for all requests and responses to improve efficiency by enabling binary encoding. This reduces bandwidth and processing time. ```python onebot_use_msgpack = True ``` -------------------------------- ### Get User Information via Bot API Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/README.md Retrieve user details by calling the get_user_info method with a user ID. ```python # Get user info info = await bot.get_user_info(user_id=456) ``` -------------------------------- ### Enable MessagePack Per-Implementation Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/endpoints.md Configure MessagePack usage on a per-implementation basis by setting ONEBOT_USE_MSGPACK to a dictionary specifying which implementations should use it. ```python # Per-implementation ONEBOT_USE_MSGPACK = { "qq": True, "telegram": False } ``` -------------------------------- ### Register Custom Event Model for QQ Implementation Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/v12-adapter.md Register a custom event model for a specific implementation like 'qq'. This allows the adapter to correctly parse and handle implementation-specific event data. ```python class QQSpecificEvent(Event): qq_specific_field: str Adapter.add_custom_model(QQSpecificEvent, impl="qq") ``` -------------------------------- ### Configure Onebot WebSocket Connection Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/README.md Configure WebSocket URLs and optional access token in a .env file. ```python # .env or .env.* ONEBOT_WS_URLS=["ws://127.0.0.1:5700"] # WebSocket connection ONEBOT_ACCESS_TOKEN=your_token # Optional: Authorization ``` -------------------------------- ### Create a logger for OneBot V11 Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/utilities.md Initializes a logger instance for the OneBot V11 adapter. Use this to create custom loggers for specific modules. ```python from nonebot.adapters.onebot.v11.utils import logger_wrapper log = logger_wrapper("OneBot V11") ``` -------------------------------- ### Enable MessagePack Globally Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/endpoints.md Set the ONEBOT_USE_MSGPACK environment variable to True to enable MessagePack encoding for all implementations. ```python # Global ONEBOT_USE_MSGPACK = True ``` -------------------------------- ### Message Construction Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/v12-message.md Demonstrates how to construct a Message object from strings, MessageSegments, or a combination of both. ```APIDOC ## Message Construction ### Description Constructs a `Message` object from various inputs including strings, lists of `MessageSegment` objects, or by combining segments. ### Usage ```python # From string msg = Message("Hello") # From segments msg = Message([ MessageSegment.mention("123"), MessageSegment.text(" Hello!") ]) # From mixed msg = MessageSegment.text("Hi ") + MessageSegment.image("img_123") ``` ``` -------------------------------- ### Invalid Configuration Data Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/configuration.md Example of an invalid configuration dictionary that will raise a ValidationError due to incorrect URL format and wrong type for API roots. ```python config_data = { "onebot_ws_urls": ["not-a-url"], # Invalid URL format "onebot_api_roots": ["not-a-dict"], # Wrong type } ``` -------------------------------- ### Extract and Process Numbers from Text Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/utilities.md Use `extract_numbers` to get all numerical values from a message string. This is useful for parsing commands that require numerical input. ```python from nonebot.adapters.onebot.v11.helpers import ( extract_numbers, convert_chinese_to_bool, ) # Extract and process numbers numbers = extract_numbers(event.message) total = sum(numbers) # Get yes/no confirmation response = convert_chinese_to_bool(event.message) if response is True: # User confirmed pass ``` -------------------------------- ### Working with Mentions Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/v12-message.md Create messages that mention specific users or all users using MessageSegment.mention and MessageSegment.mention_all. ```python from nonebot.adapters.onebot.v12 import Message, MessageSegment # Mention specific user msg = ( MessageSegment.mention("user_456") + MessageSegment.text(" please check this") ) # Mention everyone msg = ( MessageSegment.mention_all() + MessageSegment.text(": important announcement") ) await bot.send(event, msg) ``` -------------------------------- ### HandleCancellation Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/utilities.md Dependency injection utility to handle cancellation detection within command handlers. ```APIDOC ## HandleCancellation ### Description Dependency for cancellation detection. ### Function Signature ```python def HandleCancellation(cancel_prompt: Optional[str] = None) -> bool ``` ### Parameters #### cancel_prompt - **cancel_prompt** (`Optional[str]`) - Optional - Default: `None` - Description: Message to send if cancelled ### Returns - `bool` - `True` if not cancelled, `False` if cancelled ### Example ```python @matcher.handle() async def handle(not_cancelled: bool = HandleCancellation("Cancelled!")): if not_cancelled: # Process normally pass ``` ``` -------------------------------- ### Forward WebSocket Connection (Client) Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/endpoints.md The adapter can initiate WebSocket connections to OneBot implementations to send API requests and receive responses. This requires configuration of `onebot_ws_urls`. ```APIDOC ## Forward WebSocket Connection (Client) ### Description This describes how the adapter connects to OneBot implementations via WebSocket to send API requests and receive responses. Configuration is done via the `ONEBOT_WS_URLS` environment variable. ### Configuration ```env ONEBOT_WS_URLS=["ws://127.0.0.1:5700"] ``` ### Connection Details - **URL**: OneBot implementation WebSocket endpoint. - **Port**: Typically 5700 (configurable). - **Headers**: `Authorization: Bearer {token}` if token configured. - **Reconnection**: Automatic with 3-second interval. ### Request Format ```json { "action": "send_msg", "params": { "message_type": "private", "user_id": 987654321, "message": "Hello" }, "echo": "1" } ``` ### Response Format ```json { "status": "ok", "retcode": 0, "data": { "message_id": 123 }, "echo": "1" } ``` ``` -------------------------------- ### Adapter Class Methods Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/v12-adapter.md Provides static methods for interacting with the OneBot V12 adapter, such as retrieving its name, registering custom event models, and converting data to event objects. ```APIDOC ## get_name ### Description Returns the name of the adapter. ### Method `@classmethod get_name(cls) -> str` ### Returns - `str`: The string "OneBot V12" ## add_custom_model ### Description Registers a custom Event model for a specific platform implementation. ### Method `@classmethod add_custom_model(cls, model: type[Event], *, impl: str = "") -> None` ### Parameters #### Path Parameters - **model** (`type[Event]`) - Required - The Event class to register. - **impl** (`str`) - Optional - The implementation name. Defaults to an empty string. ### Example ```python class CustomQQEvent(Event): custom_field: str Adapter.add_custom_model(CustomQQEvent, impl="qq") ``` ## get_event_model ### Description Retrieves matching Event models for given event data and implementation. ### Method `@classmethod get_event_model(cls, data: dict[str, Any], *, impl: str = "") -> Generator[type[Event], None, None]` ### Parameters #### Path Parameters - **data** (`dict[str, Any]`) - Required - The event data to match. - **impl** (`str`) - Optional - The implementation name. Defaults to an empty string. ### Returns - `Generator[type[Event], None, None]` - A generator yielding matching Event models. ## json_to_event ### Description Converts raw JSON data into an Event object. ### Method `@classmethod json_to_event(cls, json_data: Any, *, impl: str = "") -> Optional[Event]` ### Parameters #### Path Parameters - **json_data** (`Any`) - Required - The raw JSON data to convert. - **impl** (`str`) - Optional - The implementation name. Defaults to an empty string. ### Returns - `Optional[Event]` - The converted Event object, or None if conversion fails. ## get_api_error ### Description Retrieves the appropriate error exception class for a given retcode. ### Method `@classmethod get_api_error(cls, retcode: str) -> Optional[type[ActionFailedWithRetcode]]` ### Parameters #### Path Parameters - **retcode** (`str`) - Required - The API retcode to look up. ### Returns - `Optional[type[ActionFailedWithRetcode]]` - The exception class if found, otherwise None. ## custom_send ### Description Overrides the default send handler for a specific implementation. ### Method `@classmethod custom_send(cls, send_func: Callable[[Bot, Event, Union[str, Message, MessageSegment]], Any], *, impl: str = "") -> None` ### Parameters #### Path Parameters - **send_func** (`Callable[[Bot, Event, Union[str, Message, MessageSegment]], Any]`) - Required - The custom send function to use. - **impl** (`str`) - Optional - The implementation name. Defaults to an empty string. ``` -------------------------------- ### Multiple Bot Instances Configuration Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/configuration.md Configure multiple OneBot instances by providing distinct WebSocket URLs and API root mappings for each bot. ```env ONEBOT_WS_URLS=["ws://127.0.0.1:5700", "ws://127.0.0.1:5701"] ONEBOT_API_ROOTS={"123456789": "http://127.0.0.1:5700", "987654321": "http://127.0.0.1:5701"} ``` -------------------------------- ### Platform-Specific Message Handling Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/v12-bot.md Use bot.platform and bot.impl to differentiate between platforms and implementations for custom logic. ```python async def handle_message(bot: Bot, event: MessageEvent): if bot.platform == "qq": # QQ-specific handling pass elif bot.platform == "telegram": # Telegram-specific handling pass if bot.impl == "custom_qq_impl": # Implementation-specific handling pass ``` -------------------------------- ### Webhook Configuration with Signature (V11) Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/endpoints.md Configure OneBot to send events to NoneBot via HTTP with signature verification. Ensure the `url` and `secret` match between OneBot and NoneBot. ```env # OneBot implementation sends events to NoneBot via HTTP # NoneBot runs on port 8080 ONEBOT_SECRET=my_secret # OneBot configuration url = "http://nonebot_server:8080/onebot/v11/http" secret = "my_secret" access_token = "optional_token" ``` -------------------------------- ### Basic Error Handling with OneBot Exceptions Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/errors.md Demonstrates basic try-except blocks for handling NetworkError, ApiNotAvailable, and ActionFailed exceptions during bot operations. ```python from nonebot.adapters.onebot.v11 import ( NetworkError, ApiNotAvailable, ActionFailed ) async def send_safe(bot: Bot, event: Event, message: str): try: return await bot.send(event, message) except NetworkError as e: print(f"Network failed: {e.msg}") # Retry or queue message except ApiNotAvailable: print("API unavailable - check configuration") except ActionFailed as e: print(f"API error {e.info.get('retcode')}: {e.info.get('msg')}") ``` -------------------------------- ### Bot Constructor Signature Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/v12-bot.md The constructor for the Bot class is called by the adapter and is not typically instantiated directly. It requires the parent adapter, the bot's unique ID, platform name, and implementation name. ```python def __init__(self, adapter: Adapter, self_id: str, *, platform: str, impl: str) -> None ``` -------------------------------- ### Dual Connection Configuration (V11) Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/endpoints.md Configure both receiving events via WebSocket and sending APIs via HTTP. Alternatively, APIs can also be sent over the same WebSocket connection. ```env # Receive events via WebSocket (forward) ONEBOT_WS_URLS=["ws://127.0.0.1:5700"] # Send APIs via HTTP ONEBOT_API_ROOTS={"123456789": "http://127.0.0.1:5700"} # Or APIs via same WebSocket # (no ONEBOT_API_ROOTS needed) ``` -------------------------------- ### _construct Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/v12-message.md Constructs a message from a string, yielding text segments. ```APIDOC ## _construct ### Description This static method constructs a message from a given string, yielding `MessageSegment` objects, typically text segments. ### Method `@staticmethod def _construct(msg: str) -> Iterable[MessageSegment]` ### Parameters * **msg** (str) - The string to construct the message from. ### Returns `Iterable[MessageSegment]` - A generator yielding text segments. ``` -------------------------------- ### Register Custom Event Model Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/v12-adapter.md Register a custom Event model for a specific platform implementation. Use an empty string for the default implementation. ```python class CustomQQEvent(Event): custom_field: str Adapter.add_custom_model(CustomQQEvent, impl="qq") ``` -------------------------------- ### Access OneBot Config in Adapter Init Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/configuration.md The OneBot adapter initializes its configuration within its `__init__` method, making it accessible via `self.onebot_config` for internal use. ```python from nonebot.adapters.onebot.v11 import Adapter class Adapter(BaseAdapter): def __init__(self, driver: Driver, **kwargs: Any): super().__init__(driver, **kwargs) self.onebot_config: Config = get_plugin_config(Config) # Now accessible as self.onebot_config ``` -------------------------------- ### Event Type Checking with Permissions Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/permissions.md Shows how to use GROUP and PRIVATE permissions to differentiate between group and private messages, with specific handlers for each event type. ```python from nonebot import on_message from nonebot.adapters.onebot.v11 import ( GROUP, PRIVATE, GroupMessageEvent, PrivateMessageEvent ) group_matcher = on_message(permission=GROUP) @group_matcher.handle() async def handle_group(event: GroupMessageEvent): await group_matcher.finish(f"Group {event.group_id}") private_matcher = on_message(permission=PRIVATE) @private_matcher.handle() async def handle_private(event: PrivateMessageEvent): await private_matcher.finish(f"Private from {event.user_id}") ``` -------------------------------- ### Handle Incoming Messages Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/README.md Process incoming messages using a matcher and respond with simple text, mentions, or replies. ```python @matcher.handle() async def handle(event: MessageEvent): # Simple reply await bot.send(event, "Got it!") # With mention await bot.send(event, "Thanks!", at_sender=True) # With reply/quote await bot.send(event, "Good point!", reply_message=True) ``` -------------------------------- ### HandleCancellation Dependency Injection Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/utilities.md A dependency injection utility that integrates with cancellation detection. It returns `True` if the user has not cancelled the operation, allowing the handler to proceed, and `False` if cancellation is detected, optionally sending a cancellation prompt. ```python @matcher.handle() async def handle(not_cancelled: bool = HandleCancellation("Cancelled!")): if not_cancelled: # Process normally pass ``` -------------------------------- ### OneBot V12 API Calling Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/v12-bot.md Demonstrates generic API calls using call_api and specific API method calls like send_message and get_user_info. ```python # Generic API call result = await bot.call_api("action_name", param1=value1, param2=value2) # Using API methods msg_id = await bot.send_message(detail_type="group", group_id="123", message=[...]) user_info = await bot.get_user_info(user_id="456") ``` -------------------------------- ### Access OneBot Configuration Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/types.md Retrieve and access OneBot adapter configuration settings like access tokens and API roots using `get_plugin_config`. ```python from nonebot import get_plugin_config from nonebot.adapters.onebot.v11 import Config async def my_handler(): config = get_plugin_config(Config) # Access configuration if config.onebot_access_token: print(f"Token configured: {config.onebot_access_token[:10]}...") # Iterate API roots for bot_id, api_root in config.onebot_api_roots.items(): print(f"Bot {bot_id} uses API root: {api_root}") ``` -------------------------------- ### Construct Message from String Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/v12-message.md Instantiate a Message object directly from a string. ```python msg = Message("Hello") ``` -------------------------------- ### Multi-Implementation Configuration (V12) Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/endpoints.md Configure multiple OneBot implementations with distinct API endpoints and specify message packing format per implementation. ```env # Different implementations on different ports ONEBOT_API_ROOTS={ "qq:123456789": "http://127.0.0.1:5700", "telegram:987654321": "http://127.0.0.1:5701" } # Different encoding per implementation ONEBOT_USE_MSGPACK={ "qq": true, "telegram": false } ``` -------------------------------- ### Sending and Receiving File IDs in V12 Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/v12-message.md Demonstrates how to send a message with a file ID and how to retrieve a file ID from an incoming event segment. File IDs are assigned by the OneBot implementation and are used instead of URLs. ```python # File IDs are assigned by OneBot implementation # Your code doesn't create them, but receives/uses them # Sending with file ID msg = MessageSegment.image("file_id_from_onebot") await bot.send(event, msg) # Receiving file ID from event if segment.type == "image": file_id = segment.data.get("file_id") # Use file_id for operations ``` -------------------------------- ### Reverse WebSocket Configuration (V11) Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/endpoints.md Configure NoneBot to connect to a OneBot implementation using reverse WebSocket. Specify the WebSocket URL and an optional access token. ```env # NoneBot connects to OneBot implementation ONEBOT_WS_URLS=["ws://127.0.0.1:5700"] ONEBOT_ACCESS_TOKEN=my_token ``` -------------------------------- ### Check OneBot V11 Adapter Exception Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/errors.md Use isinstance to check if an exception is a OneBotV11AdapterException or a general AdapterException. This helps in handling protocol-specific errors. ```python from nonebot.exception import AdapterException from nonebot.adapters.onebot.v11 import OneBotV11AdapterException # Check if exception is from OneBot V11 try: ... except Exception as e: if isinstance(e, OneBotV11AdapterException): print("This is a OneBot V11 error") elif isinstance(e, AdapterException): print("This is an adapter error from another protocol") ``` -------------------------------- ### Handle Group Messages in OneBot V12 Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/v12-bot.md Demonstrates how to process incoming group messages, check mentions, identify the platform, and handle replies. Requires importing MessageEvent and GroupMessageEvent. ```python from nonebot.adapters.onebot.v12 import MessageEvent, GroupMessageEvent async def handle_group_message(bot: Bot, event: GroupMessageEvent): # Check if mentioned if event.to_me: await bot.send(event, "You mentioned me!") # Check platform if bot.platform == "qq": # QQ-specific logic pass # Handle reply if event.reply: original_sender = event.reply.user_id await bot.send(event, f"Replying to {original_sender}") ``` -------------------------------- ### Test WebSocket Connection Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/endpoints.md This section demonstrates how to test the WebSocket connection for the OneBot adapter, including sending API calls and receiving responses. ```APIDOC ## WebSocket /onebot/v11/ws ### Description Tests the WebSocket connection and allows sending API calls to the OneBot adapter. ### Method WebSocket ### Endpoint /onebot/v11/ws ### Headers - **x-self-id** (string) - Required - The self ID for the connection. ### Request Body (API Call) - **action** (string) - Required - The API action to perform (e.g., "get_self_info"). - **params** (object) - Optional - Parameters for the API action. - **echo** (string) - Required - An identifier for the request. ### Request Example (API Call) { "action": "get_self_info", "params": {}, "echo": "1" } ### Response Example (The response will be the result of the API call, e.g., JSON string containing bot information) ``` -------------------------------- ### Test HTTP Webhook Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/endpoints.md This endpoint allows testing the HTTP webhook functionality of the OneBot adapter. You can send mock events to verify the adapter's response. ```APIDOC ## POST /onebot/v11/http ### Description Tests the HTTP webhook endpoint by sending a mock event. ### Method POST ### Endpoint /onebot/v11/http ### Headers - **x-self-id** (string) - Required - The self ID for the connection. - **content-type** (string) - Required - Must be application/json. ### Request Body - **time** (integer) - Required - Timestamp of the event. - **self_id** (integer) - Required - The self ID of the bot. - **post_type** (string) - Required - The type of post event (e.g., "meta_event"). - **meta_event_type** (string) - Required - The type of meta event (e.g., "lifecycle"). - **sub_type** (string) - Required - The subtype of the meta event (e.g., "connect"). ### Request Example { "time": 1234567890, "self_id": 123456789, "post_type": "meta_event", "meta_event_type": "lifecycle", "sub_type": "connect" } ``` -------------------------------- ### Use Implementation in Event Processing Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/v12-adapter.md When processing incoming data, specify the implementation to ensure the correct event model and parsing logic are used. This is crucial when supporting multiple OneBot implementations. ```python event = Adapter.json_to_event(data, impl="qq") ``` -------------------------------- ### Root HTTP Endpoint Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/v12-adapter.md The root endpoint for handling HTTP requests. It serves as the main entry point for HTTP communication with the adapter. ```APIDOC ## POST /onebot/v12/ ### Description Root HTTP endpoint for the v12 adapter. ### Method POST ### Endpoint /onebot/v12/ ### Authentication Bearer token in `Authorization` header ``` -------------------------------- ### log Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/utilities.md A logging function wrapper for the OneBot V11 adapter, providing a convenient way to log messages with different severity levels. ```APIDOC ## log Logging function for OneBot V11 adapter. ### Usage ```python from nonebot.adapters.onebot.v11.utils import log log("INFO", "Bot connected") log("DEBUG", f"Calling API {api}") log("WARNING", "Invalid message format") log("ERROR", "Network error", exception) ``` ``` -------------------------------- ### OneBot V11 Config Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/types.md Configuration model for the OneBot v11 adapter, specifying access tokens, secrets, WebSocket URLs, and API roots. ```APIDOC ## OneBot V11 Config ### Description Configuration model for the OneBot v11 adapter. It allows setting access tokens, secrets for request signing, WebSocket connection URLs, and HTTP API endpoints. ### Fields - **onebot_access_token** (`Optional[str]`) - Required - Bearer token for authorization. - **onebot_secret** (`Optional[str]`) - Required - HMAC-SHA1 secret for HTTP request signing. - **onebot_ws_urls** (`set[WSUrl]`) - Required - Forward WebSocket connection URLs. - **onebot_api_roots** (`dict[str, AnyUrl]`) - Required - HTTP API endpoints keyed by bot self_id. ### Aliases All fields support `onebot_v11_*` prefix aliases for backward compatibility. ### Example ```python # In .env or .env.* files ONEBOT_ACCESS_TOKEN="your_secret_token" ONEBOT_SECRET="hmac_secret" ONEBOT_WS_URLS={"ws://127.0.0.1:5700"} ONEBOT_API_ROOTS={"123456789": "http://127.0.0.1:5700"} ``` ``` -------------------------------- ### Build Messages with Segments in OneBot V12 Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/v12-bot.md Shows how to construct complex messages using text and mention segments. Requires importing Message and MessageSegment. ```python from nonebot.adapters.onebot.v12 import Message, MessageSegment # Create message msg = Message([ MessageSegment.text("Hello "), MessageSegment.mention(user_id), MessageSegment.text("!"), ]) await bot.send(event, msg) ``` -------------------------------- ### Configure MessagePack Encoding Per Implementation Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/v12-adapter.md Enable or disable MessagePack encoding on a per-implementation basis. This allows for fine-grained control over which OneBot implementations benefit from binary encoding. ```python onebot_use_msgpack = { "qq": True, "telegram": False, } ``` -------------------------------- ### Generic Environment Variables for OneBot Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/configuration.md Environment variables that work for both OneBot v11 and v12. These are shared configurations. ```env # Works for both v11 and v12 ONEBOT_WS_URLS=["ws://127.0.0.1:5700"] ONEBOT_ACCESS_TOKEN=my_token ``` -------------------------------- ### OneBot V12 Config Model Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/types.md Defines the configuration structure for the OneBot v12 adapter. Use this model to set up access tokens, WebSocket URLs, API roots, and message pack preferences. ```python class Config(BaseModel): onebot_access_token: Optional[str] = Field( default=None, alias="onebot_v12_access_token" ) onebot_ws_urls: set[WSUrl] = Field( default_factory=set, alias="onebot_v12_ws_urls" ) onebot_api_roots: dict[str, AnyUrl] = Field( default_factory=dict, alias="onebot_v12_api_roots" ) onebot_use_msgpack: Union[bool, dict[str, bool]] = Field( default=False, alias="onebot_v12_use_msgpack" ) ``` -------------------------------- ### OneBot V11 Config Model Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/types.md Defines the configuration options for the OneBot v11 adapter, including access tokens, secrets, WebSocket URLs, and API roots. Supports backward compatibility with 'onebot_v11_*' aliases. ```python class Config(BaseModel): onebot_access_token: Optional[str] = Field( default=None, alias="onebot_v11_access_token" ) onebot_secret: Optional[str] = Field( default=None, alias="onebot_v11_secret" ) onebot_ws_urls: set[WSUrl] = Field( default_factory=set, alias="onebot_v11_ws_urls" ) onebot_api_roots: dict[str, AnyUrl] = Field( default_factory=dict, alias="onebot_v11_api_roots" ) ``` ```python # In .env or .env.* files ONEBOT_ACCESS_TOKEN="your_secret_token" ONEBOT_SECRET="hmac_secret" ONEBOT_WS_URLS={"ws://127.0.0.1:5700"} ONEBOT_API_ROOTS={"123456789": "http://127.0.0.1:5700"} ``` -------------------------------- ### OneBot HTTP API Root Configuration Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/endpoints.md Environment variable configuration for specifying the root URLs for OneBot implementations when using HTTP API calls. Maps bot IDs to their API roots. ```env ONEBOT_API_ROOTS={"123456789": "http://127.0.0.1:5700"} ``` -------------------------------- ### PRIVATE Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/permissions.md Matches any private message type. This permission can be used to trigger a handler for all incoming private messages. ```APIDOC ## PRIVATE ### Description Matches any private message type. ### Permission Object ```python PRIVATE: Permission = Permission(_private) ``` ### Example ```python from nonebot import on_message from nonebot.adapters.onebot.v11 import PRIVATE matcher = on_message(permission=PRIVATE) @matcher.handle() async def handle(): # Triggered on any private message pass ``` ``` -------------------------------- ### Root WebSocket Endpoint Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/v12-adapter.md The root endpoint for establishing WebSocket connections. This is used for real-time, persistent communication. ```APIDOC ## WS /onebot/v12/ ### Description Root WebSocket endpoint for the v12 adapter. ### Method WS ### Endpoint /onebot/v12/ ### Authentication Bearer token in `Authorization` header during handshake ``` -------------------------------- ### Bot.handle_event Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/v12-bot.md Processes a received event, performing initial checks and passing it to the NoneBot handler. ```APIDOC ## Bot.handle_event ### Description Processes a received event, performing initial checks and passing it to the NoneBot handler. ### Method `async def handle_event( self, event: Event ) -> None` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Description | |-----------|------|-------------| | event | `Event` | Event to process | ### Processing Steps 1. For MessageEvent: extract text, check reply, detect mentions, check nicknames 2. Pass to NoneBot handler ``` -------------------------------- ### Implement Per-User Command Cooldown Source: https://github.com/nonebot/adapter-onebot/blob/master/_autodocs/api-reference/utilities.md Use the `Cooldown` helper with `CooldownIsolateLevel.USER` to restrict command usage to once per user within a specified time frame. This prevents spamming by individual users. ```python from nonebot.adapters.onebot.v11.helpers import ( Cooldown, CooldownIsolateLevel, ) matcher = on_command("cmd") # Per-user cooldown @matcher.handle(parameterless=[ Cooldown(cooldown=10, isolate_level=CooldownIsolateLevel.USER) ]) async def handle(): pass ```