qq-official-bot

June 18, 2026 · View on GitHub

CI Docs npm version qq group

基于 Node.js 的 QQ 官方机器人开发 SDK,采用现代化的模块化架构设计,提供完整的类型支持和丰富的功能。

✨ 特性

  • 🏗️ 模块化架构 - 采用服务化设计,职责分离,易于维护和扩展
  • 🔌 多种连接方式 - 支持 WebSocket、Webhook 和中间件模式
  • 🌐 自定义网关地址 - WebSocket 模式可配置 accessTokenUrlgatewayUrl,便于代理或私有部署
  • 📝 完整类型支持 - 使用 TypeScript 开发,提供完整的类型定义
  • 🚀 简单易用 - 提供直观的 API 接口和丰富的示例
  • 🛠️ 功能全面 - 覆盖 QQ 官方 API 的所有功能
  • 🔒 安全可靠 - 内置请求验证和错误处理机制

📦 安装

npm install qq-official-bot
# 或者
yarn add qq-official-bot
# 或者
pnpm add qq-official-bot

🎯 核心架构

项目采用分层架构设计:

  • Bot 层 - 对外提供统一的 API 接口
  • Service 层 - 业务逻辑服务,负责具体功能实现
  • Client 层 - 底层客户端,处理认证和连接管理
  • Message 层 - 消息处理和构建
  • Events 层 - 事件系统和调度器

🚀 快速开始

1. WebSocket 连接模式

import { Bot, ReceiverMode } from 'qq-official-bot'

const bot = new Bot({
    appid: 'your_app_id',           // QQ 机器人的 App ID
    secret: 'your_app_secret',      // QQ 机器人的 App Secret
    sandbox: false,                 // 是否为沙箱环境
    removeAt: true,                 // 自动移除消息中的 @机器人
    logLevel: 'info',               // 日志级别
    maxRetry: 10,                   // 最大重连次数
    intents: [
        'GROUP_AND_C2C_EVENT',     // 群聊@消息与私聊事件
        'GUILD_MESSAGES',              // 频道消息事件
        'DIRECT_MESSAGE',              // 频道私信事件
        'GUILD_MESSAGE_REACTIONS',     // 频道消息表态事件
        'GUILDS',                      // 频道变更事件
        'GUILD_MEMBERS',               // 频道成员变更事件
    ],
    mode: ReceiverMode.WEBSOCKET,   // 连接模式
})

// 启动机器人
await bot.start()

如需通过代理或自建服务接入官方网关,可自定义认证与 gateway 接口地址(WebSocket 地址仍由 gateway 响应中的 url 字段返回):

const bot = new Bot({
    appid: 'your_app_id',
    secret: 'your_app_secret',
    intents: ['GUILD_MESSAGES'],
    mode: ReceiverMode.WEBSOCKET,
    // 可选:自定义 token 接口(完整 URL)
    accessTokenUrl: 'https://your-proxy.example.com/app/getAppAccessToken',
    // 可选:自定义 gateway 接口(完整 URL 或相对路径)
    gatewayUrl: 'https://your-proxy.example.com/gateway/bot',
})

2. Webhook 连接模式

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()

3. 中间件模式 (Express/Koa)

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()

📝 基本用法

发送消息

// 监听消息事件
bot.on('message.guild', async (event) => {
    // 频道消息回复
    await event.reply('Hello, World!')
})

bot.on('message.group', async (event) => {
    // 群消息回复
    await event.reply('Hello, Group!')
})

bot.on('message.private', async (event) => {
    // 私聊消息回复
    await event.reply('Hello, Private!')
})

// 主动发送消息
await bot.sendMessage(channel_id, 'Hello from bot!')
await bot.sendGroupMessage(group_id, 'Hello, Group!')
await bot.sendPrivateMessage(user_id, 'Hello, User!')

使用服务模块

// 使用频道服务
const guilds = await bot.guildService.getGuilds()
const guildInfo = await bot.guildService.getGuild(guild_id)

// 使用消息服务
await bot.messageService.sendMessage(channel_id, 'Hello!')
await bot.messageService.recallMessage(channel_id, message_id)

// 使用成员管理服务
await bot.memberService.muteGuildMember(guild_id, user_id, '600', '0')
await bot.memberService.kickGuildMember(guild_id, user_id)

// 使用权限管理服务
const permissions = await bot.permissionService.getChannelUserPermissions(channel_id, user_id)
await bot.permissionService.updateChannelUserPermissions(channel_id, user_id, 'add_permission', 'remove_permission')

🔧 服务模块架构

项目采用服务模块化设计,每个服务负责特定的功能领域:

核心服务

