Commit 8f3b36a4 authored by nanahira's avatar nanahira

migrate to ReplySession

parent 9f1eb497
This diff is collapsed.
......@@ -44,10 +44,10 @@
"testEnvironment": "node"
},
"dependencies": {
"koishi-thirdeye": "^11.1.14"
"koishi-thirdeye": "^11.1.15"
},
"peerDependencies": {
"koishi": "^4.10.4"
"koishi": "^4.10.6"
},
"devDependencies": {
"@koishijs/plugin-console": "^4.7.1",
......
import {
Fragment,
PromptOptions,
Random,
segment,
SendOptions,
Session,
} from 'koishi';
import ApiBot from './index';
import { Prompt } from './def/prompt';
export class ApiSession extends Session {
storedMessages: string[] = [];
private midResolver: () => void;
bot: ApiBot;
currentPromise: Promise<void>;
midPromise = new Promise<void>((resolve) => {
this.midResolver = resolve;
});
async waitForPattern() {
await Promise.race([
this.currentPromise.then(() => this.midResolve(true)),
this.midPromise,
]);
return this.gatherResponseMessages();
}
getIdentifier() {
return '' + this.userId + this.channelId;
}
midResolve(finish = false) {
if (!this.midResolver) {
return;
}
this.midResolver();
if (finish) {
delete this.midResolver;
} else {
this.midPromise = new Promise<void>((resolve) => {
this.midResolver = resolve;
});
}
}
async send(content: Fragment, options: SendOptions = {}) {
if (!content) return;
options.session = this;
const children = await this.transform(segment.normalize(content));
this.storedMessages.push(
children.map((child) => child.toString()).join(''),
);
return [Random.id()];
}
gatherResponseMessages() {
const result = this.storedMessages.filter((m) => !!m);
this.storedMessages = [];
return result;
}
prompt(...args: any[]) {
const callback: (session: Session) => any =
typeof args[0] === 'function'
? args.shift()
: (session) => session.content;
const options: PromptOptions =
typeof args[0] === 'number' ? { timeout: args[0] } : args[0] ?? {};
const timeout = options.timeout ?? this.app.config.delay.prompt;
const identifier = this.getIdentifier();
const prom = new Promise<string>((resolve) => {
const prompt: Prompt = {
resolver: resolve,
timeout: setTimeout(() => {
this.bot.resolvePrompt(identifier, undefined);
}, timeout),
session: this,
contentCallback: callback,
};
this.bot.prompts.set(identifier, prompt);
});
this.midResolve();
return prom;
}
}
import { ApiSession } from '../api-session';
export interface Prompt {
resolver: (value: string) => void;
timeout: NodeJS.Timeout;
session: ApiSession;
contentCallback: (session: ApiSession) => any;
}
......@@ -3,17 +3,14 @@ import { ApiPluginConfig, ApiPluginConfigLike } from './config';
import {
DefinePlugin,
InjectConfig,
OnPlatform,
UseMiddleware,
Post,
KoaContext,
PluginSchema,
OnSelf,
Post,
Reusable,
ReplySession,
} from 'koishi-thirdeye';
import { Bot, Context, Fragment, Next, Random } from 'koishi';
import { ApiSession } from './api-session';
import { Prompt } from './def/prompt';
import { Bot, Context, Fragment, Random } from 'koishi';
export * from './config';
@Reusable()
......@@ -23,38 +20,11 @@ export default class ApiBot extends Bot {
username = 'koishi';
selfId = 'koishi';
hidden = true;
prompts = new Map<string, Prompt>();
constructor(public ctx: Context, config: ApiPluginConfigLike) {
super(ctx, { platform: 'api', selfId: config.selfId });
}
resolvePrompt(key: string, session: ApiSession) {
const prompt = this.prompts.get(key);
if (prompt) {
prompt.resolver(prompt.contentCallback(session));
clearTimeout(prompt.timeout);
this.prompts.delete(key);
return prompt;
}
return;
}
@OnSelf('{{selfId}}')
@OnPlatform('api')
@UseMiddleware()
private async handlePrompt(session: ApiSession, next: Next) {
const identifier = session.getIdentifier();
const prompt = this.resolvePrompt(identifier, session);
if (!prompt) {
return next();
}
session.storedMessages = session.storedMessages.concat(
await prompt.session.waitForPattern(),
);
return;
}
@InjectConfig()
private pluginConfig: ApiPluginConfig;
......@@ -83,7 +53,7 @@ export default class ApiBot extends Bot {
return;
}
const userId = body.userId || ctx.request.ip;
const session = new ApiSession(this, {
const session = new ReplySession(this, {
userId,
channelId: body.channelId || `private:${userId}`,
guildId: body.guildId,
......@@ -104,10 +74,10 @@ export default class ApiBot extends Bot {
ctx.body = { messages: [] };
return;
}
const currentPromise = this.ctx.app.parallel('message', session);
session.currentPromise = currentPromise;
ctx.status = 200;
ctx.body = { messages: await session.waitForPattern() };
ctx.body = {
messages: (await session.process()).map((e) => e.toString()),
};
}
async sendMessage(channelId: string, content: Fragment) {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment