Commit 5a4fdf1d authored by nanahira's avatar nanahira

first

parents
Pipeline #18687 failed with stages
in 3 minutes and 33 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
/*.memory-card.json
\ 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-wechaty
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*
/*.memory-card.json
\ No newline at end of file
{
"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-wechaty
Koishi 微信适配器。
## 安装
### npm
```bash
npm install koishi-plugin-adapter-wechaty
```
## 配置
```yaml
plugins:
adapter-wechaty:
name: 'koishi' # Wechaty 配置文件保存路径。
```
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 fs from 'fs';
const app = new App({
prefix: '.',
});
app.plugin(Help);
// Some extras
app.plugin(ExtrasInDev);
// Target plugin
app.plugin(TargetPlugin, {
name: 'puppet-wechat',
});
app.on('bot-status-updated', (bot) =>
console.log(`Bot ${bot.selfId} status updated: ${bot.status}`),
);
app.on('message', (session) =>
console.log(`Got message from ${session.channelId}: ${session.content}`),
);
app.on('message-deleted', (session) =>
console.log(`Message deleted from ${session.channelId}.`),
);
app
.command('atme')
.action(({ session }) => [segment.at(session.userId), '您好']);
app
.command('image')
.action(async () =>
segment.image(await fs.promises.readFile(__dirname + '/10000.jpg')),
);
app
.command('you')
.action(async ({ session }) =>
console.log(await session.bot.getUser(session.userId)),
);
app
.command('me')
.action(async ({ session }) => console.log(await session.bot.getSelf()));
app.on('guild-added', (session) =>
console.log(`Guild added: ${session.guildId}`),
);
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-wechaty",
"description": "Koishi 微信适配器。",
"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-plugin-adapter-wechaty.git"
},
"author": "Nanahira <nanahira@momobako.com>",
"license": "MIT",
"keywords": [
"Koishi.js",
"qqbot",
"cqhttp",
"onebot",
"wechat",
"wechaty"
],
"bugs": {
"url": "https://code.mycard.moe/3rdeye/koishi-plugin-adapter-wechaty/issues"
},
"homepage": "https://code.mycard.moe/3rdeye/koishi-plugin-adapter-wechaty",
"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": {
"file-type": "16.5.3",
"koishi-thirdeye": "^11.1.14",
"wechaty": "^1.20.2",
"wechaty-puppet-wechat": "^1.18.4"
},
"peerDependencies": {
"koishi": "^4.10.6"
},
"devDependencies": {
"@koishijs/plugin-help": "^2.0.0",
"@types/jest": "^29.2.4",
"@types/node": "^18.11.17",
"@types/raven": "^2.5.4",
"@typescript-eslint/eslint-plugin": "^5.46.1",
"@typescript-eslint/parser": "^5.46.1",
"eslint": "8.22.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-prettier": "^4.2.1",
"jest": "^29.3.1",
"prettier": "^2.8.1",
"raven": "^2.6.4",
"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,
Awaitable,
Logger,
makeArray,
MaybeArray,
Session,
} from 'koishi';
import type WechatyBot from './index';
import { DefinePlugin, InjectLogger, Reusable } from 'koishi-thirdeye';
import { PassthroughEvents } from './def';
import type { WechatyEventListeners } from 'wechaty/src/schemas/mod';
import { adaptContact, adaptMessage, adaptRoom } from './utils';
import type { ContactInterface } from 'wechaty/src/user-modules/contact';
@Reusable()
@DefinePlugin()
export class WechatyAdapter extends Adapter.Client<WechatyBot> {
@InjectLogger()
private logger: Logger;
private adaptEvent<K extends keyof WechatyEventListeners>(
event: K,
sessionBuilder: (
...args: Parameters<WechatyEventListeners[K]>
) => Awaitable<MaybeArray<Partial<Session>>>,
) {
this.bot.internal.on(event, async (...args: any[]) => {
const timestamp = Date.now();
const payloads = makeArray(
await sessionBuilder(...(args as Parameters<WechatyEventListeners[K]>)),
);
payloads.forEach((payload) => {
if (!payload) return;
payload.timestamp ??= timestamp;
const session = this.bot.session(payload);
this.bot.dispatch(session);
});
});
}
private loadEvents() {
this.adaptEvent('message', async (message) => {
const adaptedMessage = await adaptMessage(this.bot, message);
if (!adaptedMessage) return;
return {
...adaptedMessage,
type:
message.type() === this.bot.internal.Message.Type.Recalled
? 'message-deleted'
: adaptedMessage.userId === this.bot.selfId
? 'message-sent'
: 'message',
subsubtype: adaptedMessage.subtype,
};
});
this.adaptEvent('friendship', async (friendship) => {
const wechatyType = friendship.type();
let type: string;
if (wechatyType === 2) {
// receive
type = 'friend-request';
} else if (wechatyType === 1) {
// confirm
type = 'friend-added';
} else {
return;
}
return {
type,
messageId: friendship.id,
content: friendship.hello(),
channelId: 'private:' + friendship.contact().id,
...(await adaptContact(friendship.contact())),
};
});
this.adaptEvent('room-invite', async (invitation) => {
const channelName = await invitation.topic();
return {
type: 'guild-request',
messageId: invitation.id,
...(await adaptContact(await invitation.inviter())),
channelName,
channelId: channelName,
guildName: channelName,
guildId: channelName,
};
});
this.adaptEvent(
'room-join',
async (
room,
inviteeList: ContactInterface[],
inviter: ContactInterface,
date: Date,
) => {
const channel = await adaptRoom(room);
const timestamp = (date || new Date()).valueOf();
const sessions = await Promise.all(
inviteeList.map(async (invitee): Promise<Partial<Session>> => {
const invitedUser = await adaptContact(invitee);
return {
type: invitee.self() ? 'guild-added' : 'guild-member-added',
subtype: invitedUser.userId === inviter.id ? 'active' : 'passive',
...invitedUser,
targetId: invitedUser.userId,
};
}),
);
return sessions.map((s) => ({
operatorId: inviter.id,
timestamp,
...channel,
...s,
}));
},
);
this.adaptEvent(
'room-leave',
async (
room,
leaverList: ContactInterface[],
operator: ContactInterface,
date: Date,
) => {
const channel = await adaptRoom(room);
const timestamp = (date || new Date()).valueOf();
const sessions = await Promise.all(
leaverList.map(async (leaver): Promise<Partial<Session>> => {
const user = await adaptContact(leaver);
return {
type: leaver.self() ? 'guild-deleted' : 'guild-member-deleted',
subtype:
!operator || user.userId === operator.id ? 'active' : 'passive',
targetId: user.userId,
...user,
};
}),
);
return sessions.map((s) => ({
...channel,
operatorId: operator?.id,
timestamp,
...s,
}));
},
);
}
async start() {
for (const event of PassthroughEvents) {
this.bot.internal.on(event, (...args: any[]) => {
const session = this.bot.session();
session.type = `wechaty/${event}`;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
session.app.emit(session, `wechaty/${event}`, session, ...args);
});
}
this.loadEvents();
return this.bot.initialize();
}
async stop() {
await this.bot.internal.stop();
}
}
import { WechatyBuilder } from 'wechaty';
import type { WechatyEventListeners } from 'wechaty/src/schemas/mod';
import WechatyBot from './index';
import { Session } from 'koishi';
export type WechatyInstance = ReturnType<typeof WechatyBuilder['build']>;
type AddSessionToFront<F> = F extends (...args: infer A) => infer P
? (session: Session & { bot: WechatyBot }, ...args: A) => P
: never;
export const PassthroughEvents = [
'scan',
'room-topic',
'heartbeat',
'error',
] as const;
export type PassthroughEvents = typeof PassthroughEvents[number];
export type WechatyEvents = {
[K in keyof WechatyEventListeners as `wechaty/${PassthroughEvents}`]: AddSessionToFront<
WechatyEventListeners[K]
>;
};
// import 'source-map-support/register';
import {
DefinePlugin,
InjectLogger,
PluginDef,
RegisterSchema,
Reusable,
SchemaProperty,
UsePlugin,
} from 'koishi-thirdeye';
import { Bot, Fragment, Logger, Schema, segment, SendOptions } from 'koishi';
import { WechatyBuilder } from 'wechaty';
import { WechatyEvents, WechatyInstance } from './def';
import { WechatyAdapter } from './adapter';
import { adaptContact, adaptMessage, adaptRoom } from './utils';
import { WechatyMessenger } from './message';
declare module 'koishi' {
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface Events extends WechatyEvents {}
}
@RegisterSchema()
export class WechatyBotConfig {
@SchemaProperty({ required: true, description: 'Wechaty 配置文件保存路径。' })
name: string;
@SchemaProperty({
default: 'wechaty-wechat-puppet',
description: 'Wechaty 使用的 Puppet。',
hidden: true,
})
puppet: string;
@SchemaProperty({
default: { uos: true },
hidden: true,
type: Schema.object({}),
description: 'Wechaty Puppet 选项。',
})
puppetOptions: any;
platform = 'wechaty';
selfId?: string;
}
@Reusable()
@DefinePlugin()
export default class WechatyBot extends Bot<Partial<WechatyBotConfig>> {
internal: WechatyInstance;
@InjectLogger()
logger: Logger;
@UsePlugin()
loadAdapter() {
this.internal = WechatyBuilder.build({
name: this.config.name,
puppetOptions: this.config.puppetOptions,
puppet: this.config.puppet as any,
});
return PluginDef(WechatyAdapter, this);
}
async initialize() {
this.internal.on('login', (user) => {
this.selfId = user.id;
this.online();
});
this.internal.on('logout', () => {
this.offline();
});
this.internal.on('error', (error) => {
this.offline(error);
});
this.internal.on('scan', (qrcode, status) => {
this.logger.info(
`Scan (${status}): https://wechaty.js.org/qrcode/${encodeURIComponent(
qrcode,
)}`,
);
});
await this.internal.start();
}
// message
async sendMessage(
channelId: string,
content: Fragment,
guildId?: string,
options?: SendOptions,
) {
return new WechatyMessenger(this, channelId, guildId, options).send(
content,
);
}
async sendPrivateMessage(
userId: string,
content: Fragment,
options?: SendOptions,
) {
return new WechatyMessenger(
this,
'private:' + userId,
undefined,
options,
).send(content);
}
async getMessage(channelId: string, messageId: string) {
const message = await this.internal.Message.find({ id: messageId });
if (!message) return;
return adaptMessage(this, message as any);
}
async getMessageList(channelId: string, before?: string) {
const messages = await this.internal.Message.findAll({
roomId: !channelId.startsWith('private:') ? channelId : undefined,
fromId: channelId.startsWith('private:') ? channelId.slice(8) : undefined,
});
return Promise.all(messages.map((m) => adaptMessage(this, m as any)));
}
async editMessage(
channelId: string,
messageId: string,
content: segment.Fragment,
) {}
async deleteMessage(channelId: string, messageId: string) {}
// user
async getSelf() {
const self = this.internal.currentUser;
return adaptContact(self);
}
async getUser(userId: string) {
const contact = await this.internal.Contact.find({ id: userId });
return adaptContact(contact);
}
async getFriendList() {
const friends = await this.internal.Contact.findAll();
return Promise.all(friends.map(adaptContact));
}
async deleteFriend(userId: string) {}
// guild
async getGuild(guildId: string) {
const room = await this.internal.Room.find({ id: guildId });
return adaptRoom(room);
}
async getGuildList() {
const rooms = await this.internal.Room.findAll();
return Promise.all(rooms.map(adaptRoom));
}
async getChannel(channelId: string) {
return this.getGuild(channelId);
}
async getChannelList() {
return this.getGuildList();
}
async muteChannel(channelId: string, guildId?: string, enable?: boolean) {}
// guild member
async getGuildMember(guildId: string, userId: string) {
const room = await this.internal.Room.find({ id: guildId });
if (!room) return;
const members = await room.memberAll();
const member = members.find((m) => m.id === userId);
if (!member) return;
return adaptContact(member);
}
async getGuildMemberList(guildId: string) {
const room = await this.internal.Room.find({ id: guildId });
if (!room) return;
const members = await room.memberAll();
return Promise.all(members.map(adaptContact));
}
async kickGuildMember(guildId: string, userId: string, permanent?: boolean) {}
async muteGuildMember(
guildId: string,
userId: string,
duration: number,
reason?: string,
) {}
// request
async handleFriendRequest(
messageId: string,
approve: boolean,
comment?: string,
) {
if (!approve) return;
return this.internal.Friendship.load(messageId).accept();
}
async handleGuildRequest(
messageId: string,
approve: boolean,
comment?: string,
) {
if (!approve) return;
return this.internal.RoomInvitation.load(messageId).accept();
}
async handleGuildMemberRequest(
messageId: string,
approve: boolean,
comment?: string,
) {}
}
import WechatyBot from './index';
import { Element, Messenger, segment } from 'koishi';
import { Contact, Sayable } from 'wechaty';
import { elementToFileBox } from './utils';
export class WechatyMessenger extends Messenger<WechatyBot> {
buffer = '';
contactCache = new Map<string, Contact>();
addMessage(messageId: string) {
if (!messageId) return;
const session = this.bot.session();
session.messageId = messageId;
session.app.emit(session, 'send', session);
this.results.push(session);
}
private isGuild() {
return !this.channelId.startsWith('private:');
}
async post(content: Sayable) {
try {
if (!this.isGuild()) {
const contact = await this.bot.internal.Contact.find({
id: this.channelId.slice(8),
});
if (!contact) {
return;
}
const message = await contact.say(content);
if (!message) return;
this.addMessage(message.id);
} else {
const room = await this.bot.internal.Room.find({ id: this.channelId });
if (!room) {
return;
}
const message = await room.say(content);
if (!message) return;
this.addMessage(message.id);
}
} catch (e) {
this.errors.push(e);
}
}
async flush() {
if (!this.buffer) return;
await this.post(this.buffer);
this.buffer = '';
}
async sendMedia(media: Element) {
const fileBox = await elementToFileBox(media);
if (!fileBox) return;
return this.post(fileBox);
}
private text(content: string) {
this.buffer += content;
}
private async getRelatedContact(id: string) {
if (this.contactCache.has(id)) {
return this.contactCache.get(id);
}
let member: Contact;
if (this.isGuild()) {
const room = await this.bot.internal.Room.find({ id: this.channelId });
if (!room) return;
const members = await room.memberAll();
member = members.find((member) => member.id === id);
} else {
member = await this.bot.internal.Contact.find({ id });
}
if (!member) return;
this.contactCache.set(id, member);
return member;
}
async visit(element: segment) {
const { type, attrs, children } = element;
switch (type) {
case 'text':
this.text(attrs.content);
break;
case 'p':
await this.render(children);
this.text('\n');
break;
case 'a':
await this.render(children);
if (attrs.href) this.text(` (${attrs.href}) `);
break;
case 'at':
if (attrs.id) {
const contact = await this.getRelatedContact(attrs.id);
if (contact) {
this.text(`@${contact.name()} `);
}
} else if (attrs.type === 'all') {
this.text('@全体成员 ');
} else if (attrs.type === 'here') {
this.text('@在线成员 ');
} else if (attrs.role) {
this.text(`@${attrs.role}`);
}
break;
case 'image':
case 'video':
case 'audio':
case 'file':
await this.flush();
await this.sendMedia(element);
break;
case 'figure':
case 'message':
await this.flush();
await this.render(children, true);
break;
case 'wechaty:contact':
const contact = await this.getRelatedContact(attrs.id);
if (contact) {
await this.flush();
await this.post(contact);
}
break;
default:
await this.render(children);
}
}
}
import { segment, Universal, Element, Awaitable } from 'koishi';
import { ContactInterface } from 'wechaty/src/user-modules/contact';
import { RoomInterface } from 'wechaty/src/user-modules/room';
import { MessageInterface } from 'wechaty/src/user-modules/message';
import WechatyBot from './index';
import FileType from 'file-type';
export type ContactLike = Pick<
ContactInterface,
'id' | 'name' | 'avatar' | 'self'
>;
export type FileBoxLike = Awaited<ReturnType<ContactLike['avatar']>>;
import { FileBox } from 'file-box';
import path from 'path';
export type RoomLike = Pick<RoomInterface, 'id' | 'topic'>;
export type MessageLike = MessageInterface;
export const fileBoxToUrl = async (file: FileBoxLike): Promise<string> => {
if (!file) {
return undefined;
}
if (file['remoteUrl']) {
return file['remoteUrl'];
}
let buf: Buffer;
try {
buf = await file.toBuffer();
} catch (e) {
buf = file['stream'];
}
return `base64://${buf.toString('base64')}`;
};
export const adaptContact = async (
contact: ContactLike,
): Promise<Universal.User> => {
return {
userId: contact.id,
nickname: contact.name(),
avatar: await fileBoxToUrl(await contact.avatar()),
isBot: contact.self(),
};
};
export const adaptRoom = async (
room: RoomLike,
): Promise<Universal.Channel & Universal.Guild> => {
const name = await room.topic();
return {
channelId: room.id,
channelName: name,
guildId: room.id,
guildName: name,
};
};
async function extractMessageURL(
message: MessageLike,
segmentFactory: (url: string, name: string) => Awaitable<Element>,
): Promise<Element> {
const file = await message.toFileBox();
if (!file) {
return;
}
return segmentFactory(await fileBoxToUrl(file), file.name);
}
export async function messageToElement(
bot: WechatyBot,
message: MessageLike,
): Promise<Element[]> {
try {
const MessageType = bot.internal.Message.Type;
const elements: Element[] = [];
const mentions = await message.mentionList();
switch (message.type()) {
case MessageType.Recalled:
return [];
case MessageType.Text:
let text = message.text();
for (const mention of mentions) {
const name = mention.name();
console.log('mention', name);
text = text.replace(new RegExp(`@${name}\\s+`, 'g'), '');
}
console.log(text);
elements.push(segment.text(text));
break;
case MessageType.Image:
elements.push(
await extractMessageURL(message, async (url, name) =>
segment.image(url, { file: await autoFilename(url) }),
),
);
break;
case MessageType.Audio:
elements.push(
await extractMessageURL(message, async (url, name) =>
segment.audio(url, { file: await autoFilename(url) }),
),
);
break;
case MessageType.Video:
elements.push(
await extractMessageURL(message, async (url, name) =>
segment.video(url, { file: await autoFilename(url) }),
),
);
break;
case MessageType.Attachment:
elements.push(
await extractMessageURL(message, async (url, name) =>
segment.file(url, { file: name }),
),
);
break;
case MessageType.Url:
const link = await message.toUrlLink();
elements.push(
segment('a', { href: link.url() }, [
link.title() + '\n' + link.description,
segment.image(link.thumbnailUrl()),
]),
);
break;
case MessageType.Contact:
const contact = await message.toContact();
elements.push(
segment('wechaty:contact', { id: contact.id, name: contact.name() }),
);
break;
default:
return;
}
mentions.forEach((mention) => elements.unshift(segment.at(mention.id)));
return elements;
} catch (e) {
return;
}
}
export async function adaptMessage(
bot: WechatyBot,
message: MessageLike,
): Promise<Universal.Message> {
const elements = await messageToElement(bot, message);
if (!elements) return;
const room = message.room();
const from = message.talker();
if (!from) {
return;
}
const author = await adaptContact(from);
const channel = room ? await adaptRoom(room) : {};
const subtype = room ? 'group' : 'private';
return {
messageId: message.id,
author,
...author,
...channel,
channelId: room?.id || 'private:' + author.userId,
subtype,
elements,
content: elements.map((e) => e.toString()).join(''),
timestamp: (message.date() || new Date()).valueOf(),
};
}
export async function autoFilename(url: string) {
if (url.startsWith('file://')) {
return path.basename(url.slice(7));
}
if (url.startsWith('base64://')) {
const buf = Buffer.from(url.slice(9), 'base64');
const type = await FileType.fromBuffer(buf);
return `file.${type.ext}`;
}
return path.basename(new URL(url).pathname);
}
export const elementToFileBox = async (element: Element) => {
const { attrs } = element;
const { url, file } = attrs;
if (!url) return;
if (url.startsWith('file://')) {
const filePath = url.slice(7);
return FileBox.fromFile(filePath, file || (await autoFilename(url)));
}
if (url.startsWith('base64://')) {
return FileBox.fromBase64(url.slice(9), file || (await autoFilename(url)));
}
return FileBox.fromUrl(url, {
name: file || (await autoFilename(url)),
});
};
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