服务模块功能描述主要方法
GuildService频道管理getGuilds(), getGuild(), getGuildMembers()
ChannelService子频道管理getChannel(), createChannel(), updateChannel()
MessageService消息处理sendMessage(), recallMessage(), sendPrivateMessage()
MemberService成员管理muteGuildMember(), kickGuildMember(), muteGuildMembers()
PermissionService权限管理getChannelUserPermissions(), updateChannelUserPermissions()
ReactionService表态管理addGuildMessageReaction(), removeGuildMessageReaction()
ScheduleService日程管理getChannelSchedules(), createSchedule(), updateSchedule()
ThreadService帖子管理getThreads(), createThread(), deleteThread()
AudioService音频控制controlMemberMic(), kickChannelMember()
BotService机器人信息getSelfInfo(), getSelfGuilds(), postActionMessage()

服务特性

  • 统一响应格式 - 所有服务方法返回 ApiResponse<T> 格式
  • 错误处理 - 内置错误捕获和处理机制
  • 类型安全 - 完整的 TypeScript 类型定义
  • 向后兼容 - Bot 类保持原有 API 接口不变

🎯 API 参考

基础 API

功能方法参数返回值
获取机器人信息getSelfInfo()-User
获取频道列表getGuilds()-Guild[]
获取频道信息getGuild(guild_id)guild_id: stringGuild
获取子频道列表getGuildChannels(guild_id)guild_id: stringChannel[]
获取子频道信息getChannel(channel_id)channel_id: stringChannel

消息 API

功能方法参数返回值
发送频道消息sendMessage(channel_id, content)channel_id: string, content: Sendableany
发送私聊消息sendPrivateMessage(user_id, content)user_id: string, content: Sendableany
发送群消息sendGroupMessage(group_id, content)group_id: string, content: Sendableany
撤回消息recallMessage(channel_id, message_id)channel_id: string, message_id: stringany

成员管理 API

功能方法参数返回值
获取频道成员getGuildMembers(guild_id)guild_id: stringGuildMember[]
禁言成员muteGuildMember(guild_id, user_id, seconds)guild_id: string, user_id: string, seconds: stringany
踢出成员kickGuildMember(guild_id, user_id)guild_id: string, user_id: stringany

权限管理 API

功能方法参数返回值
获取用户权限getChannelUserPermissions(channel_id, user_id)channel_id: string, user_id: stringChannelMemberPermissions
更新用户权限updateChannelUserPermissions(channel_id, user_id, add?, remove?)channel_id: string, user_id: string, add?: string, remove?: stringany

🔧 配置选项

Bot 配置

interface BotConfig {
    appid: string              // 机器人 App ID
    secret: string             // 机器人 App Secret
    sandbox?: boolean          // 是否为沙箱环境,默认 false
    removeAt?: boolean         // 是否移除消息中的 @,默认 false
    logLevel?: string          // 日志级别,默认 'info'
    maxRetry?: number          // 最大重连次数,默认 10
    intents: Intent[]          // 订阅的事件类型
    mode: ReceiverMode         // 连接模式
    
    // WebSocket 模式特有配置
    accessTokenUrl?: string    // 获取 access token 的完整 URL
    gatewayUrl?: string        // 获取网关信息的 URL 或路径,响应 url 为 WebSocket 地址
    heartbeatInterval?: number // 心跳间隔(ms)
    maxRetries?: number        // 连接重试次数
    reconnectDelay?: number    // 重连延迟(ms)
    
    // Webhook 模式特有配置
    port?: number              // 监听端口
    path?: string              // Webhook 路径
    
    // 中间件模式特有配置
    application?: 'express' | 'koa'  // 使用的框架
}

事件类型 (Intents)

type Intent = 
    // 频道事件
    | 'GUILDS'
    // 频道成员事件
    | 'GUILD_MEMBERS'
    // 频道消息事件
    | 'GUILD_MESSAGES'
    // 频道消息表态事件
    | 'GUILD_MESSAGE_REACTIONS'
    // 频道私信事件
    | 'DIRECT_MESSAGE'
    // 群成员变更事件
    | 'GROUP_MEMBER'
    // 私聊与群聊消息事件
    | 'GROUP_AND_C2C_EVENT'
    // 互动事件
    | 'INTERACTION'
    // 消息审核事件
    | 'MESSAGE_AUDIT'
    // 论坛事件(仅私域)
    | 'FORUMS_EVENT'
    // 音频操作事件
    | 'AUDIO_ACTION'
    // 公域机器人消息事件
    | 'PUBLIC_GUILD_MESSAGES'

🎨 消息构建

基础消息

// 文本消息
await bot.sendMessage(channel_id, 'Hello, World!')

// 富文本消息
await bot.sendMessage(channel_id, [
    '这是一条包含 ',
    { type: 'mention', user_id: 'user123' },
    ' 的消息'
])

高级消息

import { MessageBuilder } from 'qq-official-bot'

// 使用消息构建器
const message = bot.messageBuilder
    .text('Hello ')
    .mention(user_id)
    .text('!')
    .build()

await bot.sendMessage(channel_id, message)