Skip to content

Command System

NekoBot provides a flexible command system that allows plugins to register and manage commands.

Command Overview

Commands are the main way for users to interact with the bot. Users trigger commands by sending messages in a specific format.

Command Format

Default command format: <command_prefix><command_name> [arg1] [arg2] ...

Examples:

/hello
/weather Beijing
/help group-management

Registering Commands

Basic Command Registration

Use the @register decorator to register commands:

python
from packages.backend.plugins.base import BasePlugin, register

class MyPlugin(BasePlugin):
    @register("hello", "Say hello")
    async def hello_command(self, args, message):
        await self.send_group_message(
            message['group_id'],
            message['user_id'],
            "Hello!"
        )

Commands with Aliases

python
@register("weather", "Check weather", aliases=["w", "weather"])
async def weather_command(self, args, message):
    location = args[0] if args else "Beijing"
    await self.send_group_message(
        message['group_id'],
        message['user_id'],
        f"Checking weather for {location}..."
    )

Command Arguments

Accessing Arguments

python
@register("greet", "Greet someone")
async def greet_command(self, args, message):
    if not args:
        await self.send_group_message(
            message['group_id'],
            message['user_id'],
            "Please specify who to greet, e.g., /greet Alice"
        )
        return
    
    name = args[0]
    await self.send_group_message(
        message['group_id'],
        message['user_id'],
        f"Hello, {name}!"
    )

Parsing Complex Arguments

python
@register("add", "Add two numbers")
async def add_command(self, args, message):
    try:
        num1 = float(args[0])
        num2 = float(args[1])
        result = num1 + num2
        await self.send_group_message(
            message['group_id'],
            message['user_id'],
            f"{num1} + {num2} = {result}"
        )
    except (IndexError, ValueError):
        await self.send_group_message(
            message['group_id'],
            message['user_id'],
            "Invalid format, use: /add number1 number2"
        )

Message Object

The message parameter received by command handler functions contains the following information:

python
{
    "message_id": 12345,
    "group_id": 67890,
    "user_id": 54321,
    "sender_name": "User Nickname",
    "message_type": "group",  # group or private
    "message": "/hello",
    "platform_id": "aiocqhttp",
    "raw_message": "...",  # Original message
    "timestamp": 1234567890
}

Subcommands

Implement subcommand system like Git:

python
@register("user", "User management")
async def user_command(self, args, message):
    if not args:
        await self.show_user_help(message)
        return
    
    subcommand = args[0]
    if subcommand == "info":
        await self.show_user_info(args[1:] if len(args) > 1 else None, message)
    elif subcommand == "list":
        await self.list_users(message)
    else:
        await self.send_group_message(
            message['group_id'],
            message['user_id'],
            f"Unknown subcommand: {subcommand}"
        )

async def show_user_info(self, args, message):
    user_id = args[0] if args else str(message['user_id'])
    await self.send_group_message(
        message['group_id'],
        message['user_id'],
        f"User ID: {user_id}"
    )

async def list_users(self, message):
    await self.send_group_message(
        message['group_id'],
        message['user_id'],
        "User list..."
    )

Command Conflict Handling

When multiple plugins register the same command, a conflict occurs. NekoBot provides conflict detection mechanism:

python
@register("hello", "Say hello")
async def hello_command(self, args, message):
    # Check for conflicts
    conflicts = check_command_conflicts("hello")
    if conflicts:
        await self.send_group_message(
            message['group_id'],
            message['user_id'],
            f"Command 'hello' has conflicts: {', '.join(conflicts)}"
        )
        return
    
    # Process command normally
    await self.send_group_message(
        message['group_id'],
        message['user_id'],
        "Hello!"
    )

Command Permissions

Implementing Permission Check

python
class MyPlugin(BasePlugin):
    def __init__(self):
        super().__init__()
        self.admins = [123456789]  # Admin list
    
    def is_admin(self, user_id):
        return user_id in self.admins
    
    @register("admin", "Admin command")
    async def admin_command(self, args, message):
        if not self.is_admin(message['user_id']):
            await self.send_group_message(
                message['group_id'],
                message['user_id'],
                "You don't have permission to execute this command"
            )
            return
        
        await self.send_group_message(
            message['group_id'],
            message['user_id'],
            "Admin command executed"
        )

Command Help

Auto-generating Help

python
class MyPlugin(BasePlugin):
    def __init__(self):
        super().__init__()
        self.commands = {
            "hello": {"description": "Say hello", "usage": "/hello"},
            "weather": {"description": "Check weather", "usage": "/weather [city]"},
        }
    
    @register("help", "Show help")
    async def help_command(self, args, message):
        if args:
            command = args[0]
            if command in self.commands:
                await self.show_command_help(command, message)
        else:
            await self.show_all_commands(message)
    
    async def show_command_help(self, command, message):
        cmd_info = self.commands[command]
        await self.send_group_message(
            message['group_id'],
            message['user_id'],
            f"Command: {command}\n"
            f"Description: {cmd_info['description']}\n"
            f"Usage: {cmd_info['usage']}"
        )
    
    async def show_all_commands(self, message):
        help_text = "Available commands:\n"
        for cmd, info in self.commands.items():
            help_text += f"/{cmd} - {info['description']}\n"
        await self.send_group_message(
            message['group_id'],
            message['user_id'],
            help_text
        )

Command Best Practices

  1. Parameter Validation: Always validate command parameters
  2. Error Messages: Provide clear error messages
  3. Help Documentation: Provide help documentation for each command
  4. Permission Control: Implement appropriate permission checks
  5. Response Time: Respond quickly, avoid long blocking

Command Management API

Check Command Conflicts

python
from packages.backend.core.command_management import check_command_conflicts

conflicts = check_command_conflicts("command_name")

Get All Commands

python
from packages.backend.core.command_management import get_all_commands

commands = get_all_commands()

Get Plugin Commands

python
from packages.backend.core.command_management import get_plugin_commands

commands = get_plugin_commands("plugin_name")

基于 MIT 许可发布