ErisPulse ErisPulse
Open in interactive docs →
On this page
Static mirror — the interactive version is canonical Open in interactive docs →

OneBot12 Platform Feature Documentation

OneBot12Adapter is an adapter built based on the OneBot V12 protocol, serving as the baseline protocol adapter for the ErisPulse framework.


Document Information

  • Corresponding Module Version: 4.6.2
  • Maintainer: ErisPulse
  • Protocol Version: OneBot V12
  • Last Updated: 2026-11-10

Basic Information

  • Platform Introduction: OneBot V12 is a general chatbot application interface standard and serves as the baseline protocol for the ErisPulse framework.
  • Adapter Name: OneBot12Adapter
  • Supported Protocol/API Version: OneBot V12
  • Multi-Account Support: Fully multi-account architecture, supporting simultaneous configuration and operation of multiple OneBot12 accounts.

v5 Paradigm Update (4.3.0)

This adapter has completed alignment with the v5 paradigm (incremental upgrade, API compatible):

  • BaseConverter Inheritance: Common fields of converters (id/time/platform/self/raw) are built by the framework's build_base_event, and are overridden by OB11 field names (echo/time/self_id).
  • spawn_background Task Ownership: Client mode connection tasks are now using Runtime.spawn_background (ownership assigned, shutdown automatically recycles).
  • Framework Soft Dependency: The adapter no longer declares a hard dependency on ErisPulse, avoiding pip resolution issues when adjusting framework versions; runtime detection ensures ErisPulse>=2.7.1, and logs a warning if the version is too low.
  • Startup Version Log: Outputs "OneBot12Adapter vX.Y.Z loaded" during initialization.

Existing capabilities (supported since 4.2.0): Multi-account, standard action mapping for Api DSL (get_self_info→get_login_info, etc.), Request DSL (friend/group request approval: event.approve() / event.reject()), EventMixin, i18n.

Standardized Alignment

This section describes the behaviors of the adapter that align with the ErisPulse standardization specification. For details, refer to the SDK documentation:《Request Operation Specification》(docs/en/standards/request-action-spec.md) and《API Response Specification》(docs/en/standards/api-response.md).

Request Events and Request DSL

  • request_id Guarantee: When request events are forwarded, the top-level request_id field is guaranteed (prioritizing the native request_id, falling back to mapping the flag field for OB11-style implementations; synthesizing if neither is present), for use by Request DSL
  • Default Account Fallback: When Request DSL (based on the handle_quick_request action) does not explicitly specify an account via Using(), it falls back to using the source account of the request event (request_context), ensuring correct routing of event.approve()/event.reject() within the event chain

call_api Error Handling

  • When an account is not connected or the connection is closed, call_api no longer throws a ConnectionError, but instead returns a standard failure response (status="failed", retcode=33001)
  • API calls that timeout also return a standard failure response (retcode=33001)

Dual Compatibility of Account Fields and send_context

  • call_api accepts both the standard field account_id and the legacy field _account_id (with the standard name taking precedence); the framework's ApiDSL automatically adapts, and module code is recommended to use account_id
  • Send/Recall/Edit/Batch all methods read send_context: within the event chain, the account of the current event source is automatically used, with an explicitly specified account via Using() taking precedence

Event Field Injection

  • All events inject self.account_id (source account name), ensuring correct routing back to the source account in multi-account mode
  • All events must contain the onebot12_raw_type field (original event type, conforming to event transformation specifications)
  • Emoticon/pack/sticker message segments are named onebot12_sticker (sent internally via the .Sticker() method)

Error Code Specification

retcode Meaning Triggering Scenario
0 Success Action executed successfully
33001 Network Error Account not connected, connection closed, API call timeout
10002 Unsupported Action Backend does not support the requested action
10003 Parameter Error Missing necessary parameters

The original response data returned by the backend is preserved in the onebot12_raw field.

Standard API Actions (Api DSL)

The OneBot12 backend natively supports all OB12 standard action names. The Api DSL defaults to directly delegating call_api for transparent transmission (no mapping required):

from ErisPulse import sdk
ob12 = sdk.adapter.get("onebot12")

result = await ob12.Api.get_self_info()
result = await ob12.Api.get_friend_list()
await ob12.Api.delete_message(message_id="MSG_ID")

# Specify account (multi-account)
result = await ob12.Api.Using("main").get_self_info()

# Platform extension actions
result = await ob12.Api.call("extend_action", param=1)

