### Initialize Koishi Project Source: https://koishi.chat/zh-CN/guide/develop/setup Creates a new Koishi project using the npm package initializer. This command guides the user through the setup process for a new Koishi application. ```npm npm init koishi@latest ``` -------------------------------- ### Plugin Installation Source: https://koishi.chat/zh-CN/api/service/registry This section covers methods for installing plugins within the Koishi application context. ```APIDOC ## ctx.plugin(plugin, options?) ### Description Installs a plugin in the current context. ### Method `ctx.plugin` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **plugin** (`Plugin`) - Required - The plugin to install. - **options** (`any`) - Optional - Parameters to pass to the plugin. ### Request Example ```json { "plugin": "myPlugin", "options": { "setting1": "value1" } } ``` ### Response #### Success Response (200) - **Fork** - A Fork object representing the installed plugin. #### Response Example ```json { "fork": "..." } ``` --- ## ctx.inject(deps, plugin) ### Description Installs a plugin that has service dependencies. ### Method `ctx.inject` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **deps** (`string[]`) - Required - A list of service dependencies. - **plugin** (`Plugin`) - Required - The plugin to install. ### Request Example ```json { "deps": ["serviceA", "serviceB"], "plugin": "myDependentPlugin" } ``` ### Response #### Success Response (200) - **this** (`this`) - Refers to the current context. #### Response Example ```json { "context": "..." } ``` ``` -------------------------------- ### Start k-on! Development Server Locally Source: https://koishi.chat/zh-CN/cookbook/practice/online After cloning the required repositories, navigate to the `external/webui` directory and run the `npm run dev` command. This starts the k-on! development server, allowing you to test your plugins locally. ```npm cd external/webui npm run dev ``` -------------------------------- ### Install and Use Yarn Package Manager Source: https://koishi.chat/zh-CN/manual/starter/boilerplate This snippet shows how to install the yarn package manager globally using npm and then verify the installation by checking the yarn version. It also includes a tip for Windows users on how to resolve script execution policy issues. ```sh # Install yarn npm i -g yarn # View version yarn -v ``` ```powershell Set-ExecutionPolicy RemoteSigned ``` -------------------------------- ### Start Koishi Application Source: https://koishi.chat/zh-CN/manual/starter/boilerplate This command starts the Koishi application after it has been initialized. If the application is already running, this command will restart it. Pressing Ctrl+C in the terminal will stop the application. ```npm npm start ``` -------------------------------- ### 启动 Koishi 应用 (npm) Source: https://koishi.chat/zh-CN/guide/develop/script 使用 npm 命令启动 Koishi 应用。`npm run start` 执行 `package.json` 中定义的 `start` 脚本,用于启动 Koishi 应用。 `npm run dev` 启动开发模式。 ```bash npm run start ``` ```bash npm run dev ``` -------------------------------- ### Discord Adapter Setup and Configuration Source: https://koishi.chat/zh-CN/plugins/adapter/discord Instructions on how to set up a Discord bot application and configure the Koishi Discord adapter plugin. ```APIDOC ## Discord Adapter Setup and Configuration ### Description This section details the steps to create a Discord application, obtain a bot token, and configure the Koishi plugin with various options. ### Setup Steps 1. **Create Discord Application:** Go to https://discord.com/developers/applications, log in, and create a new application. 2. **Create Bot:** Navigate to the 'Bot' tab, create a new bot, and save the bot token. **Do not share your token.** 3. **Invite Bot to Server:** Go to the 'OAuth2' tab, use the URL generator to select 'Bot' and necessary permissions, then open the generated link to invite the bot to your server. 4. **Configure Koishi:** Use the bot token obtained in step 2 as the `token` configuration option for the Discord adapter. ### Configuration Options The Discord adapter accepts all `WsClient` options plus the following: #### `options.token` * **Type:** `string` * **Description:** The token for your bot account. #### `options.endpoint` * **Type:** `string` * **Default:** `'https://discord.com/api/v8'` * **Description:** The server address to connect to. #### `options.proxyAgent` * **Type:** `string` * **Default:** `app.config.request.proxyAgent` * **Description:** The network proxy to use by default when making requests. #### `options.gateway` * **Type:** `string` * **Default:** `'wss://gateway.discord.gg/?v=8&encoding=json'` * **Description:** The WebSocket gateway to connect to. #### `options.intents` * **Type:** `number` * **Default:** `GUILD_MESSAGES | GUILD_MESSAGE_REACTIONS | DIRECT_MESSAGES | DIRECT_MESSAGE_REACTIONS` * **Description:** The bot events to subscribe to. This is a bitset representing events. Refer to Gateway Intents for details. #### `options.handleExternalAsset` * **Type:** `string` * **Optional Values:** `'download'`, `'direct'`, `'auto'` * **Default:** `'auto'` * **Description:** Method for sending external link resources: * `download`: Download first, then send. * `direct`: Send the link directly. * `auto`: Send a HEAD request. If the Content-Type is correct, send the link directly; otherwise, download first. #### `options.handleMixedContent` * **Type:** `string` * **Optional Values:** `'separate'`, `'attach'`, `'auto'` * **Default:** `'auto'` * **Description:** Method for sending mixed text and image content: * `separate`: Send each content type separately. * `attach`: If text precedes an image, send the text as an attachment to the image. * `auto`: If the image is sent directly, separate it from preceding text; otherwise, send text as an attachment. *Note:* When `handleMixedContent` is set to `attach` and sending text with images, the content will always be downloaded and sent first, regardless of the `handleExternalAsset` setting. ``` -------------------------------- ### Verify Git Installation Source: https://koishi.chat/zh-CN/guide/develop/setup Checks if Git is installed and displays its version number. This is a standard command to confirm the successful installation of the Git version control system. ```sh git --version # git version 2.39.1 ``` -------------------------------- ### Install and Verify Yarn Package Manager Source: https://koishi.chat/zh-CN/guide/develop/setup Installs the Yarn package manager globally using npm and then verifies the installation by checking the Yarn version. This is useful for users who prefer Yarn over npm for dependency management. ```sh # Install yarn npm i -g yarn # Check version yarn -v ``` -------------------------------- ### Telegram Bot Setup Source: https://koishi.chat/zh-CN/plugins/adapter/telegram Steps to set up a Telegram bot using BotFather to obtain an API token. ```APIDOC ## Telegram Bot Setup ### Description Follow these steps using Telegram's BotFather to create a new bot and obtain an API token. ### Steps 1. **Search for BotFather** on Telegram (look for the official checkmark). 2. Start a chat with BotFather and send the `/start` command. 3. Send the `/newbot` command and follow the prompts to name and username your bot. 4. After creation, BotFather will provide you with an **API token**. Keep this token secure and do not share it. 5. **Disable Privacy Mode** by sending the `/setprivacy` command to BotFather, then selecting your bot and choosing `DISABLED`. This ensures your bot receives all messages, not just commands. ### Reference For more details, refer to the [Telegram Bot API documentation](https://core.telegram.org/bots). ``` -------------------------------- ### LINE Adapter Setup Source: https://koishi.chat/zh-CN/plugins/adapter/line Instructions for setting up the LINE Messaging API channel and configuring the Koishi adapter with your channel's credentials. ```APIDOC ## Koishi LINE Adapter Setup ### Description Follow these steps to integrate your LINE channel with the Koishi LINE adapter. ### Steps 1. **Register and Create Channel**: In the LINE Developers console, register an account, create a new Provider, and within the Provider, create a Channel of type Messaging API. Fill in the required information. 2. **Configure Channel Secret**: In the Basic settings of your channel, find the `Channel secret` and enter it into the `secret` field of the Koishi plugin. 3. **Configure Channel Access Token**: In the Messaging API page, issue a token by clicking 'Issue' at the bottom. Enter this token into the `token` field of the Koishi plugin. 4. **Group Chat Permissions**: (Optional) In the 'Basic settings' page, under 'Allow bot to join group chats', click 'Edit'. In the new page, find 'Toggle features' and select 'Allow' for the first pair of radio buttons. 5. **Auto-reply and Greeting Messages**: (Optional) On the Messaging API page, click 'Edit' for 'Auto-reply messages' or 'Greeting messages' to configure platform-specific replies. 6. **Security Configuration**: On the 'Security' page, it is recommended to configure an IP whitelist. 7. **Enable Webhook**: Start the plugin and navigate to the Messaging API page. Check the 'Use webhook' option. ### Reference For more details, refer to the official LINE Messaging API documentation: https://developers.line.biz/en/docs/messaging-api/getting-started/ ``` -------------------------------- ### Login to npm Registry Source: https://koishi.chat/zh-CN/guide/develop/setup Logs the user into the npm registry using provided credentials. This is a prerequisite for publishing packages. It explicitly specifies the registry to log into. ```sh npm login --registry=https://registry.npmjs.org ``` -------------------------------- ### Set User Language Preference in Session (TypeScript) Source: https://koishi.chat/zh-CN/guide/adapter/integration This snippet shows how to set the `session.locales` property based on a user's language preference from the platform. When a user sends a message, the adapter can extract the language code (e.g., from Telegram) and set the session's locale, enabling the bot to respond in the user's preferred language. The example simplifies logic by taking the first two characters of the language code. ```typescript if (from.language_code) { // 这里为了简化逻辑,只取语言码的前两位 session.locales = [from.language_code.slice(0, 2)] } ``` -------------------------------- ### Koishi.js:为指令添加用法和示例 Source: https://koishi.chat/zh-CN/guide/basic/command 通过 .usage() 和 .example() 方法为 Koishi.js 指令添加详细的使用说明和具体示例。这能帮助用户更好地理解指令的用法,特别是参数的正确顺序。此功能依赖于 @koishijs/plugin-help 插件。 ```typescript ctx.command('echo ', '输出收到的信息') .option('timeout', '-t 设定延迟发送的时间') .usage('注意:参数请写在最前面,不然会被当成 message 的一部分!') .example('echo -t 300 Hello World 五分钟后发送 Hello World') ``` -------------------------------- ### Koishi 应用启动脚本配置 (package.json) Source: https://koishi.chat/zh-CN/guide/develop/script 展示了在 `package.json` 文件中配置 `start` 和 `dev` 脚本以启动 Koishi 应用。`start` 用于基本启动,`dev` 启用了开发模式,包括 `esbuild-register` 和 `yml-register`。 ```json { "scripts": { "dev": "cross-env NODE_ENV=development koishi start -r esbuild-register -r yml-register", "start": "koishi start" } } ``` -------------------------------- ### Clone Repositories for Local k-on! Testing Source: https://koishi.chat/zh-CN/cookbook/practice/online To test your plugin locally with k-on!, you need to clone the `koishijs/webui` and `cordiverse/ponyfills` repositories. These provide the necessary UI and polyfills for the k-on! environment. ```npm npm run clone koishijs/webui npm run clone cordiverse/ponyfills ``` -------------------------------- ### Mock Webhook GET Request Simulation Source: https://koishi.chat/zh-CN/plugins/develop/mock This code snippet illustrates how to simulate a GET request to a specific path on the Koishi server using the mock webhook functionality. It includes optional headers. ```typescript import { Mock } from '@koishijs/plugin-mock'; // Assume 'mock' is an instance of Mock service const mock = new Mock(); async function testWebhookGet() { const response = await mock.webhook.get('/api/data', { 'X-Custom-Header': 'test' }); console.log(response); } ``` -------------------------------- ### Application Control Source: https://koishi.chat/zh-CN/api/service/registry Methods for starting and stopping the Koishi application. ```APIDOC ## ctx.start() ### Description Starts the Koishi application. ### Method `ctx.start` ### Parameters None ### Request Example (No request body for this method) ### Response #### Success Response (200) - **Promise** - A promise that resolves when the application has started. #### Response Example (No specific response body, promise resolution indicates success) --- ## ctx.stop() ### Description Stops the Koishi application. ### Method `ctx.stop` ### Parameters None ### Request Example (No request body for this method) ### Response #### Success Response (200) - **Promise** - A promise that resolves when the application has stopped. #### Response Example (No specific response body, promise resolution indicates success) ``` -------------------------------- ### Define Separate Entry Points for Node.js and Browser Environments Source: https://koishi.chat/zh-CN/cookbook/practice/online To provide different entry points for Node.js and browser environments, modify your plugin's directory structure and `package.json`. Use 'node' and 'browser' directories for environment-specific code and configure the 'exports' field in `package.json` to point to the correct files. ```diff └── example ├── src + │ ├── node + │ │ └── index.ts + │ ├── browser + │ │ └── index.ts + │ ├── shared + │ │ └── index.ts │ └── index.ts ├── package.json └── tsconfig.json ``` -------------------------------- ### Configure Package.json for Separate Entry Points Source: https://koishi.chat/zh-CN/cookbook/practice/online This `package.json` configuration specifies different entry points for Node.js ('node') and browser ('browser') environments, along with shared code. This allows your plugin to be optimized for each runtime. ```package.json { "main": "lib/node/index.cjs", "types": "lib/index.d.ts", "exports": { ".": { "node": "./lib/node/index.cjs", "browser": "./lib/browser/index.mjs", "types": "./lib/index.d.ts" }, "./shared": { "require": "./lib/shared/index.cjs", "import": "./lib/shared/index.mjs" }, "./package.json": "./package.json" }, } ``` -------------------------------- ### Complex Schema Localization Example in Koishi Source: https://koishi.chat/zh-CN/guide/i18n/translation Provides a detailed example of localizing a complex Koishi schema involving `intersect`, `union`, `array`, and `dict` types. It demonstrates the use of `$desc` and `$inner` special properties in YAML to provide translations for nested structures and different types within a union. ```yaml # 对应的翻译文件 - shared: 公用的配置项。 type: $desc: 选择一个分支。 $inner: - 分支 1 - 分支 2 - - $desc: 分支 1 $inner: 一个数值。 value: 一个数值构成的数组。 - $desc: 分支 2 $inner: 一个字符串。 text: 一个字符串构成的字典。 ``` -------------------------------- ### bot.getGuildRoleIter Source: https://koishi.chat/zh-CN/api/resources/role Gets an async iterator for guild roles. ```APIDOC ## GET /bot.getGuildRoleIter ### Description Gets an async iterator for guild roles. ### Method GET ### Endpoint `/bot.getGuildRoleIter` ### Parameters #### Query Parameters - **guildId** (string) - Required - The ID of the guild. ### Request Body This method does not have a request body. ### Response #### Success Response (200) - **AsyncIterable** - An asynchronous iterator yielding GuildRole objects. #### Response Example (Returns an async iterator, typically consumed in a loop) ``` -------------------------------- ### 初始化整合包 Git 仓库 Source: https://koishi.chat/zh-CN/cookbook/practice/bundle 使用 `git init` 命令在本地模板项目下初始化一个新的 Git 仓库,将项目转化为一个整合包(Bundle)。此操作是整合包开发的第一步,允许将项目发布到 Git 仓库进行版本管理。 ```shell git init ``` -------------------------------- ### GET /api/reactions/list Source: https://koishi.chat/zh-CN/api/resources/reaction Retrieves a list of users who have added a specific reaction to a message. Supports pagination. ```APIDOC ## GET /api/reactions/list ### Description Retrieves a list of users who have added a specific reaction to a message. Supports pagination. This is an experimental feature. ### Method GET ### Endpoint /api/reactions/list ### Parameters #### Query Parameters - **channelId** (string) - Required - The ID of the channel where the message is located. - **messageId** (string) - Required - The ID of the message to get reactions from. - **emoji** (string) - Required - The name of the reaction emoji. - **next** (string) - Optional - A pagination token to retrieve the next page of results. ### Request Example ```json { "channelId": "12345", "messageId": "56789", "emoji": "👍", "next": "page_token_123" } ``` ### Response #### Success Response (200) - **users** (array) - A list of user objects who reacted. - **next** (string) - A pagination token for the next page of results, if available. #### Response Example ```json { "users": [ { "id": "user1", "name": "Alice" }, { "id": "user2", "name": "Bob" } ], "next": "page_token_456" } ``` ``` -------------------------------- ### Configure Console Extension Plugin for k-on! Source: https://koishi.chat/zh-CN/cookbook/practice/online This `package.json` configuration enables console extensions for k-on!. It specifies the main entry point, type definitions, exports, and marks the plugin as browser-compatible, while also listing public directories to be served. ```json { "main": "lib/index.cjs", "typings": "lib/index.d.ts", "exports": { ".": { "import": "./lib/index.mjs", "require": "./lib/index.cjs" }, "./package.json": "./package.json" }, "koishi": { "browser": true, "public": [ "dist" ] } } ``` -------------------------------- ### 使用 npm 发布插件 Source: https://koishi.chat/zh-CN/guide/develop/publish 在应用目录运行 `npm run pub` 命令来发布插件。缺省时会发布所有版本号发生变动的插件。发布时需注意可能出现的镜像问题。 ```bash npm run pub [...name] # 发布时使用官方镜像 npm run pub [...name] -- --registry https://registry.npmjs.org ``` -------------------------------- ### Webhook Endpoint 配置 Source: https://koishi.chat/zh-CN/guide/adapter/adapter 展示了在 HttpServer 的 start 方法中,如何调用内部接口设置 Webhook 回调地址。这是配置机器人接收平台事件的第一步。 ```typescript await this.getLogin() await bot.internal.setWebhookEndpoint({ endpoint: this.ctx.server.config.selfUrl + '/line', }) ``` -------------------------------- ### Configuration Options Source: https://koishi.chat/zh-CN/plugins/develop/server Configuration options for the server plugin, including host, port, maxPort, and selfUrl. ```APIDOC ## Configuration Options ### config.host * **Type:** `string` * **Default:** `'127.0.0.1'` * **Description:** The IP address the server listens on. Setting to `'0.0.0.0'` listens on all available network interfaces. ### config.port * **Type:** `number` * **Required:** Yes * **Description:** The initial port number to listen on. Koishi suggests `5140` as the default. ### config.maxPort * **Type:** `number` * **Default:** `config.port` * **Description:** The maximum port number to try if the initial port is occupied. The plugin will attempt to find an available port up to this limit. ### config.selfUrl * **Type:** `string` * **Description:** The public URL of the Koishi service. Required by some plugins like `adapter-telegram` or `assets-local`. ``` -------------------------------- ### Random.int(start?, end) Source: https://koishi.chat/zh-CN/api/utils/random Generates a random integer within a specified range. ```APIDOC ## Random.int(start?, end) ### Description Generates a random integer within the range `[start, end)`. ### Method `Random.int(start?, end)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **start** (`number`) - Optional - The lower bound of the range. Defaults to 0. * **end** (`number`) - Optional - The upper bound of the range. ### Request Example ```typescript import { Random } from 'koishi'; const randomInt = Random.int(0, 10); // Generates a random integer between 0 and 9 ``` ### Response #### Success Response (200) * **value** (`number`) - The generated random integer. #### Response Example ```json { "value": 7 } ``` ``` -------------------------------- ### Matrix Registry Configuration (YAML) Source: https://koishi.chat/zh-CN/plugins/adapter/matrix This YAML configuration file (`registry.yaml`) is essential for setting up the Matrix application service. It defines the application service ID, authentication tokens (`hs_token`, `as_token`), the bot's public URL, the sender local part, and namespace configurations for user IDs. Ensure tokens are kept secure and the `regex` correctly matches your bot's user ID. ```yaml id: koishi # Application Service 的 ID hs_token: # 填入任意内容,与配置文件相对应,请确保不会泄漏 as_token: # 填入任意内容,与配置文件相对应,请确保不会泄漏 url: # 你的机器人地址,通常是 {selfUrl}/matrix sender_localpart: koishi # 不能与机器人的 ID 相同 namespaces: users: - exclusive: true # 这里填入你的机器人的 userId # 如果需要同时接入多个 matrix 机器人,请使用正则表达式 regex: '@koishi:matrix.example.com' ``` -------------------------------- ### GET /api/reactions/iter Source: https://koishi.chat/zh-CN/api/resources/reaction Provides an asynchronous iterator for users who have added a specific reaction to a message. This is an experimental feature. ```APIDOC ## GET /api/reactions/iter ### Description Provides an asynchronous iterator for users who have added a specific reaction to a message. This is an experimental feature. ### Method GET ### Endpoint /api/reactions/iter ### Parameters #### Query Parameters - **channelId** (string) - Required - The ID of the channel where the message is located. - **messageId** (string) - Required - The ID of the message to get reactions from. - **emoji** (string) - Required - The name of the reaction emoji. ### Request Example ```json { "channelId": "12345", "messageId": "56789", "emoji": "👍" } ``` ### Response #### Success Response (200) - **AsyncIterable** - An asynchronous iterator yielding user objects. #### Response Example ```javascript // Example usage with async/await async function getUsers(channelId, messageId, emoji) { const response = await fetch(`/api/reactions/iter?channelId=${channelId}&messageId=${messageId}&emoji=${emoji}`); const iterator = response.body; for await (const user of iterator) { console.log(user); } } ``` ``` -------------------------------- ### Mock User and Channel Initialization Source: https://koishi.chat/zh-CN/plugins/develop/mock This snippet shows how to initialize a user and a channel within the mock database. It allows setting initial data like user ID, authority, and channel assignee. ```typescript import { Mock } from '@koishijs/plugin-mock'; // Assume 'mock' is an instance of Mock service const mock = new Mock(); async function initializeMockData() { mock.initUser('user1', 1, { name: 'Alice' }); mock.initChannel('channel1', 'bot1', { name: 'General' }); console.log('User and channel initialized.'); } ``` -------------------------------- ### Random.real(start?, end) Source: https://koishi.chat/zh-CN/api/utils/random Generates a random real number within a specified range. ```APIDOC ## Random.real(start?, end) ### Description Generates a random real number within the range `[start, end)`. ### Method `Random.real(start?, end)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **start** (`number`) - Optional - The lower bound of the range. Defaults to 0. * **end** (`number`) - Optional - The upper bound of the range. ### Request Example ```typescript import { Random } from 'koishi'; const randomNum = Random.real(1, 10); // Generates a random float between 1 and 10 ``` ### Response #### Success Response (200) * **value** (`number`) - The generated random real number. #### Response Example ```json { "value": 5.734 } ``` ``` -------------------------------- ### Configure Server Plugin Settings Source: https://koishi.chat/zh-CN/about/upgrade Shows how to migrate global settings for host, port, and maxPort to the configuration of the `@koishijs/plugin-server` plugin in version v4.16.0. This involves manually importing and loading the plugin and moving the relevant settings into its configuration object. ```yaml host: 127.0.0.1 port: 5140 maxPort: 5149 plugins: ... ... config: {} market: ... ... ``` -------------------------------- ### Basic Configuration Options Source: https://koishi.chat/zh-CN/plugins/adapter/kook Details the basic configuration options for the Kook adapter, including protocol, token, endpoint, and attachMode. ```APIDOC ## Basic Configuration Options ### `options.protocol` * **Description:** The type of protocol to use for communication. * **Type:** `string` * **Allowed Values:** `http`, `ws` ### `options.token` * **Description:** The authentication token for the bot account. * **Type:** `string` ### `options.endpoint` * **Description:** The API URL to request. * **Type:** `string` * **Default:** `'https://www.kookapp.cn/api/v3'` ### `options.attachMode` * **Description:** Controls the behavior when sending messages containing resource elements. * **Type:** `'separate' | 'mixed' | 'card'` * **Default:** `'separate'` * **Options:** * `separate`: Each resource message segment, and text between resource segments, will be sent as a separate message. * `mixed`: If the content contains multiple resource segments or a mix of resource segments and text, a card message will be sent. Otherwise, resource segments will be sent individually. * `card`: If the content contains resource segments, they will be sent in the form of a card message. ``` -------------------------------- ### Get Channel Information Source: https://koishi.chat/zh-CN/api/resources/channel Retrieves detailed information about a specific channel using its ID. ```APIDOC ## GET /api/channels/{channelId} ### Description Retrieves detailed information about a specific channel. ### Method GET ### Endpoint `/api/channels/{channelId}` #### Path Parameters - **channelId** (string) - Required - The ID of the channel to retrieve. ### Response #### Success Response (200) - **id** (string) - The unique identifier for the channel. - **name** (string) - The name of the channel. - **type** (ChannelType) - The type of the channel (e.g., TEXT, DIRECT, VOICE, CATEGORY). - **parent_id** (string) - Optional - The ID of the parent channel, if applicable. ### Response Example ```json { "id": "12345", "name": "general", "type": 0, "parent_id": "67890" } ``` ``` -------------------------------- ### Get Guild List Source: https://koishi.chat/zh-CN/api/resources/guild Retrieves a list of all group chats the bot is a member of, with optional pagination. ```APIDOC ## GET /guilds ### Description Retrieves a paginated list of all group chats the bot is a member of. ### Method GET ### Endpoint /guilds ### Parameters #### Query Parameters - **next** (string) - Optional - A token for fetching the next page of results. ### Response #### Success Response (200) - **data** (array) - A list of Guild objects. - **id** (string) - The unique identifier for the group chat. - **name** (string) - The name of the group chat. - **next** (string) - Token for the next page of results, if available. #### Response Example ```json { "data": [ { "id": "12345", "name": "Example Group 1" }, { "id": "67890", "name": "Example Group 2" } ], "next": "next-page-token" } ``` ``` -------------------------------- ### Get Guild Information Source: https://koishi.chat/zh-CN/api/resources/guild Retrieves detailed information about a specific group chat using its ID. ```APIDOC ## GET /guilds/{guildId} ### Description Retrieves detailed information about a specific group chat. ### Method GET ### Endpoint /guilds/{guildId} ### Parameters #### Path Parameters - **guildId** (string) - Required - The unique identifier for the group chat. ### Response #### Success Response (200) - **id** (string) - The unique identifier for the group chat. - **name** (string) - The name of the group chat. #### Response Example ```json { "id": "12345", "name": "Example Group" } ``` ``` -------------------------------- ### WS Configuration Options Source: https://koishi.chat/zh-CN/plugins/adapter/kook Indicates that this section includes all options for WsClient. ```APIDOC ## WS Configuration Options ### Description This section includes all options available for the `WsClient` when using the WebSocket protocol. ``` -------------------------------- ### ctx.server[method](path, middleware) Source: https://koishi.chat/zh-CN/plugins/develop/server Handles network requests on a specific path using Koa middleware. Supports HTTP methods like get, post, put, delete, patch, and all. ```APIDOC ## ctx.server[method](path, middleware) ### Description Handles network requests on a specific path. This API is based on Koa Router. ### Method GET, POST, PUT, DELETE, PATCH, ALL ### Endpoint `ctx.server.(path, middleware)` ### Parameters #### Path Parameters - **method** (string) - Required - The HTTP method (e.g., `get`, `post`, `put`, `delete`, `patch`, `all`). Must be lowercase. - **path** (string | RegExp | (string | RegExp)[]) - Required - The path or an array of paths to match. - **middleware** (Function) - Required - A Koa middleware function. ### Request Example ```javascript ctx.server.get('/hello', async (ctx) => { ctx.body = 'Hello World'; }); ``` ### Response #### Success Response (200) Depends on the middleware provided. #### Response Example ```json { "message": "Hello World" } ``` ``` -------------------------------- ### Koishi Matrix Adapter Plugin Configuration (JavaScript) Source: https://koishi.chat/zh-CN/plugins/adapter/matrix This snippet demonstrates the configuration object for the Koishi Matrix adapter plugin within a Koishi application. It requires essential parameters like `id`, `host`, `hsToken`, and `asToken` which correspond to the Matrix homeserver and application service setup. Optional parameters like `endpoint`, `name`, and `avatar` can customize the bot's behavior and appearance. ```javascript { id: 'your-bot-id', host: 'matrix.example.com', hsToken: 'your_hs_token', asToken: 'your_as_token', // Optional parameters endpoint: 'https://matrix.example.com', name: 'My Koishi Bot', avatar: 'https://example.com/avatar.png' } ``` -------------------------------- ### Database Instance Methods Source: https://koishi.chat/zh-CN/api/database/database Provides methods for interacting with the Koishi database, including selecting, joining, getting, setting, removing, creating, upserting, evaluating, and managing tables. ```APIDOC ## Instance Methods ### ctx.database.select(table, query?) Creates a new `Selection` object. * **table:** `string` - The name of the table. * **query:** `Query` - The query constraints. * **Returns:** `Selection` ### ctx.database.join(tables, query?) (Experimental) Joins multiple tables into a new virtual table. * **tables:** `TableJoin` - The tables to join. * **query:** `Callback` - The query constraints. * **Returns:** `Selection` ### ctx.database.get(table, query, modifier?) Queries data from the database. * **table:** `string` - The name of the table. * **query:** `Query` - The query constraints. * **modifier:** `Modifier` - Modifiers for the query (limit, offset, fields, sort). * **Returns:** `Promise` ### ctx.database.set(table, query, update) Updates data in the database. * **table:** `string` - The name of the table. * **query:** `Query` - The query constraints. * **update:** `Update` - The data to update. * **Returns:** `Promise` - An object containing the number of matched rows. ### ctx.database.remove(table, query) Deletes data from the database. * **table:** `string` - The name of the table. * **query:** `Query` - The query constraints. * **Returns:** `Promise` - An object containing the number of matched rows. ### ctx.database.create(table, data) Inserts data into the database. * **table:** `string` - The name of the table. * **data:** `any` - The data to insert. * **Returns:** `Promise` - The inserted data row. ### ctx.database.upsert(table, data, keys?) Inserts or updates data in the database. * **table:** `string` - The name of the table. * **data:** `Update[]` - The data to upsert. * **keys:** `string | string[]` - The fields to use for indexing. * **Returns:** `Promise` - An object containing the number of inserted and matched rows. ### ctx.database.eval(table, expr, query?) Evaluates an aggregate expression. * **table:** `string` - The name of the table. * **expr:** `Callback` - The expression to evaluate. * **query:** `Query` - The query constraints. * **Returns:** `Promise` ### ctx.database.stats() (Experimental) Retrieves database statistics. * **Returns:** `Promise` ### ctx.database.drop(table) Deletes a table from the database. **Warning:** This is a dangerous operation and data cannot be recovered. Consider using whole table migration for plugin refactoring to prevent data loss. * **table:** `string` - The name of the table to drop. * **Returns:** `Promise` ### ctx.database.dropAll() Deletes all tables from the database. **Warning:** This is a dangerous operation and data cannot be recovered. * **Returns:** `Promise` ```