### Basic Koishi Bot Setup
Source: https://github.com/koishijs/docs/blob/main/en-US/manual/starter/direct.md
This TypeScript code sets up a basic Koishi instance, enables the console, sandbox, and echo plugins, and starts the application. Ensure Node.js v18+ is installed.
```typescript
import { Context } from 'koishi'
import console from '@koishijs/plugin-console'
import * as sandbox from '@koishijs/plugin-sandbox'
import * as echo from '@koishijs/plugin-echo'
// Create a Koishi instance
const ctx = new Context({
port: 5140,
})
// Enable the above plugins
ctx.plugin(console) // Provides a console
ctx.plugin(sandbox) // Provides a debugging sandbox
ctx.plugin(echo) // Provides an echo command
// Start the application
ctx.start()
```
--------------------------------
### Initialize Project and Install Koishi with Plugins (npm)
Source: https://github.com/koishijs/docs/blob/main/en-US/manual/starter/direct.md
Use npm to initialize your project and install Koishi along with essential plugins like console, sandbox, and echo. TypeScript dependencies are also installed.
```bash
# Initialize project
npm init
# Install Koishi and related plugins
npm i koishi \
@koishijs/plugin-console \
@koishijs/plugin-sandbox \
@koishijs/plugin-echo
# Install TypeScript related dependencies (ignore if not using)
npm i typescript @types/node esbuild esbuild-register -D
```
--------------------------------
### Initialize Project and Install Koishi with Plugins (yarn)
Source: https://github.com/koishijs/docs/blob/main/en-US/manual/starter/direct.md
Use yarn to initialize your project and install Koishi along with essential plugins like console, sandbox, and echo. TypeScript dependencies are also installed.
```bash
# Initialize project
yarn init
# Install Koishi and related plugins
yarn add koishi
@koishijs/plugin-console \
@koishijs/plugin-sandbox \
@koishijs/plugin-echo
# Install TypeScript related dependencies (ignore if not using)
yarn add typescript @types/node esbuild esbuild-register -D
```
--------------------------------
### Basic Server Serve and Dispose
Source: https://github.com/koishijs/docs/blob/main/en-US/cookbook/design/disposable.md
This example demonstrates a basic function that starts a server and returns a function to close it. Use this pattern when you need to manage a single, immediate side effect with a corresponding cleanup action.
```typescript
function serve(port: number) {
const server = createServer().listen(port)
return () => server.close()
}
const dispose = serve(80) // 监听端口 80
dispose() // 回收副作用
```
--------------------------------
### Install and Bootstrap Koishi Project
Source: https://context7.com/koishijs/docs/llms.txt
Use npm or yarn to create a new Koishi project. Run `npm run dev` to start the bot in hot-module reload mode. The Koishi console is accessible at http://localhost:5140.
```sh
# Using npm
npm init koishi@latest
# Using yarn
yarn create koishi
# Start the bot
npm run dev # hot-module reload mode
# The Koishi console opens at http://localhost:5140 by default
```
--------------------------------
### Basic Koishi Application Start Script
Source: https://github.com/koishijs/docs/blob/main/en-US/guide/develop/script.md
Defines scripts in `package.json` for starting the Koishi application in production and development modes. The `start` script is for general use, while `dev` includes additional options for development.
```json
{
"scripts": {
"dev": "cross-env NODE_ENV=development koishi start -r esbuild-register -r yml-register",
"start": "koishi start"
}
}
```
--------------------------------
### Start Koishi Application with npm
Source: https://github.com/koishijs/docs/blob/main/en-US/manual/starter/boilerplate.md
Starts the Koishi application using npm. This command is typically used after the project has been initialized.
```bash
npm start
```
--------------------------------
### Check Git Installation
Source: https://github.com/koishijs/docs/blob/main/en-US/guide/develop/setup.md
Verify that Git is installed correctly by checking its version in the command line.
```sh
git --version # git version 2.39.1
```
--------------------------------
### Command Trigger Examples
Source: https://github.com/koishijs/docs/blob/main/en-US/manual/usage/command.md
These examples show different ways to trigger commands based on prefix and nickname settings.
```text
Shiki-chan, echo hello
@Shiki-chan echo hello
/echo hello
```
--------------------------------
### Start Koishi Application with Yarn
Source: https://github.com/koishijs/docs/blob/main/en-US/manual/starter/boilerplate.md
Starts the Koishi application using Yarn. This command is typically used after the project has been initialized.
```bash
yarn start
```
--------------------------------
### Install Adapter Plugins (npm)
Source: https://github.com/koishijs/docs/blob/main/en-US/manual/starter/direct.md
Install adapter plugins for integrating Koishi with chat platforms like Satori and Discord using npm.
```bash
# Install Satori and Discord adapters as examples
npm i @koishijs/plugin-adapter-satori \
@koishijs/plugin-adapter-discord
```
--------------------------------
### View Specific Command Help
Source: https://github.com/koishijs/docs/blob/main/en-US/manual/usage/command.md
To get detailed information about a specific command, append the command name to the 'help' command. This example shows help for the 'echo' command.
```plaintext
help echo
```
--------------------------------
### Install Adapter Plugins (yarn)
Source: https://github.com/koishijs/docs/blob/main/en-US/manual/starter/direct.md
Install adapter plugins for integrating Koishi with chat platforms like Satori and Discord using yarn.
```bash
# Install Satori and Discord adapters as examples
yarn add @koishijs/plugin-adapter-satori \
@koishijs/plugin-adapter-discord
```
--------------------------------
### Running Koishi Application with npm or yarn
Source: https://github.com/koishijs/docs/blob/main/en-US/guide/develop/script.md
Commands to start the Koishi application using either npm or yarn package managers. These commands execute the `start` script defined in `package.json`.
```bash
npm run start
```
```bash
yarn start
```
--------------------------------
### Install and Import Koishi Plugins
Source: https://github.com/koishijs/docs/blob/main/en-US/manual/starter/direct.md
Install necessary plugins using yarn and import them into your index.ts file. Note the difference between default and named exports for plugins.
```bash
yarn add koishi-plugin-puppeteer koishi-plugin-forward
```
```typescript
import puppeteer from 'koishi-plugin-puppeteer'
import * as forward from 'koishi-plugin-forward'
ctx.plugin(puppeteer) // Provides browser service
ctx.plugin(forward) // Provides message forwarding
```
--------------------------------
### Example Usage of Dictionary Schemas
Source: https://github.com/koishijs/docs/blob/main/en-US/schema/basic/dict.md
This example demonstrates defining a configuration object that includes a basic dictionary, a dictionary rendered as a table, and a dictionary of objects also rendered as a table.
```typescript
export default Schema.object({
dict: Schema.dict(Boolean),
table: Schema.dict(String).role('table'),
table2: Schema.dict(Schema.object({
foo: Schema.string(),
bar: Schema.number(),
})).role('table'),
})
```
--------------------------------
### Install Community Plugins (npm)
Source: https://github.com/koishijs/docs/blob/main/en-US/manual/starter/direct.md
Install community plugins, such as puppeteer and forward, using npm. Plugins typically follow naming conventions like `koishi-plugin-foo` or `@koijs/plugin-foo`.
```bash
# Using puppeteer and forward plugins as examples
npm i koishi-plugin-puppeteer koishi-plugin-forward
```
--------------------------------
### Install Community Plugins (yarn)
Source: https://github.com/koishijs/docs/blob/main/en-US/manual/starter/direct.md
Install community plugins, such as puppeteer and forward, using yarn. Plugins typically follow naming conventions like `koishi-plugin-foo` or `@koijs/plugin-foo`.
```bash
# Using puppeteer and forward plugins as examples
yarn add koishi-plugin-puppeteer koishi-plugin-forward
```
--------------------------------
### Full Example of Union Select in Object
Source: https://github.com/koishijs/docs/blob/main/en-US/schema/advanced/union-select.md
This example demonstrates a complete object schema definition incorporating both a simple union select and a union select configured as radio buttons, including descriptions for each field and option.
```typescript
export default Schema.object({
value1: Schema.union(['foo', 'bar', 'qux']),
value2: Schema.union([
Schema.const('foo').description('选项 1'),
Schema.const('bar').description('选项 2'),
Schema.const('baz').description('选项 3'),
]).role('radio'),
})
```
--------------------------------
### Create Koishi Project with npm
Source: https://github.com/koishijs/docs/blob/main/en-US/guide/develop/setup.md
Initialize a new Koishi project using the npm package initializer. Follow the on-screen prompts to complete the setup.
```npm
npm init koishi@latest
```
--------------------------------
### Create Koishi Project with Yarn
Source: https://github.com/koishijs/docs/blob/main/en-US/guide/develop/setup.md
Initialize a new Koishi project using the Yarn create command. Follow the on-screen prompts to complete the setup.
```yarn
yarn create koishi
```
--------------------------------
### Execute Download Logic in Postinstall Script
Source: https://github.com/koishijs/docs/blob/main/en-US/cookbook/design/storage.md
Create a Node.js script (e.g., `src/download.ts`) to handle the downloading of necessary files. This script should be invoked by the `postinstall` script defined in `package.json`.
```typescript
async function download() {
// Download required files to the root directory
}
if (require.main === module) {
download()
}
```
--------------------------------
### Update Task Start Date
Source: https://github.com/koishijs/docs/blob/main/en-US/plugins/adapter/dingtalk.md
Updates the start date of a task.
```APIDOC
## internal.updateTaskStartdate()
### Description
Updates the start date of a task.
### Method
POST
### Endpoint
/updateTaskStartdate
### Parameters
#### Request Body
- **taskId** (string) - Required - The ID of the task.
- **startDate** (string) - Required - The new start date for the task (e.g., YYYY-MM-DD).
```
--------------------------------
### Get Channel Webhooks
Source: https://github.com/koishijs/docs/blob/main/zh-CN/plugins/adapter/discord.md
Gets a list of channel webhooks. Requires the `MANAGE_WEBHOOKS` permission.
```APIDOC
## GET /channels/:channel.id/webhooks
### Description
Gets a list of channel webhooks.
### Method
GET
### Endpoint
`/channels/:channel.id/webhooks`
### Parameters
#### Path Parameters
- **channel.id** (snowflake) - Required - The ID of the channel.
### Response
#### Success Response (200 OK)
- **webhooks** (array[object]) - An array of webhook objects.
```
--------------------------------
### Plugin Configuration Example
Source: https://github.com/koishijs/docs/blob/main/en-US/guide/develop/config.md
Demonstrates how to configure a specific plugin, `dialogue`, within the `plugins` section of the `koishi.yml` file.
```yaml
plugins:
dialogue:
# This is the configuration for koishi-plugin-dialogue
context:
enable: true
```
--------------------------------
### Get Current Authorization Information
Source: https://github.com/koishijs/docs/blob/main/zh-CN/plugins/adapter/discord.md
Gets information about the current authorization. Requires the `identify` scope.
```APIDOC
## GET /oauth2/applications/@me
### Description
Gets information about the current authorization.
### Method
GET
### Endpoint
`/oauth2/applications/@me`
### Response
#### Success Response (200 OK)
- **id** (snowflake) - The ID of the application.
- **name** (string) - The name of the application.
- **description** (string) - The description of the application.
- **rpc_origins** (array[string]) - An array of RPC origins.
- **flags** (integer) - The flags of the application.
```
--------------------------------
### Configure Postinstall Script for Download
Source: https://github.com/koishijs/docs/blob/main/en-US/cookbook/design/storage.md
To download dependencies during installation, modify the `package.json` to include a `postinstall` script that executes a Node.js file responsible for the download process. This is suitable for small dependencies (under 10MB).
```json
{
"scripts": {
"postinstall": "node lib/download"
}
}
```
--------------------------------
### Get Current User Guilds
Source: https://github.com/koishijs/docs/blob/main/zh-CN/plugins/adapter/discord.md
Gets the current user's guilds. Requires the `guilds` scope.
```APIDOC
## GET /users/@me/guilds
### Description
Gets the current user's guilds.
### Method
GET
### Endpoint
`/users/@me/guilds`
### Query Parameters
- **before** (snowflake) - Optional - Get guilds before this guild ID.
- **after** (snowflake) - Optional - Get guilds after this guild ID.
- **limit** (integer) - Optional - Max number of guilds to return (1-100).
### Response
#### Success Response (200 OK)
- **guilds** (array[object]) - An array of guild objects.
```
--------------------------------
### Initialize Bundle Project
Source: https://github.com/koishijs/docs/blob/main/en-US/cookbook/practice/bundle.md
Run this command in your template project to initialize it as a bundle. This allows you to publish the entire workspace.
```sh
git init
```
--------------------------------
### Get Current User
Source: https://github.com/koishijs/docs/blob/main/zh-CN/plugins/adapter/discord.md
Gets the user object for the currently authenticated bot/user. Requires the `identify` scope.
```APIDOC
## GET /users/@me
### Description
Gets the user object for the currently authenticated bot/user.
### Method
GET
### Endpoint
`/users/@me`
### Response
#### Success Response (200 OK)
- **id** (snowflake) - The ID of the user.
- **username** (string) - The username of the user.
- **discriminator** (string) - The discriminator of the user.
- **avatar** (string) - The avatar hash of the user.
- **bot** (boolean) - Whether the user is a bot.
```
--------------------------------
### Get Auto Moderation Rule
Source: https://github.com/koishijs/docs/blob/main/zh-CN/plugins/adapter/discord.md
Gets a single auto moderation rule. Requires the `MANAGE_RULES` permission.
```APIDOC
## GET /guilds/:guild.id/auto-moderation/rules/:auto_moderation_rule.id
### Description
Gets a single auto moderation rule.
### Method
GET
### Endpoint
`/guilds/:guild.id/auto-moderation/rules/:auto_moderation_rule.id`
### Parameters
#### Path Parameters
- **guild.id** (snowflake) - Required - The ID of the guild.
- **auto_moderation_rule.id** (snowflake) - Required - The ID of the auto moderation rule.
### Response
#### Success Response (200 OK)
- **id** (snowflake) - ID of the rule.
- **guild_id** (snowflake) - ID of the guild to which the rule belongs.
- **name** (string) - Name of the rule.
- **creator_id** (snowflake) - ID of the user who created the rule.
- **event_type** (integer) - Type of event to trigger the rule on.
- **trigger_type** (integer) - Type of content to match.
- **trigger_metadata** (object) - Metadata for the rule trigger.
- **actions** (array[object]) - Actions to take when the rule is triggered.
- **enabled** (boolean) - Whether the rule is enabled.
```
--------------------------------
### Get Followup Message
Source: https://github.com/koishijs/docs/blob/main/zh-CN/plugins/adapter/discord.md
Gets a followup message. This can be used to retrieve messages initially sent as followup messages.
```APIDOC
## GET /webhooks/:application.id/:interaction.token/messages/:message.id
### Description
Gets a followup message.
### Method
GET
### Endpoint
`/webhooks/:application.id/:interaction.token/messages/:message.id`
### Parameters
#### Path Parameters
- **application.id** (snowflake) - Required - Your application ID.
- **interaction.token** (string) - Required - The token of the interaction.
- **message.id** (snowflake) - Required - The ID of the message to retrieve.
### Response
#### Success Response (200 OK)
- **id** (snowflake) - The ID of the message.
- **channel_id** (snowflake) - The ID of the channel the message was sent in.
- **content** (string) - The content of the message.
- **embeds** (array[object]) - An array of embed objects.
```
--------------------------------
### Get Application Command Permissions
Source: https://github.com/koishijs/docs/blob/main/zh-CN/plugins/adapter/discord.md
Gets the permissions for a specific application command in a guild. Requires the `APPLICATIONS.commands` scope.
```APIDOC
## GET /applications/:application.id/guilds/:guild.id/commands/:command.id/permissions
### Description
Gets the permissions for a specific application command in a guild.
### Method
GET
### Endpoint
`/applications/:application.id/guilds/:guild.id/commands/:command.id/permissions`
### Parameters
#### Path Parameters
- **application.id** (snowflake) - Required - The ID of the application.
- **guild.id** (snowflake) - Required - The ID of the guild.
- **command.id** (snowflake) - Required - The ID of the command.
### Response
#### Success Response (200 OK)
- **permissions** (array[object]) - Array of application command permissions.
- **id** (snowflake) - ID of the role or user.
- **type** (integer) - Type of permission: 1 for Role, 2 for User.
- **permission** (boolean) - Whether the command is enabled or not.
```
--------------------------------
### Get Microapplication Visible Scopes
Source: https://github.com/koishijs/docs/blob/main/en-US/plugins/adapter/dingtalk.md
Gets the microapplication visible range set by the enterprise. This is an internal API method.
```APIDOC
## internal.oapiMicroappVisibleScopes()
### Description
Gets the microapplication visible range set by the enterprise.
### Endpoint
[Refer to DingTalk Open Platform documentation for specific endpoint details]
### Method
[Refer to DingTalk Open Platform documentation for specific HTTP method]
### Parameters
[Refer to DingTalk Open Platform documentation for parameter details]
### Request Example
[Refer to DingTalk Open Platform documentation for request examples]
### Response
#### Success Response (200)
[Refer to DingTalk Open Platform documentation for response details]
#### Response Example
[Refer to DingTalk Open Platform documentation for response examples]
```
--------------------------------
### Loading a Koishi Plugin
Source: https://github.com/koishijs/docs/blob/main/en-US/cookbook/design/disposable.md
This example shows how to load a plugin using the `ctx.plugin()` method in Koishi. This method manages the plugin's lifecycle and its associated side effects.
```typescript
ctx.plugin(serve, { port: 80 })
```
--------------------------------
### Initiate Account Binding
Source: https://github.com/koishijs/docs/blob/main/en-US/manual/usage/platform.md
Send the 'bind' command to the bot to start the account binding process. This is the first step in linking accounts across platforms.
```text
bind
```
--------------------------------
### Get Current Bot Application Information
Source: https://github.com/koishijs/docs/blob/main/zh-CN/plugins/adapter/discord.md
Gets information about the current bot's application. Requires the `bot` scope.
```APIDOC
## GET /applications/@me
### Description
Gets information about the current bot's application.
### Method
GET
### Endpoint
`/applications/@me`
### Response
#### Success Response (200 OK)
- **id** (snowflake) - The ID of the application.
- **name** (string) - The name of the application.
- **description** (string) - The description of the application.
- **rpc_origins** (array[string]) - An array of RPC origins.
- **flags** (integer) - The flags of the application.
```
--------------------------------
### YAML Configuration for OneBot Adapter
Source: https://github.com/koishijs/docs/blob/main/en-US/about/migration.md
Example of configuring the OneBot adapter in `koishi.yml`, including protocol, disabled status, and platform settings.
```yaml
plugins:
onebot:
# 如果只有一个 bot,你仍然可以像 v3 一样直接写在这里,不用专门提供 bots 数组
protocol: http # 相当于过去的 type: 'onebot:http'
disabled: true # 不启动,可以配合网页控制台动态控制运行状态
platform: qq # 此时账户信息将从 user.qq 而非 user.onebot 访问
# 你还可以对同一个适配器下的多个 bot 实例设置多个不同的平台
```
--------------------------------
### Get Current User Guild Member
Source: https://github.com/koishijs/docs/blob/main/zh-CN/plugins/adapter/discord.md
Gets the current user's guild member object. Requires the `guilds.members.read` scope.
```APIDOC
## GET /users/@me/guilds/:guild.id/member
### Description
Gets the current user's guild member object.
### Method
GET
### Endpoint
`/users/@me/guilds/:guild.id/member`
### Parameters
#### Path Parameters
- **guild.id** (snowflake) - Required - The ID of the guild.
### Response
#### Success Response (200 OK)
- **guild_id** (snowflake) - The ID of the guild.
- **user** (object) - The user object.
- **nick** (string) - The user's nickname in the guild.
- **roles** (array[snowflake]) - An array of role IDs the user is in.
- **joined_at** (ISO 8601 timestamp) - When the user joined the guild.
- **deaf** (boolean) - Whether the user is deafened in voice channels.
- **mute** (boolean) - Whether the user is muted in voice channels.
```
--------------------------------
### Get Application Role Connection Metadata Records
Source: https://github.com/koishijs/docs/blob/main/zh-CN/plugins/adapter/discord.md
Gets metadata records for the application's role connection. Requires the `APPLICATIONS.commands` scope.
```APIDOC
## GET /applications/:application.id/role-connections/metadata
### Description
Gets metadata records for the application's role connection.
### Method
GET
### Endpoint
`/applications/:application.id/role-connections/metadata`
### Parameters
#### Path Parameters
- **application.id** (snowflake) - Required - The ID of the application.
### Response
#### Success Response (200 OK)
- **items** (array[object]) - An array of application role connection metadata objects.
- **type** (string) - Type of metadata.
- **key** (string) - Key of the metadata.
- **name** (string) - Name of the metadata.
- **description** (string) - Description of the metadata.
- **default_value** (boolean) - Default value of the metadata.
```
--------------------------------
### Plugin Lifecycle
Source: https://context7.com/koishijs/docs/llms.txt
Covers handling plugin startup with `ready`, resource cleanup with `dispose`, and managing shared state across plugin instances using `fork`.
```APIDOC
## Plugin Lifecycle (ready / dispose / fork)
Handle async startup, resource cleanup, and shared state in reusable plugins.
```ts
import { Context } from 'koishi'
import { createServer } from 'http'
// ready + dispose for resource management
export function apply(ctx: Context) {
const server = createServer((req, res) => res.end('ok'))
ctx.on('ready', () => {
server.listen(8080)
ctx.logger('my-plugin').info('Server started on :8080')
})
ctx.on('dispose', () => {
server.close()
})
}
// Reusable plugin with shared state using fork event
export const name = 'counter'
export function apply(ctx: Context) {
let instanceCount = 0
ctx.command('count').action(() => `Active instances: ${instanceCount}`)
ctx.on('fork', (ctx) => {
instanceCount++
ctx.on('dispose', () => { instanceCount-- })
})
}
// Declare plugin as reusable for multiple config blocks
export const reusable = true
export function apply(ctx: Context, config: { keyword: string; reply: string }) {
ctx.middleware((session, next) => {
if (session.content.includes(config.keyword)) return config.reply
return next()
})
}
// Usage: load the same plugin twice with different configs
ctx.plugin(apply, { keyword: 'hello', reply: 'Hi!' })
ctx.plugin(apply, { keyword: 'bye', reply: 'Goodbye!' })
```
```
--------------------------------
### Create a New Plugin Workspace
Source: https://github.com/koishijs/docs/blob/main/en-US/guide/develop/workspace.md
Use this command to set up a new plugin workspace. The `name` parameter is the package name for your plugin. Flags control features like console extensions, monorepo setup, and Git initialization.
```npm
npm run setup [name] -- [-c] [-m] [-G]
```
```yarn
yarn setup [name] [-c] [-m] [-G]
```
--------------------------------
### Start Koishi Container with Podman
Source: https://github.com/koishijs/docs/blob/main/en-US/manual/starter/docker.md
Use this command to run the official Koishi Docker image with Podman. The Koishi console will be accessible on port 5140.
```podman
podman run -p 5140:5140 koishijs/koishi
```
--------------------------------
### Install Yarn Package Manager
Source: https://github.com/koishijs/docs/blob/main/en-US/manual/starter/boilerplate.md
Install Yarn globally using npm. This command is useful for users who prefer Yarn over npm for package management.
```bash
# Install yarn
npm i -g yarn
# Check version
yarn -v
```
--------------------------------
### Configure Multiple Bot Instances with Adapters
Source: https://github.com/koishijs/docs/blob/main/en-US/manual/starter/direct.md
Configure multiple bot instances in your `index.ts` file by activating different adapter plugins with specific configurations. This example shows Satori and Discord adapters.
```typescript
import satori from '@koishijs/plugin-adapter-satori'
import discord from '@koishijs/plugin-adapter-discord'
// Using the Satori adapter for one bot
ctx.plugin(satori, {
endpoint: 'http://127.0.0.1:5500',
})
// Using the Satori adapter for another bot with different communication methods
ctx.plugin(satori, {
endpoint: 'http://127.0.0.1:5501',
})
// Using the Discord adapter for a bot
// Don't forget to install the appropriate plugins and complete the setup before using it
ctx.plugin(discord, {
token: 'QwErTyUiOpAsDfGhJkLzXcVbNm',
})
```
--------------------------------
### HTML Escaped Tag Example
Source: https://github.com/koishijs/docs/blob/main/zh-CN/api/message/syntax.md
Demonstrates how to represent HTML tags as text content by escaping special characters. This is equivalent to the example ignoring whitespace.
```html
<foo> bar
```
--------------------------------
### Display Help Information
Source: https://github.com/koishijs/docs/blob/main/en-US/manual/usage/command.md
Use the 'help' command to view a list of available commands. This is provided by the help plugin.
```plaintext
help
```
--------------------------------
### 配置插件市场和 config 插件
Source: https://github.com/koishijs/docs/blob/main/zh-CN/about/upgrade.md
在 koishi.yml 文件中添加 config 插件的配置项,以解决插件市场更新后配置页面消失的问题。
```yaml
host: 127.0.0.1
port: 5140
maxPort: 5149
plugins:
...
...
config: {} # 加一行在这里,注意左侧缩进与 market 对齐
market:
...
...
```
--------------------------------
### Plugin Lifecycle: Ready and Dispose
Source: https://context7.com/koishijs/docs/llms.txt
Manage asynchronous startup and resource cleanup in plugins using 'ready' and 'dispose' events. Ensures resources like servers are properly managed.
```typescript
import { Context } from 'koishi'
import { createServer } from 'http'
// ready + dispose for resource management
export function apply(ctx: Context) {
const server = createServer((req, res) => res.end('ok'))
ctx.on('ready', () => {
server.listen(8080)
ctx.logger('my-plugin').info('Server started on :8080')
})
ctx.on('dispose', () => {
server.close()
})
}
```
--------------------------------
### Using .env File for Environment Variables
Source: https://github.com/koishijs/docs/blob/main/en-US/guide/develop/config.md
Demonstrates how to define environment variables in a `.env` file, which is automatically supported by Koishi via dotenv, for managing sensitive information.
```sh
DISCORD_TOKEN = xxx
```
--------------------------------
### Interpolation Resolution Example
Source: https://github.com/koishijs/docs/blob/main/zh-CN/api/message/syntax.md
Shows the result of parsing the previous interpolation example with a specific data object. It demonstrates how `{bar}` becomes `"1"` and `{baz}` becomes `2`.
```html
2qux
```
--------------------------------
### Get Webhook
Source: https://github.com/koishijs/docs/blob/main/en-US/plugins/adapter/discord.md
Retrieves a webhook.
```APIDOC
## GET /webhooks/{webhook.id}
### Description
Retrieves a webhook.
### Method
GET
### Endpoint
`/webhooks/{webhook.id}`
```
--------------------------------
### Instance Methods
Source: https://github.com/koishijs/docs/blob/main/en-US/api/core/context.md
Methods available on the context instance for extending and interacting with Koishi.
```APIDOC
## ctx.extend(meta)
### Description
Creates a new context based on the current context, with specified properties overridden.
### Parameters
- **meta:** `Partial` - The properties to override.
### Returns
`this` - The new context instance.
```
```APIDOC
## ctx.command(def, desc?, config?)
### Description
Registers or modifies a command within the current context. It allows defining the command name, parameters, description, and configuration.
### Parameters
- **def:** `string` - The command name and its possible parameters.
- **desc:** `string` (Optional) - The description of the command.
- **config:** `CommandConfig` (Optional) - Configuration for the command.
- **checkUnknown:** `boolean` - Whether to check for unknown options (defaults to `false`).
- **checkArgCount:** `boolean` - Whether to check the argument count (defaults to `false`).
- **authority:** `number` - The minimum authority level required to invoke the command (defaults to `1`).
- **showWarning:** `boolean` - Whether to show a warning when the interval is less than the minimum (defaults to `true`).
### Returns
[`Command`](./command.md) - The registered or modified command.
```
```APIDOC
## ctx.broadcast(channels?, content, forced?)
### Description
Broadcasts a message to channels assigned to all bots, excluding channels marked as silent. Failures in sending messages to specific channels will not throw an error.
### Parameters
- **channels:** `string[]` (Optional) - A list of channel IDs to broadcast to.
- **content:** `string` - The content of the message to send.
- **forced:** `boolean` (Optional) - Whether to ignore the `silent` flag.
### Returns
`Promise` - A promise that resolves to a list of message IDs that were successfully sent.
```
```APIDOC
## ctx.logger(scope?)
### Description
Generates a Logger object based on a specified namespace.
### Parameters
- **scope:** `string` (Optional) - The namespace to specify for the logger. Defaults to an empty string.
### Returns
[`Logger`](../utils/logger.md) - The logger instance.
```
--------------------------------
### Start Koishi Container with Docker
Source: https://github.com/koishijs/docs/blob/main/en-US/manual/starter/docker.md
Use this command to run the official Koishi Docker image with Docker. The Koishi console will be accessible on port 5140.
```docker
docker run -p 5140:5140 koishijs/koishi
```
--------------------------------
### Get User
Source: https://github.com/koishijs/docs/blob/main/en-US/plugins/adapter/discord.md
Retrieves a user.
```APIDOC
## GET /users/{user.id}
### Description
Retrieves a user.
### Method
GET
### Endpoint
`/users/{user.id}`
```
--------------------------------
### Start Lite Koishi Container with Podman
Source: https://github.com/koishijs/docs/blob/main/en-US/manual/starter/docker.md
Run the lite version of the Koishi Docker image with Podman if you do not need the included Chromium for image rendering. The Koishi console will be accessible on port 5140.
```podman
podman run -p 5140:5140 koishijs/koishi:latest-lite
```
--------------------------------
### Get Sticker
Source: https://github.com/koishijs/docs/blob/main/en-US/plugins/adapter/discord.md
Retrieves a sticker.
```APIDOC
## GET /stickers/{sticker.id}
### Description
Retrieves a sticker.
### Method
GET
### Endpoint
`/stickers/{sticker.id}`
```
--------------------------------
### Get Invite
Source: https://github.com/koishijs/docs/blob/main/en-US/plugins/adapter/discord.md
Retrieves an invite.
```APIDOC
## GET /invites/{invite.code}
### Description
Retrieves an invite.
### Method
GET
### Endpoint
`/invites/{invite.code}`
```
--------------------------------
### Clone and Build Koishi with yarn
Source: https://github.com/koishijs/docs/blob/main/en-US/guide/develop/workspace.md
Use these yarn commands to clone the Koishi repository and build the core Koishi package within your workspace.
```yarn
yarn clone koishijs/koishi
yarn workspace @root/koishi build
```
--------------------------------
### 发布插件 (npm)
Source: https://github.com/koishijs/docs/blob/main/zh-CN/guide/develop/publish.md
使用 npm 发布插件的命令。缺省时发布所有版本号发生变动的插件。
```bash
npm run pub [...name]
```
--------------------------------
### Create and Load a Custom Plugin
Source: https://github.com/koishijs/docs/blob/main/en-US/manual/starter/direct.md
Organize interaction logic into separate plugin files. This example defines a 'ping' plugin in `ping.ts` and loads it in `index.ts`.
```typescript
import { Context } from 'koishi'
export const name = 'ping'
export function apply(ctx: Context) {
// Reply with "world", after receiving "Hello"
ctx.on('message', (session) => {
if (session.content === 'Hello') {
session.send('world')
}
})
}
```
```typescript
// Here the ./ping is the path to index.ts
import * as ping from './ping'
ctx.plugin(ping)
```
--------------------------------
### Get Guild
Source: https://github.com/koishijs/docs/blob/main/en-US/plugins/adapter/discord.md
Retrieves a guild by its ID.
```APIDOC
## GET /guilds/{guild.id}
### Description
Retrieves a guild by its ID.
### Method
GET
### Endpoint
`/guilds/{guild.id}`
```
--------------------------------
### Perform HTTP GET Request
Source: https://context7.com/koishijs/docs/llms.txt
Make a GET request to a specified URL using `ctx.http.get()`. This method supports query parameters and automatically handles global proxy, timeout, and retry settings. The response data is typed for better integration.
```typescript
ctx.command('weather ').action(async (_, city) => {
try {
// GET request
const data = await ctx.http.get<{ temp: number; desc: string }>(
`https://api.weather.example.com/current`,
{ params: { city, units: 'metric' } }
)
return `${city}: ${data.temp}°C, ${data.desc}`
} catch (e) {
return `Failed to fetch weather: ${e.message}`
}
})
```
--------------------------------
### Basic ReplBot Implementation
Source: https://github.com/koishijs/docs/blob/main/zh-CN/guide/adapter/bot.md
This snippet shows a minimal implementation of a Bot class for the REPL platform, demonstrating the `createMessage` method.
```typescript
class ReplBot extends Bot {
constructor(ctx: C, config: Config) {
super(ctx, config)
this.platform = 'repl'
this.selfId = 'koishi'
ctx.plugin(ReplAdapter, this)
}
async createMessage(channelId: string, content: h.Fragment) {
process.stdout.write(h('', content).toString(true))
process.stdout.write(EOL)
return []
}
}
```
--------------------------------
### Get Webhook With Token
Source: https://github.com/koishijs/docs/blob/main/en-US/plugins/adapter/discord.md
Retrieves a webhook with its token.
```APIDOC
## GET /webhooks/{webhook.id}/{webhook.token}
### Description
Retrieves a webhook with its token.
### Method
GET
### Endpoint
`/webhooks/{webhook.id}/{webhook.token}`
```
--------------------------------
### Conditional Plugin Loading with Environment Variables
Source: https://github.com/koishijs/docs/blob/main/en-US/guide/develop/config.md
Explains how to use environment variables for conditional logic, such as enabling a plugin only when Koishi is launched via a specific agent like the desktop client.
```yaml
plugins:
desktop:
$if: env.KOISHI_AGENT?.includes('Desktop')
```
--------------------------------
### Get Webhook Message
Source: https://github.com/koishijs/docs/blob/main/en-US/plugins/adapter/discord.md
Retrieves a webhook message.
```APIDOC
## GET /webhooks/{webhook.id}/{webhook.token}/messages/{message.id}
### Description
Retrieves a webhook message.
### Method
GET
### Endpoint
`/webhooks/{webhook.id}/{webhook.token}/messages/{message.id}`
```
--------------------------------
### Get Thread Member
Source: https://github.com/koishijs/docs/blob/main/en-US/plugins/adapter/discord.md
Retrieves a thread member.
```APIDOC
## GET /channels/{channel.id}/thread-members/{user.id}
### Description
Retrieves a thread member.
### Method
GET
### Endpoint
`/channels/{channel.id}/thread-members/{user.id}`
```
--------------------------------
### Register and Load Koishi Plugins
Source: https://context7.com/koishijs/docs/llms.txt
Plugins can be functions, classes, or objects with an `apply` method. Use `ctx.plugin()` to load them, passing the plugin and its configuration. The returned `Fork` can be used to dispose (unload) the plugin. This mirrors the `plugins` configuration in `koishi.yml`.
```ts
// --- Function plugin ---
export const name = 'my-plugin'
export function apply(ctx: Context, config: { greeting: string }) {
ctx.command('hello').action(() => config.greeting)
}
// --- Class plugin (default export) ---
export default class MyPlugin {
static reusable = true // allow multiple instances
constructor(ctx: Context, config: MyPlugin.Config) {
ctx.middleware((session, next) => {
if (session.content === 'ping') return 'pong'
return next()
})
}
}
export namespace MyPlugin {
export interface Config { reply: string }
}
// --- Loading plugins ---
import * as MyPlugin from './my-plugin'
import AnotherPlugin from './another-plugin'
const fork = ctx.plugin(MyPlugin, { greeting: 'Hello!' })
ctx.plugin(AnotherPlugin, { reply: 'pong' })
// Unload a plugin and clean up all its side effects:
fork.dispose()
// koishi.yml equivalent:
// plugins:
// my-plugin:
// greeting: Hello!
```
--------------------------------
### Get Stage Instance
Source: https://github.com/koishijs/docs/blob/main/en-US/plugins/adapter/discord.md
Retrieves a stage instance.
```APIDOC
## GET /stage-instances/{channel.id}
### Description
Retrieves a stage instance.
### Method
GET
### Endpoint
`/stage-instances/{channel.id}`
```
--------------------------------
### Adapter Configuration: Before and After v4
Source: https://github.com/koishijs/docs/blob/main/en-US/about/migration.md
Adapters are now imported as plugins. This shows the change in how adapter configurations are structured in `koishi.ts`.
```typescript
// before
export default {
bots: [ /* 机器人配置项 */ ],
discord: { /* 适配器配置项 */ },
}
// after
export default {
plugins: {
discord: {
bots: [ /* 机器人配置项 */ ],
/* 适配器配置项 */
},
},
}
```
--------------------------------
### Clone and Build Koishi with npm
Source: https://github.com/koishijs/docs/blob/main/en-US/guide/develop/workspace.md
Use these npm commands to clone the Koishi repository and build the core Koishi package within your workspace.
```npm
npm run clone koishijs/koishi
npm run build -w @root/koishi
```
--------------------------------
### Get Reactions
Source: https://github.com/koishijs/docs/blob/main/en-US/plugins/adapter/discord.md
Retrieves a list of reactions for a message.
```APIDOC
## GET /channels/{channel.id}/messages/{message.id}/reactions
### Description
Retrieves a list of reactions for a message.
### Method
GET
### Endpoint
`/channels/{channel.id}/messages/{message.id}/reactions`
```
--------------------------------
### Instance Properties
Source: https://github.com/koishijs/docs/blob/main/en-US/api/core/context.md
Properties directly available on the context instance.
```APIDOC
## ctx.root.config
### Description
The current global configuration for Koishi, representing the processed result of the configuration file with default values applied.
### Type
[`Context.Config`](./app.md)
```
```APIDOC
## ctx.baseDir
### Description
The default path for Koishi. If a configuration file is used, this path is the directory containing the configuration file; otherwise, it is the current working directory.
### Type
`string`
```
```APIDOC
## ctx.bots
### Description
An array containing all bot instances currently associated with the application.
### Type
`Bot[]`
```