Supported actions are based on the backend implementation (e.g., NapCat/Lagrange/LLOneBot); unsupported actions return errors from the backend and are transparently passed through.


Request Operations (Request DSL)

Based on the OneBot12 standard handle_quick_request action, handles approval/rejection of friend requests and group invitation requests:

Event Convenience Methods

from ErisPulse.Core.Event import request

@request.on_friend_request()
async def handle_friend_request(event):
    if event.get("platform") != "onebot12":
        return
    comment = event.get("comment", "")
    if comment == "passphrase":
        await event.approve()      # Approve
    else:
        await event.reject()       # Reject

Manual Request DSL Calls

await ob12.Request("request_flag").accept()
await ob12.Request("request_flag").reject()
await ob12.Request("request_flag").Using("main").accept()

Supported Message Sending Types

All sending methods are implemented using a fluent interface syntax, for example:

from ErisPulse.Core import adapter
onebot12 = adapter.get("onebot12")

# Send using the default account
await onebot12.Send.To("group", group_id).Text("Hello World!")

# Send using a specific account
await onebot12.Send.To("group", group_id).Account("main").Text("Message from main account")

Case-Insensitive Method Calls

All sending methods and fluent modifier methods support case-insensitive calls, and the adapter automatically maps them to the correct standard method names:

# All the following calls are equivalent
await onebot12.Send.To("user", 123).Text("hello")
await onebot12.Send.To("user", 123).text("hello")
await onebot12.Send.To("user", 123).TEXT("hello")

# Fluent modifier methods also support this
await onebot12.Send.To("group", 123).At(456).Text("hello")
await onebot12.Send.To("group", 123).at(456).TEXT("hello")
await onebot12.Send.To("group", 123).AT(456).text("hello")

Unsupported Method Calls

When calling an unsupported method, the adapter returns a friendly text message instead of raising an exception:

# Calling an unsupported method
result = await onebot12.Send.To("user", 123).UnsupportedMethod("test")

# The returned result is a text message
# Message content: [Unsupported sending type] Method name: UnsupportedMethod, Parameters: [args[0]: 'test']

Basic Message Types

  • .Text(text: str) : Send plain text messages
  • .Image(file: Union[str, bytes], filename: str = "image.png") : Send image messages (supports URL, Base64, or bytes)
  • .Audio(file: Union[str, bytes], filename: str = "audio.ogg") : Send audio messages
  • .Voice(file: Union[str, bytes], filename: str = "voice.ogg") : Send voice messages (an alias of Audio, compatible with OneBot11)
  • .Video(file: Union[str, bytes], filename: str = "video.mp4") : Send video messages

Fluent Modifier Methods (return self to support fluent chaining)

  • .At(user_id: Union[str, int]) : @ user (can be called multiple times)
  • .AtAll() : @ all members
  • .Reply(message_id: Union[str, int]) : Reply to a message

Raw Message Sending

  • .Raw_ob12(message: Union[Dict, List[Dict]], **kwargs) : Send OneBot12 raw format messages (conforms to naming conventions)

Other Message Types

  • .Sticker(file_id: str) : Send sticker/emoticon messages (onebot12_sticker message segment)
  • .Location(latitude: float, longitude: float, title: str = "", content: str = "") : Send location messages

Management Features

  • .Recall(message_id: Union[str, int]) : Recall a message
  • .Edit(message_id: Union[str, int], content: Union[str, List[Dict]]) : Edit a message
  • .Raw(message_segments: List[Dict]) : Send native OneBot12 message segments
  • .Batch(target_ids: List[str], message: Union[str, List[Dict]], target_type: str = "user") : Batch send messages

OneBot12 Standard Events

The OneBot12 adapter fully complies with the OneBot12 standard, and event formats do not require conversion, being directly submitted to the framework.

New Feature: Raw Event Type Field

Compliant with the standards/event-conversion.md specification, all events will retain the raw event type field onebot12_raw_type:

{
    "id": "event-id",
    "type": "message",              # Event type
    "onebot12_raw_type": "message", # Raw event type (same as type)
    "detail_type": "private",
    "self": {"user_id": "bot-id"},
    "user_id": "user-id",
    "message": [{"type": "text", "data": {"text": "Hello"}}],
    "alt_message": "Hello",
    "time": 1234567890
}

Message Events

