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-plugin-adapter-wecom
Koishi 企业微信适配器 Koishi 企业微信适配器。
\ No newline at end of file
## 安装
### 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 source diff could not be displayed because it is too large. You can view the blob instead.
{
"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"
}
}
import { Adapter, Bot, Dict, omit, Quester, Schema, segment } from 'koishi';
import moment, { Moment } from 'moment';
import {
CommonOutMessage,
ImageOutMessage,
OutMessage,
TextOutMessage,
TokenReturnMessage,
VideoOutMessage,
WecomMediaUploadResponse,
WecomSendMessageResponse,
WeComUser,
WeComAgentInfo,
} from './def';
import { AdapterConfig, adaptUser } from './utils';
import FormData from 'form-data';
import * as fs from 'fs';
import path from 'path';
import FileType from 'file-type';
export interface BotConfig extends Bot.BaseConfig, Quester.Config {
corpId?: string;
agentId?: string;
secret?: string;
}
export const BotConfig: Schema<BotConfig> = Schema.object({
corpId: Schema.string().required().description('企业 ID。'),
agentId: Schema.string().required().description('企业应用 ID。'),
secret: Schema.string()
.role('secret')
.required()
.description('企业应用密钥。'),
...omit(Quester.Config.dict, ['endpoint']),
});
export class WeComBot extends Bot<BotConfig> {
static schema = AdapterConfig;
private http: Quester;
private accessToken: string;
private accessTokenUntil: Moment;
constructor(adapter: Adapter, config: BotConfig) {
super(adapter, config);
this.http = adapter.ctx.http.extend(config as Quester.Config);
this.selfId = config.agentId;
}
async initialize() {
try {
const self = await this.getSelf();
if (!self) {
this.reject(new Error('Invalid credentials.'));
return;
}
Object.assign(this, self);
this.resolve();
} catch (e) {
this.reject(e);
}
}
private async fetchNewToken(): Promise<string> {
try {
const data = await this.http.get<TokenReturnMessage>(
'https://qyapi.weixin.qq.com/cgi-bin/gettoken',
{
params: {
corpid: this.config.corpId,
corpsecret: this.config.secret,
},
},
);
if (data.errcode) {
this.logger.error(
`Failed to fetch secret with code ${data.errcode}: ${data.errmsg}`,
);
return;
}
this.accessToken = data.access_token;
this.accessTokenUntil = moment().add(data.expires_in, 'seconds');
return data.access_token;
} catch (e) {
this.logger.error(`Failed to fetch secret: ${e.toString()}`);
return;
}
}
async getToken() {
if (this.accessToken && moment().isBefore(this.accessTokenUntil)) {
return this.accessToken;
}
return this.fetchNewToken();
}
async getSelf(): Promise<Bot.User> {
const token = await this.getToken();
if (!token) {
return;
}
const data = await this.http.get<WeComAgentInfo>(
'https://qyapi.weixin.qq.com/cgi-bin/agent/list',
{
params: {
access_token: await this.getToken(),
},
},
);
if (data.errcode) {
this.logger.error(`Failed to get self: ${data.errmsg}`);
return;
}
const agent = data.agentlist.find(
(a) => a.agentid.toString() === this.selfId,
);
const self: Bot.User = {
userId: agent.agentid.toString(),
username: agent.name,
avatar: agent.square_logo_url,
};
return self;
}
async getUser(userId: string) {
const data = await this.http.get<WeComUser>(
'https://qyapi.weixin.qq.com/cgi-bin/user/get',
{
params: {
access_token: await this.getToken(),
userid: userId,
},
},
);
if (data.errcode) {
this.logger.error(`Failed to get user ${userId}: ${data.errmsg}`);
return;
}
return adaptUser(data);
}
async getFriendList() {
return [];
}
async deleteFriend(userId: string) {}
// guild
async getGuild(guildId: string) {
return undefined;
}
async getGuildList() {
return [];
}
// guild member
async getGuildMember(guildId: string, userId: string) {
return undefined;
}
async getGuildMemberList(guildId: string) {
return [];
}
// channel
async getChannel(channelId: string, guildId?: string) {
return undefined;
}
async getChannelList(guildId: string) {
return [];
}
// request
async handleFriendRequest(
messageId: string,
approve: boolean,
comment?: string,
) {}
async handleGuildRequest(
messageId: string,
approve: boolean,
comment?: string,
) {}
async handleGuildMemberRequest(
messageId: string,
approve: boolean,
comment?: string,
) {}
async sendGenericMessage(messageInfo: OutMessage): Promise<string> {
const token = await this.getToken();
if (!token) {
this.logger.error(`Missing token.`);
return undefined;
}
try {
const data = await this.http.post<WecomSendMessageResponse>(
'https://qyapi.weixin.qq.com/cgi-bin/message/send',
messageInfo,
{ params: { access_token: token } },
);
if (data.errcode) {
this.logger.error(
`Failed to send message ${JSON.stringify(messageInfo)}: ${
data.errmsg
}`,
);
}
if (data.invaliduser) {
this.logger.error(`Invalid users: ${data.invaliduser}`);
}
if (data.invalidparty) {
this.logger.error(`Invalid parties: ${data.invalidparty}`);
}
if (data.invalidtag) {
this.logger.error(`Invalid tags: ${data.invalidtag}`);
}
return data.msgid;
} catch (e) {
this.logger.error(
`Failed to send message ${JSON.stringify(
messageInfo,
)}: ${e.toString()}`,
);
}
return undefined;
}
async uploadMedia(
content: Buffer,
type = 'image',
fileName?: string,
): Promise<string> {
const token = await this.getToken();
if (!token) {
this.logger.error(`Missing token.`);
return undefined;
}
const form = new FormData();
form.append('media', content, fileName);
try {
const data = await this.http.post<WecomMediaUploadResponse>(
'https://qyapi.weixin.qq.com/cgi-bin/media/upload',
form,
{ params: { access_token: token, type }, headers: form.getHeaders() },
);
if (data.errcode) {
this.logger.error(`Failed to upload media ${fileName}: ${data.errmsg}`);
}
return data.media_id;
} catch (e) {
this.logger.error(`Failed to upload media ${fileName}: ${e.toString()}`);
}
}
async sendMarkdownMessage(
message: string,
targetUsers: string[],
extras: any = {},
) {
const messageInfo: CommonOutMessage = {
agentid: this.selfId,
msgtype: 'markdown',
markdown: { content: message },
touser: targetUsers.join('|'),
...extras,
};
return this.sendGenericMessage(messageInfo);
}
async sendTextMessage(
message: string,
targetUsers: string[],
extras: any = {},
) {
const messageInfo: TextOutMessage = {
agentid: this.selfId,
msgtype: 'text',
text: { content: message },
touser: targetUsers.join('|'),
...extras,
};
return this.sendGenericMessage(messageInfo);
}
async sendMediaMessage(
type: 'image' | 'video',
fileName: string,
message: Buffer,
targetUsers: string[],
extras: any = {},
) {
const mediaId = await this.uploadMedia(message, type, fileName);
if (!mediaId) {
return;
}
const messageInfo: ImageOutMessage | VideoOutMessage = {
agentid: this.selfId,
msgtype: type,
[type]: { media_id: mediaId },
touser: targetUsers.join('|'),
...extras,
};
return this.sendGenericMessage(messageInfo);
}
async prepareBufferAndFilename(type: string, data: Dict<string>) {
const { url } = data;
if (!url) {
return;
}
let buffer: Buffer;
if (url.startsWith('file://')) {
buffer = await fs.promises.readFile(url.slice(7));
} else if (url.startsWith('base64://')) {
buffer = Buffer.from(data.url.slice(9), 'base64');
} else {
buffer = await this.http.get(url, {
responseType: 'arraybuffer',
headers: { accept: type + '/*' },
});
}
let filename = data.file;
if (!filename) {
if (!url.startsWith('base64://')) {
filename = path.basename(url);
} else {
const fileType = await FileType.fromBuffer(buffer);
if (fileType) {
filename = `media.${fileType.ext}`;
} else {
filename = 'media.bin';
}
}
}
return { buffer, filename };
}
async sendMessage(channelId: string, content: string, guildId?: string) {
return this.sendPrivateMessage(channelId, content);
}
async sendPrivateMessage(userId, content) {
const session = await this.session({
content,
subtype: 'private',
userId,
channelId: userId,
});
if (!session?.content) return [];
const chain = segment.parse(session.content);
const messageIds: string[] = [];
let isMarkdown = false;
for (const code of chain) {
const { type, data } = code;
try {
switch (type) {
case 'markdown':
isMarkdown = true;
break;
case 'text':
const content = data.content.trim();
messageIds.push(
isMarkdown
? await this.sendMarkdownMessage(content, [userId])
: await this.sendTextMessage(content, [userId]),
);
break;
case 'image':
case 'video':
if (!data.url) {
break;
}
const { buffer, filename } = await this.prepareBufferAndFilename(
type,
data,
);
const mediaId = await this.uploadMedia(buffer, type, filename);
if (!mediaId) {
break;
}
messageIds.push(
await this.sendMediaMessage(type, filename, buffer, [userId]),
);
break;
default:
break;
}
} catch (e) {
this.logger.error(
`Failed to send part ${type} ${data}: ${e.toString()}`,
);
}
}
return messageIds;
}
async deleteMessage(channelId: string, messageId: string) {
const token = await this.getToken();
if (!token) {
this.logger.error(`Missing token.`);
return;
}
try {
const data = await this.http.post<WecomSendMessageResponse>(
'https://qyapi.weixin.qq.com/cgi-bin/message/recall',
{ msgid: messageId },
{ params: { access_token: token } },
);
if (data.errcode) {
this.logger.error(
`Failed to delete message ${messageId}: ${data.errmsg}`,
);
}
} catch (e) {
this.logger.error(
`Errored to delete message ${messageId}: ${e.toString()}`,
);
}
}
}
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