NoneBot2 Documentation

repository·master·Indexed 27 days ago

https://github.com/nonebot/nonebot2

An asynchronous Python-based framework for building bots across various chat platforms. NoneBot2 features a modular plugin system, dependency injection, and support for multiple communication protocols (adapters) including OneBot, Telegram, Feishu, GitHub, and Discord. It supports driver frameworks such as FastAPI, Quart, aiohttp, and httpx, and provides the nb-cli tool for project scaffolding and management. Requires Python 3.9 or higher.

Tokens
71.1K
Snippets
199
Records
317
Agent score
93%

What's inside NoneBot2

  1. Overview of nonebot-plugin-alconna features

    master

    nonebot-plugin-alconna improves the NoneBot development experience through three main components:

    1. Enhanced Command Parsing: Uses Alconna to provide the on_alconna event responder, offering superior parsing compared to on_command or on_regex.
    2. Universal Message Components: Provides cross-platform message handling via:
      • UniMessage: A universal message model for conversion and exporting across adapters.
      • Message Segments: Text, Image, At, etc., compatible with both UniMessage and Alconna parsing.
      • Functionality: message_recall, message_edit, message_reaction.
      • Target: A universal model for active message sending.
      • Dependency Injection/Rules: UniMsg, MsgId, MsgTarget, at_in, at_me.
    3. Built-in Feature Plugins:
      • echo: Echoes reply messages.
      • help: Lists help information for on_alconna responders.
      • lang: Switches Alconna language.
      • switch: Enables/disables specific commands.
      • with: Loads command headers in the current session for sub-commands to save typing.
  2. Introduction to Alconna

    master

    Alconna is a simple, flexible, and efficient command parameter parser that is not limited to parsing command strings. It uses core components like Args, Subcommand, and Option to define command structures and returns an Arparma instance upon parsing.

    from arclet.alconna import Alconna, Args, Subcommand, Option
    
    alc = Alconna(
        "pip",
        Subcommand(
            "install",
            Args["package", str],
            Option("-r|--requirement", Args["file", str]),
            Option("-i|--index-url", Args["url", str]),
        )
    )
    
    res = alc.parse("pip install nonebot2 -i URL")
    
    print(res.all_matched_args)
    # {'package': 'nonebot2', 'url': 'URL'}
  3. Overview of NoneBot2

    master
    NoneBot2 is a modern, cross-platform, and extensible Python chatbot framework. It is built with an asynchronous-first approach (compatible with synchronous functions) and leverages Python type annotations to provide flexible support for various chatbot requirements. Users can use NoneBot without writing code by simply configuring the environment and installing existing plugins.
  4. Overview of NoneBot

    master
    NoneBot2 is a modern, cross-platform, and extensible Python chatbot framework. It leverages Python's type annotations and asynchronous capabilities to provide flexible support for various chatbot requirements. It supports multiple platforms including OneBot (v11/v12), QQ Bot, Telegram, Feishu, and GitHub.
  5. Understand Dependency Injection in NoneBot

    master

    NoneBot uses dependency injection to provide context information (like the current event or bot) to event handlers. This allows for cleaner, more reusable code.

    Key concepts:

    • Dependent: A callable (like an event handler or a custom dependency function) that uses dependency injection.
    • Dependency: The object being injected (e.g., the current Event, Bot, etc.).

    Important Rules:

    • Type Annotations are critical: They determine which dependency is injected and trigger the overload mechanism. If a type annotation does not match the actual data type, the Dependent (the handler) will be skipped.
    • Non-dependency parameters: Any parameter that cannot be resolved as a dependency and has a default value is treated as a standard non-dependency parameter and will use its default value.
    • Error Handling: If a parameter cannot be resolved and has no default value, a ValueError("Unknown parameter") is raised.
    • Debugging: To inspect the dependency resolution process, set the log level to TRACE in your configuration.
  6. Understand Permission control in NoneBot

    master

    NoneBot uses Permission objects to filter events before they reach event responders. A Permission is composed of one or more PermissionChecker functions.

    Key differences between Permission and Rule:

    1. Execution Order: Permission checks occur before Rule checks.
    2. Logic: Permission passes if any one of its PermissionChecker functions returns True (OR logic).
    3. Context: The session state is not available during permission checking.
    4. Persistence: While Rule is typically checked only when an event responder is first triggered, Permission remains continuously active throughout a conversation, restricting the event subject in subsequent interactions.
  7. Key Features of NoneBot2

    master

    NoneBot2 provides several core architectural features:

    • Asynchronous First: Built on asyncio or trio, with compatibility for synchronous functions.
    • Full Type Annotations: Implements PEP 484 for complete type hinting, enabling robust error checking via Pyright (Pylance) and improved editor support.
    • Plugin System: A modular core that allows for easy functional extension and maintenance.
    • Dependency Injection System: A custom system that allows code to declare its requirements (dependencies), which the system then provides (injects). This reduces code redundancy and coupling, making it ideal for sharing logic, database sessions (e.g., httpx.AsyncClient, sqlalchemy.Session), or user authentication/permission checks.
    • Out-of-the-box Experience: Includes nb-cli, an interactive command-line tool designed to simplify the setup and management process.
  8. Understand the core components of a NoneBot robot

    master

    A NoneBot robot consists of four primary components that work together to handle messaging and functionality:

    1. NoneBot Framework Core: The central body responsible for connecting all components and providing basic robot functionality.
    2. Driver (Driver): Implements client/server functionality. It is responsible for receiving and sending messages, typically via HTTP communication.
    3. Adapter (Adapter): Sits on top of the Driver. It is responsible for converting platform-specific messages into the NoneBot event/operating system message format.
    4. Plugin (Plugin): The implementation of the robot's actual features. Plugins typically handle events and perform a series of operations.

    While the Framework Core is mandatory, the Driver, Adapter, and Plugins can be selected and combined according to your needs. Note that some plugins may only be compatible with specific platforms depending on how they were written.

  9. Understand Event Responder Composition

    master

    An Event Responder in NoneBot consists of several key components that determine how and when a handler is triggered:

    • Type (type): The event type the responder listens for (e.g., meta_event, message, notice, request). An empty string "" matches all event types. Type checking happens before permission and rule checks.
    • Permission (permission): A Permission object checked after the type check. If it passes, the responder proceeds to rule checking.
    • Rule (rule): A Rule object checked after permission. If it passes, the responder is triggered.
    • Priority (priority): A positive integer. Lower values are triggered first. If priorities are equal, they are triggered in registration order.
    • Block (block): A boolean. If True, the event propagation stops after this responder is triggered, preventing lower-priority responders from receiving it.
    • Lifespan:
      • temp: If True, the responder is automatically destroyed after being triggered once.
      • expire_time: A datetime object. If set, the responder is destroyed after this time.
    • Default State (default_state): A dict used to initialize the responder's state when triggered.
  10. Quickstart: Install and run NoneBot2

    master

    To get started with NoneBot2, use the nb-cli scaffolding tool. This process involves installing pipx, then the CLI, and finally creating and running your project.

    1. Install pipx:
      python -m pip install --user pipx
      python -m pipx ensurepath
    2. Install the nb-cli scaffolding:
      pipx install nb-cli
    3. Create a new project:
      nb create
    4. Run your project:
      nb run
    python -m pip install --user pipx
    python -m pipx ensurepath
    pipx install nb-cli
    nb create
    nb run
  11. Construct a Message sequence

    master

    A Message is a sequence of MessageSegment objects (a subclass of List[MessageSegment]). You can construct it in several ways:

    1. Directly: Pass a str, a MessageSegment, an Iterable[MessageSegment], or adapter-specific types to the Message constructor.
    2. Arithmetic: Use the + operator to combine str, Message objects, or MessageSegment objects.
    3. From Dictionaries: Use Pydantic's TypeAdapter to validate and construct MessageSegment or Message from dictionary/list data.

    Note: Always ensure the Message type matches the platform adapter you are using (e.g., use nonebot.adapters.console.Message for Console adapter).

    from nonebot.adapters.console import Message, MessageSegment
    
    # Direct construction
    Message("Hello, world!")
    Message(MessageSegment.text("Hello, world!"))
    Message([MessageSegment.text("Hello, world!")])
    
    # From dictionaries using Pydantic
    from pydantic import TypeAdapter
    TypeAdapter(MessageSegment).validate_python(
        {"type": "text", "data": {"text": "text"}}
    )
    
    TypeAdapter(Message).validate_python(
        [MessageSegment.text("text"), {"type": "text", "data": {"text": "text"}}],
    )