Skip to content

BotClient ​

Bot 客户端,封装 WebSocket 连接、启动流程及 bot 自身信息。

构造函数 ​

ts
new BotClient(config: BotConfig)

BotConfig ​

ts
interface BotConfig {
    baseUrl: string
    accessToken?: string
    owner: number
    reconnection?: { enable?: boolean; attempts?: number; delay?: number }
    apiTimeout?: number
}
字段类型必填说明
baseUrlstring是NapCat WebSocket 地址,必须以 ws:// 或 wss:// 开头,未配置或格式错误会抛出错误
accessTokenstring否访问令牌
ownernumber是Bot 主人(管理员)QQ 号,未配置会抛出错误并拒绝启动
reconnection.enableboolean否是否自动重连,默认 true
reconnection.attemptsnumber否最大重连次数,默认 Infinity(一直重试)
reconnection.delaynumber否重连间隔(ms),默认 5000
apiTimeoutnumber否API 超时(ms),默认 120000
pluginDirstring否插件目录,默认 ./plugins
autoLoadPluginsboolean否是否自动扫描并监听插件目录,默认 true
handleSignalsboolean否是否处理 SIGINT/SIGTERM 优雅退出,默认 true
storagePathstring否存储文件路径,默认 ./data/storage.json
commandPrefixstring | string[]否命令前缀,默认 #
commandCooldownReplyboolean否命令冷却时是否回复提示,默认 false
logBotConsoleOptions否日志配置,等价于 BotConsole.configure()

依赖注入 ​

ts
new BotClient(config, {
    api?: BotApi,
    event?: BotEvent,
    scheduler?: BotScheduler,
    storage?: BotStorage,
})

可注入自定义组件,便于测试、多实例或替换实现。多实例时建议为每个 bot 配置不同的 pluginDir、storagePath 和 commandPrefix。

属性 ​

属性类型说明
apiBotApiAPI 调用入口
eventBotEvent事件监听入口
schedulerBotScheduler定时任务入口
pluginBotPluginSystem插件系统入口
commandBotCommandSystem命令系统入口
storageBotStorageJSON 键值存储
statusBotConnectionState当前连接状态
nicknamestring | null登录后 bot 昵称,启动前为 null
idnumber | null登录后 bot QQ 号,启动前为 null
ownernumber配置的 Bot 主人(管理员)QQ 号
onlinebooleanbot QQ 是否在线,掉线 / 恢复时自动更新

方法 ​

isOwner() ​

ts
isOwner(qq: number): boolean

判断指定 QQ 号是否为配置的 Bot 主人。

getStatus() ​

ts
getStatus(): BotStatus

返回 { connection, online, attempts } 状态快照。

onStatusChange(listener) ​

ts
onStatusChange(listener: (status: BotStatus) => void): () => void

监听连接/在线状态变化,返回取消函数。状态包括 idle、connecting、open、reconnecting、closed、stopped。

context(event) ​

ts
context(event: MessageEventLike): MessageContext

创建消息上下文,提供 reply()、send()、recall()、isOwner、isAdmin 等便捷方法。详见 MessageContext。

start() ​

ts
async start(): Promise<void>

连接 napcat 并初始化。启动成功后自动填充 nickname 和 id。

连接建立、断开、重连失败均会通过控制台输出提醒;默认断线后会一直按 reconnection.delay 间隔重试。若需限制次数,可设置 reconnection.attempts。

框架同时监听 notice.bot_offline、meta_event.lifecycle 和心跳状态:bot QQ 掉线或恢复在线时会输出提醒并更新 bot.online。QQ 账号本身掉线后需要在 NapCat / QQ 端重新登录,框架不会自动重新登录账号。

stop() ​

ts
async stop(): Promise<void>

优雅退出:卸载全部插件、取消定时任务、断开 WebSocket,并将状态设为 stopped。可重复调用。handleSignals 为 true 时,收到 SIGINT/SIGTERM 会自动调用它。

使用示例 ​

ts
import { BotClient } from 'hotcat-bot-qq'

const bot = new BotClient({
    baseUrl: 'ws://localhost:8082/onebot/v11/ws/',
    accessToken: 'your-access-token',
    owner: 123456789,
    reconnection: {
        enable: true,
        attempts: Infinity,
        delay: 5000,
    },
})
await bot.start()

console.log(bot.nickname) // "MyBot"
console.log(bot.id)       // 123456789
console.log(bot.owner)    // 123456789

owner 为必填项。未配置或填写了非法的 QQ 号时,new BotClient() 会抛出错误,bot 不会启动。

基于 MIT 许可发布