Commit 3de15472 authored by nanahira's avatar nanahira

first

parent 66fb150d
# 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
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',
},
};
# 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
stages:
- install
- build
- deploy
variables:
GIT_DEPTH: "1"
npm_ci:
stage: install
tags:
- linux
script:
- npm ci
artifacts:
paths:
- node_modules
.build_base:
stage: build
tags:
- linux
dependencies:
- npm_ci
build:
extends: .build_base
script: npm run build
artifacts:
paths:
- dist/
test:
extends: .build_base
script: npm run test
upload_to_minio:
stage: deploy
dependencies:
- build
tags:
- linux
script:
- aws s3 --endpoint=https://minio.mycard.moe:9000 sync --delete dist/full/ s3://nanahira/koishi-plugin/edging
only:
- master
deploy_npm:
stage: deploy
dependencies:
- build
tags:
- linux
script:
- apt update;apt -y install coreutils
- echo $NPMRC | base64 --decode > ~/.npmrc
- npm publish . --access public
only:
- master
/install-npm.sh
.git*
/data
/output
/config.yaml
.idea
.dockerignore
Dockerfile
/src
/dist/full
/coverage
/tests
/dist/tests
/dev
/dist/dev
/webpack.config.js
/.eslint*
.*ignore
.prettierrc*
{
"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 Edging
# koishi-plugin-edging
用于 *** 的插件。
\ No newline at end of file
用于 *** 的插件。
## 安装
### npm
```bash
npm install koishi-plugin-edging
```
### 直接安装
在 https://cdn02.moecube.com:444/nanahira/koishi-plugin/edging/index.js 下载即可。
## 配置
详见 `config.ts` 部分,或详见 Schema 描述配置。
import { Context } from 'koishi';
import PicsContainer from 'koishi-plugin-pics';
import PicSourceLolicon from 'koishi-plugin-picsource-lolicon';
import PicSourceYandePlugin from 'koishi-plugin-picsource-yande';
import PicSourceHeisi from 'koishi-plugin-picsource-heisi';
import PicSourceMiraikoi from 'koishi-plugin-picsource-miraikoi';
export default class ExtrasInDev {
constructor(ctx: Context) {
ctx.plugin(PicsContainer, { useBase64: true });
ctx.plugin(PicSourceLolicon, {
isDefault: true,
weight: 2,
});
ctx.plugin(PicSourceYandePlugin, {
instances: [
{
name: 'yande',
weight: 1,
endpoint: 'https://yande.re/post.json',
pageLimit: 200,
isDefault: true,
},
{
name: 'konachan',
weight: 1,
endpoint: 'https://konachan.com/post.json',
pageLimit: 200,
isDefault: true,
},
],
});
ctx.plugin(PicSourceHeisi, { isDefault: true });
ctx.plugin(PicSourceMiraikoi, { isDefault: true });
}
}
import { App } from 'koishi';
import TargetPlugin from '../src';
import ConsolePlugin from '@koishijs/plugin-console';
import SandboxPlugin from '@koishijs/plugin-sandbox';
import * as DatabasePlugin from '@koishijs/plugin-database-memory';
import CachePlugin from '@koishijs/plugin-cache-lru';
import ExtrasInDev from './extras';
const app = new App({
port: 14514,
host: 'localhost',
prefix: '.',
});
// Console and sandbox
app.plugin(SandboxPlugin);
app.plugin(ConsolePlugin, {
open: false,
});
// Some services
app.plugin(CachePlugin);
app.plugin(DatabasePlugin);
// Some extras
app.plugin(ExtrasInDev);
// Target plugin
app.plugin(TargetPlugin, {
modelRoot: './data',
picTags: ['handjob'],
defaultProfile: {
model: 'zw',
suffixes: ['', '~', '~~', '~~~'],
usePics: true,
},
});
app.start();
#!/bin/bash
npm install --save \
koishi-thirdeye
npm install --save-peer \
koishi@latest
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 \
ws \
ts-node \
@koishijs/plugin-console \
@koishijs/plugin-sandbox \
@koishijs/plugin-database-memory \
@koishijs/plugin-cache-lru \
jest \
ts-jest \
@types/jest
This diff is collapsed.
{
"name": "koishi-plugin-edging",
"description": "一个 Koishi 插件",
"version": "1.0.0",
"main": "dist/index.js",
"types": "dist/src/index.d.ts",
"scripts": {
"lint": "eslint --fix .",
"build": "webpack && env PACK_ALL=1 webpack",
"start": "ts-node ./dev",
"test": "jest --passWithNoTests"
},
"repository": {
"type": "git",
"url": "https://code.mycard.moe/3rdeye/koishi-plugin-edging.git"
},
"author": "Nanahira <nanahira@momobako.com>",
"license": "MIT",
"keywords": [
"Koishi.js",
"qqbot",
"cqhttp",
"onebot"
],
"bugs": {
"url": "https://code.mycard.moe/3rdeye/koishi-plugin-edging/issues"
},
"homepage": "https://code.mycard.moe/3rdeye/koishi-plugin-edging",
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "tests",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
},
"dependencies": {
"koishi-thirdeye": "^10.0.20",
"moment": "^2.29.3"
},
"peerDependencies": {
"koishi": "^4.6.2",
"koishi-plugin-pics": "^9.1.2"
},
"devDependencies": {
"@koishijs/plugin-cache-lru": "^1.0.0-rc.0",
"@koishijs/plugin-console": "^3.2.9",
"@koishijs/plugin-database-memory": "^1.2.0",
"@koishijs/plugin-sandbox": "^1.1.0",
"@types/jest": "^27.5.0",
"@types/node": "^17.0.31",
"@typescript-eslint/eslint-plugin": "^4.33.0",
"@typescript-eslint/parser": "^4.33.0",
"eslint": "^7.32.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-prettier": "^3.4.1",
"jest": "^28.0.3",
"koishi-plugin-pics": "^9.1.2",
"koishi-plugin-picsource-heisi": "^6.0.3",
"koishi-plugin-picsource-lolicon": "^9.0.3",
"koishi-plugin-picsource-miraikoi": "^1.0.2",
"koishi-plugin-picsource-yande": "^2.0.3",
"prettier": "^2.6.2",
"raw-loader": "^4.0.2",
"ts-jest": "^28.0.1",
"ts-loader": "^9.3.0",
"ts-node": "^10.7.0",
"typescript": "^4.6.4",
"webpack": "^5.72.0",
"webpack-cli": "^4.9.2",
"ws": "^8.6.0"
}
}
// import 'source-map-support/register';
import {
SchemaProperty,
RegisterSchema,
PutOption,
SchemaOptions,
PutSession,
} from 'koishi-thirdeye';
import { Adapter, Bot, Random, Selection, Session } from 'koishi';
import path from 'path';
import * as fs from 'fs';
import moment from 'moment';
import { sendPriv } from './utility';
const ProfileProperty = (
desc: string,
schema?: SchemaOptions,
): PropertyDecorator => {
return (target, key: string) => {
SchemaProperty({ description: desc.split(' ')[1], ...schema })(
target,
key,
);
PutOption(key, desc)(target, key);
};
};
export class EdgingProfile {
@PutSession()
session: Session;
@ProfileProperty('-b <from> 来源。')
from: string;
bot: Bot;
getBot(bots: Adapter.BotList) {
if (this.from) {
return bots.get(this.from);
} else {
return this.session.bot;
}
}
@ProfileProperty('-u <to> 目标。')
to: string;
@ProfileProperty('-d <duration> 时间,单位秒。', { default: 600 })
duration: number;
isOvertime() {
return moment().diff(this.startTime, 'seconds') > this.duration;
}
getTarget() {
if (this.to) {
return this.to;
} else {
return this.session.userId;
}
}
@ProfileProperty('-m <model> 使用模板。')
model: string;
@ProfileProperty('--encoding <encoding> 文件编码。', {
type: String,
default: 'utf8',
})
encoding: BufferEncoding;
async loadModel(root: string) {
const filename = path.join(root, `${this.model}.txt`);
const content = await fs.promises.readFile(filename, {
encoding: this.encoding,
});
this.texts = content
.split(/\r?\n/)
.map((line) => line.trim())
.filter((line) => line.length > 0);
}
texts: string[];
@SchemaProperty({ type: String, default: [''], description: '随机前缀。' })
prefixes: string[];
@SchemaProperty({ type: String, default: [''], description: '随机后缀。' })
suffixes: string[];
startTime: moment.Moment;
@ProfileProperty('-p 使用图片。')
usePics: boolean;
@ProfileProperty('-n 不使用图片。')
noUsePics: boolean;
getUsePics() {
return this.usePics && !this.noUsePics;
}
previousText = '';
attachText(text: string) {
return `${Random.pick(this.prefixes)}${text}${Random.pick(this.suffixes)}`;
}
getText() {
const texts =
this.texts.length > 1
? this.texts.filter((text) => text !== this.previousText)
: this.texts;
const text = Random.pick(texts);
this.previousText = text;
return this.attachText(text);
}
@ProfileProperty('--fail-text <tags> 败北时的消息。')
failText: string;
@ProfileProperty('--success-text <tags> 成功时的消息。')
successText: string;
@ProfileProperty('--fail-trigger-word <word> 败北检测词。')
failTriggerWord: string;
isFail(message: string) {
return this.failTriggerWord && message.startsWith(this.failTriggerWord);
}
async initialize(config: EdgingPluginConfig, bots: Adapter.BotList) {
Object.keys(config.defaultProfile).forEach((key) => {
if (!this[key] && config.defaultProfile[key]) {
this[key] = config.defaultProfile[key];
}
});
if (!this.model) {
return '没有指定模板呢。';
}
this.bot = this.getBot(bots);
if (!this.bot) {
return `没有找到陪着玩的 ${this.from} 呢。`;
}
try {
await this.loadModel(config.modelRoot);
} catch (e) {
return `模板似乎难产了: ${e.message}`;
}
this.startTime = moment();
}
send(content: string) {
const bot = this.bot;
if (
bot &&
(bot.platform === 'onebot' ||
(bot.platform === 'qqguild' && bot['parentBot']?.platform === 'onebot'))
) {
content = content.replace(/,url=base64/g, ',file=base64');
}
return sendPriv(bot, this.getTarget(), content);
}
process() {
return this.send(this.getText());
}
fail() {
if (!this.failText) {
return;
}
return this.send(this.attachText(this.failText));
}
success() {
if (!this.successText) {
return;
}
return this.send(this.attachText(this.successText));
}
describe() {
return `我在和 ${this.getTarget()} 使用模板 ${this.model} 玩耍。\n`;
}
}
@RegisterSchema()
export class EdgingProfileConfig extends EdgingProfile {}
@RegisterSchema()
export class EdgingPluginConfig {
constructor(config: EdgingPluginConfigLike) {}
@SchemaProperty({ description: '模板文件存放路径。', default: './models' })
modelRoot: string;
@SchemaProperty({ description: '图片标签。', type: String })
picTags: string[];
@SchemaProperty({ description: '图源标签。', type: String })
sourceTags: string[];
@SchemaProperty({ description: '默认配置。' })
defaultProfile: EdgingProfileConfig;
@SchemaProperty({
description: '允许进行配置的选择器。',
type: 'object',
default: {},
})
panelSelection: Selection;
@SchemaProperty({ description: '最小文本间隔。', default: 1000 })
minTextInterval: number;
@SchemaProperty({ description: '最大文本间隔。', default: 50000 })
maxTextInterval: number;
@SchemaProperty({ description: '最小图片间隔。', default: 5000 })
minPicInterval: number;
@SchemaProperty({ description: '最大图片间隔。', default: 50000 })
maxPicInterval: number;
}
export type EdgingPluginConfigLike = Partial<EdgingPluginConfig>;
// import 'source-map-support/register';
import { EdgingPluginConfig, EdgingProfile } from './config';
import {
DefinePlugin,
BasePlugin,
Provide,
Inject,
LifecycleEvents,
UseCommand,
InjectLogger,
PutObject,
PutUserId,
PutOption,
UseMiddleware,
OnPrivate,
PutBot,
} from 'koishi-thirdeye';
import { Adapter, Bot, Logger, Next, Session } from 'koishi';
import type PicsContainer from 'koishi-plugin-pics';
import { dynamicInterval } from './utility';
export * from './config';
declare module 'koishi' {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace Context {
interface Services {
edging: EdgingPlugin;
}
}
}
class UserDef {
@PutUserId()
operatorId: string;
@PutOption('userId', '-u <userId> 目标用户 ID。')
userId: string;
getUserId() {
return this.userId || this.operatorId;
}
}
@DefinePlugin()
export class EdgingPanel {
@Inject('edging')
main: Partial<EdgingPlugin>;
@UseCommand('edging', '寸止的配置。', { empty: true })
edgingCommand() {}
@UseCommand('edging.start', 'Start edging.')
start(@PutObject() profile: EdgingProfile) {
return this.main.start(profile);
}
@UseCommand('edging.stop', 'Stop edging.')
stop(@PutObject() user: UserDef) {
return this.main.stop(user.getUserId());
}
@UseCommand('edging.finish', 'Finish edging.')
finish(@PutObject() user: UserDef) {
return this.main.finish(user.getUserId());
}
@UseCommand('edging.status', 'Show edging status.')
status(@PutBot() bot: Bot) {
return this.main.status(bot);
}
}
@Provide('edging', { immediate: true })
@DefinePlugin({ name: 'edging', schema: EdgingPluginConfig })
export default class EdgingPlugin
extends BasePlugin<EdgingPluginConfig>
implements LifecycleEvents
{
onApply() {
this.ctx.select(this.config.panelSelection).plugin(EdgingPanel);
dynamicInterval(
this.ctx,
this.wrapTry(() => this.processText(), 'process text'),
this.config.minTextInterval,
this.config.maxTextInterval,
);
dynamicInterval(
this.ctx,
this.wrapTry(() => this.processPics(), 'process pic'),
this.config.minPicInterval,
this.config.maxPicInterval,
);
}
@Inject()
private bots: Adapter.BotList;
@Inject()
private pics: PicsContainer;
@InjectLogger()
private logger: Logger;
profiles = new Map<string, EdgingProfile>();
endPlay(profile: EdgingProfile) {
this.logger.info(
`Play from ${profile.bot.sid} to ${profile.getTarget()} finished.`,
);
this.profiles.delete(profile.getTarget());
}
async checkOvertime(profile: EdgingProfile) {
if (profile.isOvertime()) {
this.endPlay(profile);
await profile.success();
return true;
}
return false;
}
async runForEachProfile<T>(
fn: (profile: EdgingProfile) => T | Promise<T>,
action = 'run',
) {
const profiles = Array.from(this.profiles.values());
return Promise.all(
profiles.map((profile) => {
const wrapper = this.wrapTry(
fn,
`${action} for profile ${profile.getTarget()}`,
);
return wrapper(profile);
}),
);
}
async processText() {
this.logger.info(`Processing text...`);
return this.runForEachProfile(async (profile) => {
this.logger.info(`Processing text for profile ${profile.getTarget()}...`);
if (await this.checkOvertime(profile)) {
return;
}
return profile.process();
});
}
async processPics() {
if (!this.pics) {
return;
}
if (!Array.from(this.profiles.values()).length) {
return;
}
this.logger.info(`Processing pics...`);
const pic = await this.pics.randomPic(
this.config.picTags,
this.config.sourceTags,
);
this.logger.info(`Get pic ${pic.url}`);
if (!pic) {
this.logger.warn(`No pic found.`);
return;
}
const segment = await this.pics.getSegment(pic.url);
return this.runForEachProfile(async (profile) => {
this.logger.info(`Processing pic for profile ${profile.getTarget()}...`);
if (await this.checkOvertime(profile)) {
return;
}
return profile.send(segment);
});
}
@OnPrivate()
@UseMiddleware()
async checkFinish(session: Session, next: Next) {
const profile = this.profiles.get(session.userId);
if (!profile || session.bot !== profile.bot) {
return next();
}
if (profile.isFail(session.content)) {
await profile.fail();
this.endPlay(profile);
return;
}
return next();
}
private wrapTry<Args extends any[], T>(
fn: (...args: Args) => T | Promise<T>,
action = 'perform action',
) {
return async (...args: Args) => {
try {
return await fn(...args);
} catch (e) {
this.logger.error(`Failed to ${action}: ${e.message}`);
}
};
}
async start(profile: EdgingProfile) {
if (this.profiles.has(profile.getTarget())) {
return `${profile.getTarget()} 已经在玩耍了。`;
}
const errorMessage = await profile.initialize(this.config, this.bots);
if (errorMessage) {
return errorMessage;
}
this.profiles.set(profile.getTarget(), profile);
this.logger.info(
`Started play from ${profile.bot.sid} to ${profile.getTarget()}`,
);
return '准备好玩耍了呢。';
}
async stop(userId: string) {
const profile = this.profiles.get(userId);
if (!profile) {
return `${userId} 没有在玩耍。`;
}
this.endPlay(profile);
return '停止玩耍了呢。';
}
async finish(userId: string) {
const profile = this.profiles.get(userId);
if (!profile) {
return `${userId} 没有在玩耍。`;
}
this.endPlay(profile);
await profile.fail();
return '玩坏了呢。';
}
status(bot: Bot) {
const profiles = Array.from(this.profiles.values()).filter(
(profile) => profile.bot === bot,
);
return `${profiles.map((profile) => profile.describe())}我一共在和 ${
profiles.length
} 个人玩耍。`;
}
}
import { Bot, Context, Random } from 'koishi';
export function sendPriv(bot: Bot, userId: string, content: string) {
return bot.sendPrivateMessage
? bot.sendPrivateMessage(userId, content)
: bot.sendMessage(`@${userId}`, content);
}
export function dynamicInterval(
ctx: Context,
callback: () => void,
min: number,
max: number,
) {
return ctx.setTimeout(() => {
callback();
dynamicInterval(ctx, callback, min, max);
}, Random.int(min, max));
}
import { App } from 'koishi';
import TargetPlugin from '../src';
describe('Test of plugin.', () => {
let app: App;
beforeEach(async () => {
app = new App();
// app.plugin(TargetPlugin);
await app.start();
});
it('should pass', () => {
expect(true).toBe(true);
});
});
{
"compilerOptions": {
"outDir": "dist",
"module": "commonjs",
"target": "es2021",
"esModuleInterop": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"declaration": true,
"sourceMap": true,
"skipLibCheck": true
},
"compileOnSave": true,
"allowJs": true,
"include": [
"*.ts",
"src/**/*.ts",
"tests/**/*.ts",
"dev/**/*.ts"
]
}
const path = require('path');
const packgeInfo = require('./package.json');
function externalsFromDep() {
return Object.fromEntries(
[
...Object.keys(packgeInfo.dependencies || {}),
...Object.keys(packgeInfo.peerDependencies || {}),
]
.filter((dep) => dep !== 'source-map-support')
.map((dep) => [dep, dep]),
);
}
const packAll = !!process.env.PACK_ALL;
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, packAll ? 'dist/full' : 'dist'),
},
externals: {
koishi: 'koishi',
...(packAll ? {} : externalsFromDep()),
},
};
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