Commit 28dea3fe authored by nanahira's avatar nanahira

first

parent 9a02aaac
# 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
\ No newline at end of file
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
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-schedule-send
Koishi plugin template of sending things
\ No newline at end of file
编写自动发送消息的 Koishi 插件框架。
## 编写插件
```ts
export class Config {
@SchemaProperty()
message: string;
}
// 在这里不用写任何东西
@DefinePlugin()
export default class TestSendPlugin extends SchedulePlugin(Config) {
async send() {
return this.config.message;
}
}
```
### 配置
配置会自动从插件工厂函数中混入。
```ts
export class SchedulePluginConfig {
@SchemaProperty({ description: 'cron 时间' })
cron: string;
@SchemaProperty({ description: '执行的间隔 ms', step: 1 })
interval: number;
@SchemaProperty({
default: false,
description: '插件启动时是否立即运行一遍。',
})
immediate: boolean;
@SchemaProperty({
type: SendTarget,
description: '图片发送目标。',
})
targets: SendTarget[];
initializeTasks(ctx: Context, callback: () => void) {
if (this.immediate) {
callback();
}
if (this.cron) {
const job = scheduleJob(this.cron, callback);
ctx.on('dispose', () => {
job.cancel()
});
}
if (this.interval) {
ctx.setInterval(callback, this.interval);
}
}
}
```
import { Context } from 'koishi';
import { DefinePlugin, SchemaProperty } from 'koishi-thirdeye';
import { SchedulePlugin } from '../src';
class Config {
@SchemaProperty()
message: string;
}
@DefinePlugin()
class TestSendPlugin extends SchedulePlugin(Config) {
async send() {
return this.config.message;
}
}
export default class ExtrasInDev {
constructor(ctx: Context) {
ctx.plugin(TestSendPlugin, {
message: 'dress',
interval: 5000,
immediate: true,
targets: [
{
bot: 'sandbox:koishi',
users: ['Alice', 'Bob'],
channels: [{ channelId: '#' }],
},
],
});
}
}
import { App } from 'koishi';
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, {});
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-schedule-send",
"description": "s",
"version": "1.0.0",
"main": "dist/index.js",
"types": "dist/src/index.d.ts",
"scripts": {
"lint": "eslint --fix .",
"build": "webpack",
"start": "ts-node ./dev",
"test": "jest --passWithNoTests"
},
"repository": {
"type": "git",
"url": "https://code.mycard.moe/3rdeye/koishi-schedule-send.git"
},
"author": "Nanahira <nanahira@momobako.com>",
"license": "MIT",
"keywords": [
"Koishi.js",
"qqbot",
"cqhttp",
"onebot"
],
"bugs": {
"url": "https://code.mycard.moe/3rdeye/koishi-schedule-send/issues"
},
"homepage": "https://code.mycard.moe/3rdeye/koishi-schedule-send",
"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-target-def": "^1.0.5",
"koishi-thirdeye": "^10.0.12",
"node-schedule": "^2.1.0"
},
"peerDependencies": {
"koishi": "^4.6.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",
"@types/node-schedule": "^1.3.2",
"@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": "^27.5.1",
"prettier": "^2.6.2",
"raw-loader": "^4.0.2",
"ts-jest": "^27.1.4",
"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 { Context } from 'koishi';
import { SendTarget } from 'koishi-target-def';
import { SchemaProperty } from 'koishi-thirdeye';
import { scheduleJob } from 'node-schedule';
export class SchedulePluginConfig {
@SchemaProperty({ description: 'cron 时间' })
cron: string;
@SchemaProperty({ description: '执行的间隔 ms', step: 1 })
interval: number;
@SchemaProperty({
default: false,
description: '插件启动时是否立即运行一遍。',
})
immediate: boolean;
@SchemaProperty({
type: SendTarget,
description: '图片发送目标。',
})
targets: SendTarget[];
initializeTasks(ctx: Context, callback: () => void) {
if (this.immediate) {
callback();
}
if (this.cron) {
const job = scheduleJob(this.cron, callback);
ctx.on('dispose', () => {
job.cancel()
});
}
if (this.interval) {
ctx.setInterval(callback, this.interval);
}
}
}
// import 'source-map-support/register';
import { SchedulePluginConfig } from './config';
import {
BasePlugin,
ClassType,
Inject,
InjectLogger,
Mixin,
PluginSchema,
} from 'koishi-thirdeye';
import { Logger } from 'koishi';
import { Adapter } from 'koishi';
import { Bot } from 'koishi';
export * from './config';
export class BaseSchedulePlugin<C> extends BasePlugin<
SchedulePluginConfig & C
> {
@InjectLogger()
logger: Logger;
@Inject(true)
bots: Adapter.BotList;
async send() {
return '';
}
isOneBotBot(bot?: Bot) {
return (
bot &&
(bot.platform === 'onebot' || bot['parentBot']?.platform === 'onebot')
);
}
async processSend() {
let message: string;
this.logger.info(`Running schedule task...`);
try {
message = await this.send();
} catch (e) {
this.logger.error(`Errored when running schedule task: ${e.message}`);
return;
}
if (!message) {
this.logger.warn(`Skipped schedule task for empty content.`);
return;
}
await Promise.all(
this.config.targets.map(async (target) => {
try {
let targetMessage = message;
const bot = this.bots.get(target.bot);
if (this.isOneBotBot(bot)) {
targetMessage = message.replace(/,url=base64/g, ',file=base64');
}
this.logger.debug(`Sending message from ${target.bot}.`);
const ids = await target.send(this.bots, targetMessage);
this.logger.debug(
`Message sent from ${target.bot}: ${ids?.join(',')}`,
);
} catch (e) {
this.logger.error(
`Failed to send message from ${target.bot}: ${e.toString()}`,
);
}
}),
);
}
async onConnect() {
this.config.initializeTasks(this.ctx, () => this.processSend());
}
}
export function SchedulePlugin<C>(config?: ClassType<C>) {
const plugin = class SpecificSchedulePlugin extends BaseSchedulePlugin<C> {};
PluginSchema(Mixin(config, SchedulePluginConfig))(plugin);
return plugin;
}
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