Commit 2a8304ab authored by nanahira's avatar nanahira

first

parent 0ed80f27
Pipeline #19181 passed with stages
in 1 minute and 22 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/adapter-wechat-official
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 Adapter Wechat Official
# koishi-plugin-adapter-wechat-official
Koishi 微信公众号适配器。
\ No newline at end of file
Koishi 微信公众号适配器。
由于微信的限制,该适配器无法主动推送消息,只能被动回复消息,请注意。
## 安装
### npm
```bash
npm install koishi-plugin-adapter-wechat-official
```
### 直接安装
在 https://cdn02.moecube.com:444/nanahira/koishi-plugin/adapter-wechat-official/index.js 下载即可。
## 配置
```yaml
plugins:
adapter-wechat-official:
path: /wechat # 回调路径。若有多个则每个都需要不同。
appId: appId # 公众号 AppID
appSecret: appSecret # 公众号 AppSecret
token: token # 公众号 Token
encodingAESKey: encodingAESKey # 公众号 EncodingAESKey,如果有的话
menus:
- type: click # 一级菜单
name: 帮助
command: help # 点击后等同于该指令
- type: parent
name: 查询
children:
- type: click # 二级菜单
name: 今日运势
command: fortune
- type: click
name: 今日人品
command: jrrp
```
## 事件
- `wechat:subscribe` 用户关注公众号时触发
- `wechat:unsubscribe` 用户取消关注公众号时触发
\ No newline at end of file
import { Context } from 'koishi';
export default class ExtrasInDev {
constructor(ctx: Context) {}
}
import { App, segment } from 'koishi';
import TargetPlugin from '../src';
import * as Help from '@koishijs/plugin-help';
import ExtrasInDev from './extras';
import * as fs from 'fs';
const app = new App({
port: 3000,
host: '0.0.0.0',
prefix: '.',
});
app.plugin(Help);
// Some extras
app.plugin(ExtrasInDev);
// Target plugin
app.plugin(TargetPlugin, {
path: '/wechat',
token: 'token',
appId: 'appId',
appSecret: 'appSecret',
menus: [
{
type: 'click',
name: '帮助',
command: 'help',
},
{
type: 'click',
name: '卡片调查',
command: 'survey',
},
{
type: 'parent',
name: '卡图预览',
children: [
{
type: 'click',
name: '巨神兵',
command: 'obelisk',
},
{
type: 'click',
name: '天空龙',
command: 'silfer',
},
{
type: 'click',
name: '翼神龙',
command: 'ra',
},
],
},
],
});
app.on('wechat:subscribe', (session) => {
console.log(`subscribe: ${session.userId}`);
return session.send('欢迎关注!');
});
app.on('wechat:unsubscribe', (session) =>
console.log(`unsubscribe: ${session.userId}`),
);
app.on('message', (session) =>
console.log(`message from ${session.userId}: ${session.content}`),
);
app
.command('obelisk', '巨神兵')
.action(({ session }) =>
segment.image(
'https://cdn02.moecube.com:444/images/ygopro-images-zh-CN/10000000.jpg',
),
);
app
.command('silfer', '天空龙')
.action(({ session }) =>
segment.image(fs.readFileSync('./dev/pics/10000020.jpg'), 'image/jpeg'),
);
app
.command('ra', '翼神龙')
.action(({ session }) =>
segment.image(`file://${process.cwd()}/dev/pics/10000010.jpg`),
);
app.command('survey', '卡片调查').action(async ({ session }) => {
await session.send('你喜欢什么游戏王卡?');
const card = await session.prompt();
await session.send(`你喜欢的卡是 ${card} 吗?`);
const confirm = await session.prompt();
if (confirm === '') {
return '谢谢你的反馈!你最喜欢的卡是: ' + card;
} else {
return '谢谢你的反馈!';
}
});
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-adapter-wechat-official",
"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-adapter-wechat-official.git"
},
"author": "Nanahira <nanahira@momobako.com>",
"license": "MIT",
"keywords": [
"Koishi.js",
"qqbot",
"cqhttp",
"onebot"
],
"bugs": {
"url": "https://code.mycard.moe/3rdeye/koishi-plugin-adapter-wechat-official/issues"
},
"homepage": "https://code.mycard.moe/3rdeye/koishi-plugin-adapter-wechat-official",
"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": {
"ext2mime": "^1.0.1",
"file-type": "16.5.3",
"form-data": "^4.0.0",
"koa-wechat-public": "^0.1.13",
"koa-xml-body": "^2.2.0",
"koishi-thirdeye": "^11.1.20",
"mime2ext": "^1.0.1"
},
"peerDependencies": {
"koishi": "^4.11.0"
},
"devDependencies": {
"@koishijs/plugin-help": "^2.0.0",
"@types/jest": "^29.2.5",
"@types/koa-xml-body": "^2.2.0",
"@types/node": "^18.11.18",
"@typescript-eslint/eslint-plugin": "^5.48.0",
"@typescript-eslint/parser": "^5.48.0",
"eslint": "8.22.0",
"eslint-config-prettier": "^8.6.0",
"eslint-plugin-prettier": "^4.2.1",
"jest": "^29.3.1",
"prettier": "^2.8.1",
"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.11.0"
},
"koishi": {
"category": "adapter",
"service": {
"implements": [
"adapter"
]
}
}
}
import { Adapter, segment } from 'koishi';
import { DefinePlugin, Reusable } from 'koishi-thirdeye';
import type WechatBot from './index';
@Reusable()
@DefinePlugin()
export class WechatAdapter extends Adapter.Client<WechatBot> {
async start(bot: WechatBot) {
bot.internal.subscribe((acc) =>
bot.handleSession(acc, { type: 'wechat:subscribe' }),
);
bot.internal.unsubscribe((acc) =>
bot.handleSession(acc, { type: 'wechat:unsubscribe' }),
);
bot.internal.text(/.*/, (acc) =>
bot.handleSession(acc, {
type: 'message',
content: acc.content,
}),
);
bot.internal.image((acc) =>
bot.handleSession(acc, {
type: 'message',
content: segment.image(acc.picUrl).toString(),
}),
);
bot.internal.video(async (acc) => {
const content = await bot.transformVideo(acc.mediaId);
if (content) {
await bot.handleSession(acc, {
type: 'message',
content: content.toString(),
});
}
});
bot.internal.voice(async (acc) => {
const content = await bot.transformVoice(acc.mediaId);
if (content) {
await bot.handleSession(acc, {
type: 'message',
content: content.toString(),
});
}
});
bot.internal.menu((acc) => bot.handleMenu(acc));
await bot.initialize();
}
async stop(bot: WechatBot) {}
}
// import 'source-map-support/register';
import { RegisterSchema, SchemaProperty } from 'koishi-thirdeye';
import WechatApplication from 'koa-wechat-public';
import { WechatMenuDef } from './utils/menu';
@RegisterSchema()
export class WechatOfficialConfig
implements WechatApplication.WechatApplicationConfig
{
constructor(config: WechatOfficialConfigLike) {}
@SchemaProperty({
description: '回调路径。每个 bot 必须唯一。',
required: true,
})
path: string;
@SchemaProperty({ description: '微信公众号 ID。', required: true })
appId: string;
@SchemaProperty({
description: '微信公众号 Secret。',
required: true,
role: 'secret',
})
appSecret: string;
@SchemaProperty({
description: '微信公众号 Token。',
required: true,
role: 'secret',
})
token: string;
@SchemaProperty({
description: '微信公众号 AES Key。如果开启加密模式需要用到该项。',
role: 'secret',
})
encodingAESKey?: string;
@SchemaProperty({
description: '微信公众号菜单配置。',
type: WechatMenuDef,
default: [],
})
menus?: WechatMenuDef[];
platform = 'wechat-official';
get selfId() {
return this.appId;
}
}
export type WechatOfficialConfigLike = Partial<WechatOfficialConfig>;
This diff is collapsed.
import { createHash } from 'crypto';
import { Schema } from 'koishi';
export const WechatButtonTypes = [
'click',
'view',
'miniprogram',
'scancode_push',
'scancode_waitmsg',
'pic_sysphoto',
'pic_photo_or_album',
'pic_weixin',
'location_select',
'media_id',
'view_limited',
'article_id',
'article_view_limited',
] as const;
export type WechatButtonTypes = typeof WechatButtonTypes[number];
export interface WechatButton {
type: WechatButtonTypes;
name: string;
key?: string;
url?: string;
pagepath?: string;
appid?: string;
}
export interface WechatParentButton {
name: string;
sub_button: WechatButton[];
}
export interface WechatMenuDef {
type: WechatButtonTypes | 'parent';
name: string;
command?: string;
children?: (Omit<WechatMenuDef, 'children'> & { type: WechatButtonTypes })[];
url?: string;
pagePath?: string;
mediaId?: string;
}
const menuInfoSchemas = {
name: Schema.string().description('菜单标题。').required(),
command: Schema.string().description('菜单的响应动作指令。'),
url: Schema.string().description(
'网页链接,成员点击菜单可打开链接,不超过1024字节。',
),
pagePath: Schema.string().description('小程序的页面路径。'),
appId: Schema.string().description('小程序的appid。'),
};
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
export const WechatMenuDef: Schema<WechatMenuDef> = Schema.object({
type: Schema.union(['parent', ...WechatButtonTypes])
.required()
.description('菜单的响应动作类型。'),
...menuInfoSchemas,
children: Schema.array(
Schema.object({
type: Schema.union(WechatButtonTypes)
.required()
.description('菜单的响应动作类型。'),
...menuInfoSchemas,
}),
).description('子菜单。'),
});
export const adaptMenu = (
menu: WechatMenuDef,
registerMap?: Map<string, string>,
): WechatButton | WechatParentButton => {
if (!menu.type && !menu.children) {
throw new Error('Menu type or children must be set');
}
if (menu.type !== 'parent') {
const key = createHash('sha512')
.update(`${menu.type}${menu.name}${menu.command || ''}`)
.digest('hex');
if (menu.command) {
registerMap?.set(key, menu.command);
}
return {
type: menu.type as WechatButtonTypes,
name: menu.name,
key,
url: menu.url,
pagepath: menu.pagePath,
appid: menu.mediaId,
};
} else {
return {
name: menu.name,
sub_button: menu.children.map((c) => adaptMenu(c, registerMap)),
} as WechatParentButton;
}
};
export interface WechatMenu {
button: WechatButton[];
}
import { Element } from 'koishi';
const patternTypes = ['message', 'p', 'a'];
export function getFirstElement(elements: Element[]): Element {
if (!elements.length) return;
const firstElement = elements[0];
if (patternTypes.includes(firstElement.type)) {
const innerFirst = getFirstElement(firstElement.children);
if (innerFirst) return innerFirst;
return getFirstElement(elements.slice(1));
}
return firstElement;
}
export function getPlainText(elements: Element[]) {
let buffer = '';
for (const element of elements) {
if (element.type === 'text') {
buffer += element.attrs.content;
} else if (patternTypes.includes(element.type)) {
buffer += getPlainText(element.children);
buffer += '\n';
if (element.type === 'a' && element.attrs.href) {
buffer += ` (${element.attrs.href})`;
}
} else if (element.type === 'at') {
if (element.attrs.id) {
buffer += `@${element.attrs.id}`;
} else if (element.attrs.type === 'all') {
buffer += '@全体成员';
} else if (element.attrs.type === 'here') {
buffer += '@在线成员';
} else if (element.attrs.role) {
buffer += `@${element.attrs.role}`;
}
} else if (element.type === 'sharp') {
buffer += ` #${element.attrs.name} `;
}
}
return buffer.trim();
}
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