Commit 6674a1a5 authored by nanahira's avatar nanahira

first

parent 4fa7996c
Pipeline #6310 passed with stages
in 36 seconds
webpack.config.js
dist/*
build/*
\ No newline at end of file
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
root: true,
env: {
node: true,
jest: true,
},
ignorePatterns: ['.eslintrc.js'],
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
};
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# TypeScript v1 declaration files
typings/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
.env.test
# parcel-bundler cache (https://parceljs.org/)
.cache
# Next.js build output
.next
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and *not* Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
/build
/output
/dest
/config.yaml
.idea
stages:
- build
- deploy
variables:
GIT_DEPTH: "1"
build:
stage: build
tags:
- linux
script:
- npm ci
- npm run build
artifacts:
paths:
- dist/
upload_to_minio:
stage: deploy
dependencies:
- build
tags:
- linux
script:
- aws s3 --endpoint=https://minio.mycard.moe:9000 sync --delete dist/ s3://nanahira/koishi-plugin/thesaurus
only:
- master
deploy_npm:
stage: deploy
dependencies:
- build
tags:
- linux
script:
- apt update;apt -y install coreutils
- echo $NPMRC | base64 --decode > ~/.npmrc
- npm publish . || true
only:
- master
/install-npm.sh
.git*
/output
/dest
/config.yaml
.idea
.dockerignore
Dockerfile
/src
.eslintrc.js
.prettierrc
webpack.config.js
tsconfig.json
\ No newline at end of file
{
"singleQuote": true,
"trailingComma": "all"
}
\ No newline at end of file
The MIT License (MIT)
Copyright (c) 2021 Nanahira
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# Koishi Plugin Thesaurus
# koishi-plugin-thesaurus
Koishi.js chat plugin for https://github.com/Kyomotoi/AnimeThesaurus
\ No newline at end of file
Koishi.js 的 [AnimeThesaurus](https://github.com/Kyomotoi/AnimeThesaurus) 聊天插件。
本插件使用词库项目的名称 Thesaurus 以示对 AnimeThesaurus 词库项目的尊重。
## 安装
### npm
```bash
npm install koishi-plugin-thesaurus
```
### 直接安装
在 https://cdn02.moecube.com:444/nanahira/koishi-plugin/thesaurus/index.js 下载即可。
## 配置
* `path` 词库本地路径或 URL ,默认使用 [MyCard](https://mycard.moe/) 的镜像。
* `chatTimeout` 聊天超时时间 ms 。
* `trackingLength` 追溯会话长度。
* `useDatabase` 从数据库获取用户名。
## 使用
使用命令 `startchat` 开始聊天。可以使用 `startchat --name Shigma` 指定自己的聊天昵称。
聊天期间输入 `quit` 即可结束聊天。
\ No newline at end of file
#!/bin/bash
npm install --save \
source-map-support
npm install --save-dev \
@types/node \
typescript \
'@typescript-eslint/eslint-plugin@^4.28.2' \
'@typescript-eslint/parser@^4.28.2 '\
'eslint@^7.30.0' \
'eslint-config-prettier@^8.3.0' \
'eslint-plugin-prettier@^3.4.0' \
prettier \
raw-loader \
ts-loader \
webpack \
webpack-cli \
koishi@^4.0.0-alpha.9 \
koishi-utils-schemagen
This diff is collapsed.
{
"name": "koishi-plugin-thesaurus",
"version": "1.0.0",
"description": "Koishi.js chat plugin for https://github.com/Kyomotoi/AnimeThesaurus",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"lint": "eslint --fix .",
"build": "webpack"
},
"repository": {
"type": "git",
"url": "https://code.mycard.moe/3rdeye/koishi-plugin-thesaurus.git"
},
"author": "Nanahira <nanahira@momobako.com>",
"license": "MIT",
"keywords": [
"Koishi.js",
"qqbot",
"cqhttp",
"onebot",
"ygo",
"yugioh",
"ygopro"
],
"bugs": {
"url": "https://code.mycard.moe/3rdeye/koishi-plugin-thesaurus/issues"
},
"homepage": "https://code.mycard.moe/3rdeye/koishi-plugin-thesaurus",
"dependencies": {
"source-map-support": "^0.5.20"
},
"peerDependencies": {
"koishi": "^4.0.0-alpha.9"
},
"devDependencies": {
"@types/lodash": "^4.14.175",
"@types/lru-cache": "^5.1.1",
"@types/node": "^16.11.1",
"@typescript-eslint/eslint-plugin": "^4.33.0",
"@typescript-eslint/parser": "^4.33.0",
"eslint": "^7.32.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^3.4.1",
"koishi": "^4.0.0-alpha.9",
"koishi-utils-schemagen": "^1.1.3",
"lodash": "^4.17.21",
"lru-cache": "^6.0.0",
"prettier": "^2.4.1",
"proxy-agent": "^5.0.0",
"raw-loader": "^4.0.2",
"ts-loader": "^9.2.6",
"typescript": "^4.4.4",
"webpack": "^5.58.2",
"webpack-cli": "^4.9.1"
}
}
import 'source-map-support/register';
import { DefineSchema } from 'koishi-utils-schemagen';
export class MyPluginConfig {
@DefineSchema({
desc: '词库本地路径或 URL。',
default:
'https://code.mycard.moe/3rdeye/AnimeThesaurus/-/raw/main/data.json',
})
path: string;
@DefineSchema({
desc: '聊天超时时间 ms。',
default: 600000,
})
chatTimeout: number;
@DefineSchema({
desc: '追溯会话长度',
default: 10,
})
trackingLength: number;
@DefineSchema({
desc: '从数据库获取用户名。',
default: false,
})
useDatabase: boolean;
}
export type MyPluginConfigLike = Partial<MyPluginConfig>;
import 'source-map-support/register';
import { Context } from 'koishi';
import { MyPlugin } from './plugin';
import { MyPluginConfigLike } from './config';
export { MyPluginConfig } from './config';
export const name = 'thesaurus';
const plugin = new MyPlugin();
export const schema = plugin.schema;
export function apply(ctx: Context, config: Partial<MyPluginConfigLike>) {
ctx.plugin(plugin, config);
}
import 'source-map-support/register';
import { Context, Schema, Random } from 'koishi';
import { MyPluginConfig, MyPluginConfigLike } from './config';
import { schemaFromClass, schemaTransform } from 'koishi-utils-schemagen';
import { promises as fs } from 'fs';
import { sleep } from 'koishi';
import LRUCache from 'lru-cache';
import _ from 'lodash';
interface ChatSession {
name: string;
playedWords: string[];
}
export class MyPlugin {
private config: MyPluginConfig;
private ctx: Context;
private wordData: Record<string, string[]> = {};
private useDatabase = false;
private async loadWords(): Promise<void> {
const path = this.config.path;
try {
if (path.match(/^https?:\/\//)) {
this.wordData = await this.ctx.http.get(path);
} else {
this.wordData = JSON.parse(await fs.readFile(path, 'utf-8'));
}
this.ctx
.logger('thesaurus')
.info(
`Loaded ${
Object.keys(this.wordData).length
} patterns from source ${path} .`,
);
} catch (e) {
this.ctx
.logger('thesaurus')
.error(`Failed to load words from source ${path}: ${e.toString()}`);
await sleep(5000);
return this.loadWords();
}
}
// should be replaced with Koishi cache in future version
private lru: LRUCache<string, ChatSession>;
private async getFromCache(userId: string) {
if (!userId) {
return;
}
return this.lru.get(userId);
}
private async setToCache(userId: string, chatSession: ChatSession) {
if (!userId) {
return;
}
return this.lru.set(userId, chatSession, this.config.chatTimeout);
}
private async clearCacheOf(userId: string) {
if (!userId) {
return;
}
return this.lru.del(userId);
}
private async replyWith(
word: string,
userId: string,
chatSession: ChatSession,
) {
if (!word) {
return;
}
chatSession.playedWords.push(word);
if (chatSession.playedWords.length > this.config.trackingLength) {
chatSession.playedWords.shift();
}
await this.setToCache(userId, chatSession);
return word.replace(/你/g, chatSession.name).trim();
}
private tryPatterns(patterns: string[], usedWords: Set<string>) {
if (!patterns.length) {
return;
}
const pattern = Random.pick(patterns);
const availableWords = this.wordData[pattern].filter(
(w) => !usedWords.has(w),
);
if (!availableWords.length) {
const shrinkedPatterns = patterns.filter((p) => p !== pattern);
return this.tryPatterns(shrinkedPatterns, usedWords);
}
return Random.pick(availableWords);
}
private async replyChat(
word: string,
userId: string,
chatSession: ChatSession,
) {
const matchingPatterns = Object.keys(this.wordData).filter((w) =>
word.includes(w),
);
if (!matchingPatterns.length) {
const allWords = _.flatten(Object.values(this.wordData));
let remainingAllWords = allWords.filter(
(w) => !chatSession.playedWords.includes(w),
);
if (!remainingAllWords.length) {
remainingAllWords = allWords;
}
return this.replyWith(
Random.pick(remainingAllWords),
userId,
chatSession,
);
}
const replyWord =
this.tryPatterns(
matchingPatterns,
new Set<string>(chatSession.playedWords),
) || this.tryPatterns(matchingPatterns, new Set<string>());
return this.replyWith(replyWord, userId, chatSession);
}
private formatName(name: string) {
if (name.match(/^[a-zA-Z0-9]/)) {
name = ` ${name}`;
}
if (name.match(/[a-zA-Z0-9]$/)) {
name = `${name} `;
}
return name;
}
name = 'thesaurus-main';
schema: Schema<MyPluginConfigLike> = schemaFromClass(MyPluginConfig);
async apply(ctx: Context, config: MyPluginConfigLike) {
this.ctx = ctx;
this.config = schemaTransform(MyPluginConfig, config);
ctx.on('connect', () => {
if (ctx.database && this.config.useDatabase) this.useDatabase = true;
});
this.lru = new LRUCache<string, ChatSession>({
maxAge: this.config.chatTimeout,
});
await this.loadWords();
ctx.middleware(async (session, next) => {
const chatSession = await this.getFromCache(session.userId);
if (chatSession) {
//ctx
// .logger('thesaurus')
// .warn(`${session.userId} in chat ${JSON.stringify(chatSession)}`);
if (session.content === 'quit') {
await this.clearCacheOf(session.userId);
return session.send('记得下次再找我聊喔~');
}
const reply = await this.replyChat(
session.content,
session.userId,
chatSession,
);
return session.send(reply);
}
//ctx.logger('thesaurus').warn(`${session.userId} outside session`);
return next();
});
ctx
.command('startchat', '开始聊天')
.usage('聊天开始后, quit 停止聊天。')
.example('startchat --name Shigma 可以使用 Shigma 作为自己的名字来聊天。')
.option('name', '--name <name:string>')
.userFields(['name'])
.action(async (argv) => {
const { session, options } = argv;
const userId = session.userId;
let name =
session.author?.nickname ||
session.author?.username ||
session.username;
if (this.useDatabase) {
if (session.user.name) {
name = session.user.name;
}
}
if (options.name) {
name = options.name;
}
if (!name) {
name = '';
}
const formattedName = this.formatName(name);
await this.setToCache(userId, {
name: formattedName,
playedWords: [],
});
return `${formattedName},开始和我聊天吧。聊累了的话,输入 quit 就可以结束聊天哦。`.trim();
});
}
}
{
"compilerOptions": {
"outDir": "dist",
"module": "commonjs",
"target": "es2021",
"esModuleInterop": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"declaration": true,
"sourceMap": true
},
"compileOnSave": true,
"allowJs": true,
"include": [
"*.ts",
"src/**/*.ts"
]
}
const path = require("path");
module.exports = {
entry: "./src/index.ts",
mode: "production",
target: "node",
devtool: "source-map",
module: {
rules: [
{
test: /\.tsx?$/,
use: "ts-loader",
exclude: /node_modules/,
},
{ test: /\.mustache$/, use: "raw-loader" },
],
},
resolve: {
extensions: [".tsx", ".ts", ".js"],
},
output: {
filename: "index.js",
library: {
type: "commonjs",
},
path: path.resolve(__dirname, "dist"),
},
externals: {
'koishi': 'koishi',
}
};
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