Skip to content

Commit

Permalink
feat: 适配器优化
Browse files Browse the repository at this point in the history
  • Loading branch information
lc-cn committed Feb 17, 2025
1 parent b76b874 commit fb0b980
Show file tree
Hide file tree
Showing 26 changed files with 57 additions and 52 deletions.
12 changes: 4 additions & 8 deletions core/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,11 +112,7 @@ export class App extends EventEmitter {
return this.commandList.find(command => command.name === name);
}

getSupportMiddlewares<P extends Adapters>(
adapter: Adapter<P>,
bot: Adapter.Bot<P>,
event: Message<P>,
): Middleware<P>[] {
getSupportMiddlewares<P extends Adapters>({ bot, adapter }: Message<P>): Middleware<P>[] {
return (
this.pluginList
// 过滤不支持当前适配器的插件
Expand All @@ -139,9 +135,9 @@ export class App extends EventEmitter {
.flatMap(plugin => plugin.commandList);
}

handleMessage<P extends Adapters>(adapter: Adapter<P>, bot: Adapter.Bot<P>, event: Message<P>) {
const middleware = Middleware.compose(this.getSupportMiddlewares(adapter, bot, event));
middleware(adapter, bot, event);
handleMessage<P extends Adapters>(event: Message<P>) {
const middleware = Middleware.compose(this.getSupportMiddlewares(event));
middleware(event);
}

plugin(plugin: Plugin): this {
Expand Down
18 changes: 4 additions & 14 deletions core/src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export namespace Middleware {
for (const fn of middlewares) {
if (typeof fn !== 'function') throw new TypeError('Middleware must be composed of functions!');
}
return (adapter: Adapter<P>, bot: Adapter.Bot<P>, event: Message<P>, next?: Next) => {
return (event: Message<P>, next?: Next) => {
let index = -1;
const dispatch: (i: number, ctx?: Message<P>) => Promise<any> = (i: number, ctx: Message<P> = event) => {
if (i <= index) return Promise.reject(new Error('next() called multiple times'));
Expand All @@ -19,7 +19,7 @@ export namespace Middleware {
if (i === middlewares.length) fn = next;
if (!fn) return Promise.resolve();
try {
return Promise.resolve(fn(adapter, bot, ctx, dispatch.bind(null, i + 1)));
return Promise.resolve(fn(ctx, dispatch.bind(null, i + 1)));
} catch (err) {
return Promise.reject(err);
}
Expand All @@ -29,16 +29,6 @@ export namespace Middleware {
}
}
export namespace Compose {
export type Middleware<P extends Adapters> = (
adapter: Adapter<P>,
bot: Adapter.Bot<P>,
event: Message<P>,
next: Next,
) => any;
export type ComposedMiddleware<P extends Adapters> = (
adapter: Adapter<P>,
bot: Adapter.Bot<P>,
event: Message<P>,
next?: Next,
) => Promise<void>;
export type Middleware<P extends Adapters> = (event: Message<P>, next: Next) => any;
export type ComposedMiddleware<P extends Adapters> = (event: Message<P>, next?: Next) => Promise<void>;
}
2 changes: 1 addition & 1 deletion core/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export class Plugin extends EventEmitter {
set display_name(name: string) {
this.name = name;
}
useConfig<T>(configPath: string, schema: Schema<T>): T | undefined {
useConfig<T>(configPath: string, schema: Schema<T>): T {
if (schema.meta.type !== 'object') throw new Error(`config schema root must be type object`);
const config = new Config<T & object>(configPath, schema.meta.default as any);
return schema(config.data);
Expand Down
6 changes: 3 additions & 3 deletions core/src/prompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export class Prompt<P extends keyof App.Adapters> {
});
}
middleware(callback: (input: string | Error) => any, timeout: number = 3 * 60 * 1000, timeoutText = '输入超时') {
const middleware: Middleware = (adapter, bot, event, next) => {
const middleware: Middleware = (event, next) => {
if (this.getChannelAddress(event) !== this.getChannelAddress(this.event)) return next();
callback(event.raw_message);
dispose();
Expand Down Expand Up @@ -214,7 +214,7 @@ export namespace Prompt {
}
export interface PickConfig<T extends SingleType = SingleType, M extends boolean = false> {
type: T;
defaultValue?: M extends true ? SingleMap[T] : SingleMap[T][];
defaultValue?: PickResult<T, M>;
separator?: string;
timeout?: number;
options: PickOption<T>[];
Expand All @@ -229,7 +229,7 @@ export namespace Prompt {
export type Result<T extends SingleType> = SingleMap[T];
export type Config<R = any> = {
tips: string;
defaultValue: any;
defaultValue?: R;
timeout?: number;
timeoutText?: string;
format: (input: string) => R;
Expand Down
2 changes: 1 addition & 1 deletion packages/adapters/com-wechat/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ const messageHandler = (bot: WechatClient, event: ClientMessage) => {
raw_message: ClientMessage.formatToString(event.message),
message_type: event.detail_type as any,
});
adapter.app!.emit('message', adapter, bot, message);
adapter.app!.emit('message', message);
};
const stopBots = () => {
for (const bot of adapter.bots) {
Expand Down
2 changes: 1 addition & 1 deletion packages/adapters/dingtalk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ const messageHandler = (bot: Adapter.Bot<'dingtalk'>, event: DingMsgEvent) => {
permissions: [],
},
});
dingTalkAdapter.app!.emit('message', dingTalkAdapter, bot, message);
dingTalkAdapter.app!.emit('message', message);
};
const stopBots = () => {
for (const bot of dingTalkAdapter.bots) {
Expand Down
2 changes: 1 addition & 1 deletion packages/adapters/discord/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ const messageHandler = (bot: Adapter.Bot<'discord'>, event: DiscordMessageEvent)
raw_message: sendableToString(event.message).trim(),
message_type: event.message_type,
});
discordAdapter.app!.emit('message', discordAdapter, bot, message);
discordAdapter.app!.emit('message', message);
};
const stopBots = () => {
for (const bot of discordAdapter.bots) {
Expand Down
2 changes: 1 addition & 1 deletion packages/adapters/email/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ const startBots = (configs: Adapter.BotConfig<'email'>[]) => {
for (const config of configs) {
const bot = new EmailClient(config) as Adapter.Bot<'email'>;
bot.on('message', (message: Message<'email'>) => {
adapter.app?.emit('message', adapter, bot, message);
adapter.app?.emit('message', message);
});
bot
.start()
Expand Down
2 changes: 1 addition & 1 deletion packages/adapters/icqq/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ const startBots = async (configs: Adapter.BotConfig<'icqq'>[]) => {
};
const messageHandler = (bot: QQClient, event: QQMessageEvent) => {
const message = Message.from(icqqAdapter, bot, createMessageBase(event));
icqqAdapter.app!.emit('message', icqqAdapter, bot, message);
icqqAdapter.app!.emit('message', message);
};
const botLogin = async (bot: QQClient) => {
return new Promise<void>(resolve => {
Expand Down
2 changes: 1 addition & 1 deletion packages/adapters/kritor/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ const messageHandler = (bot: Adapter.Bot<'kritor'>, event: kritor.common.IPushMe
},
});
bot.logger.info(`recv [${message.channel})]: ${message.raw_message}`);
adapter.app!.emit('message', adapter, bot, message);
adapter.app!.emit('message', message);
};
const startBots = (configs: Adapter.BotConfig<'kritor'>[]) => {
for (const config of configs) {
Expand Down
2 changes: 1 addition & 1 deletion packages/adapters/onebot-11/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ const messageHandler = (bot: OneBotClient, event: MessageV11) => {
},
message_type: event.message_type,
});
oneBotV11.app!.emit('message', oneBotV11, bot, message);
oneBotV11.app!.emit('message', message);
};
const stopBots = () => {
for (const bot of oneBotV11.bots) {
Expand Down
2 changes: 1 addition & 1 deletion packages/adapters/onebot-12/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ const messageHandler = (bot: OneBotClient, event: MessageV12) => {
},
raw_message: MessageV12.formatToString(event.message),
});
oneBotV12Adapter.app!.emit('message', oneBotV12Adapter, bot, message);
oneBotV12Adapter.app!.emit('message', message);
};
const stopBots = () => {
for (const bot of oneBotV12Adapter.bots) {
Expand Down
2 changes: 1 addition & 1 deletion packages/adapters/qq/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ const messageHandler = (bot: QQClient, event: QQMessageEvent) => {
if (event.source) {
message.quote = event.source;
}
qqAdapter.app!.emit('message', qqAdapter, bot, message);
qqAdapter.app!.emit('message', message);
};
const stopBots = () => {
for (const bot of qqAdapter.bots) {
Expand Down
2 changes: 1 addition & 1 deletion packages/adapters/web-wechat/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ const messageHandler = (bot: WechatClient, event: DingMsgEvent) => {
permissions: [],
},
});
wechatAdapter.app!.emit('message', wechatAdapter, bot, message);
wechatAdapter.app!.emit('message', message);
};
const stopBots = () => {
for (const bot of wechatAdapter.bots) {
Expand Down
2 changes: 1 addition & 1 deletion packages/plugins/qa/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ qaCommand.command('问答详情 <no:number>').action(async (_, no) => {
2,
)}`;
});
qaPlugin.middleware(async (adapter, bot, message, next) => {
qaPlugin.middleware(async (message, next) => {
const beforeMessage = message.raw_message;
await next();
const afterMessage = message.raw_message;
Expand Down
6 changes: 3 additions & 3 deletions packages/plugins/transfer/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,17 +65,17 @@ transferPlugin
},
});
});
transferPlugin.middleware(async (adapter, bot, message, next) => {
transferPlugin.middleware(async (message, next) => {
const transferList = await transferPlugin.database.get<TransportConfig[]>('transfer', []);
const transfer = transferList.find(
transfer => transfer.from.adapter === adapter.name && transfer.from.bot_id === bot.unique_id,
transfer => transfer.from.adapter === message.adapter.name && transfer.from.bot_id === message.bot.unique_id,
);
if (!transfer) return next();
const toAdapter = transferPlugin.app?.adapters.get(transfer.to.adapter);
if (!toAdapter) return next();
const toBot = toAdapter.bots.find(b => b.unique_id === transfer.to.bot_id);
if (!toBot) return next();
adapter.app?.emit('message', toAdapter, toBot, message);
transferPlugin.app?.emit('message', message);
return next();
});
export default transferPlugin;
2 changes: 1 addition & 1 deletion packages/services/github/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const config = plugin.useConfig(
}),
);
plugin.mounted(app => {
plugin.middleware(async (_a, _b, message, next) => {
plugin.middleware(async (message, next) => {
await next();
const mathReg = /^(?:https?:\/\/)?(?:www\.)?github\.com\/([^/]+)\/([^/]+)\/?$/;
const match = message.raw_message.match(mathReg);
Expand Down
3 changes: 2 additions & 1 deletion test/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"@zhinjs/plugin-schedule": "workspace:^",
"@zhinjs/plugin-qa": "workspace:^",
"@zhinjs/plugin-guild-manage": "workspace:^",
"@zhinjs/plugin-group-manage": "workspace:^"
"@zhinjs/plugin-group-manage": "workspace:^",
"@zhinjs/plugin-ollama": "workspace:^"
}
}
3 changes: 1 addition & 2 deletions test/plugins/foo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ useCommand('bar')
return '我不知道该说啥呀';
});

registerMiddleware((_adapter, _bot, message, next) => {
// console.log(_adapter, _bot, message);
registerMiddleware((message, next) => {
next();
});
8 changes: 5 additions & 3 deletions test/plugins/test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { Plugin, Message } from 'zhin';
import '@zhinjs/plugin-sandbox';
import type {} from '@zhinjs/plugin-ollama';
import * as path from 'path';
import type {} from '@zhinjs/web';

const test = new Plugin('测试插件'); // 定义插件
test.ollama.chat;
test
.command('test-confirm') // 插件功能
.hidden()
Expand Down Expand Up @@ -84,15 +86,15 @@ test
})
.join('\n==============\n');
});
test.with('web', app => {
test.waitServices('web', app => {
app.web.addEntry(path.resolve(__dirname, '../client/index.ts'));
});
test.with('register', async app => {
test.waitServices('register', async app => {
app.register('hello', function (this: Message, foo, bar, isExist = false) {
return `receive from ${this.message_type},args is ${foo},${bar},${isExist}`;
});
});
test.with('component', app => {
test.waitServices('component', app => {
app.component({
name: 'test2',
render(_, context) {
Expand Down
1 change: 1 addition & 0 deletions zhin/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export {
useCommand,
waitServices,
logger,
useConfig,
} from './plugins/setup';
export * from './constants';
import {
Expand Down
2 changes: 1 addition & 1 deletion zhin/src/plugins/commandParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const executeCommand = async (message: Message) => {
}
};
const commandParser = new Plugin('commandParser');
commandParser.middleware(async (_a, _b, message, next) => {
commandParser.middleware(async (message, next) => {
const result = await executeCommand(message);
if (result) return;
return next();
Expand Down
2 changes: 1 addition & 1 deletion zhin/src/plugins/database/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ database.mounted(async app => {
// 初始化用户、群表
await db.get('group', []);
await db.get('user', []);
app.middleware(async (_a, _b, message, next) => {
app.middleware(async (message, next) => {
const userInfo = await db.find<UserInfo[]>('user', user => {
return user.user_id === message.sender.user_id;
});
Expand Down
2 changes: 1 addition & 1 deletion zhin/src/plugins/functionParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ plugin.mounted(app => {
plugin.service('functions', functionManager.functions);
plugin.service('register', functionManager.register);
});
plugin.middleware(async (_1, _2, event, next) => {
plugin.middleware(async (event, next) => {
await next();
return plugin.functionManager.match(event);
});
Expand Down
2 changes: 1 addition & 1 deletion zhin/src/plugins/processAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ processAdapter.on('start', () => {
message_type: 'private',
});
processAdapter.logger.info(`recv [${message.channel}]: ${message.raw_message}`);
processAdapter.app!.emit('message', processAdapter, bot, message);
processAdapter.app!.emit('message', message);
});
setTimeout(() => {
processAdapter.emit('bot-ready', bot);
Expand Down
18 changes: 17 additions & 1 deletion zhin/src/plugins/setup.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,15 @@
import { Adapter, Adapters, App, ArgsType, Command, getCallerStack, Message, Middleware, Plugin } from '@zhinjs/core';
import {
Adapter,
Adapters,
App,
ArgsType,
Command,
getCallerStack,
Message,
Middleware,
Plugin,
Schema,
} from '@zhinjs/core';
import * as path from 'path';
const setup = new Plugin('setup');
const resolveCallerPlugin = (): [boolean, Plugin] => {
Expand Down Expand Up @@ -83,6 +94,7 @@ export interface Context {
message: string,
source?: Message,
): Promise<any>;
useConfig<T>(configPath: string, schema: Schema<T>): T;
onMount(callback: Plugin.CallBack): Plugin;
onUnmount(callback: Plugin.CallBack): Plugin;
listen<E extends keyof App.EventMap>(event: E, callback: App.EventMap[E]): Plugin;
Expand All @@ -103,6 +115,9 @@ export const context = {
inject<T extends keyof App.Services>(name: T) {
return context.plugin.service(name);
},
useConfig<T>(configPath: string, schema: Schema<T>): T {
return context.plugin.useConfig(configPath, schema);
},
waitServices<T extends keyof App.Services>(...args: [...T[], callabck: (app: App) => void]) {
return context.plugin.waitServices(...args);
},
Expand Down Expand Up @@ -202,6 +217,7 @@ export const sendDirectMessage = context.sendDirectMessage;
export const onMount = context.onMount;
export const onUnmount = context.onUnmount;
export const listen = context.listen;
export const useConfig = context.useConfig;
export const logger = {
trace(message: any, ...args: any[]): void {
context.plugin.logger.debug(message, ...args);
Expand Down

0 comments on commit fb0b980

Please sign in to comment.