Commit 6e606d10 authored by nanahira's avatar nanahira

first

parent 77e9e4a6
Pipeline #19406 passed with stages
in 1 minute and 16 seconds
# 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',
tsconfigRootDir : __dirname,
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
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/apisend
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 && curl -X PUT "https://registry-direct.npmmirror.com/$(cat package.json | jq '.name' | sed 's/\"//g')/sync?sync_upstream=true" || true
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 Apisend # koishi-plugin-apisend
API 推送消息插件。 API 推送消息插件。
\ No newline at end of file
## 安装
### npm
```bash
npm install koishi-plugin-apisend
```
### 直接安装
在 https://cdn02.moecube.com:444/nanahira/koishi-plugin/apisend/index.js 下载即可。
## 配置
部分配置见 [koishi-target-def](https://www.npmjs.com/package/koishi-target-def) 的定义。
```yaml
# koishi.yaml
plugins:
apisend:foo:
path: '/send'
token: koishi # 如果有的话,Authorization: Bearer <token>
targets: # 见 koishi-target-def
- bot: 'onebot:1111111111'
users:
- '2222222222'
```
## 使用
POST `/send` 或自己指定的路径。
### 参数
- `content`: `string` 消息内容。
### 返回
- `messageIds`: `string[]` 消息 ID。
- `error`: `string` 错误信息。
import { Context } from 'koishi';
export default class ExtrasInDev {
constructor(ctx: Context) {}
}
import { App } from 'koishi';
import TargetPlugin from '../src';
import ConsolePlugin from '@koishijs/plugin-console';
import * as SandboxPlugin from '@koishijs/plugin-sandbox';
import DatabasePlugin from '@koishijs/plugin-database-memory';
import * as Help from '@koishijs/plugin-help';
import ExtrasInDev from './extras';
const app = new App({
port: 14514,
host: 'localhost',
prefix: '.',
});
app.plugin(Help);
// Console and sandbox
app.plugin(SandboxPlugin);
app.plugin(ConsolePlugin, {
open: false,
});
// Some services
app.plugin(DatabasePlugin);
// Some extras
app.plugin(ExtrasInDev);
// Target plugin
app.plugin(TargetPlugin, {
path: '/send',
token: 'koishi',
targets: [{ bot: 'sandbox:koishi', users: ['Alice', 'Bob'] }],
});
app.start();
#!/bin/bash
npm install --save \
koishi-thirdeye
npm install --save-peer \
koishi
npm i --save-exact --save-dev eslint@8.22.0
npm install --save-dev \
@types/node \
typescript \
'@typescript-eslint/eslint-plugin@^5.0.0' \
'@typescript-eslint/parser@^5.0.0 '\
'eslint-config-prettier@^8.3.0' \
'eslint-plugin-prettier@^4.0.0' \
prettier \
raw-loader \
ts-loader \
webpack \
webpack-cli \
ws \
ts-node \
@koishijs/plugin-help \
@koishijs/plugin-console \
@koishijs/plugin-sandbox \
@koishijs/plugin-database-memory \
jest \
ts-jest \
@types/jest
This diff is collapsed.
{
"name": "koishi-plugin-apisend",
"description": "API 推送消息插件。",
"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-apisend.git"
},
"author": "Nanahira <nanahira@momobako.com>",
"license": "MIT",
"keywords": [
"Koishi.js",
"qqbot",
"cqhttp",
"onebot"
],
"bugs": {
"url": "https://code.mycard.moe/3rdeye/koishi-plugin-apisend/issues"
},
"homepage": "https://code.mycard.moe/3rdeye/koishi-plugin-apisend",
"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": "^2.1.2",
"koishi-thirdeye": "^11.1.21"
},
"peerDependencies": {
"koishi": "^4.11.1"
},
"devDependencies": {
"@koishijs/plugin-console": "^5.1.2",
"@koishijs/plugin-database-memory": "^2.2.2",
"@koishijs/plugin-help": "^2.0.2",
"@koishijs/plugin-sandbox": "^2.5.2",
"@types/jest": "^29.2.5",
"@types/node": "^18.11.18",
"@typescript-eslint/eslint-plugin": "^5.48.1",
"@typescript-eslint/parser": "^5.48.1",
"eslint": "8.22.0",
"eslint-config-prettier": "^8.6.0",
"eslint-plugin-prettier": "^4.2.1",
"jest": "^29.3.1",
"prettier": "^2.8.2",
"raw-loader": "^4.0.2",
"ts-jest": "^29.0.3",
"ts-loader": "^9.4.2",
"ts-node": "^10.9.1",
"typescript": "^4.9.4",
"webpack": "^5.75.0",
"webpack-cli": "^5.0.1",
"ws": "^8.12.0"
}
}
import { SendTarget } from 'koishi-target-def';
import { SchemaProperty, RegisterSchema } from 'koishi-thirdeye';
@RegisterSchema()
export class ApiSendPluginConfig {
constructor(config: ApiSendPluginConfigLike) {}
@SchemaProperty({ description: '接口路径。', required: true })
path: string;
@SchemaProperty({ description: '接口 Token。', role: 'secret' })
token: string;
@SchemaProperty({ description: '发送目标。', type: SendTarget })
targets: SendTarget[];
}
export type ApiSendPluginConfigLike = Partial<ApiSendPluginConfig>;
import { ApiSendPluginConfig } from './config';
import {
DefinePlugin,
Inject,
InjectLogger,
KoaContext,
Post,
Reusable,
StarterPlugin,
} from 'koishi-thirdeye';
import { Bot, Logger } from 'koishi';
export * from './config';
@Reusable()
@DefinePlugin({ name: 'apisend' })
export default class ApiSendPlugin extends StarterPlugin(ApiSendPluginConfig) {
@Inject(true)
private bots: Bot[];
@InjectLogger()
private logger: Logger;
@Post('{{path}}')
private async send(ctx: KoaContext) {
if (this.config.token) {
let authorization = ctx.request.headers.authorization;
if (authorization.startsWith('Bearer ')) {
authorization = authorization.slice(7);
}
if (authorization !== this.config.token) {
ctx.status = 403;
ctx.body = { error: 'Invalid token' };
return;
}
}
const { content } = ctx.request.body;
if (!content) {
ctx.status = 400;
ctx.body = { error: 'Empty content' };
return;
}
try {
const messageIds = await Promise.all(
this.config.targets.map((t) => t.send(this.bots, content)),
);
ctx.body = { messageIds: messageIds.flat(1) };
ctx.status = 200;
} catch (e) {
const error = `Error: ${e.message}`;
this.logger.error(error);
ctx.status = 500;
ctx.body = { error };
}
}
}
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,
"jsx": "react-jsx",
"jsxImportSource": "@satorijs/element"
},
"compileOnSave": true,
"allowJs": true,
"include": [
"*.ts",
"src/**/*.ts",
"tests/**/*.ts",
"dev/**/*.ts",
"*.tsx",
"src/**/*.tsx",
"tests/**/*.tsx",
"dev/**/*.tsx"
]
}
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.tsx',
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',
'@satorijs/element': '@satorijs/element',
'@satorijs/element/jsx-runtime': '@satorijs/element',
...(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