# Private message
{
    "id": "event-id",
    "type": "message",
    "onebot12_raw_type": "message",
    "detail_type": "private",
    "self": {"user_id": "bot-id"},
    "user_id": "user-id",
    "message": [{"type": "text", "data": {"text": "Hello"}}],
    "alt_message": "Hello",
    "time": 1234567890
}

# Group message
{
    "id": "event-id",
    "type": "message",
    "onebot12_raw_type": "message",
    "detail_type": "group",
    "self": {"user_id": "bot-id"},
    "user_id": "user-id",
    "group_id": "group-id",
    "message": [{"type": "text", "data": {"text": "Hello group"}}],
    "alt_message": "Hello group",
    "time": 1234567890
}

Notice Events

# Group member increase
{
    "id": "event-id",
    "type": "notice",
    "onebot12_raw_type": "notice",
    "detail_type": "group_member_increase",
    "self": {"user_id": "bot-id"},
    "group_id": "group-id",
    "user_id": "user-id",
    "operator_id": "operator-id",
    "sub_type": "approve",
    "time": 1234567890
}

# Group member decrease
{
    "id": "event-id",
    "type": "notice",
    "onebot12_raw_type": "notice",
    "detail_type": "group_member_decrease",
    "self": {"user_id": "bot-id"},
    "group_id": "group-id",
    "user_id": "user-id",
    "operator_id": "operator-id",
    "sub_type": "leave",
    "time": 1234567890
}

Request Events

# Friend request
{
    "id": "event-id",
    "type": "request",
    "onebot12_raw_type": "request",
    "detail_type": "friend",
    "self": {"user_id": "bot-id"},
    "user_id": "user-id",
    "comment": "Application message",
    "request_id": "request-flag",
    "flag": "request-flag",
    "time": 1234567890
}

# Group invitation request
{
    "id": "event-id",
    "type": "request",
    "onebot12_raw_type": "request",
    "detail_type": "group",
    "self": {"user_id": "bot-id"},
    "group_id": "group-id",
    "user_id": "user-id",
    "comment": "Application message",
    "request_id": "request-flag",
    "flag": "request-flag",
    "sub_type": "invite",
    "time": 1234567890
}

Meta Events

# Lifecycle event
{
    "id": "event-id",
    "type": "meta_event",
    "onebot12_raw_type": "meta_event",
    "detail_type": "lifecycle",
    "self": {"user_id": "bot-id"},
    "sub_type": "enable",
    "time": 1234567890
}

// Heartbeat event
{
    "id": "event-id",
    "type": "meta_event",
    "onebot12_raw_type": "meta_event",
    "detail_type": "heartbeat",
    "self": {"user_id": "bot-id"},
    "interval": 5000,
    "status": {"online": true},
    "time": 1234567890
}

Configuration Options

Account Configuration

Each account independently configures the following options:

  • mode: The running mode of this account ("server" or "client")
  • server_path: WebSocket path in Server mode
  • server_token: Authentication token in Server mode (optional)
  • client_url: WebSocket address to connect in Client mode
  • client_token: Authentication token in Client mode (optional)
  • enabled: Whether to enable this account
  • platform: Platform identifier, default is "onebot12"
  • implementation: Implementation identifier, such as "go-cqhttp" (optional)

Configuration Example

[OneBotv12_Adapter.accounts.main]
mode = "server"
server_path = "/onebot12-main"
server_token = "main_token"
enabled = true
platform = "onebot12"
implementation = "go-cqhttp"

[OneBotv12_Adapter.accounts.backup]
mode = "client"
client_url = "ws://127.0.0.1:3002"
client_token = "backup_token"
enabled = true
platform = "onebot12"
implementation = "shinonome"

[OneBotv12_Adapter.accounts.test]
mode = "client"
client_url = "ws://127.0.0.1:3003"
enabled = false

Default Configuration

If no account is configured, the adapter will automatically create:

[OneBotv12_Adapter.accounts.default]
mode = "server"
server_path = "/onebot12"
enabled = true
platform = "onebot12"

Send Method Return Values

Message Sending Methods

All message sending methods (such as .Text(), .Image(), .Raw_ob12(), etc.) return an asyncio.Task object, which can be directly awaited to get the sending result:

task = await onebot12.Send.To("group", 123456).Text("Hello")

Chain Modifier Methods

All chain modifier methods (such as .At(), .AtAll(), .Reply()) return self, supporting chain calls:

