forked from TimeRainStarSky/Yunzai-QQBot-Plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
1675 lines (1526 loc) · 51.3 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
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import _ from 'lodash'
import fs from 'node:fs'
import QRCode from 'qrcode'
import { join } from 'node:path'
import imageSize from 'image-size'
import { randomUUID } from 'node:crypto'
import { encode as encodeSilk } from 'silk-wasm'
import {
Dau,
importJS,
Runtime,
Handler,
config,
configSave,
refConfig,
splitMarkDownTemplate,
getMustacheTemplating
} from './Model/index.js'
const QQBot = await (async () => {
try {
return (await import('qq-official-bot')).Bot
} catch (error) {
return (await import('qq-group-bot')).Bot
}
})()
const startTime = new Date()
logger.info(logger.yellow('- 正在加载 QQBot 适配器插件'))
const userIdCache = {}
const markdown_template = await importJS('Model/template/markdownTemplate.js', 'default')
const TmplPkg = await importJS('templates/index.js')
const adapter = new class QQBotAdapter {
constructor () {
this.id = 'QQBot'
this.name = 'QQBot'
this.path = 'data/QQBot/'
this.version = 'qq-group-bot v11.45.14'
if (typeof config.toQRCode == 'boolean') {
this.toQRCodeRegExp = config.toQRCode ? /(?<!\[(.*?)\]\()https?:\/\/[-\w_]+(\.[-\w_]+)+([-\w.,@?^=%&:/~+#]*[-\w@?^=%&/~+#])?/g : false
} else {
this.toQRCodeRegExp = new RegExp(config.toQRCode, 'g')
}
this.sep = config.sep || ((process.platform == 'win32') && '') || ':'
}
async makeRecord (file) {
if (config.toBotUpload) {
for (const i of Bot.uin) {
if (!Bot[i].uploadRecord) continue
try {
const url = await Bot[i].uploadRecord(file)
if (url) return url
} catch (err) {
Bot.makeLog('error', ['Bot', i, '语音上传错误', file, err])
}
}
}
const inputFile = join('temp', randomUUID())
const pcmFile = join('temp', randomUUID())
try {
fs.writeFileSync(inputFile, await Bot.Buffer(file))
await Bot.exec(`ffmpeg -i "${inputFile}" -f s16le -ar 48000 -ac 1 "${pcmFile}"`)
file = 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) { }
}
return file
}
async makeQRCode (data) {
return (await QRCode.toDataURL(data)).replace('data:image/png;base64,', 'base64://')
}
async makeRawMarkdownText (data, text, button) {
const match = text.match(this.toQRCodeRegExp)
if (match) {
for (const url of match) {
button.push(...this.makeButtons(data, [[{ text: url, link: url }]]))
const img = await this.makeMarkdownImage(data, await this.makeQRCode(url), '二维码')
text = text.replace(url, `${img.des}${img.url}`)
}
}
return text.replace(/@/g, '@')
}
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 makeMarkdownImage (data, file, summary = '图片') {
const buffer = await Bot.Buffer(file)
const image =
await this.makeBotImage(buffer) ||
{ url: await Bot.fileToUrl(file) }
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)
}
}
image.width = Math.floor(image.width * config.markdownImgScale)
image.height = Math.floor(image.height * config.markdownImgScale)
return {
des: `![${summary} #${image.width || 0}px #${image.height || 0}px]`,
url: `(${image.url})`
}
}
makeButton (data, button) {
const msg = {
id: randomUUID(),
render_data: {
label: button.text,
visited_label: button.clicked_text,
style: button.style ?? 1,
...button.QQBot?.render_data
}
}
if (button.input) {
msg.action = {
type: 2,
permission: { type: 2 },
data: button.input,
enter: button.send,
...button.QQBot?.action
}
} else if (button.callback) {
if (config.toCallback) {
msg.action = {
type: 1,
permission: { type: 2 },
...button.QQBot?.action
}
if (!Array.isArray(data._ret_id)) data._ret_id = []
data.bot.callback[msg.id] = {
id: data.message_id,
user_id: data.user_id,
group_id: data.group_id,
message: button.callback,
message_id: data._ret_id
}
setTimeout(() => delete data.bot.callback[msg.id], 300000)
} else {
msg.action = {
type: 2,
permission: { type: 2 },
data: button.callback,
enter: true,
...button.QQBot?.action
}
}
} else if (button.link) {
msg.action = {
type: 0,
permission: { type: 2 },
data: button.link,
...button.QQBot?.action
}
} else return false
if (button.permission) {
if (button.permission == 'admin') {
msg.action.permission.type = 1
} else {
msg.action.permission.type = 0
msg.action.permission.specify_user_ids = []
if (!Array.isArray(button.permission)) button.permission = [button.permission]
for (let id of button.permission) {
if (config.toQQUin && userIdCache[id]) id = userIdCache[id]
msg.action.permission.specify_user_ids.push(id.replace(`${data.self_id}${this.sep}`, ''))
}
}
}
return msg
}
makeButtons (data, button_square) {
const msgs = []
for (const button_row of button_square) {
const buttons = []
for (let button of button_row) {
button = this.makeButton(data, button)
if (button) buttons.push(button)
}
if (buttons.length) { msgs.push({ type: 'button', buttons }) }
}
return msgs
}
async makeRawMarkdownMsg (data, msg) {
const messages = []
const button = []
let content = ''
let reply
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 'record':
i.type = 'audio'
i.file = await this.makeRecord(i.file)
case 'video':
case 'face':
case 'ark':
case 'embed':
messages.push([i])
break
case 'file':
if (i.file) i.file = await Bot.fileToUrl(i.file, i.type)
content += await this.makeRawMarkdownText(data, `文件:${i.file}`, button)
break
case 'at':
if (i.qq == 'all') { content += '@everyone' } else { content += `<@${i.qq?.replace?.(`${data.self_id}${this.sep}`, '')}>` }
break
case 'text':
content += await this.makeRawMarkdownText(data, i.text, button)
break
case 'image': {
const { des, url } = await this.makeMarkdownImage(data, i.file, i.summary)
content += `${des}${url}`
break
} case 'markdown':
if (typeof i.data == 'object') messages.push([{ type: 'markdown', ...i.data }])
else content += i.data
break
case 'button':
button.push(...this.makeButtons(data, i.data))
break
case 'reply':
if (i.id.startsWith('event_')) {
reply = { type: 'reply', event_id: i.id.replace(/^event_/, '') }
} else {
reply = i
}
continue
case 'node':
for (const { message } of i.data) { messages.push(...(await this.makeRawMarkdownMsg(data, message))) }
continue
case 'raw':
messages.push(Array.isArray(i.data) ? i.data : [i.data])
break
default:
content += await this.makeRawMarkdownText(data, JSON.stringify(i), button)
}
}
if (content) { messages.unshift([{ type: 'markdown', content }]) }
if (button.length) {
for (const i of messages) {
if (i[0].type == 'markdown') { i.push(...button.splice(0, 5)) }
if (!button.length) break
}
while (button.length) {
messages.push([
{ type: 'markdown', content: ' ' },
...button.splice(0, 5)
])
}
}
if (reply) {
for (const i in messages) {
if (Array.isArray(messages[i])) messages[i].unshift(reply)
else messages[i] = [reply, messages[i]]
}
}
return messages
}
makeMarkdownText (data, text, button) {
const match = text.match(this.toQRCodeRegExp)
if (match) {
for (const url of match) {
button.push(...this.makeButtons(data, [[{ text: url, link: url }]]))
text = text.replace(url, '[链接(请点击按钮查看)]')
}
}
return text.replace(/\n/g, '\r').replace(/@/g, '@')
}
makeMarkdownTemplate (data, template) {
let keys; let custom_template_id; let params = []; let index = 0; let type = 0
const result = []
if (markdown_template) {
custom_template_id = markdown_template.custom_template_id
params = _.cloneDeep(markdown_template.params)
type = 1
} else {
const custom = config.customMD?.[data.self_id]
custom_template_id = custom?.custom_template_id || config.markdown[data.self_id]
keys = _.cloneDeep(custom?.keys) || config.markdown.template.split('')
}
for (const temp of template) {
if (!temp.length) continue
for (const i of splitMarkDownTemplate(temp)) {
if (index == (type == 1 ? markdown_template.params.length : keys.length)) {
result.push({
type: 'markdown',
custom_template_id,
params: _.cloneDeep(params)
})
params = type == 1 ? _.cloneDeep(markdown_template.params) : []
index = 0
}
if (type == 1) {
params[index].values = [i]
} else {
params.push({
key: keys[index],
values: [i]
})
}
index++
}
}
if (config.mdSuffix?.[data.self_id]) {
if (!params.some(p => config.mdSuffix[data.self_id].some(c => (c.key === p.key && p.values[0] !== '\u200B')))) {
for (const i of config.mdSuffix[data.self_id]) {
if (data.group_id) data.group = data.bot.pickGroup(data.group_id)
if (data.user_id) data.friend = data.bot.pickFriend(data.user_id)
if (data.user_id && data.group_id) data.member = data.bot.pickMember(data.group_id, data.user_id)
const value = getMustacheTemplating(i.values[0], { e: data })
params.push({ key: i.key, values: [value] })
}
}
}
if (params.length) {
result.push({
type: 'markdown',
custom_template_id,
params
})
}
return result
}
async makeMarkdownMsg (data, msg) {
const messages = []
const button = []
let template = []
let content = ''
let reply
const length = markdown_template?.params?.length || config.customMD?.[data.self_id]?.keys?.length || config.markdown.template.length
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 'record':
i.type = 'audio'
i.file = await this.makeRecord(i.file)
case 'video':
case 'face':
case 'ark':
case 'embed':
messages.push([i])
break
case 'file':
if (i.file) i.file = await Bot.fileToUrl(i.file, i, i.type)
button.push(...this.makeButtons(data, [[{ text: i.name || i.file, link: i.file }]]))
content += '[文件(请点击按钮查看)]'
break
case 'at':
if (i.qq == 'all') content += '@everyone'
else {
if (config.toQQUin && userIdCache[i.qq]) i.qq = userIdCache[i.qq]
content += `<@${i.qq?.replace?.(`${data.self_id}${this.sep}`, '')}>`
}
break
case 'text':
content += this.makeMarkdownText(data, i.text, button)
break
case 'node':
if (Handler.has('ws.tool.toImg') && config.toImg) {
const getButton = data => {
return data.flatMap(item => {
if (Array.isArray(item.message)) {
return item.message.flatMap(msg => {
if (msg.type === 'node') return getButton(msg.data)
if (msg.type === 'button') return msg
return []
})
}
if (typeof item.message === 'object') {
if (item.message.type === 'button') return item.message
if (item.message.type === 'node') return getButton(item.message.data)
}
return []
})
}
const btn = getButton(i.data)
let result = btn.reduce((acc, cur) => {
const duplicate = acc.find(obj => obj.text === cur.text && obj.callback === cur.callback && obj.input === cur.input && obj.link === cur.link)
if (!duplicate) return acc.concat([cur])
else return acc
}, [])
const e = {
reply: (msg) => {
i = msg
},
user_id: data.bot.uin,
nickname: data.bot.nickname
}
e.runtime = new Runtime(e)
i.data.cfg = { retType: 'msgId', returnID: true }
let { wsids } = await Handler.call('ws.tool.toImg', e, i.data)
if (!result.length && data.wsids && data.wsids?.fnc) {
wsids = wsids.map((id, k) => ({ text: `${data.wsids.text}${k}`, callback: `#ws查看${id}` }))
result = _.chunk(_.tail(wsids), data.wsids.col)
}
for (const b of result) {
button.push(...this.makeButtons(data, b.data ? b.data : [b]))
}
} else if (TmplPkg && TmplPkg?.nodeMsg) {
messages.push(...(await this.makeMarkdownMsg(data, TmplPkg.nodeMsg(i.data))))
continue
} else {
for (const { message } of i.data) {
messages.push(...(await this.makeMarkdownMsg(data, message)))
}
continue
}
case 'image': {
const { des, url } = await this.makeMarkdownImage(data, i.file, i.summary)
const limit = template.length % (length - 1)
// 图片数量超过模板长度时
if (template.length && !limit) {
if (content) template.push(content)
template.push(des)
} else template.push(content + des)
content = url
break
} case 'markdown':
if (typeof i.data == 'object') messages.push([{ type: 'markdown', ...i.data }])
else content += i.data
break
case 'button':
button.push(...this.makeButtons(data, i.data))
break
case 'reply':
if (i.id.startsWith('event_')) {
reply = { type: 'reply', event_id: i.id.replace(/^event_/, '') }
} else {
reply = i
}
continue
case 'raw':
messages.push(Array.isArray(i.data) ? i.data : [i.data])
break
case 'custom':
template.push(...i.data)
break
default:
content += this.makeMarkdownText(data, JSON.stringify(i), button)
}
}
if (content) template.push(content)
if (template.length > length) {
const templates = _(template).chunk(length).map(v => this.makeMarkdownTemplate(data, v)).value()
messages.push(...templates)
} else if (template.length) {
const tmp = this.makeMarkdownTemplate(data, template)
if (tmp.length > 1) {
messages.push(...tmp.map(i => ([i])))
} else {
messages.push(tmp)
}
}
if (template.length && button.length < 5 && config.btnSuffix[data.self_id]) {
let { position, values } = config.btnSuffix[data.self_id]
position = +position - 1
if (position > button.length) {
position = button.length
}
const btn = values.filter(i => {
if (i.show) {
switch (i.show.type) {
case 'random':
if (i.show.data <= _.random(1, 100)) return false
break
default:
break
}
}
return true
})
button.splice(position, 0, ...this.makeButtons(data, [btn]))
}
if (button.length) {
for (const i of messages) {
if (i[0].type == 'markdown') i.push(...button.splice(0, 5))
if (!button.length) break
}
while (button.length) {
messages.push([
...this.makeMarkdownTemplate(data, [' ']),
...button.splice(0, 5)
])
}
}
if (reply) {
for (const i of messages) {
i.unshift(reply)
}
}
return messages
}
async makeMsg (data, msg) {
const sendType = ['audio', 'image', 'video', 'file']
const messages = []
const button = []
let message = []
let reply
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 (config.toQQUin && userIdCache[user_id]) {
// i.qq = userIdCache[user_id]
// }
// i.qq = i.qq?.replace?.(`${data.self_id}${this.sep}`, "")
continue
case 'text':
case 'face':
case 'ark':
case 'embed':
break
case 'record':
i.type = 'audio'
i.file = await this.makeRecord(i.file)
case 'video':
case 'image':
if (message.some(s => sendType.includes(s.type))) {
messages.push(message)
message = []
}
break
case 'file':
if (i.file) i.file = await Bot.fileToUrl(i.file, i, i.type)
i = { type: 'text', text: `文件:${i.file}` }
break
case 'reply':
if (i.id.startsWith('event_')) {
reply = { type: 'reply', event_id: i.id.replace(/^event_/, '') }
} else {
reply = i
}
continue
case 'markdown':
if (typeof i.data == 'object') { i = { type: 'markdown', ...i.data } } else { i = { type: 'markdown', content: i.data } }
break
case 'button':
config.sendButton && button.push(...this.makeButtons(data, i.data))
continue
case 'node':
if (Handler.has('ws.tool.toImg') && config.toImg) {
const e = {
reply: (msg) => {
i = msg
},
user_id: data.bot.uin,
nickname: data.bot.nickname
}
e.runtime = new Runtime(e)
await Handler.call('ws.tool.toImg', e, i.data)
// i.file = await Bot.fileToUrl(i.file)
if (message.some(s => sendType.includes(s.type))) {
messages.push(message)
message = []
}
} else {
for (const { message } of i.data) {
messages.push(...(await this.makeMsg(data, message)))
}
}
break
case 'raw':
if (Array.isArray(i.data)) {
messages.push(i.data)
continue
}
i = i.data
break
default:
i = { type: 'text', text: JSON.stringify(i) }
}
if (i.type === 'text' && i.text) {
const match = i.text.match(this.toQRCodeRegExp)
if (match) {
for (const url of match) {
const msg = segment.image(await Bot.fileToUrl(await this.makeQRCode(url)))
if (message.some(s => sendType.includes(s.type))) {
messages.push(message)
message = []
}
message.push(msg)
i.text = i.text.replace(url, '[链接(请扫码查看)]')
}
}
}
if (i.type !== 'node') message.push(i)
}
if (message.length) { messages.push(message) }
while (button.length) {
messages.push([{
type: 'keyboard',
content: { rows: button.splice(0, 5) }
}])
}
if (reply) {
for (const i of messages) i.unshift(reply)
}
return messages
}
async sendMsg (data, send, msg) {
const rets = { message_id: [], data: [], error: [] }
let msgs
const sendMsg = async () => {
for (const i of msgs) {
try {
Bot.makeLog('debug', ['发送消息', i], data.self_id)
const ret = await send(i)
Bot.makeLog('debug', ['发送消息返回', ret], data.self_id)
rets.data.push(ret)
if (ret.id) rets.message_id.push(ret.id)
Bot[data.self_id].dau.setDau('send_msg', data)
} catch (err) {
// Bot.makeLog('error', ['发送消息错误', i, err], data.self_id)
logger.error(data.self_id, '发送消息错误', i, err)
rets.error.push(err)
return false
}
}
}
if (TmplPkg && TmplPkg?.Button && !data.toQQBotMD) {
let fncName = /\[.*?\((\S+)\)\]/.exec(data.logFnc)[1]
const Btn = TmplPkg.Button[fncName]
if (msg.type === 'node') data.wsids = { toImg: config.toImg }
let res
if (Btn) res = Btn(data, msg)
if (res?.nodeMsg) {
data.toQQBotMD = true
data.wsids = {
text: res.nodeMsg,
fnc: fncName,
col: res.col
}
} else if (res) {
data.toQQBotMD = true
res = segment.button(...res)
msg = _.castArray(msg)
let _btn = msg.findIndex(b => b.type === 'button')
if (_btn === -1) msg.push(res)
else msg[_btn] = res
}
}
if ((config.markdown[data.self_id] || (data.toQQBotMD === true && config.customMD[data.self_id])) && data.toQQBotMD !== false) {
if (config.markdown[data.self_id] == 'raw') msgs = await this.makeRawMarkdownMsg(data, msg)
else msgs = await this.makeMarkdownMsg(data, msg)
const [mds, btns] = _.partition(msgs[0], v => v.type === 'markdown')
if (mds.length > 1) {
for (const idx in mds) {
msgs = mds[idx]
if (idx === mds.length - 1) msgs.push(...btns)
await sendMsg()
}
return rets
}
} else {
msgs = await this.makeMsg(data, msg)
}
if (await sendMsg() === false) {
msgs = await this.makeMsg(data, msg)
await sendMsg()
}
if (Array.isArray(data._ret_id)) { data._ret_id.push(...rets.message_id) }
return rets
}
sendFriendMsg (data, msg, event) {
return this.sendMsg(data, msg => data.bot.sdk.sendPrivateMessage(data.user_id, msg, event), msg)
}
async sendGroupMsg (data, msg, event) {
if (Handler.has('QQBot.group.sendMsg')) {
const res = await Handler.call(
'QQBot.group.sendMsg',
data,
{
self_id: data.self_id,
group_id: `${data.self_id}${this.sep}${data.group_id}`,
raw_group_id: data.group_id,
user_id: data.user_id,
msg,
event
}
)
if (res !== false) {
return res
}
}
return this.sendMsg(data, msg => data.bot.sdk.sendGroupMessage(data.group_id, msg, event), msg)
}
async makeGuildMsg (data, msg) {
const messages = []
let message = []
let reply
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':
i.user_id = i.qq?.replace?.(/^qg_/, '')
case 'text':
case 'face':
case 'ark':
case 'embed':
break
case 'image':
message.push(i)
messages.push(message)
message = []
continue
case 'record':
case 'video':
case 'file':
if (i.file) i.file = await Bot.fileToUrl(i.file, i)
i = { type: 'text', text: `文件:${i.file}` }
break
case 'reply':
if (i.id.startsWith('event_')) {
reply = { type: 'reply', event_id: i.id.replace(/^event_/, '') }
} else {
reply = i
}
continue
case 'markdown':
if (typeof i.data == 'object') { i = { type: 'markdown', ...i.data } } else { i = { type: 'markdown', content: i.data } }
break
case 'button':
continue
case 'node':
for (const { message } of i.data) { messages.push(...(await this.makeGuildMsg(data, message))) }
continue
case 'raw':
if (Array.isArray(i.data)) {
messages.push(i.data)
continue
}
i = i.data
break
default:
i = { type: 'text', text: JSON.stringify(i) }
}
if (i.type == 'text' && i.text) {
const match = i.text.match(this.toQRCodeRegExp)
if (match) {
for (const url of match) {
const msg = segment.image(await this.makeQRCode(url))
message.push(msg)
messages.push(message)
message = []
i.text = i.text.replace(url, '[链接(请扫码查看)]')
}
}
}
message.push(i)
}
if (message.length) {
messages.push(message)
}
if (reply) {
for (const i of messages) i.unshift(reply)
}
return messages
}
async sendGMsg (data, send, msg) {
const rets = { message_id: [], data: [], error: [] }
let msgs
const sendMsg = async () => {
for (const i of msgs) {
try {
Bot.makeLog('debug', ['发送消息', i], data.self_id)
const ret = await send(i)
Bot.makeLog('debug', ['发送消息返回', ret], data.self_id)
rets.data.push(ret)
if (ret.id) rets.message_id.push(ret.id)
Bot[data.self_id].dau.setDau('send_msg', data)
} catch (err) {
// Bot.makeLog('error', ['发送消息错误', i, err], data.self_id)
logger.error(data.self_id, '发送消息错误', i, err)
rets.error.push(err)
return false
}
}
}
msgs = await this.makeGuildMsg(data, msg)
if (await sendMsg() === false) {
msgs = await this.makeGuildMsg(data, msg)
await sendMsg()
}
return rets
}
async sendDirectMsg (data, msg, event) {
if (!data.guild_id) {
if (!data.src_guild_id) {
Bot.makeLog('error', [`发送频道私聊消息失败:[${data.user_id}] 不存在来源频道信息`, msg], data.self_id)
return false
}
const dms = await data.bot.sdk.createDirectSession(data.src_guild_id, data.user_id)
data.guild_id = dms.guild_id
data.channel_id = dms.channel_id
data.bot.fl.set(`qg_${data.user_id}`, {
...data.bot.fl.get(`qg_${data.user_id}`),
...dms
})
}
return this.sendGMsg(data, msg => data.bot.sdk.sendDirectMessage(data.guild_id, msg, event), msg)
}
async recallMsg (data, recall, message_id) {
if (!Array.isArray(message_id)) message_id = [message_id]
const msgs = []
for (const i of message_id) {
try {
msgs.push(await recall(i))
} catch (err) {
Bot.makeLog('debug', ['撤回消息错误', i, err], data.self_id)
msgs.push(false)
}
}
return msgs
}
recallFriendMsg (data, message_id) {
Bot.makeLog('info', `撤回好友消息:[${data.user_id}] ${message_id}`, data.self_id)
return this.recallMsg(data, i => data.bot.sdk.recallFriendMessage(data.user_id, i), message_id)
}
recallGroupMsg (data, message_id) {
Bot.makeLog('info', `撤回群消息:[${data.group_id}] ${message_id}`, data.self_id)
return this.recallMsg(data, i => data.bot.sdk.recallGroupMessage(data.group_id, i), message_id)
}
recallDirectMsg (data, message_id, hide = config.hideGuildRecall) {
Bot.makeLog('info', `撤回${hide ? '并隐藏' : ''}频道私聊消息:[${data.guild_id}] ${message_id}`, data.self_id)
return this.recallMsg(data, i => data.bot.sdk.recallDirectMessage(data.guild_id, i, hide), message_id)
}
recallGuildMsg (data, message_id, hide = config.hideGuildRecall) {
Bot.makeLog('info', `撤回${hide ? '并隐藏' : ''}频道消息:[${data.channel_id}] ${message_id}`, data.self_id)
return this.recallMsg(data, i => data.bot.sdk.recallGuildMessage(data.channel_id, i, hide), message_id)
}
sendGuildMsg (data, msg, event) {
return this.sendGMsg(data, msg => data.bot.sdk.sendGuildMessage(data.channel_id, msg, event), msg)
}
pickFriend (id, user_id) {
if (config.toQQUin && userIdCache[user_id]) user_id = userIdCache[user_id]
if (user_id.startsWith('qg_')) return this.pickGuildFriend(id, user_id)
const i = {
...Bot[id].fl.get(user_id),
self_id: id,
bot: Bot[id],
user_id: user_id.replace(`${id}${this.sep}`, '')
}
return {
...i,
sendMsg: msg => this.sendFriendMsg(i, msg),
recallMsg: message_id => this.recallFriendMsg(i, message_id),
getAvatarUrl: () => `https://q.qlogo.cn/qqapp/${i.bot.info.appid}/${i.user_id}/0`
}
}
pickMember (id, group_id, user_id) {
if (config.toQQUin && userIdCache[user_id]) {
user_id = userIdCache[user_id]
}
if (user_id.startsWith('qg_')) { return this.pickGuildMember(id, group_id, user_id) }
const i = {
...Bot[id].fl.get(user_id),
...Bot[id].gml.get(group_id)?.get(user_id),
self_id: id,
bot: Bot[id],
user_id: user_id.replace(`${id}${this.sep}`, ''),
group_id: group_id.replace(`${id}${this.sep}`, '')
}
return {
...this.pickFriend(id, user_id),
...i
}
}
pickGroup (id, group_id) {
if (group_id.startsWith?.('qg_')) { return this.pickGuild(id, group_id) }
const i = {
...Bot[id].gl.get(group_id),
self_id: id,
bot: Bot[id],
group_id: group_id.replace?.(`${id}${this.sep}`, '') || group_id
}
return {
...i,
sendMsg: msg => this.sendGroupMsg(i, msg),
pickMember: user_id => this.pickMember(id, group_id, user_id),
recallMsg: message_id => this.recallGroupMsg(i, message_id),
getMemberMap: () => i.bot.gml.get(group_id)
}
}
pickGuildFriend (id, user_id) {
const i = {
...Bot[id].fl.get(user_id),
self_id: id,
bot: Bot[id],
user_id: user_id.replace(/^qg_/, '')
}
return {
...i,
sendMsg: msg => this.sendDirectMsg(i, msg),
recallMsg: (message_id, hide) => this.recallDirectMsg(i, message_id, hide)