### Install qq-official-bot Source: https://github.com/zhinjs/qq-official-bot/blob/master/README.md Install the library using npm, yarn, or pnpm. ```bash npm install qq-official-bot # 或者 yarn add qq-official-bot # 或者 pnpm add qq-official-bot ``` -------------------------------- ### Start Bot Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/api/common.md Starts the bot and establishes a connection with the QQ server. It's recommended to listen for the 'ready' event to confirm successful startup. ```APIDOC ## Start Bot ### Description Starts the bot and establishes a connection with the QQ server. ### Method `bot.start()` ### Request Example ```typescript await bot.start() console.log('Bot started successfully') // Listen for startup event bot.on('ready', () => { console.log(`Bot ${bot.nickname} is online`) }) ``` ``` -------------------------------- ### Install and Import Bot Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/segment/index.md Install the library and import necessary classes. Initialize the Bot with your application credentials and choose the connection mode. ```typescript import { Bot, MessageBuilder } from 'qq-official-bot' const bot = new Bot({ appid: 'your_app_id', secret: 'your_secret', mode: 'websocket' }) ``` -------------------------------- ### Music Template Example (ID: 24) Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/segment/ark.md Provides an example of an ARK message using a music-based template (ID: 24). ```APIDOC ## Music Template Example (ID: 24) ### Description An example of an ARK message for sharing music, including song title, singer, music URL, and cover image. ### Template ID `24` ### Key-Value Pairs - **#MUSIC.TITLE#** (string) - Required - The title of the song. - **#MUSIC.SINGER#** (string) - Required - The name of the singer or artist. - **#MUSIC.URL#** (string) - Required - The direct URL to the music file. - **#MUSIC.COVER#** (string) - Required - The URL of the music cover image. ### Code Example ```typescript const musicArk = { type: 'ark' as const, template_id: 24, kv: [ { key: '#MUSIC.TITLE#', value: '歌曲名称' }, { key: '#MUSIC.SINGER#', value: '歌手名称' }, { key: '#MUSIC.URL#', value: 'https://music.example.com/song.mp3' }, { key: '#MUSIC.COVER#', value: 'https://music.example.com/cover.jpg' } ] } ``` ``` -------------------------------- ### Service Call Example Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/interface/index.md Shows how to use service modules to get guild information and send messages. Check the success property of the returned data. ```typescript // 使用服务模块 const guildInfo = await bot.guildService.getInfo('guild_id') if (guildInfo.success) { console.log('频道信息:', guildInfo.data) } // 发送消息 const result = await bot.messageService.sendGuildMessage( 'channel_id', '这是一条消息' ) ``` -------------------------------- ### Text Template Example (ID: 1) Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/segment/ark.md Provides an example of an ARK message using a text-based template (ID: 1). ```APIDOC ## Text Template Example (ID: 1) ### Description An example of an ARK message utilizing a text-focused template. ### Template ID `1` ### Key-Value Pairs - **#DESC#** (string) - Required - The main descriptive text. - **#PROMPT#** (string) - Required - A prompt or supplementary text. ### Code Example ```typescript const textArk = { type: 'ark' as const, template_id: 1, kv: [ { key: '#DESC#', value: '这是一条文本消息' }, { key: '#PROMPT#', value: '提示文本' } ] } ``` ``` -------------------------------- ### Start Bot Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/api/common.md Initiates the bot and establishes a connection with the QQ server. Listen for the 'ready' event to confirm successful startup. ```typescript await bot.start() console.log('机器人启动成功') ``` ```typescript bot.on('ready', () => { console.log(`机器人 ${bot.nickname} 已上线`) }) ``` -------------------------------- ### Handle Complex Game Interactions with Buttons Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/segment/button.md This example demonstrates managing game states and handling multiple button interactions for a game. It includes sending game interfaces and processing actions like starting, viewing scores, and resetting the game. ```typescript import { Bot, segment } from 'qq-official-bot' const bot = new Bot(config) // 游戏状态管理 const gameStates = new Map() // 发送游戏界面 async function sendGameInterface(channelId: string, userId: string) { const gameState = gameStates.get(userId) || { score: 0, level: 1 } const buttons = [ { id: 'game_start', render_data: { label: '开始游戏', style: 3 }, action: { type: 0, data: 'start_game' } }, { id: 'game_score', render_data: { label: '查看分数', style: 1 }, action: { type: 0, data: 'view_score' } }, { id: 'game_reset', render_data: { label: '重置游戏', style: 2 }, action: { type: 0, data: 'reset_game' } } ] await bot.client.sendMessage(channelId, [ segment.markdown(`## 🎮 游戏中心\n当前等级: ${gameState.level}\n分数: ${gameState.score}`), segment.button({ buttons }) ]) } // 处理游戏按钮 bot.on('interaction.button', async (event) => { const userId = event.user_id const channelId = event.channel_id switch (event.data) { case 'start_game': const gameState = gameStates.get(userId) || { score: 0, level: 1 } gameState.score += 10 gameStates.set(userId, gameState) await sendGameInterface(channelId, userId) break case 'view_score': const currentState = gameStates.get(userId) || { score: 0, level: 1 } await bot.client.sendMessage(channelId, [ segment.text(`你的当前分数:${currentState.score}`) ]) break case 'reset_game': gameStates.set(userId, { score: 0, level: 1 }) await sendGameInterface(channelId, userId) break } }) ``` -------------------------------- ### Link Template Example (ID: 23) Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/segment/ark.md Provides an example of an ARK message using a link-based template (ID: 23). ```APIDOC ## Link Template Example (ID: 23) ### Description An example of an ARK message designed for sharing links, including title, description, image, and the target URL. ### Template ID `23` ### Key-Value Pairs - **#TITLE#** (string) - Required - The title of the linked content. - **#METADESC#** (string) - Required - A short description of the linked content. - **#IMG#** (string) - Required - URL of the image to display for the link. - **#LINK#** (string) - Required - The target URL for the link. ### Code Example ```typescript const linkArk = { type: 'ark' as const, template_id: 23, kv: [ { key: '#TITLE#', value: '链接标题' }, { key: '#METADESC#', value: '链接描述' }, { key: '#IMG#', value: 'https://example.com/thumb.jpg' }, { key: '#LINK#', value: 'https://example.com' } ] } ``` ``` -------------------------------- ### Send Music Clip with Parameters Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/segment/audio.md Example of sending a music clip with specified duration and format. ```typescript import { Bot, segment } from 'qq-official-bot' const bot = new Bot(config) await bot.client.sendMessage(channelId, [ segment.text('分享一段音乐:'), segment.audio('./music_clip.mp3', { duration: 60, format: 'mp3' }) ]) ``` -------------------------------- ### Event Listening Example Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/interface/index.md Demonstrates how to listen for guild and private message events using the QQ Official Bot SDK. Ensure correct intents are configured. ```typescript import { Bot, GuildMessageEvent, PrivateMessageEvent } from 'qq-official-bot' const bot = new Bot({ appid: 'your_app_id', secret: 'your_secret', intents: ['GUILD_MESSAGES', 'DIRECT_MESSAGE'], mode: 'websocket' }) // 频道消息事件 bot.on('message.guild', (event: GuildMessageEvent) => { console.log(`收到频道消息: ${event.raw_message}`) event.reply('你好!') }) // 私聊消息事件 bot.on('message.private.friend', (event: PrivateMessageEvent) => { console.log(`收到私聊消息: ${event.raw_message}`) event.reply('私聊回复') }) ``` -------------------------------- ### Send Help Documentation Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/segment/markdown.md Illustrates how to send a comprehensive help document in Markdown, detailing basic and management commands, usage examples, and important notes. Requires Bot and segment imports. ```typescript import { Bot, segment } from 'qq-official-bot' const bot = new Bot(config) // 帮助文档 const helpMarkdown = segment.markdown(` # 🤖 机器人使用指南 ## 基础指令 ### 查询类 - \`/weather [城市]\` - 查询天气 - \`/time\` - 获取当前时间 - \`/help\` - 显示帮助信息 ### 管理类 - \`/mute @用户\` - 禁言用户 - \`/unmute @用户\` - 解除禁言 - \`/clean [数量]\` - 清理消息 ## 使用示例 \`\`\` /weather 北京 /time /clean 10 \`\`\` ## 注意事项 > ⚠️ **重要** > - 管理类指令需要相应权限 > - 指令不区分大小写 > - 参数用空格分隔 --- 如有问题,请联系管理员。 `) await bot.client.sendMessage(channelId, [helpMarkdown]) ``` -------------------------------- ### Example Usage for Extracting Mentions Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/segment/at.md Demonstrates how to use the `extractMentions` and `extractMentionsFromContent` functions with sample data. ```typescript // 使用示例 const userIds = extractMentions(messageElements) console.log('被@的用户:', userIds) const contentMentions = extractMentionsFromContent('<@123456> <@everyone> 大家好') console.log('内容中的@:', contentMentions) // ['123456', 'everyone'] ``` -------------------------------- ### Plugin System Design for QQ Bots Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/guide/instruction.md Define and manage plugins for modular bot functionality using a PluginManager. Includes interfaces for plugins and example of an AutoReplyPlugin. ```typescript // 插件接口定义 interface BotPlugin { name: string version: string description: string dependencies?: string[] onLoad(bot: Bot): Promise onUnload(bot: Bot): Promise onMessage?(ctx: MessageContext): Promise onCommand?(ctx: CommandContext): Promise } // 插件管理器 class PluginManager { private plugins: Map = new Map() private loadOrder: string[] = [] constructor(private bot: Bot) {} async loadPlugin(plugin: BotPlugin): Promise { // 检查依赖 if (plugin.dependencies) { for (const dep of plugin.dependencies) { if (!this.plugins.has(dep)) { throw new Error(`Missing dependency: ${dep}`) } } } // 加载插件 await plugin.onLoad(this.bot) this.plugins.set(plugin.name, plugin) this.loadOrder.push(plugin.name) console.log(`Plugin loaded: ${plugin.name} v${plugin.version}`) } async unloadPlugin(name: string): Promise { const plugin = this.plugins.get(name) if (!plugin) return await plugin.onUnload(this.bot) this.plugins.delete(name) const index = this.loadOrder.indexOf(name) if (index > -1) { this.loadOrder.splice(index, 1) } console.log(`Plugin unloaded: ${name}`) } async handleMessage(ctx: MessageContext): Promise { for (const name of this.loadOrder) { const plugin = this.plugins.get(name) if (plugin?.onMessage) { try { await plugin.onMessage(ctx) } catch (error) { console.error(`Plugin ${name} error:`, error) } } } } } // 示例插件:自动回复 class AutoReplyPlugin implements BotPlugin { name = 'auto-reply' version = '1.0.0' description = '自动回复插件' private replyRules: Map = new Map() async onLoad(bot: Bot): Promise { // 加载回复规则 this.replyRules.set('你好', '你好!我是QQ机器人助手') this.replyRules.set('帮助', '输入 /help 查看可用命令') } async onUnload(bot: Bot): Promise { this.replyRules.clear() } async onMessage(ctx: MessageContext): Promise { const content = ctx.message.content const reply = this.replyRules.get(content) if (reply) { await ctx.bot.message.send(ctx.channel.id, [{ type: 'text', text: reply }]) } } } ``` -------------------------------- ### Get Guild List Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/api/guild.md Fetches the list of guilds the bot has joined. Use the service module for recommended usage. ```typescript // 使用服务模块(推荐) const result = await bot.guildService.getList() if (result.success) { console.log('频道列表:', result.data) } ``` ```typescript // 使用传统方法(向后兼容) const guilds = await bot.getGuildList() ``` -------------------------------- ### Send a Button Group Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/segment/button.md This example shows how to send a group of buttons together in a single message. Each button in the group can have distinct properties and actions. ```typescript import { Bot, segment } from 'qq-official-bot' const bot = new Bot(config) // 发送按钮组 const buttons = [ { id: 'yes_btn', render_data: { label: '是', style: 3 }, action: { type: 0, data: 'yes' } }, { id: 'no_btn', render_data: { label: '否', style: 2 }, action: { type: 0, data: 'no' } }, { id: 'cancel_btn', render_data: { label: '取消', style: 0 }, action: { type: 0, data: 'cancel' } } ] await bot.client.sendMessage(channelId, [ segment.markdown('你确定要执行此操作吗?'), segment.button({ buttons }) ]) ``` -------------------------------- ### Define Bot Configuration Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/api/common.md Use type-safe configuration definitions for bot setup. Specify app ID, secret, receiver mode, intents, and logging level. ```typescript import { defineConfig, ReceiverMode } from 'qq-official-bot' const config = defineConfig({ appid: 'your_app_id', secret: 'your_app_secret', mode: ReceiverMode.WEBSOCKET, intents: ['GUILD_MESSAGES'], sandbox: false, logLevel: 'info', }) const bot = new Bot(config) ``` -------------------------------- ### Process Admin Commands in Group Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/api/group.md Identify and process commands sent by administrators in a group. This example checks for the 'admin' permission and messages starting with '/'. ```typescript // 管理员命令处理 bot.on('message.group', async (event) => { if (event.sender.permissions.includes('admin') && event.raw_message.startsWith('/')) { // 处理管理员命令 const command = event.raw_message.slice(1) await handleAdminCommand(event, command) } }) ``` -------------------------------- ### 初始化项目 Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/guide/start.md 创建新的项目目录并初始化 npm。 ```bash mkdir my-qq-bot cd my-qq-bot npm init -y ``` -------------------------------- ### Using Service Modules Source: https://github.com/zhinjs/qq-official-bot/blob/master/README.md This section demonstrates how to use various service modules provided by the bot for managing guilds, messages, members, permissions, and more. ```APIDOC ## Using Service Modules ### Guild Service Manage guild-related operations: ```typescript // Get a list of guilds const guilds = await bot.guildService.getGuilds(); // Get specific guild information const guildInfo = await bot.guildService.getGuild(guild_id); ``` ### Message Service Handle message sending and recall: ```typescript // Send a message await bot.messageService.sendMessage(channel_id, 'Hello!'); // Recall a message await bot.messageService.recallMessage(channel_id, message_id); ``` ### Member Service Manage guild members, including muting and kicking: ```typescript // Mute a guild member await bot.memberService.muteGuildMember(guild_id, user_id, '600', '0'); // Kick a guild member await bot.memberService.kickGuildMember(guild_id, user_id); ``` ### Permission Service Manage user permissions within channels: ```typescript // Get user permissions for a channel const permissions = await bot.permissionService.getChannelUserPermissions(channel_id, user_id); // Update user permissions for a channel await bot.permissionService.updateChannelUserPermissions(channel_id, user_id, 'add_permission', 'remove_permission'); ``` ``` -------------------------------- ### Configure Bot for Production Environment Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/config.md Instantiate a Bot client for the production environment. Set `sandbox` to `false` and `logLevel` to 'info' for standard operation. ```typescript const prodBot = new Bot({ appid: 'your_app_id', secret: 'your_app_secret', sandbox: false, logLevel: 'info', // ...other configurations }) ``` -------------------------------- ### qq-official-bot Modular Architecture Overview Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/guide/instruction.md Illustrates the service module architecture of the qq-official-bot SDK, showing the core engine, business services, receivers, and utility layers. ```typescript // Service module architecture ├── Bot (Core Engine) ├── Services (Business Services Layer) │ ├── MessageService (Message Service) │ ├── ChannelService (Channel Service) │ ├── GuildService (Guild Service) │ ├── MemberService (Member Management Service) │ └── PermissionService (Permission Service) ├── Receivers (Receiver Layer) │ ├── WebhookReceiver (Webhook Receiver) │ └── WebSocketReceiver (WebSocket Receiver) └── Utils (Utility Layer) ├── MessageBuilder (Message Builder) ├── FileProcessor (File Processor) └── SecurityValidator (Security Validator) ``` -------------------------------- ### Get Channel Source: https://github.com/zhinjs/qq-official-bot/blob/master/README.md Retrieves information about a specific channel. ```APIDOC ## GET /getChannel/{channel_id} ### Description Retrieves information about a specific channel. ### Method GET ### Endpoint /getChannel/{channel_id} ### Parameters #### Path Parameters - **channel_id** (string) - Required - The ID of the channel. ``` -------------------------------- ### Get Guild Source: https://github.com/zhinjs/qq-official-bot/blob/master/README.md Retrieves information about a specific guild. ```APIDOC ## GET /getGuild/{guild_id} ### Description Retrieves information about a specific guild. ### Method GET ### Endpoint /getGuild/{guild_id} ### Parameters #### Path Parameters - **guild_id** (string) - Required - The ID of the guild. ``` -------------------------------- ### Get Self Info Source: https://github.com/zhinjs/qq-official-bot/blob/master/README.md Retrieves information about the bot itself. ```APIDOC ## GET /getSelfInfo ### Description Retrieves information about the bot. ### Method GET ### Endpoint /getSelfInfo ### Parameters None ### Response #### Success Response (200) - **User** (object) - Information about the bot user. ``` -------------------------------- ### 安装依赖 Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/guide/start.md 使用 npm, yarn, 或 pnpm 安装 qq-official-bot SDK。 ```bash # 使用 npm npm install qq-official-bot # 使用 yarn yarn add qq-official-bot # 使用 pnpm pnpm add qq-official-bot ``` -------------------------------- ### Get Guild Members Source: https://github.com/zhinjs/qq-official-bot/blob/master/README.md Retrieves a list of members in a specific guild. ```APIDOC ## GET /getGuildMembers/{guild_id} ### Description Retrieves a list of members in a specific guild. ### Method GET ### Endpoint /getGuildMembers/{guild_id} ### Parameters #### Path Parameters - **guild_id** (string) - Required - The ID of the guild. ``` -------------------------------- ### Create Bot Instance Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/api/common.md A factory method for quickly creating a bot instance with the specified configuration. ```APIDOC ## Create Bot Instance ### Description Factory method for quickly creating a bot instance. ### Method `createBot(config)` ### Request Example ```typescript import { createBot, ReceiverMode } from 'qq-official-bot' const bot = createBot({ appid: 'your_app_id', secret: 'your_app_secret', mode: ReceiverMode.WEBSOCKET, intents: ['GUILD_MESSAGES'], }) await bot.start() ``` ``` -------------------------------- ### Get Sub-Channel Message Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/api/channel.md Retrieves a specific message from a specified sub-channel. ```APIDOC ## GET /messageService/getGuildMessage ### Description Retrieves a specific message from a specified sub-channel. ### Method GET ### Endpoint /messageService/getGuildMessage ### Parameters #### Path Parameters - None #### Query Parameters - **channelId** (string) - Required - The ID of the sub-channel. - **messageId** (string) - Required - The ID of the message. ### Request Example ```json { "channelId": "your_channel_id", "messageId": "your_message_id" } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. - **data** (object) - The message content and details, if successful. #### Response Example ```json { "success": true, "data": { "content": "Message content here" } } ``` ``` -------------------------------- ### Get Guilds Source: https://github.com/zhinjs/qq-official-bot/blob/master/README.md Retrieves a list of guilds (servers) the bot is a part of. ```APIDOC ## GET /getGuilds ### Description Retrieves a list of guilds the bot is a part of. ### Method GET ### Endpoint /getGuilds ### Parameters None ### Response #### Success Response (200) - **Guild[]** (array) - An array of guild objects. ``` -------------------------------- ### Create Channel Jump Link Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/segment/link.md Demonstrates how to create a link segment that navigates to a specific channel within the QQ platform. Ensure the 'qq-official-bot' library is imported. ```typescript import { segment } from 'qq-official-bot' // 创建频道跳转链接 const channelLink = segment.link('目标频道ID') ``` -------------------------------- ### Get Channel User Permissions Source: https://github.com/zhinjs/qq-official-bot/blob/master/README.md Retrieves the permissions of a user in a specific channel. ```APIDOC ## GET /getChannelUserPermissions/{channel_id}/{user_id} ### Description Retrieves the permissions of a user in a specific channel. ### Method GET ### Endpoint /getChannelUserPermissions/{channel_id}/{user_id} ### Parameters #### Path Parameters - **channel_id** (string) - Required - The ID of the channel. - **user_id** (string) - Required - The ID of the user. ``` -------------------------------- ### Get Guild Channels Source: https://github.com/zhinjs/qq-official-bot/blob/master/README.md Retrieves a list of channels within a specific guild. ```APIDOC ## GET /getGuildChannels/{guild_id} ### Description Retrieves a list of channels within a specific guild. ### Method GET ### Endpoint /getGuildChannels/{guild_id} ### Parameters #### Path Parameters - **guild_id** (string) - Required - The ID of the guild. ``` -------------------------------- ### Get Guild Roles Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/api/guild.md Retrieves a list of all roles within a specified guild. ```APIDOC ## Get Guild Roles ### Description Retrieves a list of all roles within a specified guild. ### Method `bot.guildService.getRoles(guildId)` or `bot.getGuildRoles(guildId)` ### Parameters #### Path Parameters - **guildId** (string) - Required - The ID of the guild. ### Request Example ```typescript const result = await bot.guildService.getRoles(guild_id) if (result.success) { console.log('Role list:', result.data) } ``` ``` -------------------------------- ### Initialize Bot with Webhook Connection Source: https://github.com/zhinjs/qq-official-bot/blob/master/README.md Initialize the Bot class for Webhook connections. Specify the `port` and `path` for the webhook endpoint. ```typescript import { Bot, ReceiverMode } from 'qq-official-bot' const bot = new Bot({ appid: 'your_app_id', secret: 'your_app_secret', // ...其他配置 mode: ReceiverMode.WEBHOOK, port: 3000, // Webhook 监听端口 path: '/webhook', // Webhook 路径 }) await bot.start() ``` -------------------------------- ### Love Expressions Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/segment/face.md Examples of sending romantic and love-themed emoticons such as heart, rose, and kiss. ```APIDOC ## Love Expressions ### Description Examples of sending romantic and love-themed emoticons such as heart, rose, and kiss. ### Method Signature `segment.face(id: number): FaceElement` ### Parameters #### Path Parameters - **id** (number) - Required - The ID of the face emoticon. Range: 0-348. ### Request Example ```typescript import { segment } from 'qq-official-bot' // Love related expressions const heart = segment.face(66) // Heart const heartBreak = segment.face(67) // Broken heart const kiss = segment.face(2) // Kiss const rose = segment.face(63) // Rose ``` ``` -------------------------------- ### 创建子频道 Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/api/channel.md 使用 `bot.channelService.create` 在指定频道下创建新的子频道。`channelInfo` 对象包含子频道的名称、类型、位置等信息。 ```typescript const result = await bot.channelService.create(guild_id, { name: '新的文字频道', type: 0, position: 1 }) ``` -------------------------------- ### Using the Services Module to Create and Send ARK Messages Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/segment/ark.md Illustrates how to use the `bot.services.message.createArk` method to generate an ARK message and then send it via `bot.services.channel.sendMessage`. ```APIDOC ## Using the Services Module for ARK Messages ### Description This example demonstrates using the `bot.services` module to create an ARK message with structured fields and then send it to a specified channel. ### Methods 1. `bot.services.message.createArk(options)` 2. `bot.services.channel.sendMessage(channelId, messageSegments)` ### Parameters for `createArk` #### options - **options** (object) - Required - Configuration for the ARK message. - **templateId** (number) - Required - The ID of the ARK template. - **fields** (object) - Required - An object containing the fields to populate the template. - **title** (string) - Optional - The title for the message. - **description** (string) - Optional - The description for the message. - **image** (string) - Optional - URL for the image. - **url** (string) - Optional - The URL the message links to. ### Parameters for `sendMessage` #### channelId - **channelId** (string) - Required - The ID of the channel to send the message to. #### messageSegments - **messageSegments** (Array) - Required - An array containing the ARK message segment. ### Request Example ```typescript const arkMessage = await bot.services.message.createArk({ templateId: 23, fields: { title: '新闻标题', description: '新闻摘要内容', image: 'https://example.com/news-image.jpg', url: 'https://example.com/news/123' } }) await bot.services.channel.sendMessage(channelId, [arkMessage]) ``` ``` -------------------------------- ### Create Channel Link with Text and Title Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/segment/link.md Illustrates creating a channel link with custom display text, a title, and a description. This provides richer context for the link. ```typescript import { segment } from 'qq-official-bot' // 频道跳转链接 const channelLink = segment.link({ channel_id: 'target_channel_id', text: '前往讨论区' }) // 带描述的频道链接 const richChannelLink = segment.link({ channel_id: 'announcements_channel_id', text: '查看公告', title: '公告频道', description: '查看最新的频道公告和更新' }) ``` -------------------------------- ### Best Practice: Platform Compatibility Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/segment/segment-api.md Demonstrates checking for platform support (e.g., channel messages) and conditionally adding specific message segments like embeds. ```typescript // 检查平台支持的消息段类型 const isChannelMessage = true // 根据实际情况判断 const message = [ segment.text('通用消息'), segment.face(14) ] // 只在频道中使用embed if (isChannelMessage) { message.push(segment.embed('标题', '描述', {}, [])) } ``` -------------------------------- ### Send Local Voice Message Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/segment/audio.md Example of sending a local voice message using `segment.audio`. ```typescript import { Bot, segment } from 'qq-official-bot' const bot = new Bot(config) // 发送本地语音 await bot.client.sendMessage(channelId, [ segment.audio('./voice.mp3') ]) ``` -------------------------------- ### Configure Bot for Sandbox Environment Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/config.md Instantiate a Bot client for the development or sandbox environment. Set `sandbox` to `true` and `logLevel` to 'debug' for detailed logs during development. ```typescript const devBot = new Bot({ appid: 'your_app_id', secret: 'your_app_secret', sandbox: true, logLevel: 'debug', // ...other configurations }) ``` -------------------------------- ### Get Guild Info Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/api/guild.md Retrieves detailed information for a specific guild. The guildId parameter is required. ```typescript // 使用服务模块 const result = await bot.guildService.getInfo(guild_id) if (result.success) { console.log('频道信息:', result.data) } ``` ```typescript // 使用传统方法 const guildInfo = await bot.getGuildInfo(guild_id) ``` -------------------------------- ### Send Markdown Ordered Lists Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/segment/markdown.md Demonstrates how to create ordered lists with nested sub-steps using numbers and indentation. ```typescript import { segment } from 'qq-official-bot' // 有序列表 const orderedList = segment.markdown(` 1. 第一步 2. 第二步 1. 子步骤2.1 2. 子步骤2.2 3. 第三步 `) ``` -------------------------------- ### Send Network Audio Message Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/segment/audio.md Example of sending a network audio message using `segment.audio` with a URL. ```typescript // 发送网络音频 await bot.client.sendMessage(channelId, [ segment.audio('https://example.com/audio.mp3') ]) ``` -------------------------------- ### Send Markdown Code Blocks Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/segment/markdown.md Provides examples of embedding code blocks with syntax highlighting for JavaScript and Python. ```typescript import { segment } from 'qq-official-bot' // 代码块 const codeMarkdown = segment.markdown(` `javascript function hello() { console.log("Hello, World!"); } ` `python def hello(): print("Hello, World!") ` `) ``` -------------------------------- ### Initialize Bot with Middleware Connection (Express/Koa) Source: https://github.com/zhinjs/qq-official-bot/blob/master/README.md Initialize the Bot class for Middleware connections, specifying the application framework ('express' or 'koa'). The bot's middleware is then integrated into the application's request handling pipeline. ```typescript import { Bot, ReceiverMode } from 'qq-official-bot' import express from 'express' const bot = new Bot({ appid: 'your_app_id', secret: 'your_app_secret', // ...其他配置 mode: ReceiverMode.MIDDLEWARE, application: 'express', // 或 'koa' }) const app = express() app.use(bot.middleware) app.listen(3000) await bot.start() ``` -------------------------------- ### Hand Gesture Expressions Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/segment/face.md Examples of sending various hand gesture emoticons like thumbs up, clap, and pray. ```APIDOC ## Hand Gesture Expressions ### Description Examples of sending various hand gesture emoticons like thumbs up, clap, and pray. ### Method Signature `segment.face(id: number): FaceElement` ### Parameters #### Path Parameters - **id** (number) - Required - The ID of the face emoticon. Range: 0-348. ### Request Example ```typescript import { segment } from 'qq-official-bot' // Hand gestures const thumbsUp = segment.face(76) // Thumbs up const thumbsDown = segment.face(77) // Thumbs down const clap = segment.face(70) // Clap const pray = segment.face(71) // Pray const ok = segment.face(74) // OK ``` ``` -------------------------------- ### Kubernetes Deployment and Service Configuration Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/guide/instruction.md Kubernetes的Deployment配置用于管理QQ官方机器人的副本数量、资源限制和探针检查。Service配置则用于暴露机器人服务。 ```yaml # k8s-deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: name: qq-bot labels: app: qq-bot spec: replicas: 3 selector: matchLabels: app: qq-bot template: metadata: labels: app: qq-bot spec: containers: - name: qq-bot image: qq-bot:latest ports: - containerPort: 3000 env: - name: BOT_APP_ID valueFrom: secretKeyRef: name: bot-secrets key: app-id - name: BOT_TOKEN valueFrom: secretKeyRef: name: bot-secrets key: token resources: limits: memory: "512Mi" cpu: "500m" requests: memory: "256Mi" cpu: "250m" livenessProbe: httpGet: path: /health port: 3000 initialDelaySeconds: 30 periodSeconds: 10 readinessProbe: httpGet: path: /ready port: 3000 initialDelaySeconds: 5 periodSeconds: 5 --- apiVersion: v1 kind: Service metadata: name: qq-bot-service spec: selector: app: qq-bot ports: - protocol: TCP port: 80 targetPort: 3000 type: LoadBalancer ``` -------------------------------- ### Basic Expressions Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/segment/face.md Examples of sending common happy, sad, and angry expressions using their respective face IDs. ```APIDOC ## Basic Expressions ### Description Examples of sending common happy, sad, and angry expressions using their respective face IDs. ### Method Signature `segment.face(id: number): FaceElement` ### Parameters #### Path Parameters - **id** (number) - Required - The ID of the face emoticon. Range: 0-348. ### Request Example ```typescript import { segment } from 'qq-official-bot' // Happy expressions const happy = segment.face(14) // Smiling face const laugh = segment.face(1) // Laughing face const shy = segment.face(13) // Shy face // Sad expressions const cry = segment.face(9) // Crying face const sad = segment.face(6) // Sad face const angry = segment.face(59) // Angry face ``` ``` -------------------------------- ### Dockerfile for QQ Official Bot Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/guide/instruction.md 使用Node.js 18 Alpine镜像构建QQ官方机器人的Docker镜像。包含依赖安装、代码复制、用户切换、端口暴露、健康检查和启动命令。 ```dockerfile # Dockerfile FROM node:18-alpine WORKDIR /app # 复制依赖文件 COPY package*.json ./ RUN npm ci --only=production # 复制源代码 COPY . . # 构建应用 RUN npm run build # 创建非root用户 RUN addgroup -g 1001 -S nodejs RUN adduser -S bot -u 1001 # 切换用户 USER bot # 暴露端口 EXPOSE 3000 # 健康检查 HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ CMD node healthcheck.js # 启动应用 CMD ["npm", "start"] ``` -------------------------------- ### Create Bot Instance Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/api/common.md A factory method for quickly creating a bot instance. Configure with app ID, secret, receiver mode, and intents. ```typescript import { createBot, ReceiverMode } from 'qq-official-bot' const bot = createBot({ appid: 'your_app_id', secret: 'your_app_secret', mode: ReceiverMode.WEBSOCKET, intents: ['GUILD_MESSAGES'], }) await bot.start() ``` -------------------------------- ### 获取子频道列表 Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/api/channel.md 使用 `bot.channelService.getList` 或 `bot.getChannelList` 获取指定频道下的所有子频道。推荐使用服务模块。 ```typescript const result = await bot.channelService.getList(guild_id) if (result.success) { console.log('子频道列表:', result.data) } ``` ```typescript const channels = await bot.getChannelList(guild_id) ``` -------------------------------- ### Get Guild Member List Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/api/guild.md Retrieves a list of members for a specific guild. This functionality is available only for private domain bots. ```APIDOC ## Get Guild Member List ### Description Retrieves the member list of a guild (available only for private domain bots). ### Method `bot.memberService.getGuildMemberList(guildId)` / `bot.getGuildMemberList(guildId)` ### Parameters #### Path Parameters - **guildId** (string) - Required - The ID of the guild ### Request Example ```typescript // Using the service module const result = await bot.memberService.getGuildMemberList(guild_id) if (result.success) { console.log('Member list:', result.data) } // Using the traditional method const members = await bot.getGuildMemberList(guild_id) ``` ### Response Data Structure ```typescript interface GuildMember.ApiInfo { member_id: string // Member ID nickname: string // Nickname avatar: string // Avatar URL joined_at: string // Join timestamp roles: string[] // List of roles } ``` ``` -------------------------------- ### Get Bot Information Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/api/common.md Retrieve basic information about the current bot. Use the `botService` module for recommended error handling. ```typescript const result = await bot.botService.getSelfInfo() if (result.success) { console.log('机器人信息:', result.data) } ``` ```typescript const botInfo = await bot.getSelfInfo() ``` -------------------------------- ### Verify AT Message Implementation with Official API Format Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/AT_MESSAGE_UPDATE_REPORT.md Compares the project's AT message implementation with the official QQ API format. Ensures the conversion logic correctly handles user IDs and the 'everyone' alias. ```typescript this.messagePayload.content += x`<@${elem.user_id === 'all' ? 'everyone' : elem.user_id}> x`; ``` -------------------------------- ### Get Group Member List Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/api/group.md Retrieves a list of members for a specified group. Note: This method might not be supported in the current implementation. ```APIDOC ## GET /group/member/list ### Description Retrieves a list of members for a specified group. ### Method `bot.getGroupMemberList(groupId)` ### Parameters #### Path Parameters - **groupId** (string) - Required - The ID of the group. ### Request Example ```typescript // Note: This method may not be supported in the current implementation, please check specific error messages try { const members = await bot.getGroupMemberList(group_id) console.log('Group member list:', members) } catch (error) { console.log('Failed to get group member list:', error.message) } ``` ### Response #### Success Response (200) - **members** (array) - A list of group members. #### Response Example ```json { "members": [ { "userId": "string", "nickname": "string", "avatar": "string" } ] } ``` ``` -------------------------------- ### Get Guild Info Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/api/guild.md Retrieves detailed information for a specific guild. This method supports both the service module and traditional method calls. ```APIDOC ## Get Guild Info ### Description Retrieves detailed information for a specific guild. ### Method `bot.guildService.getInfo(guildId)` / `bot.getGuildInfo(guildId)` ### Parameters #### Path Parameters - **guildId** (string) - Required - The ID of the guild ### Request Example ```typescript // Using the service module const result = await bot.guildService.getInfo(guild_id) if (result.success) { console.log('Guild info:', result.data) } // Using the traditional method const guildInfo = await bot.getGuildInfo(guild_id) ``` ``` -------------------------------- ### Combining @ with Text, Image, Reply, and Face Segments Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/segment/at.md Demonstrates combining the '@' message segment with text, image, reply, and face segments for various messaging scenarios. Ensure the 'qq-official-bot' library is imported. ```typescript import { Bot, segment } from 'qq-official-bot' const bot = new Bot(config) // 与文本消息段组合 await bot.client.sendMessage(channelId, [ segment.at('123456789'), segment.text(' 你好,请查看这个重要信息') ]) // 与图片消息段组合 await bot.client.sendMessage(channelId, [ segment.at('123456789'), segment.text(' 请看这张图片:'), segment.image('/path/to/image.jpg') ]) // 与回复消息段组合 await bot.client.sendMessage(channelId, [ segment.reply(originalMessageId), segment.at('123456789'), segment.text(' 关于你刚才的问题') ]) // 与表情消息段组合 await bot.client.sendMessage(channelId, [ segment.at('123456789'), segment.text(' '), segment.face(1), // 微笑表情 segment.text(' 早上好!') ]) ``` -------------------------------- ### Send Audio with Parameters Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/segment/audio.md Provide additional parameters like duration and format when sending audio. ```typescript import { segment } from 'qq-official-bot' // 指定音频信息 const audio = segment.audio('./voice.mp3', { duration: 30, format: 'mp3' }) ``` -------------------------------- ### Get Guild Member List Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/api/guild.md Fetches the member list for a guild. This functionality is only available for private bots. The guildId parameter is required. ```typescript // 使用服务模块 const result = await bot.memberService.getGuildMemberList(guild_id) if (result.success) { console.log('成员列表:', result.data) } ``` ```typescript // 使用传统方法 const members = await bot.getGuildMemberList(guild_id) ``` -------------------------------- ### 安装 TypeScript 支持 Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/guide/start.md 安装 TypeScript 和 Node.js 类型定义,并初始化 tsconfig.json。 ```bash npm install -D typescript @types/node npx tsc --init ``` -------------------------------- ### Get Pinned Messages in a Sub-Channel Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/api/channel.md Retrieves a list of pinned message IDs for a given sub-channel. Use this to fetch all messages that are currently pinned. ```typescript const result = await bot.channelService.getPins(channel_id) if (result.success) { console.log('置顶消息 ID 列表:', result.data) } ``` -------------------------------- ### Get Group Member Info Source: https://github.com/zhinjs/qq-official-bot/blob/master/docs/src/api/group.md Retrieves detailed information for a specific group member. Note: This method might not be supported in the current implementation. ```APIDOC ## GET /group/member/info ### Description Retrieves detailed information for a specific group member. ### Method `bot.getGroupMemberInfo(groupId, memberId)` ### Parameters #### Path Parameters - **groupId** (string) - Required - The ID of the group. - **memberId** (string) - Required - The ID of the member. ### Request Example ```typescript // Note: This method may not be supported in the current implementation, please check specific error messages try { const memberInfo = await bot.getGroupMemberInfo(group_id, member_id) console.log('Group member info:', memberInfo) } catch (error) { console.log('Failed to get group member info:', error.message) } ``` ### Response #### Success Response (200) - **memberInfo** (object) - Detailed information about the group member. #### Response Example ```json { "memberInfo": { "userId": "string", "nickname": "string", "joinTime": "string", "role": "string" } } ``` ```