Skip to content

适配器开发

Saukko 的聊天平台适配器属于插件。为了统一 API 并方便开发,我们提供了 Bot 抽象类,供适配器插件继承与实现。

不稳定的 API

Saukko Core 的适配器 API 尚处于开发阶段,可能会发生重大变化。

Bot 抽象类

typescript
import { Bot, Context } from '@saukkojs/core';
import eventbus from /* ... */;

declare module '@saukkojs/core' {
    interface Events {
        'message.private': {
          /* ... */
          // 此处无需声明 bot 属性。
        }
    }
}

class MyBot extends Bot {
  constructor(context: Context) {
    super(context);
    eventbus.on('message', (message) => {
      // 来自 `Bot` 的 `emit` 方法会将 `MyBot` 对象放在事件的 `bot` 属性里传递给上下文的事件。
      this.emit('message.private', message);
    });
  }
  sendPrivateMessage(userId: string, content: string): Promise<void> {
    return /* ... */;
  }
}

export default function (context: Context) {
  const bot = new MyBot(context);
  context.mountBot(bot);
}

约定

  • 适配器是插件,遵循插件的全部规则(形态、依赖、清理),见 插件开发
  • 事件类型通过对 Events 接口的声明扩展注册,bot 属性由 Bot.emit 自动附加;
  • 挂载的 bot 实例出现在所有插件的 context.bots 数组中;
  • 适配器持有的连接等资源,应在 context.lifecycle.onStop 中释放,框架会等待清理完成(见 生命周期与清理)。

Last updated:

Saukko.js 系列项目均使用 Apache 2.0 协议开源。