Commit 8c941730 authored by nanahira's avatar nanahira

support Koishi 4.8

parent 596ddeb9
# compiled output
/dist
/node_modules
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
/coverage
/.nyc_output
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
/data
/output
/config.yaml
.git*
Dockerfile
.dockerignore
...@@ -2,8 +2,8 @@ import { App } from 'koishi'; ...@@ -2,8 +2,8 @@ import { App } from 'koishi';
import TargetPlugin from '../src'; import TargetPlugin from '../src';
import ConsolePlugin from '@koishijs/plugin-console'; import ConsolePlugin from '@koishijs/plugin-console';
import SandboxPlugin from '@koishijs/plugin-sandbox'; import SandboxPlugin from '@koishijs/plugin-sandbox';
import * as DatabasePlugin from '@koishijs/plugin-database-memory'; import DatabasePlugin from '@koishijs/plugin-database-memory';
import CachePlugin from '@koishijs/plugin-cache-lru'; // import CachePlugin from '@koishijs/plugin-cache-lru';
import ExtrasInDev from './extras'; import ExtrasInDev from './extras';
const app = new App({ const app = new App({
...@@ -19,7 +19,7 @@ app.plugin(ConsolePlugin, { ...@@ -19,7 +19,7 @@ app.plugin(ConsolePlugin, {
}); });
// Some services // Some services
app.plugin(CachePlugin); // app.plugin(CachePlugin);
app.plugin(DatabasePlugin); app.plugin(DatabasePlugin);
// Some extras // Some extras
......
This diff is collapsed.
...@@ -44,21 +44,21 @@ ...@@ -44,21 +44,21 @@
"testEnvironment": "node" "testEnvironment": "node"
}, },
"dependencies": { "dependencies": {
"koishi-thirdeye": "^10.3.2" "koishi-thirdeye": "^11.0.6"
}, },
"peerDependencies": { "peerDependencies": {
"koishi": "^4.7.5" "koishi": "^4.8.2"
}, },
"devDependencies": { "devDependencies": {
"@koishijs/plugin-cache-lru": "^1.0.0-rc.0", "@koishijs/plugin-console": "^4.1.1",
"@koishijs/plugin-console": "^3.3.2", "@koishijs/plugin-database-memory": "^1.4.1",
"@koishijs/plugin-database-memory": "^1.3.0", "@koishijs/plugin-sandbox": "^2.0.1",
"@koishijs/plugin-sandbox": "^1.1.3",
"@types/jest": "^27.4.1", "@types/jest": "^27.4.1",
"@types/node": "^17.0.22", "@types/node": "^17.0.22",
"@types/supertest": "^2.0.12", "@types/supertest": "^2.0.12",
"@typescript-eslint/eslint-plugin": "^4.33.0", "@typescript-eslint/eslint-plugin": "^4.33.0",
"@typescript-eslint/parser": "^4.33.0", "@typescript-eslint/parser": "^4.33.0",
"esbuild-loader": "^2.19.0",
"eslint": "^7.32.0", "eslint": "^7.32.0",
"eslint-config-prettier": "^8.5.0", "eslint-config-prettier": "^8.5.0",
"eslint-plugin-prettier": "^3.4.1", "eslint-plugin-prettier": "^3.4.1",
......
import { getSessionId, Random, Session } from 'koishi'; import { getSessionId, Random, Session } from 'koishi';
import { ApiBot } from './index'; import ApiBot from './index';
import { Prompt } from './def/prompt'; import { Prompt } from './def/prompt';
export class ApiSession extends Session { export class ApiSession extends Session {
......
...@@ -2,21 +2,30 @@ ...@@ -2,21 +2,30 @@
import { ApiPluginConfig, ApiPluginConfigLike } from './config'; import { ApiPluginConfig, ApiPluginConfigLike } from './config';
import { import {
DefinePlugin, DefinePlugin,
LifecycleEvents,
Inject,
InjectConfig, InjectConfig,
OnPlatform,
UseMiddleware,
Post,
KoaContext,
PluginSchema,
} from 'koishi-thirdeye'; } from 'koishi-thirdeye';
import { Adapter, Bot, Context, getSessionId, Random, Router } from 'koishi'; import { Bot, Context, getSessionId, Next, Random } from 'koishi';
import { ApiSession } from './api-session'; import { ApiSession } from './api-session';
import { Prompt } from './def/prompt'; import { Prompt } from './def/prompt';
export * from './config'; export * from './config';
export class ApiBot extends Bot { @PluginSchema(ApiPluginConfig)
@DefinePlugin()
export default class ApiBot extends Bot {
username = 'koishi'; username = 'koishi';
selfId = 'koishi'; selfId = 'koishi';
hidden = true; hidden = true;
prompts = new Map<string, Prompt>(); prompts = new Map<string, Prompt>();
constructor(public ctx: Context, config: ApiPluginConfigLike) {
super(ctx, { platform: 'api', selfId: 'koishi' });
}
resolvePrompt(key: string, value: string) { resolvePrompt(key: string, value: string) {
const prompt = this.prompts.get(key); const prompt = this.prompts.get(key);
if (prompt) { if (prompt) {
...@@ -28,13 +37,9 @@ export class ApiBot extends Bot { ...@@ -28,13 +37,9 @@ export class ApiBot extends Bot {
return; return;
} }
constructor(public adapter: ApiAdapter, config: Bot.BaseConfig) { @OnPlatform('api')
super(adapter, config); @UseMiddleware()
this.adapter.ctx async handlePrompt(session: ApiSession, next: Next) {
.any()
.platform('api')
.self(this.selfId)
.middleware(async (session: ApiSession, next) => {
const identifier = getSessionId(session); const identifier = getSessionId(session);
const prompt = this.resolvePrompt(identifier, session.content); const prompt = this.resolvePrompt(identifier, session.content);
if (!prompt) { if (!prompt) {
...@@ -44,49 +49,13 @@ export class ApiBot extends Bot { ...@@ -44,49 +49,13 @@ export class ApiBot extends Bot {
await prompt.session.waitForPattern(), await prompt.session.waitForPattern(),
); );
return; return;
}, true);
}
async sendMessage(channelId: string, content: string) {
return [];
} }
async sendPrivateMessage(userId: string, content: string) {
return [];
}
}
export interface MessageBody {
channelId?: string;
guildId?: string;
messageId?: string;
content: string;
userId?: string;
username?: string;
avatar?: string;
}
@DefinePlugin({ name: 'api', schema: ApiPluginConfig })
export default class ApiAdapter extends Adapter implements LifecycleEvents {
constructor(ctx: Context, config: ApiPluginConfigLike) {
super(ctx, config);
}
@Inject('bots', true)
private botList: Adapter.BotList;
@Inject(true)
private router: Router;
@InjectConfig() @InjectConfig()
private pluginConfig: ApiPluginConfig; private pluginConfig: ApiPluginConfig;
onApply() { @Post('{{path}}')
this.platform = 'api'; async onHttpPost(ctx: KoaContext) {
this.botList.adapters.api = this;
const bot = this.botList.create('api', {}, ApiBot);
this.router.post(this.pluginConfig.path, async (ctx) => {
if (this.pluginConfig.token) { if (this.pluginConfig.token) {
const header = ctx.request.headers['authorization']; const header = ctx.request.headers['authorization'];
const tokenFromRequest = header?.startsWith('Bearer ') const tokenFromRequest = header?.startsWith('Bearer ')
...@@ -110,7 +79,7 @@ export default class ApiAdapter extends Adapter implements LifecycleEvents { ...@@ -110,7 +79,7 @@ export default class ApiAdapter extends Adapter implements LifecycleEvents {
return; return;
} }
const userId = body.userId || ctx.request.ip; const userId = body.userId || ctx.request.ip;
const session = new ApiSession(bot, { const session = new ApiSession(this, {
userId, userId,
channelId: body.channelId || `private:${userId}`, channelId: body.channelId || `private:${userId}`,
guildId: body.guildId, guildId: body.guildId,
...@@ -130,10 +99,23 @@ export default class ApiAdapter extends Adapter implements LifecycleEvents { ...@@ -130,10 +99,23 @@ export default class ApiAdapter extends Adapter implements LifecycleEvents {
session.currentPromise = currentPromise; session.currentPromise = currentPromise;
ctx.status = 200; ctx.status = 200;
ctx.body = { messages: await session.waitForPattern() }; ctx.body = { messages: await session.waitForPattern() };
});
} }
async start() {} async sendMessage(channelId: string, content: string) {
return [];
}
async stop() {} async sendPrivateMessage(userId: string, content: string) {
return [];
}
}
export interface MessageBody {
channelId?: string;
guildId?: string;
messageId?: string;
content: string;
userId?: string;
username?: string;
avatar?: string;
} }
...@@ -12,21 +12,21 @@ describe('Test of plugin.', () => { ...@@ -12,21 +12,21 @@ describe('Test of plugin.', () => {
}); });
it('should check token', () => { it('should check token', () => {
request(app._httpServer) request(app.router._http)
.post('/api') .post('/api')
.send({ userId: '111111', content: 'wwww' }) .send({ userId: '111111', content: 'wwww' })
.expect(401); .expect(401);
request(app._httpServer) request(app.router._http)
.post('/api') .post('/api')
.send({ userId: '111111', content: 'wwww' }) .send({ userId: '111111', content: 'wwww' })
.set('Authorization', 'dress') .set('Authorization', 'dress')
.expect(200); .expect(200);
request(app._httpServer) request(app.router._http)
.post('/api') .post('/api')
.send({ userId: '111111', content: 'wwww' }) .send({ userId: '111111', content: 'wwww' })
.set('Authorization', 'Bearer dress') .set('Authorization', 'Bearer dress')
.expect(200); .expect(200);
request(app._httpServer) request(app.router._http)
.post('/api') .post('/api')
.send({ userId: '111111', content: 'wwww' }) .send({ userId: '111111', content: 'wwww' })
.set('Authorization', 'Bearer skirt') .set('Authorization', 'Bearer skirt')
...@@ -35,7 +35,7 @@ describe('Test of plugin.', () => { ...@@ -35,7 +35,7 @@ describe('Test of plugin.', () => {
it('should reply message', () => { it('should reply message', () => {
app.command('dress').action((a) => '梦梦女装!'); app.command('dress').action((a) => '梦梦女装!');
request(app._httpServer) request(app.router._http)
.post('/api') .post('/api')
.send({ userId: '111111', content: 'dress' }) .send({ userId: '111111', content: 'dress' })
.set('Authorization', 'dress') .set('Authorization', 'dress')
...@@ -47,7 +47,7 @@ describe('Test of plugin.', () => { ...@@ -47,7 +47,7 @@ describe('Test of plugin.', () => {
it('should correctly ref userId', () => { it('should correctly ref userId', () => {
app.command('dress').action((a) => `${a.session.userId} 让梦梦女装!`); app.command('dress').action((a) => `${a.session.userId} 让梦梦女装!`);
request(app._httpServer) request(app.router._http)
.post('/api') .post('/api')
.send({ userId: '111111', content: 'dress' }) .send({ userId: '111111', content: 'dress' })
.set('Authorization', 'dress') .set('Authorization', 'dress')
...@@ -62,7 +62,7 @@ describe('Test of plugin.', () => { ...@@ -62,7 +62,7 @@ describe('Test of plugin.', () => {
await a.session.send('梦梦换衣服啦!'); await a.session.send('梦梦换衣服啦!');
return '梦梦女装啦!'; return '梦梦女装啦!';
}); });
request(app._httpServer) request(app.router._http)
.post('/api') .post('/api')
.send({ userId: '111111', content: 'dress' }) .send({ userId: '111111', content: 'dress' })
.set('Authorization', 'dress') .set('Authorization', 'dress')
...@@ -82,7 +82,7 @@ describe('Test of plugin.', () => { ...@@ -82,7 +82,7 @@ describe('Test of plugin.', () => {
const colorOfSkirt = await a.session.prompt(100000); const colorOfSkirt = await a.session.prompt(100000);
return `原来 ${a.session.userId} 今天穿的是 ${colorOfShirt} 的衣服,和 ${colorOfSkirt} 的裙子!`; return `原来 ${a.session.userId} 今天穿的是 ${colorOfShirt} 的衣服,和 ${colorOfSkirt} 的裙子!`;
}); });
await request(app._httpServer) await request(app.router._http)
.post('/api') .post('/api')
.send({ userId: '111111', content: 'ask' }) .send({ userId: '111111', content: 'ask' })
.set('Authorization', 'dress') .set('Authorization', 'dress')
...@@ -93,7 +93,7 @@ describe('Test of plugin.', () => { ...@@ -93,7 +93,7 @@ describe('Test of plugin.', () => {
], ],
}) })
.then(); .then();
await request(app._httpServer) await request(app.router._http)
.post('/api') .post('/api')
.send({ userId: '111112', content: 'ask' }) .send({ userId: '111112', content: 'ask' })
.set('Authorization', 'dress') .set('Authorization', 'dress')
...@@ -104,7 +104,7 @@ describe('Test of plugin.', () => { ...@@ -104,7 +104,7 @@ describe('Test of plugin.', () => {
], ],
}) })
.then(); .then();
await request(app._httpServer) await request(app.router._http)
.post('/api') .post('/api')
.send({ userId: '111111', content: '红色' }) .send({ userId: '111111', content: '红色' })
.set('Authorization', 'dress') .set('Authorization', 'dress')
...@@ -113,7 +113,7 @@ describe('Test of plugin.', () => { ...@@ -113,7 +113,7 @@ describe('Test of plugin.', () => {
messages: ['那你能告诉我你今天穿了什么颜色的裙子吗?'], messages: ['那你能告诉我你今天穿了什么颜色的裙子吗?'],
}) })
.then(); .then();
await request(app._httpServer) await request(app.router._http)
.post('/api') .post('/api')
.send({ userId: '111112', content: '蓝色' }) .send({ userId: '111112', content: '蓝色' })
.set('Authorization', 'dress') .set('Authorization', 'dress')
...@@ -122,7 +122,7 @@ describe('Test of plugin.', () => { ...@@ -122,7 +122,7 @@ describe('Test of plugin.', () => {
messages: ['那你能告诉我你今天穿了什么颜色的裙子吗?'], messages: ['那你能告诉我你今天穿了什么颜色的裙子吗?'],
}) })
.then(); .then();
await request(app._httpServer) await request(app.router._http)
.post('/api') .post('/api')
.send({ userId: '111111', content: '白色' }) .send({ userId: '111111', content: '白色' })
.set('Authorization', 'dress') .set('Authorization', 'dress')
...@@ -131,7 +131,7 @@ describe('Test of plugin.', () => { ...@@ -131,7 +131,7 @@ describe('Test of plugin.', () => {
messages: ['原来 111111 今天穿的是 红色 的衣服,和 白色 的裙子!'], messages: ['原来 111111 今天穿的是 红色 的衣服,和 白色 的裙子!'],
}) })
.then(); .then();
await request(app._httpServer) await request(app.router._http)
.post('/api') .post('/api')
.send({ userId: '111112', content: '黑色' }) .send({ userId: '111112', content: '黑色' })
.set('Authorization', 'dress') .set('Authorization', 'dress')
...@@ -144,6 +144,6 @@ describe('Test of plugin.', () => { ...@@ -144,6 +144,6 @@ describe('Test of plugin.', () => {
afterEach(async () => { afterEach(async () => {
await app.stop(); await app.stop();
app._httpServer.close(); app.router._http.close();
}); });
}); });
const path = require('path'); const path = require('path');
const packgeInfo = require('./package.json'); const packgeInfo = require('./package.json');
const { ESBuildMinifyPlugin } = require('esbuild-loader');
function externalsFromDep() { function externalsFromDep() {
return Object.fromEntries( return Object.fromEntries(
...@@ -43,4 +44,11 @@ module.exports = { ...@@ -43,4 +44,11 @@ module.exports = {
koishi: 'koishi', koishi: 'koishi',
...(packAll ? {} : externalsFromDep()), ...(packAll ? {} : externalsFromDep()),
}, },
optimization: {
minimizer: [
new ESBuildMinifyPlugin({
keepNames: true,
}),
],
},
}; };
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