YiriMirai Documentation

website·Indexed 29 days ago

https://yiri-mirai.vercel.app

A lightweight, low-coupling Python SDK based on mirai-api-http for developing QQ bots. It features an event-driven architecture with a Mirai object for bot instances, support for message chains, ASGI service embedding, and extension modules for event triggering and filtering. The SDK supports Python 3.7+ and provides tools for event handling, background tasks, and deployment on Linux.

Tokens
22.7K
Snippets
111
Records
152
Agent score
75%

What's inside YiriMirai

  1. Overview of YiriMirai Network Adapters

    YiriMirai uses Adapter classes to handle different connection methods to mirai-api-http. There are three primary adapter implementations:

    • HTTPAdapter: YiriMirai acts as a client sending HTTP requests to mirai-api-http (HTTP polling).
    • WebSocketAdapter: YiriMirai acts as a client establishing a WebSocket connection with mirai-api-websocket.
    • WebHookAdapter: YiriMirai acts as a server, receiving event reports from mirai-api-http via HTTP requests.
  2. Overview of YiriMirai Python SDK

    YiriMirai is a lightweight, low-coupling Python SDK based on mirai-api-http. It is designed for interacting with the mirai-api-http interface using asynchronous I/O.

    Key features include:

    • Full support for new APIs in mirai-api-http 2.X.
    • Built on asyncio for high-efficiency asynchronous I/O.
    • Uses pydantic for data parsing and encapsulation, providing better readability and IDE auto-completion support.
  3. Overview of YiriMirai Python SDK

    YiriMirai is a pure Python SDK for mirai-api-http. Unlike full-featured bot frameworks, YiriMirai is designed as a lightweight wrapper that focuses exclusively on encapsulating mirai-api-http and providing conversion between JSON data and Python objects. It avoids imposing architectural constraints like modularity or built-in message dispatchers, allowing developers to build their own custom frameworks or logic on top of it.
  4. Overview of Yiri Mirai Trigger

    Yiri Mirai Trigger is an extension for Mirai that provides event handling capabilities similar to the Graia Framework's interruption system. It is primarily used for two scenarios: implementing command interruptions (e.g., requiring a user to send /confirm to proceed with a command) and filtering/parsing incoming events (e.g., only responding to messages that start with a slash /).
  5. Overview of Python Asynchronous Programming Concepts

    Asynchronous programming in Python is designed to prevent performance waste during I/O-bound tasks (like network requests or sleep timers) where the CPU would otherwise sit idle. Key components include:

    • Asynchrony: A programming paradigm where the execution order of code does not necessarily match the written order.
    • async/await: Python keywords used to define and manage asynchronous logic.
    • asyncio: A built-in Python library (introduced in 3.4) that provides the foundation for coroutines and their management.
  6. Understand the concept of Callbacks in asynchronous programming

    A callback is a design pattern where a part of a program is passed as a function to be executed by an external entity (a runtime) once a time-consuming operation (like a network request) completes. This allows the main program flow to continue without blocking while waiting for the operation to finish.
    def get_async(url, callback): 
        # Hypothetical async function that initiates a request
        # and calls the callback upon completion
        pass
    
    def job1_continuation(response):
        print(response.text.count('e'))
    
    # Initiate async request; program continues to the loop immediately
    get_async('http://example.org/very_large_file.txt', callback=job1_continuation)
    
    for i in range(10):
        print(i)
  7. Understand and install YiriMirai extension modules

    YiriMirai provides optional functionality through extension modules to keep the core SDK lightweight. These modules are distributed via PyPI and are accessed using the mirai_extensions namespace after installation.
  8. YiriMirai Available API Models Overview

    YiriMirai provides a comprehensive set of API models for bot interaction, including user and group management, file operations, and messaging. The primary API models are categorized under mirai.models.api and include:

    • Bot & Account Management: BotProfile, About
    • Friend Management: FriendList, FriendProfile, DeleteFriend, RespNewFriendRequestEvent
    • Group Management: GroupList, GroupConfig, MemberList, MemberInfo, MemberProfile, MemberAdmin, Kick, Mute, Unmute, MuteAll, UnmuteAll, RespBotInvitedJoinGroupRequestEvent, RespMemberJoinRequestEvent
    • Messaging: SendMessage, SendFriendMessage, SendGroupMessage, SendTempMessage, SendNudge, Recall, SetEssence, MessageFromId, OtherClientMessage
    • File Operations: FileInfo, FileList, FileMkdir, FileMove, FileRename, FileDelete, UploadImage, UploadVoice
    • System & Execution: CmdRegister, CmdExecute, Quit, RespEvent, RespOperate, ApiModel
  9. Implement professional scheduled tasks with APScheduler

    For production-ready scheduled tasks with better scalability, use the APScheduler library. Specifically, AsyncIOScheduler is used for YiriMirai's asynchronous architecture. You can use CronTrigger to define execution times using Linux-style crontab expressions (e.g., specifying hour and minute).
    pip install apscheduler
    from apscheduler.schedulers.asyncio import AsyncIOScheduler
    from apscheduler.triggers.cron import CronTrigger
    from mirai import Startup, Shutdown
    
    scheduler = AsyncIOScheduler()
    
    @bot.on(Startup)
    def start_scheduler(_):
        scheduler.start() # Start the scheduler
    
    @bot.on(Shutdown)
    def stop_scheduler(_):
        scheduler.shutdown(True) # Stop the scheduler
    
    # Schedule a task for 7:30 AM daily
    @scheduler.scheduled_job(CronTrigger(hour=7, minute=30))
    async def timer():
        await bot.send_group_message(12345678, "早安")
    
    # Schedule a task to run every hour on the hour (minute 0)
    @scheduler.scheduled_job(CronTrigger(hour='*', minute=0))
    async def hourly_report():
        import datetime
        await bot.send_group_message(12345678, f"Time report: {datetime.datetime.now().hour}:00")
  10. Understand YiriMirai's design philosophy and positioning

    YiriMirai is positioned as an SDK rather than a full-fledged framework, operating closer to the underlying layer to facilitate simple and pure communication with Mirai. Unlike some frameworks, YiriMirai does not provide built-in modularity to maintain simplicity and minimize overhead for users who do not require complex modular systems.
  11. Understand YiriMirai's four-layer architecture

    YiriMirai is designed with four decoupled layers to manage communication and data processing:

    1. Base Network Layer (mirai-api-http): The foundation that handles raw network communication.
    2. Base Layer (Adapters and Event Bus): Communicates directly with mirai-api-http to provide basic connectivity.
    3. Model Layer (mirai.models): An abstraction layer using Pydantic BaseModel to parse raw data from the base layer into structured objects for easier manipulation.
    4. Interface Layer (Mirai class): The top-level coordinator that provides a user-friendly API by integrating the functions of all underlying layers.
  12. Implement asynchronous event handlers

    Event handlers should be defined as async functions because API calls (like send_friend_message) are asynchronous and require await. Alternatively, you can use the 'quick response' mechanism by returning the coroutine directly from the handler, which YiriMirai will then execute automatically.