Commit 82efc477 authored by nanahira's avatar nanahira

first

parent e6c60dc3
Pipeline #10819 failed with stages
in 2 minutes and 42 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',
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/myplugin
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-adapter-wecom
Koishi 企业微信适配器
\ No newline at end of file
Koishi 企业微信适配器。
## 安装
### npm
```bash
npm install koishi-plugin-adapter-wecom
```
## 配置
在企业微信后台中 [应用管理](https://work.weixin.qq.com/wework_admin/frame#apps) 中创建企业自建应用,并配置 API 接收消息,填入配置中即可。
```ts
{
bots: [
{
corpId: 'corpId', // 企业 ID,在企业信息 https://work.weixin.qq.com/wework_admin/frame#profile 中查看
agentId: 'agentId', // 应用 ID,在应用管理中查看
secret: 'secret', // 应用密钥,在应用管理中查看
},
],
path: '/wecom', // 回调 API 路径
token: 'token', // 回调 API token,在应用消息接收设置中设置并填入
encodingAESKey: 'encodingAESKey', // 加密密钥,在应用消息接收设置中设置并填入
}
```
import { Context } from 'koishi';
export default class ExtrasInDev {
constructor(ctx: Context) {}
}
import { App, segment } from 'koishi';
import ExtrasInDev from './extras';
import { adapterPlugin } from '../src';
import * as fs from 'fs';
const app = new App({
port: 3000,
host: '0.0.0.0',
prefix: '.',
});
// Some extras
app.plugin(ExtrasInDev);
// Target plugin
app.plugin(adapterPlugin, {
bots: [
{
corpId: 'corpId', // 企业 ID,在企业信息 https://work.weixin.qq.com/wework_admin/frame#profile 中查看
agentId: 'agentId', // 应用 ID,在应用管理中查看
secret: 'secret', // 应用密钥,在应用管理中查看
},
],
path: '/wecom', // 回调 API 路径
token: 'token', // 回调 API token,在应用消息接收设置中设置并填入
encodingAESKey: 'encodingAESKey', // 加密密钥,在应用消息接收设置中设置并填入
});
app.on('wecom/event', (session) => {
console.log(`Got event ${JSON.stringify(session.wecom)}`);
});
app.on('message', (session) => {
console.log(`Got message ${session.content}`);
});
app
.command('test1')
.action(async () =>
segment.image(await fs.promises.readFile(__dirname + '/10000.jpg')),
);
app
.command('test2')
.action(async () =>
segment.image(
'https://cdn02.moecube.com:444/images/ygopro-images-zh-CN/10000.jpg',
),
);
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-adapter-wecom",
"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-myplugin.git"
},
"author": "Nanahira <nanahira@momobako.com>",
"license": "MIT",
"keywords": [
"Koishi.js",
"qqbot",
"cqhttp",
"onebot",
"impl:adapter"
],
"bugs": {
"url": "https://code.mycard.moe/3rdeye/koishi-plugin-myplugin/issues"
},
"homepage": "https://code.mycard.moe/3rdeye/koishi-plugin-myplugin",
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "tests",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
},
"peerDependencies": {
"koishi": "^4.4.1"
},
"devDependencies": {
"@types/jest": "^27.4.1",
"@types/node": "^17.0.21",
"@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.0",
"raw-loader": "^4.0.2",
"ts-jest": "^27.1.3",
"ts-loader": "^9.2.8",
"ts-node": "^10.7.0",
"typescript": "^4.6.2",
"webpack": "^5.70.0",
"webpack-cli": "^4.9.2",
"ws": "^8.5.0"
},
"dependencies": {
"@wecom/crypto": "^1.0.1",
"fast-xml-parser": "^4.0.6",
"file-type": "^16.5.3",
"form-data": "^4.0.0",
"moment": "^2.29.1",
"raw-body": "^2.5.1"
}
}
This diff is collapsed.
export interface WeComAgentInfo {
errcode: number;
errmsg: string;
agentlist: Agentlist[];
}
interface Agentlist {
agentid: number;
name: string;
square_logo_url: string;
}
export interface WeComUser {
errcode: number;
errmsg: string;
userid: string;
name: string;
department: number[];
order: number[];
position: string;
mobile: string;
gender: string;
email: string;
biz_mail: string;
is_leader_in_dept: number[];
direct_leader: string[];
avatar: string;
thumb_avatar: string;
telephone: string;
alias: string;
address: string;
open_userid: string;
main_department: number;
extattr: Extattr;
status: number;
qr_code: string;
external_position: string;
external_profile: Externalprofile;
}
interface Externalprofile {
external_corp_name: string;
wechat_channels: Wechatchannels;
external_attr: Externalattr[];
}
interface Externalattr {
type: number;
name: string;
text?: Text;
web?: Web;
miniprogram?: Miniprogram;
}
interface Miniprogram {
appid: string;
pagepath: string;
title: string;
}
interface Wechatchannels {
nickname: string;
status: number;
}
interface Extattr {
attrs: Attr[];
}
interface Attr {
type: number;
name: string;
text?: Text;
web?: Web;
}
interface Web {
url: string;
title: string;
}
interface Text {
value: string;
}
export interface WecomApiResponse {
errcode: number;
errmsg: string;
}
export interface WecomReceiveMessageDto {
msg_signature: string;
timestamp: number;
nonce: number;
}
export interface WecomRegisterDto extends WecomReceiveMessageDto {
echostr: string;
}
export interface WecomDecodedMessage {
message: string;
id: string;
random: Buffer;
}
export type WecomEventResponse = WecomResponse<WecomEventBody>;
export interface WecomResponse<T> {
ToUserName: string;
AgentID: number;
Encrypt: string;
data?: WecomDecodedMessage;
body?: T;
}
export interface WecomEventBody {
ToUserName: string;
FromUserName: string;
CreateTime: number;
MsgType: string;
Event?: string;
AgentID: number;
MsgId?: number;
}
export interface WecomChatBody extends WecomEventBody {
Content: string;
}
export interface WecomMediaBody extends WecomEventBody {
MediaId: number;
}
export interface WecomPicBody extends WecomMediaBody {
PicUrl: string;
}
export interface WecomOnEventBody extends WecomEventBody {
EventKey: string;
}
export interface CardEventSelectedItems {
SelectedItem: CardEventSelectedItem | CardEventSelectedItem[];
}
export interface CardEventSelectedItem {
QuestionKey: string;
OptionIds: CardEventOptionIds;
}
export interface CardEventOptionIds {
OptionId: string | string[];
}
export interface WecomCardEventBody extends WecomOnEventBody {
TaskId: string;
CardType: string;
SelectedItems?: CardEventSelectedItems;
}
export interface WecomLocationBody extends WecomOnEventBody {
Latitude: number;
Longitude: number;
Precision: number;
}
export interface TokenReturnMessage extends WecomApiResponse {
access_token: string;
expires_in: number;
}
export interface OutMessage {
msgtype: string;
agentid: string;
touser?: string;
toparty?: string;
totag?: string;
}
export interface CommonOutMessage extends OutMessage {
msgtype: 'markdown';
markdown: { content: string };
}
export interface TextOutMessage extends OutMessage {
msgtype: 'text';
text: { content: string };
}
export interface MediaIdObject {
media_id: string;
}
export interface ImageOutMessage extends OutMessage {
msgtype: 'image';
image: MediaIdObject;
}
export interface VideoOutMessage extends OutMessage {
msgtype: 'video';
video: MediaIdObject;
}
export interface WecomSendMessageResponse extends WecomApiResponse {
invaliduser: string;
invalidparty: string;
invalidtag: string;
msgid: string;
response_code: string;
}
export interface WecomMediaUploadResponse extends WecomApiResponse {
type: string;
media_id: string;
created_at: string;
}
export * from './def';
export * from './WeComUser';
export * from './WeComAgentInfo';
import { Adapter, Logger } from 'koishi';
import { AdapterConfig, dispatchSession } from './utils';
import { BotConfig, WeComBot } from './bot';
import { decrypt, getSignature } from '@wecom/crypto';
import {
WecomEventResponse,
WecomReceiveMessageDto,
WecomRegisterDto,
WecomResponse,
} from './def';
import rawBody from 'raw-body';
import { XMLParser } from 'fast-xml-parser';
const logger = new Logger('wecom');
export default class HttpServer extends Adapter<BotConfig, AdapterConfig> {
private xmlParser = new XMLParser();
static schema = BotConfig;
stop() {
logger.debug('http server closing');
}
private checkSignature(dto: WecomReceiveMessageDto, body: string) {
const { msg_signature, timestamp, nonce } = dto;
const signature = getSignature(this.config.token, timestamp, nonce, body);
return {
valid: signature === msg_signature,
signature,
msg_signature,
};
}
public bots: WeComBot[];
async connect(bot: WeComBot) {
return bot.initialize();
}
async start() {
const { path } = this.config;
this.ctx.router.get(path, async (ctx) => {
const query = ctx.request.query as unknown as WecomRegisterDto;
const { echostr } = query;
const signatureResult = this.checkSignature(query, echostr);
if (!signatureResult.valid) {
logger.warn(
`Invalid signature: ${signatureResult.msg_signature} vs ${signatureResult.signature}`,
);
ctx.status = 403;
ctx.body = 'invalid signature';
return;
}
const decrypted = decrypt(this.config.encodingAESKey, echostr);
const message = decrypted?.message;
if (!message) {
logger.warn('Invalid message: %s', decrypted);
ctx.status = 400;
ctx.body = 'invalid message';
return;
}
logger.success(`Registered: ${message}`);
ctx.body = message;
});
this.ctx.router.post(path, async (ctx) => {
const query = ctx.request.query as unknown as WecomReceiveMessageDto;
const rawData = (await rawBody(ctx.req)).toString('utf8').trim();
const { xml: parsedData } = (await this.xmlParser.parse(rawData)) as {
xml: WecomResponse<any>;
};
if (!parsedData?.Encrypt) {
logger.warn('Invalid xml: %s', rawData);
ctx.status = 400;
ctx.body = 'invalid message';
return;
}
const signatureResult = this.checkSignature(query, parsedData.Encrypt);
if (!signatureResult.valid) {
logger.warn(
`Invalid signature: ${signatureResult.msg_signature} vs ${signatureResult.signature}`,
);
ctx.status = 403;
ctx.body = 'invalid signature';
return;
}
const bot = this.bots.find(
(bot) =>
bot.config.agentId === parsedData.AgentID?.toString() &&
bot.config.corpId === parsedData.ToUserName,
);
if (!bot) {
ctx.status = 404;
ctx.body = 'Bot not found.';
return;
}
parsedData.data = decrypt(this.config.encodingAESKey, parsedData.Encrypt);
if (!parsedData.data) {
logger.warn('Invalid decrypted message: %s', parsedData.Encrypt);
ctx.status = 400;
ctx.body = 'invalid message';
return;
}
parsedData.body = this.xmlParser.parse(parsedData.data.message)
.xml as WecomEventResponse;
if (!parsedData.body) {
logger.warn(
'Invalid decrypted xml message: %s',
parsedData.data.message,
);
}
dispatchSession(bot, parsedData);
ctx.body = 'success';
ctx.status = 200;
});
}
}
// import 'source-map-support/register';
import { WecomEventResponse } from './def';
import { Adapter, Session } from 'koishi';
import HttpServer from './http';
import { BotConfig, WeComBot } from './bot';
import { AdapterConfig } from './utils';
declare module 'koishi' {
interface Session {
wecom?: WecomEventResponse;
}
interface EventMap {
'wecom/event'(session: Session): void;
}
}
export * from './def';
export * from './bot';
export * from './http';
export const adapterPlugin = Adapter.define<BotConfig, AdapterConfig>(
'wecom',
WeComBot,
HttpServer,
);
export default adapterPlugin;
import { Bot, Schema, segment, Session } from 'koishi';
import { WeComBot } from './bot';
import {
WecomChatBody,
WecomEventResponse,
WecomPicBody,
WecomResponse,
WeComUser,
} from './def';
export interface AdapterConfig {
path?: string;
token?: string;
encodingAESKey?: string;
}
export const AdapterConfig: Schema<AdapterConfig> = Schema.object({
path: Schema.string().description('企业微信回调路径。').default('/wecom'),
token: Schema.string()
.role('secret')
.required()
.description('应用消息上报 token。'),
encodingAESKey: Schema.string()
.role('secret')
.required()
.description('应用消息上播 AES 密钥。'),
});
export function adaptUser(user: WeComUser): Bot.User {
return {
userId: user.userid,
username: user.name,
nickname: user.name,
avatar: user.avatar,
};
}
export function adaptSession(bot: WeComBot, input: WecomEventResponse) {
const { body } = input;
if (!body) {
return;
}
const session: Partial<Session> = {
selfId: bot.selfId,
messageId: body.MsgId?.toString(),
wecom: input,
userId: body.FromUserName,
channelId: body.FromUserName,
timestamp: body.CreateTime,
};
if (body.MsgType === 'event') {
session.type = 'wecom/event';
session.subtype = body.Event;
} else {
session.type = 'message';
session.subtype = 'private';
session.author = {
userId: session.userId,
};
switch (body.MsgType) {
case 'text':
const textBody = body as WecomChatBody;
session.content = textBody.Content;
break;
case 'image':
const imageBody = body as WecomPicBody;
session.content = segment('image', {
url: imageBody.PicUrl,
});
break;
default:
return;
}
}
return session;
}
export function dispatchSession(bot: WeComBot, message: WecomResponse<any>) {
const payload = adaptSession(bot, message);
if (!payload) return;
const session = new Session(bot, payload);
session.wecom = message;
bot.adapter.dispatch(session);
}
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