Commit b36db486 authored by nanahira's avatar nanahira

bump to Koishi 4.8

parent 67d71753
import { App } from 'koishi'; import { Context } 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 AragamiPlugin from 'koishi-plugin-cache-aragami';
import ExtrasInDev from './extras'; import ExtrasInDev from './extras';
const app = new App({ const app = new Context({
port: 14514, port: 14514,
host: 'localhost', host: 'localhost',
prefix: '.', prefix: '.',
...@@ -19,7 +19,7 @@ app.plugin(ConsolePlugin, { ...@@ -19,7 +19,7 @@ app.plugin(ConsolePlugin, {
}); });
// Some services // Some services
app.plugin(CachePlugin); app.plugin(AragamiPlugin);
app.plugin(DatabasePlugin); app.plugin(DatabasePlugin);
// Some extras // Some extras
......
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -21,26 +21,26 @@ ...@@ -21,26 +21,26 @@
"qqbot", "qqbot",
"cqhttp", "cqhttp",
"onebot", "onebot",
"required:cache" "required:cache-aragami"
], ],
"bugs": { "bugs": {
"url": "https://code.mycard.moe/3rdeye/koishi-plugin-thesaurus/issues" "url": "https://code.mycard.moe/3rdeye/koishi-plugin-thesaurus/issues"
}, },
"homepage": "https://code.mycard.moe/3rdeye/koishi-plugin-thesaurus", "homepage": "https://code.mycard.moe/3rdeye/koishi-plugin-thesaurus",
"dependencies": { "dependencies": {
"koishi-thirdeye": "^10.3.2", "koishi-thirdeye": "^11.0.6",
"lodash": "^4.17.21" "lodash": "^4.17.21"
}, },
"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.0", "@types/jest": "^27.4.0",
"@types/lodash": "^4.14.175", "@types/lodash": "^4.14.175",
"@types/node": "^16.11.1", "@types/node": "^16.11.1",
"@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.3.0", "eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^3.4.1", "eslint-plugin-prettier": "^3.4.1",
...@@ -56,7 +56,8 @@ ...@@ -56,7 +56,8 @@
"ws": "^8.3.0" "ws": "^8.3.0"
}, },
"peerDependencies": { "peerDependencies": {
"koishi": "^4.7.5" "koishi": "^4.8.2",
"koishi-plugin-cache-aragami": "^1.0.4"
}, },
"jest": { "jest": {
"moduleFileExtensions": [ "moduleFileExtensions": [
......
// import 'source-map-support/register'; // import 'source-map-support/register';
import { Random, sleep, Cache } from 'koishi'; import { Random, sleep, Session } from 'koishi';
import { ThesaurusPluginConfig } from './config'; import { ThesaurusPluginConfig } from './config';
import { promises as fs } from 'fs'; import { promises as fs } from 'fs';
import _ from 'lodash'; import _ from 'lodash';
import { import {
BasePlugin, StarterPlugin,
DefinePlugin, DefinePlugin,
Inject, Inject,
LifecycleEvents, LifecycleEvents,
UseMiddleware,
UseCommand,
CommandUsage,
CommandExample,
PutOption,
PutUserName,
PutSession,
} from 'koishi-thirdeye'; } from 'koishi-thirdeye';
import AragamiPlugin, { CacheKey } from 'koishi-plugin-cache-aragami';
import { Next } from 'koa';
export interface ChatSession { class ChatSession {
@CacheKey()
sessionId: string;
name: string; name: string;
playedWords: string[]; playedWords: string[];
} }
export * from './config'; export * from './config';
declare module 'koishi' {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace Cache {
interface Tables {
thesaurusChatSession: ChatSession;
}
}
}
@DefinePlugin({ name: 'thesaurus', schema: ThesaurusPluginConfig }) @DefinePlugin({ name: 'thesaurus', schema: ThesaurusPluginConfig })
export default class ThesaurusPlugin export default class ThesaurusPlugin
extends BasePlugin<ThesaurusPluginConfig> extends StarterPlugin(ThesaurusPluginConfig)
implements LifecycleEvents implements LifecycleEvents
{ {
@Inject(true) @Inject(true)
private cache: Cache; private aragami: AragamiPlugin;
private wordData: Record<string, string[]> = {}; private wordData: Record<string, string[]> = {};
private async loadWords(): Promise<void> { private async loadWords(): Promise<void> {
...@@ -63,31 +65,16 @@ export default class ThesaurusPlugin ...@@ -63,31 +65,16 @@ export default class ThesaurusPlugin
if (!sessionId) { if (!sessionId) {
return; return;
} }
return this.cache.get('thesaurusChatSession', sessionId); return this.aragami.get(ChatSession, sessionId);
} }
private async setToCache(sessionId: string, chatSession: ChatSession) { private async setToCache(chatSession: ChatSession) {
if (!sessionId) { return this.aragami.set(ChatSession, chatSession);
return;
}
return this.cache.set(
'thesaurusChatSession',
sessionId,
chatSession,
this.config.chatTimeout,
);
} }
private async clearCacheOf(sessionId: string) { private async clearCacheOf(sessionId: string) {
if (!sessionId) { return this.aragami.del(ChatSession, sessionId);
return;
}
return this.cache.del('thesaurusChatSession', sessionId);
} }
private async replyWith( private async replyWith(word: string, chatSession: ChatSession) {
word: string,
sessionId: string,
chatSession: ChatSession,
) {
if (!word) { if (!word) {
return; return;
} }
...@@ -95,7 +82,7 @@ export default class ThesaurusPlugin ...@@ -95,7 +82,7 @@ export default class ThesaurusPlugin
if (chatSession.playedWords.length > this.config.trackingLength) { if (chatSession.playedWords.length > this.config.trackingLength) {
chatSession.playedWords.shift(); chatSession.playedWords.shift();
} }
await this.setToCache(sessionId, chatSession); await this.setToCache(chatSession);
return word.replace(/你/g, chatSession.name).trim(); return word.replace(/你/g, chatSession.name).trim();
} }
...@@ -114,11 +101,7 @@ export default class ThesaurusPlugin ...@@ -114,11 +101,7 @@ export default class ThesaurusPlugin
return Random.pick(availableWords); return Random.pick(availableWords);
} }
private async replyChat( private async replyChat(word: string, chatSession: ChatSession) {
word: string,
sessionId: string,
chatSession: ChatSession,
) {
const matchingPatterns = Object.keys(this.wordData).filter((w) => const matchingPatterns = Object.keys(this.wordData).filter((w) =>
word.includes(w), word.includes(w),
); );
...@@ -130,18 +113,14 @@ export default class ThesaurusPlugin ...@@ -130,18 +113,14 @@ export default class ThesaurusPlugin
if (!remainingAllWords.length) { if (!remainingAllWords.length) {
remainingAllWords = allWords; remainingAllWords = allWords;
} }
return this.replyWith( return this.replyWith(Random.pick(remainingAllWords), chatSession);
Random.pick(remainingAllWords),
sessionId,
chatSession,
);
} }
const replyWord = const replyWord =
this.tryPatterns( this.tryPatterns(
matchingPatterns, matchingPatterns,
new Set<string>(chatSession.playedWords), new Set<string>(chatSession.playedWords),
) || this.tryPatterns(matchingPatterns, new Set<string>()); ) || this.tryPatterns(matchingPatterns, new Set<string>());
return this.replyWith(replyWord, sessionId, chatSession); return this.replyWith(replyWord, chatSession);
} }
private formatName(name: string) { private formatName(name: string) {
if (name.match(/^[a-zA-Z0-9]/)) { if (name.match(/^[a-zA-Z0-9]/)) {
...@@ -153,56 +132,42 @@ export default class ThesaurusPlugin ...@@ -153,56 +132,42 @@ export default class ThesaurusPlugin
return name; return name;
} }
async onConnect() { @UseMiddleware()
const ctx = this.ctx; async replyMessage(session: Session, next: Next) {
this.cache.table('thesaurusChatSession', { const sessionId = `${session.platform}.${session.selfId}.${session.userId}`;
maxAge: this.config.chatTimeout, const chatSession = await this.getFromCache(sessionId);
}); if (chatSession) {
await this.loadWords(); if (session.content === 'quit') {
ctx.middleware(async (session, next) => { await this.clearCacheOf(sessionId);
const sessionId = `${session.platform}.${session.selfId}.${session.userId}`; return '记得下次再找我聊喔~';
const chatSession = await this.getFromCache(sessionId);
if (chatSession) {
//ctx
// .logger('thesaurus')
// .warn(`${session.userId} in chat ${JSON.stringify(chatSession)}`);
if (session.content === 'quit') {
await this.clearCacheOf(sessionId);
await session.send('记得下次再找我聊喔~');
return;
}
const reply = await this.replyChat(
session.content,
sessionId,
chatSession,
);
await session.send(reply);
} }
//ctx.logger('thesaurus').warn(`${session.userId} outside session`); return await this.replyChat(session.content, chatSession);
return next(); }
return next();
}
@UseCommand('startchat', '开始聊天')
@CommandUsage('聊天开始后, quit 停止聊天。')
@CommandExample(
'startchat --name Shigma 可以使用 Shigma 作为自己的名字来聊天。',
)
async startChat(
@PutOption('name', '--name <name:string>') optionName: string,
@PutUserName() databaseName: string,
@PutSession() session: Session,
) {
const sessionId = `${session.platform}.${session.selfId}.${session.userId}`;
const name = optionName || databaseName;
const formattedName = this.formatName(name);
await this.setToCache({
sessionId,
name: formattedName,
playedWords: [],
}); });
ctx return `${formattedName},开始和我聊天吧。聊累了的话,输入 quit 就可以结束聊天哦。`.trim();
.command('startchat', '开始聊天') }
.usage('聊天开始后, quit 停止聊天。')
.example('startchat --name Shigma 可以使用 Shigma 作为自己的名字来聊天。') async onConnect() {
.option('name', '--name <name:string>') await this.loadWords();
.userFields(['name'])
.action(async (argv) => {
const { session, options } = argv;
const sessionId = `${session.platform}.${session.selfId}.${session.userId}`;
let name = session.username;
if (options.name) {
name = options.name;
}
if (!name) {
name = '';
}
const formattedName = this.formatName(name);
await this.setToCache(sessionId, {
name: formattedName,
playedWords: [],
});
return `${formattedName},开始和我聊天吧。聊累了的话,输入 quit 就可以结束聊天哦。`.trim();
});
} }
} }
import { App } from 'koishi'; import { Context } from 'koishi';
import TargetPlugin from '../src'; import TargetPlugin from '../src';
describe('Test of plugin.', () => { describe('Test of plugin.', () => {
let app: App; let app: Context;
beforeEach(async () => { beforeEach(async () => {
app = new App(); app = new Context();
// app.plugin(TargetPlugin); // app.plugin(TargetPlugin);
await app.start(); await app.start();
}); });
......
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