# Combine multiple modifier methods
await onebot12.Send.To("group", 123456).Reply("msg123").At(789).At(790).Text("text")

API Response Standard

The adapter follows the ErisPulse standardized return specification (standards/api-response.md):

# Success response
{
    "status": "ok",              // Required: execution status
    "retcode": 0,                // Required: return code (0 indicates success)
    "data": {                     // Required: response data
        "message_id": "123456",
        "time": 1632847927.599013
    },
    "message_id": "123456",       // Required: message ID (empty string if none)
    "message": "",                // Required: error message (empty if successful)
    "echo": "1234",               // Optional: echo returned as-is from the request
    "onebot12_raw": {...}        // Optional: raw response data
}

# Failure response
{
    "status": "failed",           // Required: execution status
    "retcode": 10003,            // Required: return code (non-zero indicates failure)
    "data": None,                // Required: null on failure
    "message_id": "",            // Required: empty string on failure
    "message": "Missing required parameter",    // Required: error description
    "echo": "1234",              // Optional: echo returned as-is from the request
    "onebot12_raw": {...}        // Optional: raw response data
}

Error Code Specification

Follows OneBot12 standard error codes:

  • 0: Success
  • 1xxxx: Action request error
  • 2xxxx: Action handler error
  • 3xxxx: Action execution error (33001 for network timeout)

Multi-Account Sending Syntax

# Account selection methods
await onebot12.Send.Using("main").To("group", 123456).Text("Main account message")
await onebot12.Send.Using("backup").To("group", 123456).Image("http://example.com/image.jpg")

# API call method
await onebot12.call_api("send_message", account_id="main", 
    detail_type="group", group_id=123456, 
    content=[{"type": "text", "data": {"text": "Hello"}}])

Asynchronous Processing Mechanism

The OneBot12 adapter uses an asynchronous non-blocking design:

  1. Message sending does not block the event handling loop.
  2. Multiple concurrent sending operations can be performed simultaneously.
  3. API responses are handled promptly.
  4. WebSocket connections remain active.
  5. Multi-account concurrent processing, with each account running independently.

Error Handling

The adapter provides a comprehensive error handling mechanism:

  1. Automatic reconnection for network connection exceptions (supports independent reconnection for each account, with a 30-second interval)
  2. API call timeout handling (fixed 30-second timeout; timeout returns the standard failure response retcode=33001)
  3. When an account is not connected or the connection is closed, call_api returns the standard failure response retcode=33001 instead of throwing a ConnectionError
  4. Calling unsupported methods will return a friendly text prompt

Event Handling Enhancement

In multi-account mode, all events are automatically appended with account information:

{
    "type": "message",
    "onebot12_raw_type": "message",  // Raw event type
    "detail_type": "private",
    "self": {"user_id": "123456"},  // Account ID that sent the event (standard field)
    "platform": "onebot12",
    // ... other event fields
}

Management Interface

# Get all account information
accounts = onebot12.accounts

# Check account connection status
connection_status = {
    account_id: connection is not None and not connection.closed
    for account_id, connection in onebot12.connections.items()
}

# Dynamically enable/disable accounts (requires adapter restart)
onebot12.accounts["test"].enabled = False

OneBot12 Standard Features

Message Segment Standard

OneBot12 uses standardized message segment formats:

# Text message segment
{"type": "text", "data": {"text": "Hello"}}

# Image message segment
{"type": "image", "data": {"file_id": "image-id"}}

# Mention message segment
{"type": "mention", "data": {"user_id": "user-id", "user_name": "Username"}}

# Reply message segment
{"type": "reply", "data": {"message_id": "msg-id"}}

API Standard

Follows OneBot12 standard API specifications:

  • send_message: Send message
  • delete_message: Recall message
  • edit_message: Edit message
  • get_message: Get message
  • get_self_info: Get self information
  • get_user_info: Get user information
  • get_group_info: Get group information

Best Practices

  1. Configuration Management: It is recommended to use multi-account configuration to separate management of robots with different purposes.
  2. Error Handling: Always check the return status of API calls.
  3. Message Sending: Use appropriate message types and avoid sending unsupported messages.
  4. Connection Monitoring: Regularly check connection status to ensure service availability.
  5. Performance Optimization: Use the Batch method for batch sending to reduce network overhead.
  6. Method Calls: Standard camelCase naming (e.g., .Text()) is recommended, but lowercase forms are also supported for compatibility with different programming styles (this may be incompatible with older versions).