@zhin.js/adapter-milky 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +159 -0
- package/lib/adapter.d.ts +25 -0
- package/lib/adapter.d.ts.map +1 -0
- package/lib/adapter.js +94 -0
- package/lib/adapter.js.map +1 -0
- package/lib/api.d.ts +10 -0
- package/lib/api.d.ts.map +1 -0
- package/lib/api.js +48 -0
- package/lib/api.js.map +1 -0
- package/lib/bot-sse.d.ts +31 -0
- package/lib/bot-sse.d.ts.map +1 -0
- package/lib/bot-sse.js +194 -0
- package/lib/bot-sse.js.map +1 -0
- package/lib/bot-webhook.d.ts +34 -0
- package/lib/bot-webhook.d.ts.map +1 -0
- package/lib/bot-webhook.js +187 -0
- package/lib/bot-webhook.js.map +1 -0
- package/lib/bot-ws.d.ts +35 -0
- package/lib/bot-ws.d.ts.map +1 -0
- package/lib/bot-ws.js +243 -0
- package/lib/bot-ws.js.map +1 -0
- package/lib/bot-wss.d.ts +34 -0
- package/lib/bot-wss.d.ts.map +1 -0
- package/lib/bot-wss.js +225 -0
- package/lib/bot-wss.js.map +1 -0
- package/lib/index.d.ts +20 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +27 -0
- package/lib/index.js.map +1 -0
- package/lib/types.d.ts +75 -0
- package/lib/types.d.ts.map +1 -0
- package/lib/types.js +5 -0
- package/lib/types.js.map +1 -0
- package/lib/utils.d.ts +35 -0
- package/lib/utils.d.ts.map +1 -0
- package/lib/utils.js +157 -0
- package/lib/utils.js.map +1 -0
- package/package.json +51 -0
- package/src/adapter.ts +115 -0
- package/src/api.ts +63 -0
- package/src/bot-sse.ts +226 -0
- package/src/bot-webhook.ts +222 -0
- package/src/bot-ws.ts +279 -0
- package/src/bot-wss.ts +268 -0
- package/src/eventsource.d.ts +12 -0
- package/src/index.ts +40 -0
- package/src/types.ts +73 -0
- package/src/utils.ts +174 -0
package/src/adapter.ts
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Milky 适配器:单一适配器支持 WS 正向 / SSE / Webhook / 反向 WS,由 config.connection 区分
|
|
3
|
+
*/
|
|
4
|
+
import type { Router } from '@zhin.js/http';
|
|
5
|
+
import {
|
|
6
|
+
Adapter,
|
|
7
|
+
Plugin,
|
|
8
|
+
createGroupManagementTools,
|
|
9
|
+
GROUP_MANAGEMENT_SKILL_KEYWORDS,
|
|
10
|
+
GROUP_MANAGEMENT_SKILL_TAGS,
|
|
11
|
+
type IGroupManagement,
|
|
12
|
+
} from 'zhin.js';
|
|
13
|
+
import { MilkyWsClient } from './bot-ws.js';
|
|
14
|
+
import { MilkySseClient } from './bot-sse.js';
|
|
15
|
+
import { MilkyWebhookBot } from './bot-webhook.js';
|
|
16
|
+
import { MilkyWssServer } from './bot-wss.js';
|
|
17
|
+
import type {
|
|
18
|
+
MilkyBotConfig,
|
|
19
|
+
MilkyWsConfig,
|
|
20
|
+
MilkySseConfig,
|
|
21
|
+
MilkyWebhookConfig,
|
|
22
|
+
MilkyWssConfig,
|
|
23
|
+
} from './types.js';
|
|
24
|
+
|
|
25
|
+
export type MilkyBot = MilkyWsClient | MilkySseClient | MilkyWebhookBot | MilkyWssServer;
|
|
26
|
+
|
|
27
|
+
export class MilkyAdapter extends Adapter<MilkyBot> {
|
|
28
|
+
#router?: Router;
|
|
29
|
+
|
|
30
|
+
constructor(plugin: Plugin) {
|
|
31
|
+
super(plugin, 'milky', []);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
createBot(config: MilkyBotConfig): MilkyBot {
|
|
35
|
+
switch (config.connection) {
|
|
36
|
+
case 'ws':
|
|
37
|
+
return new MilkyWsClient(this, config as MilkyWsConfig);
|
|
38
|
+
case 'sse':
|
|
39
|
+
return new MilkySseClient(this, config as MilkySseConfig);
|
|
40
|
+
case 'webhook':
|
|
41
|
+
if (!this.#router) throw new Error('Milky connection: webhook 需要 router,请安装并在配置中启用 @zhin.js/http');
|
|
42
|
+
return new MilkyWebhookBot(this, this.#router, config as MilkyWebhookConfig);
|
|
43
|
+
case 'wss':
|
|
44
|
+
if (!this.#router) throw new Error('Milky connection: wss 需要 router,请安装并在配置中启用 @zhin.js/http');
|
|
45
|
+
return new MilkyWssServer(this, this.#router, config as MilkyWssConfig);
|
|
46
|
+
default:
|
|
47
|
+
throw new Error(`Unknown Milky connection: ${(config as MilkyBotConfig).connection}`);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async kickMember(botId: string, sceneId: string, userId: string) {
|
|
52
|
+
const bot = this.bots.get(botId);
|
|
53
|
+
if (!bot) throw new Error(`Bot ${botId} 不存在`);
|
|
54
|
+
return bot.kickMember(Number(sceneId), Number(userId), false);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async muteMember(botId: string, sceneId: string, userId: string, duration = 600) {
|
|
58
|
+
const bot = this.bots.get(botId);
|
|
59
|
+
if (!bot) throw new Error(`Bot ${botId} 不存在`);
|
|
60
|
+
return bot.muteMember(Number(sceneId), Number(userId), duration);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async muteAll(botId: string, sceneId: string, enable = true) {
|
|
64
|
+
const bot = this.bots.get(botId);
|
|
65
|
+
if (!bot) throw new Error(`Bot ${botId} 不存在`);
|
|
66
|
+
return bot.muteAll(Number(sceneId), enable);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async setAdmin(botId: string, sceneId: string, userId: string, enable = true) {
|
|
70
|
+
const bot = this.bots.get(botId);
|
|
71
|
+
if (!bot) throw new Error(`Bot ${botId} 不存在`);
|
|
72
|
+
return bot.setAdmin(Number(sceneId), Number(userId), enable);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async setMemberNickname(botId: string, sceneId: string, userId: string, nickname: string) {
|
|
76
|
+
const bot = this.bots.get(botId);
|
|
77
|
+
if (!bot) throw new Error(`Bot ${botId} 不存在`);
|
|
78
|
+
return bot.setCard(Number(sceneId), Number(userId), nickname);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async setGroupName(botId: string, sceneId: string, name: string) {
|
|
82
|
+
const bot = this.bots.get(botId);
|
|
83
|
+
if (!bot) throw new Error(`Bot ${botId} 不存在`);
|
|
84
|
+
return bot.setGroupName(Number(sceneId), name);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async listMembers(botId: string, sceneId: string) {
|
|
88
|
+
const bot = this.bots.get(botId);
|
|
89
|
+
if (!bot) throw new Error(`Bot ${botId} 不存在`);
|
|
90
|
+
const members = await bot.getMemberList(Number(sceneId));
|
|
91
|
+
return { members: Array.isArray(members) ? members : [], count: Array.isArray(members) ? members.length : 0 };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
async getGroupInfo(botId: string, sceneId: string) {
|
|
95
|
+
const bot = this.bots.get(botId);
|
|
96
|
+
if (!bot) throw new Error(`Bot ${botId} 不存在`);
|
|
97
|
+
return bot.getGroupInfo(Number(sceneId));
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async start(): Promise<void> {
|
|
101
|
+
// 同步获取已就绪的 router,或通过 useContext 在 router 挂载后赋值
|
|
102
|
+
this.#router = (this.plugin.inject as (key: string) => Router | undefined)('router');
|
|
103
|
+
(this.plugin.useContext as (key: string, fn: (router: Router) => void) => void)('router', (router: Router) => {
|
|
104
|
+
this.#router = router;
|
|
105
|
+
});
|
|
106
|
+
const groupTools = createGroupManagementTools(this as unknown as IGroupManagement, this.name);
|
|
107
|
+
groupTools.forEach((t) => this.addTool(t));
|
|
108
|
+
this.declareSkill({
|
|
109
|
+
description: 'Milky 协议群管理:踢人、禁言、全员禁言、设管理员、改群名、查成员等。',
|
|
110
|
+
keywords: GROUP_MANAGEMENT_SKILL_KEYWORDS,
|
|
111
|
+
tags: GROUP_MANAGEMENT_SKILL_TAGS,
|
|
112
|
+
});
|
|
113
|
+
await super.start();
|
|
114
|
+
}
|
|
115
|
+
}
|
package/src/api.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Milky HTTP API 封装:鉴权 + POST /api/:api
|
|
3
|
+
*/
|
|
4
|
+
import type { MilkyApiResponse } from './types.js';
|
|
5
|
+
|
|
6
|
+
export interface MilkyApiClientOptions {
|
|
7
|
+
baseUrl: string;
|
|
8
|
+
access_token?: string;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** 鉴权:Header Authorization: Bearer {token} 或 URL query access_token=xxx */
|
|
12
|
+
function authHeaders(access_token?: string): Record<string, string> {
|
|
13
|
+
const headers: Record<string, string> = {};
|
|
14
|
+
if (access_token) {
|
|
15
|
+
headers['Authorization'] = `Bearer ${access_token}`;
|
|
16
|
+
}
|
|
17
|
+
return headers;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function authQuery(access_token?: string): string {
|
|
21
|
+
if (!access_token) return '';
|
|
22
|
+
return `access_token=${encodeURIComponent(access_token)}`;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* 调用协议端 API:POST {baseUrl}/api/{apiName},Body JSON,鉴权。
|
|
27
|
+
* 非 200 或 retcode !== 0 时抛错。
|
|
28
|
+
*/
|
|
29
|
+
export async function callApi<T = unknown>(
|
|
30
|
+
options: MilkyApiClientOptions,
|
|
31
|
+
apiName: string,
|
|
32
|
+
params: Record<string, unknown> = {},
|
|
33
|
+
): Promise<T> {
|
|
34
|
+
const { baseUrl, access_token } = options;
|
|
35
|
+
const url = new URL(`/api/${apiName}`, baseUrl.replace(/\/$/, ''));
|
|
36
|
+
const q = authQuery(access_token);
|
|
37
|
+
if (q) url.search = (url.search ? url.search + '&' : '') + q;
|
|
38
|
+
|
|
39
|
+
const res = await fetch(url.toString(), {
|
|
40
|
+
method: 'POST',
|
|
41
|
+
headers: {
|
|
42
|
+
'Content-Type': 'application/json',
|
|
43
|
+
...authHeaders(access_token),
|
|
44
|
+
},
|
|
45
|
+
body: JSON.stringify(Object.keys(params).length ? params : {}),
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
const text = await res.text();
|
|
49
|
+
let body: MilkyApiResponse<T>;
|
|
50
|
+
try {
|
|
51
|
+
body = JSON.parse(text) as MilkyApiResponse<T>;
|
|
52
|
+
} catch {
|
|
53
|
+
throw new Error(`Milky API ${apiName}: invalid JSON response (${res.status}) ${text.slice(0, 200)}`);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
if (res.status !== 200) {
|
|
57
|
+
throw new Error(`Milky API ${apiName}: HTTP ${res.status} ${body.message ?? text}`);
|
|
58
|
+
}
|
|
59
|
+
if (body.retcode !== 0) {
|
|
60
|
+
throw new Error(`Milky API ${apiName}: retcode=${body.retcode} ${body.message ?? ''}`);
|
|
61
|
+
}
|
|
62
|
+
return (body.data ?? {}) as T;
|
|
63
|
+
}
|
package/src/bot-sse.ts
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Milky SSE Bot:应用 GET 协议端 /event,Accept: text/event-stream,解析 SSE 的 milky_event
|
|
3
|
+
*/
|
|
4
|
+
import EventSource from 'eventsource';
|
|
5
|
+
import { EventEmitter } from 'events';
|
|
6
|
+
import { Bot, Message, SendOptions, segment } from 'zhin.js';
|
|
7
|
+
import { callApi } from './api.js';
|
|
8
|
+
import type { MilkySseConfig, MilkyEvent } from './types.js';
|
|
9
|
+
import type { MilkyAdapter } from './adapter.js';
|
|
10
|
+
import {
|
|
11
|
+
formatMilkyMessagePayload,
|
|
12
|
+
parseMessageReceiveData,
|
|
13
|
+
toMilkyOutgoingSegments,
|
|
14
|
+
parseMilkyMessageId,
|
|
15
|
+
} from './utils.js';
|
|
16
|
+
|
|
17
|
+
export class MilkySseClient extends EventEmitter implements Bot<MilkySseConfig, MilkyEvent> {
|
|
18
|
+
$connected: boolean;
|
|
19
|
+
private es?: EventSource;
|
|
20
|
+
|
|
21
|
+
get logger() {
|
|
22
|
+
return this.adapter.plugin.logger;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
constructor(public adapter: MilkyAdapter, public $config: MilkySseConfig) {
|
|
26
|
+
super();
|
|
27
|
+
this.$connected = false;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
get $id() {
|
|
31
|
+
return this.$config.name;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
private get eventUrl(): string {
|
|
35
|
+
const base = this.$config.baseUrl.replace(/\/$/, '');
|
|
36
|
+
const url = `${base}/event`;
|
|
37
|
+
const token = this.$config.access_token;
|
|
38
|
+
if (token) return `${url}${url.includes('?') ? '&' : '?'}access_token=${encodeURIComponent(token)}`;
|
|
39
|
+
return url;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
private apiOptions() {
|
|
43
|
+
return { baseUrl: this.$config.baseUrl, access_token: this.$config.access_token };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async $connect(): Promise<void> {
|
|
47
|
+
const headers: Record<string, string> = { Accept: 'text/event-stream' };
|
|
48
|
+
if (this.$config.access_token) {
|
|
49
|
+
headers['Authorization'] = `Bearer ${this.$config.access_token}`;
|
|
50
|
+
}
|
|
51
|
+
this.es = new EventSource(this.eventUrl, { headers });
|
|
52
|
+
this.$connected = true;
|
|
53
|
+
if (!this.$config.access_token) this.logger.warn('missing access_token, SSE connection is not secured');
|
|
54
|
+
|
|
55
|
+
this.es.addEventListener('milky_event', (e: MessageEvent) => {
|
|
56
|
+
try {
|
|
57
|
+
const event = JSON.parse(e.data) as MilkyEvent;
|
|
58
|
+
this.handleEvent(event);
|
|
59
|
+
} catch (err: unknown) {
|
|
60
|
+
this.emit('error', err instanceof Error ? err : new Error(String(err)));
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
this.es.onerror = (err: unknown) => {
|
|
65
|
+
this.emit('error', err instanceof Error ? err : new Error(String(err)));
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async $disconnect(): Promise<void> {
|
|
70
|
+
if (this.es) {
|
|
71
|
+
this.es.close();
|
|
72
|
+
this.es = undefined;
|
|
73
|
+
}
|
|
74
|
+
this.$connected = false;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
$formatMessage(event: MilkyEvent): Message<MilkyEvent> {
|
|
78
|
+
const data = parseMessageReceiveData(event);
|
|
79
|
+
if (!data) {
|
|
80
|
+
return Message.from(event, {
|
|
81
|
+
$id: '',
|
|
82
|
+
$adapter: 'milky',
|
|
83
|
+
$bot: this.$config.name,
|
|
84
|
+
$channel: { id: '', type: 'private' },
|
|
85
|
+
$sender: { id: '', name: '' },
|
|
86
|
+
$content: [],
|
|
87
|
+
$raw: '',
|
|
88
|
+
$timestamp: event.time ?? 0,
|
|
89
|
+
$recall: async () => {},
|
|
90
|
+
$reply: async () => '',
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
const payload = formatMilkyMessagePayload(
|
|
94
|
+
event,
|
|
95
|
+
data,
|
|
96
|
+
(id) => this.$recallMessage(id),
|
|
97
|
+
(channel, content) =>
|
|
98
|
+
this.adapter.sendMessage({
|
|
99
|
+
...channel,
|
|
100
|
+
context: 'milky',
|
|
101
|
+
bot: this.$config.name,
|
|
102
|
+
content: content as import('zhin.js').SendContent,
|
|
103
|
+
}),
|
|
104
|
+
'milky',
|
|
105
|
+
this.$config.name,
|
|
106
|
+
);
|
|
107
|
+
return Message.from(event, payload);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
private handleEvent(event: MilkyEvent): void {
|
|
111
|
+
const data = parseMessageReceiveData(event);
|
|
112
|
+
if (data) {
|
|
113
|
+
const message = this.$formatMessage(event);
|
|
114
|
+
this.adapter.emit('message.receive', message);
|
|
115
|
+
this.logger.debug(
|
|
116
|
+
`${this.$config.name} recv ${message.$channel.type}(${message.$channel.id}):${segment.raw(message.$content)}`,
|
|
117
|
+
);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
async $sendMessage(options: SendOptions): Promise<string> {
|
|
122
|
+
const content = Array.isArray(options.content) ? options.content : [options.content];
|
|
123
|
+
const segments = content.map((c) =>
|
|
124
|
+
typeof c === 'string' ? { type: 'text' as const, data: { text: c } } : (c as { type: string; data?: Record<string, unknown> }),
|
|
125
|
+
);
|
|
126
|
+
const message = toMilkyOutgoingSegments(segments);
|
|
127
|
+
if (options.type === 'group') {
|
|
128
|
+
const result = await callApi(this.apiOptions(), 'send_group_message', {
|
|
129
|
+
group_id: parseInt(options.id, 10),
|
|
130
|
+
message,
|
|
131
|
+
});
|
|
132
|
+
const seq = (result as { message_seq?: number }).message_seq;
|
|
133
|
+
this.logger.debug(`${this.$config.name} send group(${options.id}):${segment.raw(options.content)}`);
|
|
134
|
+
return seq != null ? `group:${options.id}:${seq}` : '';
|
|
135
|
+
}
|
|
136
|
+
if (options.type === 'private') {
|
|
137
|
+
const result = await callApi(this.apiOptions(), 'send_private_message', {
|
|
138
|
+
user_id: parseInt(options.id, 10),
|
|
139
|
+
message,
|
|
140
|
+
});
|
|
141
|
+
const seq = (result as { message_seq?: number }).message_seq;
|
|
142
|
+
this.logger.debug(`${this.$config.name} send private(${options.id}):${segment.raw(options.content)}`);
|
|
143
|
+
return seq != null ? `friend:${options.id}:${seq}` : '';
|
|
144
|
+
}
|
|
145
|
+
throw new Error('Either group or private must be provided');
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async $recallMessage(id: string): Promise<void> {
|
|
149
|
+
const parsed = parseMilkyMessageId(id);
|
|
150
|
+
if (!parsed) throw new Error(`Invalid message id: ${id}`);
|
|
151
|
+
if (parsed.message_scene === 'group') {
|
|
152
|
+
await callApi(this.apiOptions(), 'recall_group_message', {
|
|
153
|
+
group_id: parsed.peer_id,
|
|
154
|
+
message_seq: parsed.message_seq,
|
|
155
|
+
});
|
|
156
|
+
} else {
|
|
157
|
+
await callApi(this.apiOptions(), 'recall_private_message', {
|
|
158
|
+
user_id: parsed.peer_id,
|
|
159
|
+
message_seq: parsed.message_seq,
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
async kickMember(groupId: number, userId: number, rejectAddRequest = false): Promise<boolean> {
|
|
165
|
+
await callApi(this.apiOptions(), 'kick_group_member', {
|
|
166
|
+
group_id: groupId,
|
|
167
|
+
user_id: userId,
|
|
168
|
+
reject_add_request: rejectAddRequest,
|
|
169
|
+
});
|
|
170
|
+
return true;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
async muteMember(groupId: number, userId: number, duration = 600): Promise<boolean> {
|
|
174
|
+
await callApi(this.apiOptions(), 'set_group_member_mute', {
|
|
175
|
+
group_id: groupId,
|
|
176
|
+
user_id: userId,
|
|
177
|
+
duration,
|
|
178
|
+
});
|
|
179
|
+
return true;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
async muteAll(groupId: number, enable = true): Promise<boolean> {
|
|
183
|
+
await callApi(this.apiOptions(), 'set_group_whole_mute', { group_id: groupId, is_mute: enable });
|
|
184
|
+
return true;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
async setAdmin(groupId: number, userId: number, enable = true): Promise<boolean> {
|
|
188
|
+
await callApi(this.apiOptions(), 'set_group_member_admin', {
|
|
189
|
+
group_id: groupId,
|
|
190
|
+
user_id: userId,
|
|
191
|
+
is_set: enable,
|
|
192
|
+
});
|
|
193
|
+
return true;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
async setCard(groupId: number, userId: number, card: string): Promise<boolean> {
|
|
197
|
+
await callApi(this.apiOptions(), 'set_group_member_card', {
|
|
198
|
+
group_id: groupId,
|
|
199
|
+
user_id: userId,
|
|
200
|
+
card,
|
|
201
|
+
});
|
|
202
|
+
return true;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
async setTitle(groupId: number, userId: number, title: string): Promise<boolean> {
|
|
206
|
+
await callApi(this.apiOptions(), 'set_group_member_special_title', {
|
|
207
|
+
group_id: groupId,
|
|
208
|
+
user_id: userId,
|
|
209
|
+
special_title: title,
|
|
210
|
+
});
|
|
211
|
+
return true;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
async setGroupName(groupId: number, name: string): Promise<boolean> {
|
|
215
|
+
await callApi(this.apiOptions(), 'set_group_name', { group_id: groupId, new_group_name: name });
|
|
216
|
+
return true;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
async getMemberList(groupId: number): Promise<unknown[]> {
|
|
220
|
+
return callApi(this.apiOptions(), 'get_group_member_list', { group_id: groupId }) as Promise<unknown[]>;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
async getGroupInfo(groupId: number): Promise<unknown> {
|
|
224
|
+
return callApi(this.apiOptions(), 'get_group_info', { group_id: groupId });
|
|
225
|
+
}
|
|
226
|
+
}
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Milky Webhook Bot:无长连接,在 router.post(path) 接收 POST 事件,鉴权后转 Message
|
|
3
|
+
*/
|
|
4
|
+
import { EventEmitter } from 'events';
|
|
5
|
+
import { Bot, Message, SendOptions, segment } from 'zhin.js';
|
|
6
|
+
import type { Router, RouterContext } from '@zhin.js/http';
|
|
7
|
+
import { callApi } from './api.js';
|
|
8
|
+
import type { MilkyWebhookConfig, MilkyEvent } from './types.js';
|
|
9
|
+
import type { MilkyAdapter } from './adapter.js';
|
|
10
|
+
import {
|
|
11
|
+
formatMilkyMessagePayload,
|
|
12
|
+
parseMessageReceiveData,
|
|
13
|
+
toMilkyOutgoingSegments,
|
|
14
|
+
parseMilkyMessageId,
|
|
15
|
+
} from './utils.js';
|
|
16
|
+
|
|
17
|
+
function getAccessTokenFromRequest(ctx: RouterContext): string | undefined {
|
|
18
|
+
const auth = ctx.headers['authorization'];
|
|
19
|
+
if (typeof auth === 'string' && auth.startsWith('Bearer ')) return auth.slice(7);
|
|
20
|
+
const q = ctx.request.query?.access_token;
|
|
21
|
+
return typeof q === 'string' ? q : undefined;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export class MilkyWebhookBot extends EventEmitter implements Bot<MilkyWebhookConfig, MilkyEvent> {
|
|
25
|
+
$connected: boolean = true;
|
|
26
|
+
|
|
27
|
+
get logger() {
|
|
28
|
+
return this.adapter.plugin.logger;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
constructor(
|
|
32
|
+
public adapter: MilkyAdapter,
|
|
33
|
+
public router: Router,
|
|
34
|
+
public $config: MilkyWebhookConfig,
|
|
35
|
+
) {
|
|
36
|
+
super();
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
get $id() {
|
|
40
|
+
return this.$config.name;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async $connect(): Promise<void> {
|
|
44
|
+
const path = this.$config.path.startsWith('/') ? this.$config.path : `/${this.$config.path}`;
|
|
45
|
+
const token = this.$config.access_token;
|
|
46
|
+
this.router.post(path, async (ctx: RouterContext) => {
|
|
47
|
+
const received = getAccessTokenFromRequest(ctx);
|
|
48
|
+
if (token && received !== token) {
|
|
49
|
+
ctx.status = 401;
|
|
50
|
+
ctx.body = { retcode: 401, message: 'Unauthorized' };
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
const body = ctx.request.body;
|
|
54
|
+
if (!body || typeof body !== 'object') {
|
|
55
|
+
ctx.status = 400;
|
|
56
|
+
ctx.body = { retcode: 400, message: 'Invalid JSON' };
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
const event = body as MilkyEvent;
|
|
60
|
+
this.handleEvent(event);
|
|
61
|
+
ctx.status = 200;
|
|
62
|
+
ctx.body = { retcode: 0 };
|
|
63
|
+
});
|
|
64
|
+
this.logger.info(`Milky Webhook 注册路径: ${path}`);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async $disconnect(): Promise<void> {
|
|
68
|
+
this.$connected = false;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
$formatMessage(event: MilkyEvent): Message<MilkyEvent> {
|
|
72
|
+
const data = parseMessageReceiveData(event);
|
|
73
|
+
if (!data) {
|
|
74
|
+
return Message.from(event, {
|
|
75
|
+
$id: '',
|
|
76
|
+
$adapter: 'milky',
|
|
77
|
+
$bot: this.$config.name,
|
|
78
|
+
$channel: { id: '', type: 'private' },
|
|
79
|
+
$sender: { id: '', name: '' },
|
|
80
|
+
$content: [],
|
|
81
|
+
$raw: '',
|
|
82
|
+
$timestamp: event.time ?? 0,
|
|
83
|
+
$recall: async () => {},
|
|
84
|
+
$reply: async () => '',
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
const payload = formatMilkyMessagePayload(
|
|
88
|
+
event,
|
|
89
|
+
data,
|
|
90
|
+
(id) => this.$recallMessage(id),
|
|
91
|
+
(channel, content) =>
|
|
92
|
+
this.adapter.sendMessage({
|
|
93
|
+
...channel,
|
|
94
|
+
context: 'milky',
|
|
95
|
+
bot: this.$config.name,
|
|
96
|
+
content: content as import('zhin.js').SendContent,
|
|
97
|
+
}),
|
|
98
|
+
'milky',
|
|
99
|
+
this.$config.name,
|
|
100
|
+
);
|
|
101
|
+
return Message.from(event, payload);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
private handleEvent(event: MilkyEvent): void {
|
|
105
|
+
const data = parseMessageReceiveData(event);
|
|
106
|
+
if (data) {
|
|
107
|
+
const message = this.$formatMessage(event);
|
|
108
|
+
this.adapter.emit('message.receive', message);
|
|
109
|
+
this.logger.debug(
|
|
110
|
+
`${this.$config.name} recv ${message.$channel.type}(${message.$channel.id}):${segment.raw(message.$content)}`,
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
private apiOptions() {
|
|
116
|
+
return { baseUrl: this.$config.baseUrl, access_token: this.$config.access_token };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async $sendMessage(options: SendOptions): Promise<string> {
|
|
120
|
+
const content = Array.isArray(options.content) ? options.content : [options.content];
|
|
121
|
+
const segments = content.map((c) =>
|
|
122
|
+
typeof c === 'string' ? { type: 'text' as const, data: { text: c } } : (c as { type: string; data?: Record<string, unknown> }),
|
|
123
|
+
);
|
|
124
|
+
const message = toMilkyOutgoingSegments(segments);
|
|
125
|
+
if (options.type === 'group') {
|
|
126
|
+
const result = await callApi(this.apiOptions(), 'send_group_message', {
|
|
127
|
+
group_id: parseInt(options.id, 10),
|
|
128
|
+
message,
|
|
129
|
+
});
|
|
130
|
+
const seq = (result as { message_seq?: number }).message_seq;
|
|
131
|
+
return seq != null ? `group:${options.id}:${seq}` : '';
|
|
132
|
+
}
|
|
133
|
+
if (options.type === 'private') {
|
|
134
|
+
const result = await callApi(this.apiOptions(), 'send_private_message', {
|
|
135
|
+
user_id: parseInt(options.id, 10),
|
|
136
|
+
message,
|
|
137
|
+
});
|
|
138
|
+
const seq = (result as { message_seq?: number }).message_seq;
|
|
139
|
+
return seq != null ? `friend:${options.id}:${seq}` : '';
|
|
140
|
+
}
|
|
141
|
+
throw new Error('Either group or private must be provided');
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async $recallMessage(id: string): Promise<void> {
|
|
145
|
+
const parsed = parseMilkyMessageId(id);
|
|
146
|
+
if (!parsed) throw new Error(`Invalid message id: ${id}`);
|
|
147
|
+
if (parsed.message_scene === 'group') {
|
|
148
|
+
await callApi(this.apiOptions(), 'recall_group_message', {
|
|
149
|
+
group_id: parsed.peer_id,
|
|
150
|
+
message_seq: parsed.message_seq,
|
|
151
|
+
});
|
|
152
|
+
} else {
|
|
153
|
+
await callApi(this.apiOptions(), 'recall_private_message', {
|
|
154
|
+
user_id: parsed.peer_id,
|
|
155
|
+
message_seq: parsed.message_seq,
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
async kickMember(groupId: number, userId: number, rejectAddRequest = false): Promise<boolean> {
|
|
161
|
+
await callApi(this.apiOptions(), 'kick_group_member', {
|
|
162
|
+
group_id: groupId,
|
|
163
|
+
user_id: userId,
|
|
164
|
+
reject_add_request: rejectAddRequest,
|
|
165
|
+
});
|
|
166
|
+
return true;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
async muteMember(groupId: number, userId: number, duration = 600): Promise<boolean> {
|
|
170
|
+
await callApi(this.apiOptions(), 'set_group_member_mute', {
|
|
171
|
+
group_id: groupId,
|
|
172
|
+
user_id: userId,
|
|
173
|
+
duration,
|
|
174
|
+
});
|
|
175
|
+
return true;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
async muteAll(groupId: number, enable = true): Promise<boolean> {
|
|
179
|
+
await callApi(this.apiOptions(), 'set_group_whole_mute', { group_id: groupId, is_mute: enable });
|
|
180
|
+
return true;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
async setAdmin(groupId: number, userId: number, enable = true): Promise<boolean> {
|
|
184
|
+
await callApi(this.apiOptions(), 'set_group_member_admin', {
|
|
185
|
+
group_id: groupId,
|
|
186
|
+
user_id: userId,
|
|
187
|
+
is_set: enable,
|
|
188
|
+
});
|
|
189
|
+
return true;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
async setCard(groupId: number, userId: number, card: string): Promise<boolean> {
|
|
193
|
+
await callApi(this.apiOptions(), 'set_group_member_card', {
|
|
194
|
+
group_id: groupId,
|
|
195
|
+
user_id: userId,
|
|
196
|
+
card,
|
|
197
|
+
});
|
|
198
|
+
return true;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
async setTitle(groupId: number, userId: number, title: string): Promise<boolean> {
|
|
202
|
+
await callApi(this.apiOptions(), 'set_group_member_special_title', {
|
|
203
|
+
group_id: groupId,
|
|
204
|
+
user_id: userId,
|
|
205
|
+
special_title: title,
|
|
206
|
+
});
|
|
207
|
+
return true;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
async setGroupName(groupId: number, name: string): Promise<boolean> {
|
|
211
|
+
await callApi(this.apiOptions(), 'set_group_name', { group_id: groupId, new_group_name: name });
|
|
212
|
+
return true;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
async getMemberList(groupId: number): Promise<unknown[]> {
|
|
216
|
+
return callApi(this.apiOptions(), 'get_group_member_list', { group_id: groupId }) as Promise<unknown[]>;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
async getGroupInfo(groupId: number): Promise<unknown> {
|
|
220
|
+
return callApi(this.apiOptions(), 'get_group_info', { group_id: groupId });
|
|
221
|
+
}
|
|
222
|
+
}
|