### example() Method Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/command.md Adds an example usage of the command. Multiple examples can be added. ```APIDOC ### `example()` ```typescript example(example: string): this ``` Add an example usage of the command. Multiple examples may be added. | Parameter | Type | Description | |-----------|------|-------------| | example | `string` | Example command usage | ``` -------------------------------- ### Install Koishi Source: https://github.com/koishijs/koishi/blob/master/_autodocs/README.md Install the Koishi framework using npm. This is the first step to setting up your chatbot. ```bash npm install koishi ``` -------------------------------- ### Usage Examples Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/command.md Illustrative examples of how to use the Command API. ```APIDOC ## Usage Examples ### Basic Command ```typescript ctx.command('hello', 'Say hello') .action(({ session }) => { return `Hello, ${session.username}!` }) ``` ### Command with Arguments ```typescript ctx.command('greet ', 'Greet someone') .action(({ session }, name) => { return `Hello, ${name}!` }) ``` ### Command with Options ```typescript ctx.command('send ', 'Send a message') .option('bold', 'Make bold', { type: Boolean, default: false }) .action(({ session, options }, message) => { if (options.bold) { message = `**${message}**` } return message }) ``` ### Subcommands ```typescript const cmd = ctx.command('admin', 'Admin commands') cmd.subcommand('reload', 'Reload plugins') .action(() => 'Reloading...') cmd.subcommand('ban ', 'Ban a user') .action(({ session }, user) => `Banned ${user}`) ``` ### Permission-Based Commands ```typescript ctx.command('secret', 'Secret command') .userFields(['authority']) .action(async (argv) => { if (argv.session.user?.authority < 2) { return 'You don\'t have permission' } return 'Secret content' }) ``` ### Command with Checkers ```typescript ctx.command('slow', 'Slow command') .before(({ session }) => { if (session.platform !== 'discord') { return 'Only on Discord' } }) .action(() => 'Executed!') ``` ### Multi-Action Command ```typescript ctx.command('process') .action(async (argv, next) => { console.log('Step 1') await next() }) .action(async (argv, next) => { console.log('Step 2') await next() }) .action(() => { console.log('Step 3') }) ``` ``` -------------------------------- ### Advanced Setup with Groups Source: https://github.com/koishijs/koishi/blob/master/_autodocs/configuration.md A complex setup demonstrating multiple adapters, a MySQL database, and advanced plugin options. ```yaml name: AdvancedBot prefix: ['.', '!'] nickname: ['alice', 'bot'] autoAssign: true autoAuthorize: 1 minSimilarity: 0.5 delay: character: 10 message: 100 cancel: 1000 broadcast: 500 prompt: 300000 plugins: http: timeout: 10000 server: port: 5500 host: 0.0.0.0 selfUrl: https://bot.example.com "adapter-group": $priority: 10 discord: token: "DISCORD_TOKEN" telegram: token: "TELEGRAM_TOKEN" "database-mysql": host: "db.example.com" port: 3306 username: "koishi" password: "secure_password" database: "koishi_prod" "@koishijs/plugin-admin": restricted: true ``` -------------------------------- ### Adding Command Example Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/command.md Adds an example usage string for the command. Multiple examples can be added to illustrate different ways to use the command. ```typescript example(example: string): this ``` -------------------------------- ### YAML Configuration Example Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/loader.md Example of Koishi configuration using YAML format. Shows plugin definitions and their settings. ```yaml plugins: http: {} proxy-agent: {} server: port: 5500 host: localhost "@koishijs/plugin-example": setting1: value1 setting2: value2 ``` -------------------------------- ### JSON Configuration Example Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/loader.md Example of Koishi configuration using JSON format. Demonstrates plugin structure and options. ```json { "plugins": { "http": {}, "proxy-agent": {}, "server": { "port": 5500, "host": "localhost" } } } ``` -------------------------------- ### JavaScript Configuration Example Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/loader.md Example of Koishi configuration using JavaScript (ES module) format. Exports a configuration object. ```javascript export default { plugins: { http: {}, 'proxy-agent': {}, server: { port: 5500, host: 'localhost', }, }, } ``` -------------------------------- ### Usage Examples Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/filter.md Examples demonstrating how to use the filter methods for various scenarios. ```APIDOC ## Usage Examples ### Basic Filtering ```typescript // Apply command only to Discord ctx.platform('discord').command('info', 'Bot info') .action(() => 'I am a bot!') // Apply command only to specific user ctx.user('123456789').command('admin') .action(() => 'Admin only') // Apply command only to specific channel ctx.channel('general', 'announcements').command('news') .action(() => 'Latest news...') ``` ``` ```APIDOC ### Platform-Specific Logic ```typescript // Different responses per platform ctx.platform('discord') .on('message', () => { // Discord-specific handling }) ctx.platform('telegram') .on('message', () => { // Telegram-specific handling }) ``` ``` -------------------------------- ### Plugin Meta Options Example Source: https://github.com/koishijs/koishi/blob/master/_autodocs/configuration.md Demonstrates special plugin meta options like priority, passive loading, and context filtering. ```yaml plugins: "plugin-name": $priority: 10 # Load order (higher = earlier) $passive: false # Don't load if not explicitly required $filter: true # Apply context filters # ... actual config ``` -------------------------------- ### Initialize Koishi Loader Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/loader.md Example of initializing the NodeLoader and loading the initial configuration file for a Koishi bot. ```typescript import NodeLoader from '@koishijs/loader' const loader = new NodeLoader() await loader.init('koishi.config.yml') const config = await loader.readConfig(true) ``` -------------------------------- ### Development Configuration Source: https://github.com/koishijs/koishi/blob/master/_autodocs/configuration.md Example configuration for a development environment, using SQLite for the database. ```yaml name: TestBot prefix: ['/'] plugins: http: {} server: port: 5500 "database-sqlite": path: "data/test.db" ``` -------------------------------- ### Custom Koishi Configuration File Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/loader.md An example of a `koishi.config.yml` file specifying bot name, plugins, and their configurations. ```yaml # koishi.config.yml name: MyBot plugins: http: {} server: port: 5500 "@koishijs/plugin-admin": restricted: true "my-custom-plugin": apiUrl: "https://api.example.com" timeout: 5000 ``` -------------------------------- ### Plugin Groups Example Source: https://github.com/koishijs/koishi/blob/master/_autodocs/configuration.md Shows how to organize plugins hierarchically using groups for nested structure and shared options. ```yaml plugins: admin-group: $priority: 10 ban: enabled: true kick: enabled: true mute: timeout: 3600000 ``` -------------------------------- ### Plugin Configuration Example Source: https://github.com/koishijs/koishi/blob/master/_autodocs/configuration.md Demonstrates how to configure plugins in the `plugins` section of the configuration file. Options are defined as key-value pairs within the plugin's name. ```yaml plugins: plugin-name: option1: value1 option2: value2 ``` -------------------------------- ### Command with Arguments Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/command.md Example of a command that accepts and uses a string argument. ```typescript ctx.command('greet ', 'Greet someone') .action(({ session }, name) => { return `Hello, ${name}!` }) ``` -------------------------------- ### Multi-Action Command Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/command.md Example of a command with multiple sequential actions that are executed in order. ```typescript ctx.command('process') .action(async (argv, next) => { console.log('Step 1') await next() }) .action(async (argv, next) => { console.log('Step 2') await next() }) .action(() => { console.log('Step 3') }) ``` -------------------------------- ### Multi-Platform Setup Source: https://github.com/koishijs/koishi/blob/master/_autodocs/configuration.md Configure Koishi to work on multiple platforms like Discord and Telegram by specifying their respective adapter tokens. ```yaml name: MultiBot prefix: ['/'] nickname: ['bot'] plugins: http: {} server: port: 5500 "adapter-discord": token: "YOUR_DISCORD_TOKEN" "adapter-telegram": token: "YOUR_TELEGRAM_TOKEN" "database-sqlite": path: "data/database.db" ``` -------------------------------- ### Production Configuration Source: https://github.com/koishijs/koishi/blob/master/_autodocs/configuration.md Example configuration for a production environment, using MySQL and environment variables for sensitive data. ```yaml name: ProductionBot prefix: ['/'] plugins: http: timeout: 10000 server: port: 8080 selfUrl: https://api.bot.com "database-mysql": host: "db.prod.example.com" username: "koishi" password: "${DATABASE_PASSWORD}" database: "koishi_prod" ``` -------------------------------- ### Environment Variables Configuration Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/loader.md Examples of setting Koishi configuration via environment variables, including direct variables and .env file usage. ```bash # Set configuration via env vars KOISHI_NAME=MyBot KOISHI_PLUGINS='{"http":{},"server":{"port":5500}}' # .env file KOISHI_NAME=MyBot DATABASE_URL=postgresql://... API_KEY=secret123 ``` -------------------------------- ### Localization Example Source: https://github.com/koishijs/koishi/blob/master/_autodocs/README.md Demonstrates Koishi's internationalization (i18n) features. It shows how to define translations for a locale and how to use them within a session. ```typescript ctx.i18n.define('en-US', { 'greeting': 'Hello!', 'farewell': 'Goodbye!', }) session.send(session.text('greeting')) ``` -------------------------------- ### Schema Composition Examples Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/schema.md Provides examples of common schema composition patterns: intersection, union, object, and array. ```typescript // Intersection: requires both schemas Schema.intersect([schema1, schema2]) // Union: accepts one of the schemas Schema.union([schema1, schema2]) // Object: combines multiple fields Schema.object({ field1: schema1, field2: schema2, }) // Array: list of schema items Schema.array(itemSchema) ``` -------------------------------- ### Basic Command Registration Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/command.md Example of registering a simple command that responds with a greeting. ```typescript ctx.command('hello', 'Say hello') .action(({ session }) => { return `Hello, ${session.username}!` }) ``` -------------------------------- ### Asynchronous Operations Example Source: https://github.com/koishijs/koishi/blob/master/_autodocs/README.md Highlights the asynchronous nature of I/O operations in Koishi. This snippet shows examples of awaiting database calls and prompts. ```typescript // Wait for database const user = await session.getUser() // Send and receive const response = await session.prompt() // Chain operations await ctx.database.setUser(platform, pid, data) ``` -------------------------------- ### Koishi Configuration File Source: https://github.com/koishijs/koishi/blob/master/_autodocs/README.md Example of a Koishi configuration file in YAML format. It shows how to enable plugins like http, server, and adapter-discord, including specific settings for the server port and Discord token. ```yaml # koishi.config.yml plugins: http: {} server: port: 5500 "adapter-discord": token: "YOUR_TOKEN" ``` -------------------------------- ### Create New Channel Example Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/database.md Illustrates creating a new channel with initial data, such as assignee and locales, triggered by a 'guild-added' event. ```typescript ctx.on('guild-added', async (payload) => { await ctx.database.createChannel( payload.platform, payload.guildId, { assignee: ctx.bot.selfId, locales: ['en-US'], } ) }) ``` -------------------------------- ### Permission-Based Logic Example Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/database.md Illustrates how to check user authority and permissions to implement role-based access control within message handlers. ```typescript ctx.on('message', async (session) => { const user = await session.getUser() if (user.authority >= 2) { // Admin-only logic } if (user.permissions.includes('manage_channels')) { // Permission check } }) ``` -------------------------------- ### Context Forking with Filters Source: https://github.com/koishijs/koishi/blob/master/_autodocs/README.md Illustrates how to create context forks for specific sessions using filters. This example shows filtering by platform and user. ```typescript ctx.platform('discord') // Discord only .user('123456') // Specific user .command('restricted') // Restricted command ``` -------------------------------- ### Subcommands Registration Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/command.md Example of creating a parent command with nested subcommands. ```typescript const cmd = ctx.command('admin', 'Admin commands') cmd.subcommand('reload', 'Reload plugins') .action(() => 'Reloading...') cmd.subcommand('ban ', 'Ban a user') .action(({ session }, user) => `Banned ${user}`) ``` -------------------------------- ### Programmatic Koishi Configuration Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/loader.md Example of configuring a Koishi bot programmatically using a TypeScript object, specifying bot name, prefixes, and plugins. ```typescript const config: Context.Config = { name: 'MyBot', prefix: ['/', '!'], plugins: { http: {}, 'proxy-agent': {}, server: { port: 5500, host: 'localhost', }, }, } const ctx = new Context(config) ``` -------------------------------- ### Plugin Development with Configuration Schema Source: https://github.com/koishijs/koishi/blob/master/_autodocs/README.md A TypeScript example demonstrating how to develop a Koishi plugin. It includes defining a configuration interface, a schema for validation and defaults, and the main plugin logic. ```typescript import { Context, Schema } from 'koishi' export interface Config { greeting: string } export const schema = Schema.object({ greeting: Schema.string() .default('Hello!') .description('Greeting message'), }) export function apply(ctx: Context, config: Config) { ctx.command('greet ', 'Greet someone') .action(({ session }, name) => { return `${config.greeting}, ${name}!` }) } ``` -------------------------------- ### Command with Before Hook Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/command.md Example of a command using the 'before' hook to perform checks before the action is executed. ```typescript ctx.command('slow', 'Slow command') .before(({ session }) => { if (session.platform !== 'discord') { return 'Only on Discord' } }) .action(() => 'Executed!') ``` -------------------------------- ### get() Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/i18n.md Get translated string for a given key, with support for locale fallback. It returns a map of locale to the translated string. ```APIDOC ## get() ### Description Get translated string for a given key, with support for locale fallback. It returns a map of locale to the translated string. ### Method Signature ```typescript get(key: string, locales?: string[]): Dict ``` ### Parameters - **key** (`string`) - Required - I18n key - **locales** (`string[]`) - Optional - Preferred locales ### Returns - `Dict` - Map of locale to translated string. ``` -------------------------------- ### Command with Options Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/command.md Example of a command that uses boolean options to modify its behavior. ```typescript ctx.command('send ', 'Send a message') .option('bold', 'Make bold', { type: Boolean, default: false }) .action(({ session, options }, message) => { if (options.bold) { message = `**${message}**` } return message }) ``` -------------------------------- ### Type-Safe Command with Generics Source: https://github.com/koishijs/koishi/blob/master/_autodocs/README.md Demonstrates Koishi's full TypeScript support with generics. This example shows a command with typed arguments and optional parameters, and how to access session user and channel data with specific fields. ```typescript ctx.command('typed [optional:number]') .userFields(['authority']) .channelFields(['guildId']) .action(async (argv, arg, optional) => { // arg: string, optional: number | undefined const user = argv.session.user // User with authority const channel = argv.session.channel // Channel with guildId }) ``` -------------------------------- ### Fetch User Data Example Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/database.md Demonstrates how to fetch user data, including specific fields like authority and permissions, within a message event handler. ```typescript ctx.on('message', async (session) => { const user = await ctx.database.getUser( session.platform, session.userId, { fields: ['authority', 'permissions'] } ) console.log('User authority:', user.authority) }) ``` -------------------------------- ### Message Handler Example Source: https://github.com/koishijs/koishi/blob/master/_autodocs/README.md A common pattern for handling incoming messages in Koishi. This snippet shows how to access user information and send a personalized greeting. ```typescript ctx.on('message', async (session) => { // Handle incoming message const user = await session.getUser() session.send(`Hello, ${user.name}`) }) ``` -------------------------------- ### Command with Options Source: https://github.com/koishijs/koishi/blob/master/_autodocs/README.md Example of defining a Koishi command that accepts arguments and options. This snippet demonstrates how to use the 'option' method and access option values within the action. ```typescript ctx.command('config ') .option('force', '-f', { type: Boolean }) .action(({ options }, key, value) => { if (options.force) { // Force action } }) ``` -------------------------------- ### Apply Command to Specific Platform Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/filter.md Example of applying a command only to sessions originating from the 'discord' platform. This ensures the command is only accessible in that environment. ```typescript // Apply command only to Discord ctx.platform('discord').command('info', 'Bot info') .action(() => 'I am a bot!') ``` -------------------------------- ### Get Assigned Channels for Broadcast Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/database.md Fetches assigned channels and maps their IDs for use in a broadcast message. This example shows how to get channel IDs and platforms. ```typescript ctx.command('broadcast ', 'Broadcast to all channels') .action(async (argv, message) => { const channels = await ctx.database.getAssignedChannels(['id', 'platform']) const ids = channels.map(c => `${c.platform}:${c.id}`) return ctx.broadcast(ids, message) }) ``` -------------------------------- ### Platform-Specific Event Handling (Discord) Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/filter.md Example demonstrating how to handle events differently based on the platform. This snippet shows Discord-specific logic for the 'message' event. ```typescript // Different responses per platform ctx.platform('discord') .on('message', () => { // Discord-specific handling }) ``` -------------------------------- ### Schema Validation Example Source: https://github.com/koishijs/koishi/blob/master/_autodocs/configuration.md Defines a schema for plugin configuration using Koishi's Schema utility, including required fields and default values. ```typescript export const schema = Schema.object({ apiKey: Schema.string() .required() .role('password'), timeout: Schema.natural() .default(5000) .role('ms'), debug: Schema.boolean() .default(false), }) ``` -------------------------------- ### Get Permission Graph Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/permissions.md The `subgraph` method retrieves related permissions by following either inheritance or dependency links starting from a set of parent permissions. ```typescript subgraph( type: 'inherits' | 'depends', parents: Iterable, result = new Set() ): Set ``` -------------------------------- ### Suggest Command from Input Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/session.md Use `session.suggest` to provide input suggestions to the user. This method helps in guiding user input by offering a list of expected options. ```typescript ctx.command('choose [name:string]', 'Choose an option') .action(async (argv) => { const { session } = argv const choice = await session.suggest({ expect: ['apple', 'banana', 'cherry'], actual: argv.args[0] || '', suffix: '?', }) return `You chose ${choice}` }) ``` -------------------------------- ### Appel Matching (Mention/Prefix) Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/middleware.md Register a matcher that requires the bot to be mentioned or the input to start with a prefix before matching 'remind'. It prompts the user for what to be reminded about. ```typescript ctx.match('remind', 'What should I remind you about?', { appel: true }) ``` -------------------------------- ### Platform-Specific Event Handling (Telegram) Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/filter.md Example demonstrating how to handle events differently based on the platform. This snippet shows Telegram-specific logic for the 'message' event. ```typescript ctx.platform('telegram') .on('message', () => { // Telegram-specific handling }) ``` -------------------------------- ### Basic Configuration Command Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/schema.md Demonstrates a basic Koishi command for configuring a plugin, showing how to define options with types and default values, and logging them when the command is executed. ```typescript ctx.command('config', 'Configure plugin') .option('timeout', '-t ', { default: 5000 }) .option('debug', '-d', { type: Boolean, default: false }) .action(({ options }) => { console.log(`Timeout: ${options.timeout}ms`) console.log(`Debug: ${options.debug}`) }) ``` -------------------------------- ### Create Koishi Bot Instance Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/loader.md Demonstrates how to create a Koishi bot instance using the NodeLoader, initializing the loader, and setting up the application context. ```typescript import { Context } from 'koishi' import NodeLoader from '@koishijs/loader' const loader = new NodeLoader() await loader.init('koishi.config.yml') const ctx = new Context() loader.app = ctx await loader.readConfig(true) ``` -------------------------------- ### Environment-Based Koishi Configuration Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/loader.md Shows how to configure Koishi using environment variables, including bot name, plugins, and database connection strings. ```bash # .env KOISHI_NAME=TestBot KOISHI_PLUGINS={"http":{},"server":{"port":5500}}} DATABASE_URL=sqlite:data/database.db API_KEY=secret123 ``` -------------------------------- ### Command Constructor Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/command.md Initializes a new Command instance with a name, declaration string, context, and configuration. ```APIDOC ## Constructor ```typescript constructor(name: string, decl: string, ctx: Context, config: Command.Config) ``` | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | name | `string` | Yes | Command name (normalized to lowercase with dashes) | | decl | `string` | Yes | Declaration string (usage pattern) | | ctx | `Context` | Yes | Context instance | | config | `Command.Config` | Yes | Configuration options | ``` -------------------------------- ### Permission-Based Command Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/command.md Example of a command that checks user authority before executing its action. ```typescript ctx.command('secret', 'Secret command') .userFields(['authority']) .action(async (argv) => { if (argv.session.user?.authority < 2) { return 'You don\'t have permission' } return 'Secret content' }) ``` -------------------------------- ### Registering a Plugin Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/context.md Demonstrates how to register a plugin with the Koishi framework using the `ctx.plugin()` method. The framework handles service registration and provides essential services like filtering, i18n, and permissions. ```typescript ctx.plugin(MyPlugin, options) ``` -------------------------------- ### Minimal Configuration Source: https://github.com/koishijs/koishi/blob/master/_autodocs/configuration.md This snippet shows a minimal Koishi configuration with HTTP support and a web server enabled. ```yaml plugins: http: {} server: port: 5500 ``` -------------------------------- ### List All Defined Permissions Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/permissions.md Create a command to list all available permissions. This is useful for debugging and understanding the permission landscape of your bot. ```typescript ctx.command('perms', 'List permissions') .action(() => { const all = ctx.permissions.list() return all.join('\n') }) ``` -------------------------------- ### fallback() Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/i18n.md Get the fallback chain for a given set of locales. This helps in determining the order in which locales should be checked for translations. ```APIDOC ## fallback() ### Description Get the fallback chain for a given set of locales. This helps in determining the order in which locales should be checked for translations. ### Method Signature ```typescript fallback(locales: string[]): string[] ``` ### Parameters - **locales** (`string[]`) - Required - Requested locales ### Returns - `string[]` - Array of locales in fallback order. ``` -------------------------------- ### Loader init() Method Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/loader.md Initializes the loader with an optional configuration file path. ```typescript async init(filename?: string): Promise ``` -------------------------------- ### Koishi Plugin Configuration Structure Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/loader.md Illustrates how to configure plugins in Koishi, including basic plugins, plugins with options, aliased plugins, disabled plugins, and meta options. ```yaml plugins: # Plugin with no config "plugin-name": {} # Plugin with config "plugin-with-config": option1: value1 option2: value2 # Plugin with alternate name "plugin-name@instance": instance-specific: config # Disabled plugin (prefixed with ~) "~disabled-plugin": {} # Meta options (prefixed with $) "plugin-name": $priority: 10 $passive: false actual: config ``` -------------------------------- ### Define Translations for 'zh-CN' Locale Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/i18n.md Example of defining multiple translations for the 'zh-CN' locale, mirroring the English translations with Chinese equivalents. ```typescript ctx.i18n.define('zh-CN', { 'hello': '你好!', 'commands.greet.description': '问候某人', 'commands.greet.arguments.name': '人名', 'errors.not-found': '未找到', }) ``` -------------------------------- ### Context Constructor Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/context.md Creates a new Context instance with optional configuration. The configuration object can include settings for i18n, delay, and request handling, as well as basic and advanced context settings. ```APIDOC ## Constructor Context ### Description Creates a new Context with optional configuration. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | config | `Context.Config` | No | `{}` | Configuration object for the context | ``` -------------------------------- ### plugin() Method Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/context.md Registers a plugin within the Koishi Context. The framework automatically sets up essential services like bot, database, session mixins, FilterService, I18n, Permissions, Processor, and SchemaService. ```APIDOC ## plugin() ### Description Registers a plugin within the Koishi Context. The framework automatically sets up essential services like bot, database, session mixins, FilterService, I18n, Permissions, Processor, and SchemaService. ### Method `ctx.plugin(MyPlugin, options)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | MyPlugin | `Plugin` | Yes | The plugin to register | | options | `any` | No | Optional configuration for the plugin | ``` -------------------------------- ### Get Localized Text Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/session.md Retrieves localized text from the i18n dictionary based on a path and optional parameters. Returns a plain string. ```typescript text(path: string | string[], params?: object): string ``` -------------------------------- ### Context Constructor Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/context.md Creates a new Context instance with optional configuration. This is the entry point for initializing a Koishi bot. ```typescript constructor(config: Context.Config = {}) ``` -------------------------------- ### Command Constructor Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/command.md Initializes a new Command instance with a name, declaration string, context, and configuration. ```typescript constructor(name: string, decl: string, ctx: Context, config: Command.Config) ``` -------------------------------- ### Update User Authority Example Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/database.md Shows how to update a user's authority level using the `setUser` method within a command action. ```typescript ctx.command('promote ', 'Promote user') .action(async (argv, userId) => { await ctx.database.setUser( 'discord', userId, { authority: 2 } ) return 'User promoted' }) ``` -------------------------------- ### Koishi Plugin Hot Reloading Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/loader.md Demonstrates how to implement hot reloading for plugins using `ctx.accept()`, allowing plugins to update their state when configuration changes. ```typescript export function apply(ctx: Context, config: Config) { ctx.accept((neo) => { // config updated to neo // Plugin can update state here }) } ``` -------------------------------- ### Send Translated Greeting on Message Event Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/i18n.md An example of how to use the `session.text()` method to retrieve a translated greeting and send it in response to a message event. ```typescript ctx.on('message', (session) => { const greeting = session.text('hello') session.send(greeting) }) ``` -------------------------------- ### Apply Command to Specific User Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/filter.md Example of restricting a command to a specific user ID. Only the user with the ID '123456789' can execute the 'admin' command. ```typescript // Apply command only to specific user ctx.user('123456789').command('admin') .action(() => 'Admin only') ``` -------------------------------- ### Execute Command Middleware Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/middleware.md Use the `` tag to run a command string and get its result. The command to execute is passed as the children of the tag. ```typescript {command} ``` -------------------------------- ### Create a Command with Context Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/context.md Define a new command using `ctx.command()` and specify its name, description, and action. The action handler receives a session object for interaction. ```typescript // Create a command ctx.command('hello', 'Say hello') .action(({ session }) => session.send('Hello!')) ``` -------------------------------- ### Namespace Organization Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/i18n.md Organize i18n definitions by feature or namespace to maintain a clear structure. This example defines messages for 'database' and 'api' features in 'en-US'. ```typescript ctx.i18n.define('en-US', { 'database.error.connection': 'Database connection failed', 'database.error.timeout': 'Database query timeout', 'api.error.unauthorized': 'Unauthorized access', 'api.error.rate-limit': 'Rate limit exceeded', }) ``` -------------------------------- ### Grouping Koishi Plugins Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/loader.md Shows how to group plugins hierarchically for batch management and organization within the Koishi configuration. ```yaml plugins: group-name: nested-plugin1: setting: value nested-plugin2: {} $priority: 10 ``` -------------------------------- ### option() Method Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/command.md Defines a command option with optional type conversion, description, and configuration. ```APIDOC ### `option()` ```typescript option(name: K, desc: string, config?: Argv.OptionConfig): Command> ``` Define a command option with optional type conversion. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | name | `string` | Yes | Option name (camelCased) | | desc | `string` | Yes | Option description | | config | `Argv.OptionConfig` | No | Type, default, authority settings | ``` -------------------------------- ### Define Scoped Translations for a Plugin Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/i18n.md Example of defining translations that are scoped to a specific plugin, using a unique namespace for keys like 'enabled' and 'disabled'. ```typescript ctx.i18n.define('plugin-name', { 'enabled': 'Plugin is enabled', 'disabled': 'Plugin is disabled', }) ``` -------------------------------- ### Hello World Bot Source: https://github.com/koishijs/koishi/blob/master/_autodocs/README.md A basic Koishi bot that responds to commands and messages. It sets up a context, registers a 'hello' command, and listens for 'ping' messages. ```typescript import { Context } from 'koishi' const ctx = new Context({ prefix: ['/'], nickname: ['bot'], }) ctx.command('hello', 'Say hello') .action(({ session }) => { return `Hello, ${session.username}!` }) ctx.on('message', (session) => { if (session.content === 'ping') { session.send('pong') } }) ``` -------------------------------- ### Apply Command to Specific Channels Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/filter.md Example of restricting a command to specific channel IDs. The 'news' command will only be active in channels named 'general' and 'announcements'. ```typescript // Apply command only to specific channel ctx.channel('general', 'announcements').command('news') .action(() => 'Latest news...') ``` -------------------------------- ### Initialize Koishi Context Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/context.md Initialize the Koishi Context with custom configuration options for prefixes, nicknames, and automatic assignments. This sets up the core environment for your bot. ```typescript import { Context } from 'koishi' const ctx = new Context({ prefix: ['/', '!'], nickname: ['bot', 'alice'], autoAssign: true, autoAuthorize: 1, delay: { character: 0, message: 100, cancel: 0, broadcast: 500, prompt: 60000, }, }) ``` -------------------------------- ### Permission Error Handling in Middleware Source: https://github.com/koishijs/koishi/blob/master/_autodocs/errors.md A middleware example that checks for user permissions before allowing access to an admin command. Throws a SessionError if permissions are insufficient. ```typescript ctx.middleware(async (session, next) => { const hasPermission = await ctx.permissions.test( ['admin'], session ) if (!hasPermission && session.content.startsWith('/admin')) { throw new SessionError('errors.permission-denied') } return next() }) ``` -------------------------------- ### Server Plugin Configuration Source: https://github.com/koishijs/koishi/blob/master/_autodocs/configuration.md Configures the Koishi server, specifying the port, host, and public URL. The `port` option defaults to 5500. ```yaml server: port: 5500 host: localhost selfUrl: "" maxPort: null ``` -------------------------------- ### Loader migrate() Method Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/loader.md Asynchronously runs configuration migrations to update settings. ```typescript async migrate(): Promise ``` -------------------------------- ### Get fallback chain for locales Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/i18n.md Determines the fallback order for a given array of requested locales. Returns an array of locales in the determined fallback sequence. ```typescript fallback(locales: string[]): string[] ``` -------------------------------- ### Command Configuration with Options Source: https://github.com/koishijs/koishi/blob/master/_autodocs/configuration.md Configures a command with options, including default values and custom types. ```typescript ctx.command('cmd', 'Description') .option('timeout', '-t ', { default: 5000 }) .option('silent', '-s', { type: Boolean }) .action(({ options }, ...args) => { // options.timeout, options.silent }) ``` -------------------------------- ### Get Schema Method Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/schema.md Retrieves a schema by its name. If the schema does not exist, it creates an empty intersection to ensure a valid schema object is always returned. ```typescript get(name: string): Schema ``` -------------------------------- ### PostgreSQL Database Configuration Source: https://github.com/koishijs/koishi/blob/master/_autodocs/configuration.md Configures the PostgreSQL database connection for Koishi. Requires host, port, user, password, and database name. ```yaml database-postgres: host: localhost port: 5432 user: postgres password: "" database: koishi ``` -------------------------------- ### Permissions.subgraph() Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/permissions.md Retrieves a permission graph by following either inheritance or dependency links starting from a set of parent permissions. Returns a Set of related permissions. ```APIDOC ## Permissions.subgraph() ### Description Get permission graph by following inheritance or dependency links. ### Method `subgraph(type: 'inherits' | 'depends', parents: Iterable, result = new Set()): Set` ### Parameters #### Path Parameters - **type** ('inherits' | 'depends') - Required - Graph type - **parents** (Iterable) - Required - Starting permissions - **result** (Set) - Optional - Result set to populate ### Returns - `Set` - Set of all related permissions. ``` -------------------------------- ### usage() Method Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/command.md Sets the command's usage text or function, which can be static or dynamic. ```APIDOC ### `usage()` ```typescript usage(text: Command.Usage): this ``` Set the command's usage text or function. | Parameter | Type | Description | |-----------|------|-------------| | text | `string \| (session: Session) => Awaitable` | Static or dynamic usage text | ``` -------------------------------- ### HTTP Plugin Configuration Source: https://github.com/koishijs/koishi/blob/master/_autodocs/configuration.md Configures the HTTP client for Koishi. Sets request timeout, proxy agent, and keep-alive options. Default timeout is 5000ms. ```yaml http: timeout: 5000 proxyAgent: "" keepAlive: true ``` -------------------------------- ### Conditional Translations with Pluralization Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/i18n.md Use `session.i18n` to handle conditional translations, such as pluralization based on a count. This example uses 'item' or 'items' depending on the value of `items.length`. ```typescript session.i18n('message.plural', { count: items.length, items: items.length === 1 ? 'item' : 'items' }) ``` -------------------------------- ### Check Permissions in Middleware Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/permissions.md Integrate permission checks directly into middleware. This example denies access to commands containing 'sensitive' if the user lacks 'admin-action' permission. ```typescript ctx.middleware(async (session, next) => { const hasAdmin = await ctx.permissions.test(['admin-action'], session) if (session.content.includes('sensitive') && !hasAdmin) { return 'Permission denied' } return next() }) ``` -------------------------------- ### Context.options Accessor (Deprecated) Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/context.md Deprecated accessor for the root context configuration. Use `koishi.config` instead for accessing bot configuration. ```typescript get options(): Context.Config ``` -------------------------------- ### Define Command with Translated Description and Action Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/i18n.md Demonstrates defining a command with a translated description key and using `session.text()` within the action to send a translated greeting that includes a name parameter. ```typescript ctx.command('greet ', 'commands.greet.description') .action(({ session }, name) => { return session.text('hello.with-name', { name }) }) ``` -------------------------------- ### Define Translations for 'en-US' Locale Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/i18n.md Example of defining multiple translations for the 'en-US' locale, including greetings, command descriptions, argument names, and error messages. ```typescript ctx.i18n.define('en-US', { 'hello': 'Hello!', 'commands.greet.description': 'Greet someone', 'commands.greet.arguments.name': 'Person name', 'errors.not-found': 'Not found', }) ``` -------------------------------- ### before() Method Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/context.md Registers a listener for a 'before-event' on a message handling event. Listeners are prepended by default, but can be appended if specified. ```APIDOC ## before() ### Description Register a listener for a before-event on a message handling event. The listener is prepended by default. ### Method `before(name: K, listener: BeforeEventMap[K], append = false): void` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | name | `K extends BeforeEventName` | Yes | Event name without 'before-' prefix | | listener | `BeforeEventMap[K]` | Yes | Event listener callback | | append | `boolean` | No | If true, listener is appended instead of prepended | ``` -------------------------------- ### Get Localized Content as h Elements Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/session.md Retrieves localized content as an array of h elements, which supports markup. Useful for rendering rich localized messages. ```typescript i18n(path: string | string[], params?: object): h[] ``` -------------------------------- ### suggest() Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/session.md Prompts the user to choose from a list of suggestions with fuzzy matching. It allows specifying expected options, actual input, and various configuration options for filtering and matching. ```APIDOC ## `suggest()` ### Description Prompt user to choose from suggestions with fuzzy matching. ### Parameters #### Path Parameters - **options.expect** (`string[]`) - Required - Expected options to suggest - **options.actual** (`string`) - Optional - Actual user input - **options.filter** (`Function`) - Optional - Custom filter for options - **options.prefix** (`string`) - Optional - Prefix for suggestions - **options.suffix** (`string`) - Required - Suffix for suggestions - **options.timeout** (`number`) - Optional - Timeout in milliseconds - **options.minSimilarity** (`number`) - Optional - Similarity threshold ``` -------------------------------- ### Basic Settings Interface Source: https://github.com/koishijs/koishi/blob/master/_autodocs/configuration.md Defines basic bot settings like command prefixes, nicknames, and fuzzy matching thresholds. Ensure prefixes are provided as an array of strings. ```typescript interface Basic extends Commander.Config { prefix?: string[] // Command prefixes prefixMode?: 'auto' | 'strict' // Prefix matching mode nickname?: string[] // Bot nicknames autoAssign?: Computed // Auto-assign channels autoAuthorize?: Computed // Default authority minSimilarity?: number // Fuzzy match threshold } ``` -------------------------------- ### Filter Based on Evaluated Expression Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/filter.md Use a computed function with `ctx.intersect()` for dynamic filtering based on session properties. This example restricts a command to only run on the Discord platform. ```typescript const botFilter = (session: Session) => { return session.platform === 'discord' } ctx .intersect(botFilter) .command('discord-only') .action(() => 'Discord!') ``` -------------------------------- ### Admin in Specific Channel Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/filter.md Combine multiple filters like user and channel to create a highly specific context. This example targets administrators in a designated staff channel. ```typescript ctx .user('admin123', 'admin456') .channel('staff-channel') .command('staff-action') .action(() => 'Staff action') ``` -------------------------------- ### action() Method Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/command.md Registers a command action handler. Multiple actions form a chain. ```APIDOC ### `action()` ```typescript action(callback: Command.Action, prepend = false): this ``` Register a command action handler. Multiple actions form a chain. | Parameter | Type | Description | |-----------|------|-------------| | callback | `Command.Action` | Action function | | prepend | `boolean` | If true, prepends instead of appends | ``` -------------------------------- ### Fallback Locales Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/i18n.md Use fallback locales to ensure a message is translated even if the primary locale is not available. This example tries 'zh-CN', then 'en-US', and finally the default locale. ```typescript ctx.on('message', (session) => { // Try zh-CN, then en-US, then default const text = session.text('message', {}, ['zh-CN', 'en-US']) session.send(text) }) ``` -------------------------------- ### Defining Custom Permissions Source: https://github.com/koishijs/koishi/blob/master/_autodocs/README.md Example of defining a custom permission check in Koishi. This snippet shows how to use 'permissions.define' with a 'check' function to implement custom authorization logic. ```typescript ctx.permissions.define('admin', { check: async (_, session) => { return session.user?.authority >= 3 }, }) ``` -------------------------------- ### MySQL Database Configuration Source: https://github.com/koishijs/koishi/blob/master/_autodocs/configuration.md Configures the MySQL database connection for Koishi. Requires host, port, username, password, and database name. ```yaml database-mysql: host: localhost port: 3306 username: root password: "" database: koishi ``` -------------------------------- ### Observe and Persist User Changes Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/database.md Demonstrates observing user data, making modifications (e.g., adding a permission), and then persisting those changes using `$update()`. ```typescript ctx.on('message', async (session) => { const user = await session.observeUser(['authority', 'permissions']) // Make changes user.permissions.push('admin') // Persist changes await user.$update() }) ``` -------------------------------- ### SQLite Database Configuration Source: https://github.com/koishijs/koishi/blob/master/_autodocs/configuration.md Configures the SQLite database for Koishi. Specify the database file path using the `path` option. ```yaml database-sqlite: path: data/koishi.db ``` -------------------------------- ### Match Discord OR Telegram using Union Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/filter.md Employ `ctx.union()` to create a filter that matches if any of the provided conditions are met. This example allows a command to work on either Discord or Telegram. ```typescript ctx.platform('discord').union(ctx.platform('telegram')) .command('social', 'Social command') .action(() => 'Working on both platforms!') ``` -------------------------------- ### createUser Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/database.md Creates a new user entry in the database with the provided platform, user ID, and initial data. ```APIDOC ## createUser ### Description Creates a new user in the database. ### Method `createUser` ### Parameters #### Path Parameters - **platform** (string) - Required - Platform identifier - **pid** (string) - Required - Platform-specific user ID - **data** (Partial) - Required - Initial user data ### Response #### Success Response - Returns a Promise that resolves to the newly created User object. ``` -------------------------------- ### Handling Command Error Events Source: https://github.com/koishijs/koishi/blob/master/_autodocs/errors.md Listens for the 'command-error' event emitted by Koishi commands. Logs the command source and the error, and includes an example for reporting to a service like Sentry. ```typescript ctx.on('command-error', (argv, error) => { logger.error(`Command failed: ${argv.source}`) logger.error(error) // Custom error tracking reportToSentry(error) }) ``` -------------------------------- ### Get Channel Data Method Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/session.md Fetches channel data from the database. Allows specifying a channel ID and specific fields to retrieve. Defaults to the current channel if no ID is provided. ```typescript getChannel( id?: string, fields?: K[] ): Promise ``` -------------------------------- ### Pattern Matching (Text) Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/middleware.md Registers a handler that responds to a specific text input. This is a simple way to create command-like behavior. ```APIDOC ## Pattern Matching (Text) ### Description Registers a handler for a simple text match. ### Method `ctx.match(pattern, response)` ### Parameters - **pattern** (`string`) - Required - The exact text to match. - **response** (`string`) - Required - The response to send when the pattern matches. ``` -------------------------------- ### Get User Data Method Source: https://github.com/koishijs/koishi/blob/master/_autodocs/api-reference/session.md Fetches user data from the database. Allows specifying a user ID and specific fields to retrieve. Defaults to the current user if no ID is provided. ```typescript getUser(userId?: string, fields?: K[]): Promise ```