-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
732 lines (689 loc) · 25.1 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
logger.info(logger.yellow('- 正在加载 Satori 适配器插件'))
import fs from 'node:fs'
import WebSocket from 'ws'
import fetch from 'node-fetch'
import { join } from 'node:path'
import imageSize from 'image-size'
import { parse } from 'node-html-parser'
import { encode as encodeSilk } from 'silk-wasm'
import { createHash, randomUUID } from 'node:crypto'
import Runtime from '../../lib/plugins/runtime.js'
import Handler from '../../lib/plugins/handler.js'
import makeConfig from '../../lib/plugins/config.js'
const { config, configSave } = await makeConfig('Satori', {
markdown: {
mode: false
},
img: 'md5',
node: 1,
toBotUpload: false,
token: []
})
class SatoriBot {
constructor(host, port, token) {
this.id = "QQ"
this.name = 'satori'
this.adapter = this
this.host = host
this.port = port
this.token = token
this.fl = new Map
this.gl = new Map
this.gml = new Map
this.stat = {
start_time: Date.now() / 1000
}
}
async sendApi(api, body) {
const res = await fetch(`http://${this.host}:${this.port}/v1/${api}`, {
method: 'POST',
body: JSON.stringify(body),
headers: {
'Authorization': `Bearer ${this.token}`,
'Content-Type': 'application/json',
'X-Platform': this.platform,
'X-Self-ID': this.self_id
}
})
return res.ok ? await res.json() : logger.error('请求失败', await res.text())
}
sendWs(op, body) {
this.ws.send(JSON.stringify({ op, body }))
}
pickGroup(group_id) {
const i = {
...this.gl.get(group_id),
group_id
}
return {
...i,
sendMsg: msg => this.sendGroupMsg(group_id, msg),
pickMember: user_id => this.pickMember(group_id, user_id),
recallMsg: message_id => this.deleteMsg(message_id),
muteMember: (user_id, duration) => this.mute(group_id, user_id, duration),
kickMember: (user_id) => this.setGroupKick(group_id, user_id, false),
quit: () => this.setGroupLeave(group_id),
makeForwardMsg: msg => { return { type: "node", data: msg } },
pokeMember: (user_id) => this.pickMember(group_id, user_id).poke(user_id),
getAvatarUrl: (size = 0, history = 0) => `https://p.qlogo.cn/gh/${group_id}/${group_id}${history ? "_" + history : ""}/` + size,
muteAll: (enable) => this.muteAll(group_id, enable)
}
}
pickFriend(user_id) {
const i = {
...this.gl.get(user_id),
user_id
}
return {
...i,
sendMsg: msg => this.sendPrivateMsg(user_id, msg),
recallMsg: message_id => this.deleteMsg(message_id),
delete: block => this.deleteFriend(user_id, block),
makeForwardMsg: msg => { return { type: "node", data: msg } },
poke: () => this.poke(`private:${user_id}`),
getAvatarUrl: (size = 0) => `https://q1.qlogo.cn/g?b=qq&s=${size}&nk=${user_id}`
}
}
pickMember(group_id, user_id) {
const i = {
...this.fl.get(user_id),
...this.gml.get(group_id)?.get(user_id),
group_id,
user_id
}
return {
...i,
...this.pickFriend(user_id),
kick: () => this.setGroupKick(group_id, user_id, false),
getAvatarUrl: (size = 0) => `https://q1.qlogo.cn/g?b=qq&s=${size}&nk=${user_id}`,
poke: (id) => this.poke(group_id, id ? id : user_id),
mute: (duration) => this.mute(group_id, user_id, duration)
}
}
deleteFriend(user_id, block) {
return this.sendApi('unsafe.friend.remove', { user_id })
}
async sendGroupMsg(group_id, msg) {
let content, log
if (config.markdown.mode) {
[content, log] = await this.makeMarkdownMsg(msg)
} else {
[content, log] = await this.msgToContent(msg)
}
logger.info(`${logger.blue(`[${this.uin} => ${group_id}]`)} 发送群消息:${log}`)
const result = (await this.sendApi('message.create', {
channel_id: group_id,
content
}))?.pop()
return result ? { message_id: `${group_id}-${result.id}` } : logger.error('发送群聊消息失败: 暂不支持此类型消息')
}
async sendPrivateMsg(user_id, msg) {
let content, log
if (config.markdown.mode) {
[content, log] = await this.makeMarkdownMsg(msg)
} else {
[content, log] = await this.msgToContent(msg)
}
logger.info(`${logger.blue(`[${this.uin} => ${user_id}]`)} 发送好友消息:${log}`)
const result = (await this.sendApi('message.create', {
channel_id: `private:${user_id}`,
content
}))?.pop()
return result ? { message_id: `private:${user_id}-${result.id}` } : logger.error('发送好友消息失败: 暂不支持此类型消息')
}
/**
* @param guild_id 群id
* @param user_id 被禁言的用户id
* @param duration 禁言时长(毫秒),默认10分钟
*/
mute(guild_id, user_id, duration = 600000) {
return this.sendApi('guild.member.mute', {
channel_id: guild_id,
user_id: String(user_id),
duration: duration
})
}
/**
* @param channel_id 群id
* @param {boolean} enable 是否禁言
*/
muteAll(channel_id, enable) {
return this.sendApi('unsafe.channel.mute', {
channel_id: channel_id,
enable: enable
})
}
setGroupKick(guild_id, user_id, permanent) {
return this.sendApi('guild.member.kick', {
channel_id: guild_id,
user_id: String(user_id),
permanent: permanent
})
}
setGroupLeave(guild_id) {
return this.sendApi('unsafe.guild.remove', { guild_id })
}
poke(channel_id, user_id) {
const content = user_id ? `<chronocat:poke user-id="${user_id}"/>` : `<chronocat:poke />`
let result = this.sendApi('message.create', {
channel_id: channel_id,
content
})
if (!Array.isArray(result)) {
result = [result]
}
const poppedResult = result.pop()
return {
message_id: `${channel_id}-${poppedResult.id}`
}
}
async getFriendList() {
const friend_list = await this.sendApi('friend.list', { next: '' })
for (const i of friend_list.data) {
// bug: login.get没有name
if (i.id == this.self_id) {
this.nickname = i.name
}
this.fl.set(i.id, {
...i,
bot_id: this.self_id,
user_id: i.id,
nickname: i.name,
remark: i.nick
})
}
return this.fl
}
async getGroupList() {
const group_list = await this.sendApi('guild.list', { next: '' })
for (const i of group_list.data) {
this.gl.set(i.id, {
...i,
bot_id: this.self_id,
group_id: i.id,
group_name: i.name,
})
}
return this.gl
}
deleteMsg(id) {
const [channel_id, message_id] = id.split('-')
return this.sendApi('message.delete', { channel_id, message_id })
}
async makeBot(data, bot) {
Bot[data.self_id] = bot
if (!Bot.uin.includes(data.self_id))
Bot.uin.push(data.self_id)
const info = await bot.sendApi('login.get')
bot.info = {
...info,
...info.user,
uin: info.self_id,
user_id: info.self_id,
nickname: info.user.name
}
this.platform = info.platform
this.self_id = info.self_id
this.uin = info.self_id
this.avatar = info.user.avatar
this.getGroupList()
this.getFriendList()
logger.mark(`${logger.blue(`[${data.self_id}]`)} ${this.name}(${this.id}) ${bot.version.version} 已连接`)
Bot.em(`connect.${data.self_id}`, data)
}
async makeMessage(data, bot) {
let event, e = {
bot,
adapter: bot.adapter,
user_id: data.user.id,
nickname: data.user.name,
self_id: data.self_id
}
switch (data.type) {
// 收到消息
case 'message-created':
e.post_type = 'message'
e.sender = {
user_id: data.user.id,
nickname: data.user.name,
}
e.message_id = data.message.id
let content
[e.message, content] = await this.contentToMsg(data.message.content)
e.raw_message = content || data.message.content
if (e.message.length == 0) {
return
}
if (e.message.some(i => i.type === 'chronocat:poke')) {
e.sub_type = 'poke'
} else {
if (data.channel.type == 0) {
e.message_type = 'group'
e.sub_type = 'normal'
e.group_name = data.guild.name
e.group_id = data.guild.id
logger.info(`${logger.blue(`[${e.self_id}]`)} 群消息:[${e.group_name}(${e.group_id}), ${e.nickname}(${e.user_id})] ${e.raw_message}`)
} else {
e.message_type = 'private'
e.sub_type = 'friend'
logger.info(`${logger.blue(`[${e.self_id}]`)} 好友消息:[${e.nickname}(${e.user_id})] ${e.raw_message}`)
}
event = `${e.post_type}.${e.message_type}.${e.sub_type}`
}
break
// 解除禁言
case 'unsafe-guild-unmute':
e.duration = 0
break
// 群禁言
case 'unsafe-guild-mute':
e.sub_type ||= 'ban'
break
// 群员增加
case 'guild-member-added':
e.post_type = 'notice'
e.notice_type = 'group'
e.sub_type ||= 'increase';
e.nickname = data.user.name
e.group_id = data.guild.id
event = `${e.post_type}.${e.notice_type}.${e.sub_type}`
break
// 新增群员
case 'guild-member-added':
// {
// id: number,
// type: 'guild-member-added',
// platform: string,
// self_id: string,
// timestamp: number,
// user: {
// name: string,
// avatar: string
// },
// channel: { type: number, id: string, name: string },
// guild: {
// id: string,
// name: string,
// avatar: string
// },
// member: {},
// message: { id: string, content: string },
// operator: {}
// }
break
default:
break
}
event && Bot.em(event, e)
}
makeEvents(data, bot) {
try {
data = JSON.parse(data)
} catch (error) {
logger.error(`数据解码失败`, data)
}
switch (data.op) {
case 0:
this.makeMessage(data.body, bot)
break
case 2:
break
case 4:
this.makeBot(data.body.logins[0], bot)
break
default:
break
}
}
async contentToMsg(content) {
const root = parse(content, { blockTextElements: { script: false, style: false, pre: false } })
const msg = []
let msg_content = ''
for (const i of root.childNodes) {
const data = {}
if (i.rawTagName) {
data.type = i.rawTagName
for (const attr of i.rawAttrs.split(' ')) {
let [key, value] = attr.split('=')
data[key] = value?.replace(/"/g, '')
}
} else {
data.type = 'text'
data.text = i.rawText
}
// for (const c of i.childNodes) {
// data.child.push(...await this.contentToMsg(c))
// }
switch (data.type) {
case 'at':
data.qq = data.id
msg_content += `{at: ${data.id}} `
break
case 'text':
msg_content += data.text
break
case 'img':
data.type = 'image'
switch (config.img) {
case 'raw':
data.url = data.src
break
case 'md5':
data.url = `https://gchat.qpic.cn/gchatpic_new/0/0-0-${await this.getImageMD5(data.src)}/0`
break
default:
data.url = data.src
break
}
msg_content += `{image:${await this.getImageMD5(data.src)}}`
break
case 'audio':
data.type = 'record'
data.url = data.src
msg_content += `{ptt:}`
break
// case 'video':
// break
case 'chronocat:poke':
break
case 'chronocat:pcpoke':
data.type = 'poke'
msg_content += `{poke: ${data.id}}`
break
case 'chronocat:face':
data.type = 'face'
msg_content += `{face:${data.id},text:${data.name}}`
break
default:
continue
}
msg.push(data)
}
return [msg, msg_content]
}
async msgToContent(msg) {
if (!Array.isArray(msg)) msg = [msg]
let content = '', log = ''
for (let i of msg) {
if (typeof i != 'object') i = { type: 'text', text: i }
switch (i.type) {
case 'reply':
content += `<quote id="${i.id}"/>`
break
case 'text':
content += i.text
log += i.text
break
case 'at':
if (i.qq == 'all') {
content += `<at type="all"/>`
} else {
content += `<at id="${i.qq}"/>`
}
log += `@${i.qq}`
break
case 'image':
content += `<img src="${this.getImageContent(i.file)}"/>`
log += '[图片]'
break
case 'record':
content += `<audio src="${await this.getRecordContent(i.file)}"/>`
log += '[语音]'
break
case 'poke':
//发送窗口戳一戳 示例: e.reply({ type: 'poke', id: 1 })
content += `<chronocat:pcpoke id="${i.id}">`
log += '[戳一戳]'
break
case 'face':
//发送qq表情 示例: e.reply({ type: 'face', id: 11 })
content += `<chronocat:face id="${i.id}">`
log += '[表情]'
break
case 'markdown':
content += await this.makeMarkdownMsg(msg)
log += '[markdown消息]'
break
case 'node':
switch (config.node) {
case 2:
for (const { message, user_id, nickname } of i.data) {
const { content: c, log: l } = await this.msgToContent(message)
content += `<message>${c}</message>`
log += l
}
break
case 3:
if (Handler.has('ws.tool.toImg')) {
const e = {
reply: (msg) => {
content += `<img src="${this.getImageContent(msg.file)}"/>`
log += '[图片]'
},
user_id: this.self_id,
nickname: this.nickname
}
e.runtime = new Runtime(e)
await Handler.call('ws.tool.toImg', e, i.data)
break
}
default:
content += '<message>'
for (const { message, user_id, nickname } of i.data) {
const { content: c, log: l } = await this.msgToContent(message)
content += `<author id="${user_id || this.self_id} name="${this.nickname}">${c}<author/><br/>`
log += l
}
content += '</message>'
break
}
break
default:
break
}
}
return [content, log]
}
async getImageMD5(url) {
const buffer = Buffer.from(await (await fetch(url)).arrayBuffer())
const hash = createHash('md5')
hash.update(buffer)
return hash.digest('hex').toUpperCase()
}
getImageContent(data) {
let buffer, contentType = 'image/png', content
if (Buffer.isBuffer(data)) {
buffer = data
} else if (data.match(/^base64:\/\//)) {
buffer = Buffer.from(data.replace(/^base64:\/\//, ""), 'base64')
} else if (data.match(/^(http|file:\/\/)/)) {
content = data
} else {
try {
buffer = fs.readFileSync(data)
contentType = mimeTypes[extname(data)]
} catch (error) {
buffer = Buffer.from(data, 'base64')
contentType = 'image/png'
}
}
if (buffer) {
return `data:${contentType};base64,${buffer.toString('base64')}`
}
return content
}
async getRecordContent(data) {
let buffer
const inputFile = join('temp', randomUUID())
const pcmFile = join('temp', randomUUID())
try {
fs.writeFileSync(inputFile, await Bot.Buffer(data))
await Bot.exec(`ffmpeg -i "${inputFile}" -f s16le -ar 48000 -ac 1 "${pcmFile}"`)
buffer = Buffer.from((await encodeSilk(fs.readFileSync(pcmFile), 48000)).data)
} catch (err) {
logger.error(`silk 转码错误:${err}`)
}
for (const i of [inputFile, pcmFile]) {
try {
fs.unlinkSync(i)
} catch (err) { }
}
if (buffer) return `data:application/octet-stream;base64,${buffer.toString('base64')}`
}
async makeBotImage(file) {
if (config.toBotUpload) {
for (const i of Bot.uin) {
if (!Bot[i].uploadImage) continue
try {
const image = await Bot[i].uploadImage(file)
if (image.url) return image
} catch (err) {
Bot.makeLog('error', ['Bot', i, '图片上传错误', file, err])
}
}
}
}
async makeMarkdownMsg(msg) {
let content = '<chronocat:markdown>', log = '[markdown消息]', markdown = false
for (let i of Array.isArray(msg) ? msg : [msg]) {
if (typeof i == "object")
i = { ...i }
else
i = { type: "text", text: i }
switch (i.type) {
case "at":
if (i.qq == "all") {
content += `[@全体成员](mqqapi://markdown/mention?at_type=everyone)`
} else {
if (i.name) i.name += `(${i.qq})`
else i.name = i.qq
content += `[@${i.name}](mqqapi://markdown/mention?at_type=1&at_tinyid=${i.qq})`
}
markdown = true
break
case "text":
content += `${this.makeMarkdownText(i.text)}`
markdown = true
break
case "image":
const { des, url } = await this.makeMarkdownImage(i.file)
if (!des || !url) {
content = '', log = ''
markdown = false
return await this.msgToContent(msg)
} else {
content += `${des}${url}`
markdown = true
}
break
case "markdown":
content += `${i.data}`
markdown = true
break
default:
content = '', log = ''
markdown = false
return await this.msgToContent(msg)
}
}
if (markdown === true) content += `</chronocat:markdown>`
return [content, log]
}
makeMarkdownText(text) {
let match
try { match = text.match(/https?:\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/g) } catch { }
if (match) for (const url of match)
text = text.replace(url, `<${url}>`)
return text
}
async makeMarkdownImage(file) {
const image = await this.makeBotImage(file)
if (!image) return false
if (!image.width || !image.height) {
try {
const size = imageSize(buffer)
image.width = size.width
image.height = size.height
} catch (err) {
Bot.makeLog('error', ['图片分辨率检测错误', file, err], data.self_id)
}
}
return {
des: `![图片 #${image?.width || 0}px #${image?.height || 0}px]`,
url: `(${image?.url})`,
}
}
}
const adapter = new class Adapter {
constructor() {
this.id = "QQ"
this.name = 'satori'
}
async connect(data) {
const [host, port, token] = data.split(':')
const bot = new SatoriBot(host, port, token)
try {
const [name, version] = (await fetch(`http://${host}:${port}`)).headers.get('server').split('/')
bot.version = {
id: this.id,
name: this.name,
version
}
} catch (error) {
logger.error(error)
return false
}
bot.ws = new WebSocket(`http://${host}:${port}/v1/events`)
bot.ws.on('open', () => {
bot.sendWs(3, { token })
setInterval(() => {
bot.sendWs(1)
}, 10 * 1000)
})
bot.ws.on('message', events => bot.makeEvents(events, bot))
bot.ws.on('close', () => { })
return true
}
async load() {
for (const token of config.token) {
await new Promise(resolve => {
adapter.connect(token).then(resolve)
setTimeout(resolve, 5000)
})
}
}
}()
Bot.adapter.push(adapter)
export class SatoriAdapter extends plugin {
constructor() {
super({
name: 'SatoriAdapter',
dsc: 'Satori 适配器设置',
event: 'message',
rule: [
{
reg: /^#Satori设置.+:.+:.+$/i,
fnc: 'Token',
permission: 'master'
},
]
})
}
async Token() {
const token = this.e.msg.replace(/^#Satori设置/i, '').trim()
if (config.token.includes(token)) {
config.token = config.token.filter(item => item != token)
this.reply(`账号已删除,重启后生效,共${config.token.length}个账号`, true)
} else {
if (await adapter.connect(token)) {
config.token.push(token)
this.reply(`账号已连接,共${config.token.length}个账号`, true)
} else {
this.reply('账号连接失败', true)
return false
}
}
await configSave()
}
}
logger.info(logger.green('- Satori 适配器插件 加载完成'))