aiocqhttp SDK

repository·master·Indexed 43 days ago

https://github.com/nonebot/aiocqhttp

An asynchronous Python SDK for interacting with OneBot implementations (such as CQHTTP). It provides a high-level abstraction for HTTP and Reverse WebSocket communication protocols, supporting OneBot v11 and Python 3.7+. The SDK includes tools for parsing CQ codes via Message and MessageSegment classes, event handling via decorators, and integration with ASGI servers like Uvicorn for production deployment.

Tokens
3.2K
Snippets
15
Records
18
Agent score
55%

What's inside aiocqhttp

  1. Overview of aiocqhttp

    master

    aiocqhttp is a Python SDK for OneBot (formerly the CQHTTP plugin for 酷Q). It is designed to help Python developers build plugins using asynchronous I/O. It encapsulates web server logic and supports two primary communication methods:

    1. HTTP: Standard HTTP communication.
    2. Reverse WebSocket: Allows the SDK to act as a backend for multiple bot accounts simultaneously.

    Requirements:

    • Python 3.7 or higher.
    • It is recommended to use a OneBot implementation that supports OneBot v11.
  2. Use Quick Operations in event handlers

    master

    A 'Quick Operation' is a way to perform simple actions by returning a dictionary from your event handler. The SDK serializes this dictionary to JSON and returns it to CQHTTP as the response to the event report. This is useful for simple replies or group actions like banning/recalling messages.

    Example of replying to a message via Quick Operation:

    @bot.on_message('private')
    async def _(event: Event):
        # This returns a 'reply' action to CQHTTP
        return {'reply': event.message}
  3. Initialize the CQHttp client

    master

    The CQHttp class is the main entry point of the SDK. It encapsulates a Quart web server to handle incoming connections via HTTP or WebSocket.

    • HTTP Communication: You must provide the api_root parameter so the bot knows where to send API requests (e.g., bot.send).
    • WebSocket Communication: Supports multiple CQHTTP connections simultaneously. When using bot.send, the SDK automatically selects the correct account to send the message.
    from aiocqhttp import CQHttp
    
    bot = CQHttp(api_root='http://127.0.0.1:8080')
  4. Handle synchronous functions and use bot.sync

    master

    While asynchronous operations (using aiofiles, aiohttp, httpx.AsyncClient, etc.) are recommended, the SDK supports synchronous handler functions.

    Synchronous handlers decorated with @bot.on_message will run in the asyncio loop's default executor (multi-threaded). To perform API calls within a synchronous handler, you must use the bot.sync attribute to access synchronous versions of the API methods.

    @bot.on_message
    def sync_handle_msg(event):
        import time
        time.sleep(5)  # Simulating blocking I/O
        # Use bot.sync for API calls in sync handlers
        bot.sync.send_private_msg(user_id=event.user_id, message='处理完毕')
  5. Parse and construct messages with Message and MessageSegment

    master

    The SDK provides Message and MessageSegment classes to parse and construct CQ codes. You can manually wrap event.message in a Message object to iterate through segments or use MessageSegment to create specific content like images.

    To avoid manual wrapping, you can configure the CQHttp instance to automatically use a specific message class by passing it to the message_class parameter during initialization. This ensures event.message is automatically instantiated as that class.

    from aiocqhttp import Message, MessageSegment
    
    @bot.on_message
    async def handle_msg(event):
        # Manually parsing
        msg = Message(event.message)
        for seg in msg:
            if seg == MessageSegment.at(event.self_id):
                await bot.send(event, 'at 我干啥')
                break
    
        # Constructing segments
        img = MessageSegment.image('http://example.com/somepic.png')
        await bot.send(event, img + '\n上面这是一张图')
    
    # Automatic message class assignment
    bot = CQHttp(message_class=Message)
  6. Deploy using an ASGI server

    master

    While bot.run() is available for development (running in debug mode by default), it is not recommended for production. Instead, use a professional ASGI server like Uvicorn, Daphne, or Hypercorn.

    To deploy with Uvicorn, expose the bot.asgi attribute from your application module.

    # main.py
    from aiocqhttp import CQHttp
    bot = CQHttp()
    
    # Command to run with Uvicorn
    # uvicorn --host 127.0.0.1 --port 8080 main:bot.asgi
  7. Requirements for aiocqhttp

    master

    To use aiocqhttp, ensure your environment meets the following requirements:

    • Python Version: Python 3.7 or higher.
    • OneBot Version: It is recommended to use a OneBot implementation that supports OneBot v11.
  8. Configure CQHTTP to use HTTP

    master

    To connect CQHTTP to your bot via HTTP, follow these steps:

    1. In your Python code, initialize CQHttp with the api_root pointing to the CQHTTP listener: bot = CQHttp(api_root='http://<cqhttp_host>:<cqhttp_port>').
    2. In the CQHTTP configuration file, set post_url to http://<your_bot_host>:<your_bot_port>/.
    3. Set use_http to true (this is the default).
    4. Restart CQHTTP.
    # bot.py configuration for HTTP mode
    bot = CQHttp(api_root='http://127.0.0.1:5700')
  9. Install aiocqhttp

    master

    Install the aiocqhttp package using pip. By default, it installs Quart and aiocqhttp. To install optional dependencies including ujson, use the [all] extra.

    # Standard installation
    pip install aiocqhttp
    
    # Installation with optional dependencies (ujson)
    pip install aiocqhttp[all]
  10. Add custom routes and configure import_name

    master

    The SDK registers several default routes (/, /ws, /ws/api, /ws/event) for CQHTTP service. You can add custom routes (e.g., for webhooks or admin panels) by interacting with the bot.server_app (which is a Quart instance).

    If you encounter issues with relative paths (e.g., when loading templates via render_template), pass the import_name argument to the CQHttp constructor.

    # Adding a custom route
    @bot.server_app.route('/webhook')
    async def webhook():
        pass
    
    # Configuring import_name for template resolution
    bot = CQHttp(__name__)
    
    @bot.server_app.route('/admin')
    async def admin():
        return await render_template('admin.html')
  11. Use the default bot object for simple tasks

    master

    For simple features or testing, you can use the built-in default bot object provided by aiocqhttp.default instead of creating a CQHttp instance. This allows you to use decorators like @on_message and utility functions like send, api, and run directly.

    If you need to modify the configuration of the default bot (e.g., changing the api_root), use the reconfigure_default_bot function.

    from aiocqhttp.default import on_message, send, api, run
    from aiocqhttp.default import reconfigure_default_bot
    
    @on_message
    async def handle_msg(event):
        await send(event, event.message)
        await api.send_private_msg(user_id=event.user_id, message='。。。')
    
    run(host='127.0.0.1', port=8080)
    
    # Reconfiguring the default bot
    reconfigure_default_bot(api_root='http://127.0.0.1:8080')