This repository was archived by the owner on Aug 21, 2026. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathhuhobot.js
More file actions
1320 lines (1209 loc) · 35 KB
/
Copy pathhuhobot.js
File metadata and controls
1320 lines (1209 loc) · 35 KB
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
//LiteLoaderScript Dev Helper
/// <reference path="E:\\MCServer\\HelperLib\\src\\index.d.ts"/>
const UPDATEURL =
"https://huhobot.release.txssb.cn/lse/HuHoBot-BDS-{VERSION}.js";
const LATESTURL = "https://huhobot.release.txssb.cn/lse/latest.json";
const VERSION = "0.3.7";
const CONFIG_VERSION = 8;
const PLUGINNAME = "HuHoBot";
const PATH = `plugins/${PLUGINNAME}/`;
const CONFIGPATH = `${PATH}config.json`;
const CUSTOM_MARKDOWN_PATH = `${PATH}online.md`;
const BLOCKPATH = `${PATH}blockMsg.json`;
const BDSALLOWLISTPATH = "allowlist.json";
const RECONNECT_INTERVAL = 5000;
const MAX_RECONNECT_RETRIES = 5;
const ALLOWLIST_PAGE_SIZE = 10;
const HEARTBEAT_INTERVAL = 5000;
const AUTO_RECONNECT_TIMEOUT = 6 * 60 * 60 * 1000;
let WebsocketObject = null;
let cachedConfig = null;
/**
* 获取配置(带缓存)
* @param {boolean} forceReload 是否强制重新读取
* @returns {Object}
*/
function getConfig(forceReload = false) {
if (!cachedConfig || forceReload) {
cachedConfig = readFile(CONFIGPATH);
}
return cachedConfig;
}
let callbackEvent = {
run: {},
runAdmin: {},
inline: {},
};
logger.setTitle(PLUGINNAME);
/**
* 读取文件
* @param {string} file
* @returns
*/
function readFile(file) {
try {
return JSON.parse(File.readFrom(file));
} catch (_) {
logger.error("文件读取出错,请尝试清空数据");
return {};
}
}
/**
* 写入文件
* @param {string} file
* @param {Object} data
* @returns
*/
function writeFile(file, data) {
return File.writeTo(file, JSON.stringify(data, null, "\t"));
}
/**
* 分割数组
* @param {Array} array
* @param {number} itemsPerPage
* @returns
*/
function paginateArray(array, itemsPerPage) {
let pages = [];
try {
for (let i = 0; i < array.length; i += itemsPerPage) {
pages.push(array.slice(i, i + itemsPerPage));
}
} catch (_) {
pages.push("白名单解析出现异常,请管理员检查白名单");
}
return pages;
}
/**
* 数组搜索关键词
* @param {Array} array 需要查询的数组
* @param {string} keyword 关键词
* @param {boolean} caseInsensitive 是否进行大小写不敏感的搜索
* @returns
*/
function filterByKeyword(array, keyword, caseInsensitive = true) {
// 使用filter方法查询包含关键词的元素
return array.filter((item) => {
// 如果需要大小写不敏感的搜索,将item和keyword都转换为小写
if (caseInsensitive) {
return item.toLowerCase().includes(keyword.toLowerCase());
} else {
return item.includes(keyword);
}
});
}
/**
* 为当前支持的配置结构补齐缺失字段
* @param {Object} rawConfig
* @returns {{config: Object, changedFields: string[]}}
*/
function applyConfigDefaults(rawConfig) {
const config = { ...(rawConfig || {}) };
const changedFields = [];
const motd =
config.motd != null &&
typeof config.motd === "object" &&
!Array.isArray(config.motd)
? { ...config.motd }
: {};
if (config.connectMethod == null) {
config.connectMethod = 1;
changedFields.push("connectMethod");
}
if (
config.motd == null ||
typeof config.motd !== "object" ||
Array.isArray(config.motd)
) {
changedFields.push("motd");
}
if (motd.markdown == null) {
motd.markdown = true;
changedFields.push("motd.markdown");
}
if (motd.customMarkdown == null) {
motd.customMarkdown = false;
changedFields.push("motd.customMarkdown");
}
config.motd = motd;
return { config, changedFields };
}
/**
* 补齐当前配置缺失的受支持字段
* @returns {boolean} 是否写回了配置
*/
function repairCurrentConfig() {
const currentConfig = getConfig();
const { config, changedFields } = applyConfigDefaults(currentConfig);
if (changedFields.length === 0) {
return false;
}
config.version = currentConfig.version;
writeFile(CONFIGPATH, config);
getConfig(true);
logger.info(`已补齐缺失配置项: ${changedFields.join(", ")}`);
return true;
}
/**
* 获取在线玩家名称列表
* @param {Object} config
* @returns {string[]}
*/
function getOnlinePlayerNames(config) {
const onlinePlayers = mc.getOnlinePlayers();
const playerNames = [];
for (let i = 0; i < onlinePlayers.length; i++) {
let playerName = onlinePlayers[i].name;
if (
onlinePlayers[i].isSimulatedPlayer() &&
config.addSimulatedPlayerTip === true
) {
playerName += "(假人)";
}
playerNames.push(playerName);
}
return playerNames;
}
/**
* 生成查询在线消息
* @param {string[]} playerNames
* @returns {string}
*/
function motdMsgBuilder(playerNames) {
const config = getConfig();
const motd = config.motd || {};
const useMarkdown = motd.markdown === true;
const outputOnlineList = motd.output_online_list === true;
const textTemplate = typeof motd.text === "string" ? motd.text : "";
if (useMarkdown) {
return playerNames.join(", ");
}
let result = "";
if (outputOnlineList) {
if (playerNames.length > 0) {
result += "\n在线玩家列表:\n";
for (let i = 0; i < playerNames.length; i++) {
result += playerNames[i] + "\n";
}
} else {
result += "\n当前没有在线玩家\n";
}
}
result += textTemplate.replace("{online}", playerNames.length.toString());
return result;
}
/**
* 读取自定义在线 Markdown 内容
* @returns {string}
*/
function readCustomMarkdown() {
try {
const content = File.readFrom(CUSTOM_MARKDOWN_PATH);
if (typeof content !== "string") {
throw new Error("online.md read result is not string");
}
return content;
} catch (_) {
logger.warn(
"无法读取online.md,请检查文件是否存在(该文件需要手动创建)。",
);
return "";
}
}
/**
* 注册一个回调事件
* @param {"run"|"runAdmin"|"inline"} callType
* @param {string} keyWord
* @param {string} nameSpace
* @param {string} funcName
* @returns boolean 是否注册成功
*/
function regCallbackEvent(callType, keyWord, nameSpace, funcName) {
if (typeof keyWord !== "string") {
return false;
}
if (keyWord.startsWith("#")) {
callType = "inline";
}
if (!(callType in callbackEvent)) {
return false;
}
if (!ll.hasExported(nameSpace, funcName)) {
return false;
}
let func = ll.imports(nameSpace, funcName);
if (callType == "inline") {
if (!(keyWord in callbackEvent.inline)) {
callbackEvent.inline[keyWord] = [];
}
callbackEvent.inline[keyWord].push(func);
} else {
if (keyWord in callbackEvent[callType]) {
return false;
}
callbackEvent[callType][keyWord] = func;
}
logger.info(
`注册${callType}类型事件: 关键词(${keyWord}) 回调函数(${nameSpace}::${funcName}) 成功`,
);
return true;
}
/**
* 调用指定内置事件下注册的全部回调
* @param {string} keyWord
* @param {object} body
*/
function callInlineEvent(keyWord, body) {
let callbacks = callbackEvent.inline[keyWord] || [];
for (let i = 0; i < callbacks.length; i++) {
callbacks[i](body);
}
}
/**
* 发送一条自定义消息
* @param {string} msg 消息内容
* @param {string} msgType 消息类型(默认为"聊天")
*/
function postCustomMsg(msg, msgType = "聊天") {
if (WebsocketObject) {
WebsocketObject._postChat(msg, msgType);
return true;
}
logger.warn("服务端链接未初始化,无法发送消息");
return false;
}
class FWebsocketClient {
constructor(name, log) {
this.name = name;
this.log = log;
let WSC = new WSClient();
this.WSC = WSC;
WSC.Open = 0;
WSC.Closing = 1;
WSC.Closed = 2;
this.isShakeHand = false;
this.tryConnect = false;
this.heart = null;
//事件监听
this.Events = {
shaked: null,
chat: null,
success: null,
add: null,
delete: null,
cmd: null,
queryList: null,
queryOnline: null,
shutdown: null,
};
this.autoReconnect = null;
this.bindMap = {};
this._InitMsgProcess();
}
_ConnectDone(isSuccess) {
if (isSuccess) {
logger.info(`服务端连接成功!`);
logger.info(`开始握手...`);
this._sendShakeHand();
} else {
logger.error(`服务端连接失败,请检查后尝试手动重连.`);
}
}
/**
* 连接服务器
* @param {"nginx"|"direct"|"local"} connectLinkType
* @returns boolean 是否连接成功.
*/
_Connect() {
let config = getConfig();
let connectMethod = config.connectMethod || 0;
if (connectMethod == 0) {
logger.info(`正在使用同步方法连接服务器...`);
let isSuccess = this.WSC.connect(wsPath_Direct);
this._ConnectDone(isSuccess);
return isSuccess;
} else {
logger.info(`正在使用异步方法连接服务器...`);
let isSuccess = this.WSC.connectAsync(wsPath_Direct, (success) => {
this._ConnectDone(success);
});
return isSuccess;
}
}
/**
* 重连服务器
* 注意:异步连接模式下 _Connect 的返回值不代表最终连接结果,
* 但保留 Promise 结构以兼容现有调用链。
* @returns
*/
_ReConnect() {
this._Close();
let config = getConfig();
this.name = config.serverName;
let isSuccess = this._Connect();
return new Promise((cBack, _cErr) => {
cBack(isSuccess);
});
}
/**
* 断开与服务器连接
* @returns
*/
_Close() {
this.isShakeHand = false;
this.tryConnect = false;
if (this.WSC.status == this.WSC.Open) {
return this.close(false);
}
return this.close(true);
}
/**
* Websocket内置方法-设定监听消息
*/
_InitMsgProcess() {
let wsc = this.WSC;
wsc.listen("onBinaryReceived", (data) => {
logger.warn("客户端不支持Binary消息!自动断开!");
this._Close();
});
wsc.listen("onError", (msg) => {
logger.error(`WSC出现异常: ${msg}`);
let forceReconnect = msg.indexOf("select") >= 0;
this._handleConnectionError(forceReconnect);
});
wsc.listen("onLostConnection", (code) => {
logger.warn(`WSC服务器连接丢失!CODE: ${code}`);
let allowErrorCode = [1006];
let forceReconnect = allowErrorCode.indexOf(code) >= 0;
this._handleConnectionError(forceReconnect);
});
wsc.listen("onTextReceived", (msg) => {
try {
let json = JSON.parse(msg);
//log(json)
this._processMessage(json.header, json.body);
} catch (_) {
logger.error(_);
logger.error(`WSC无法解析接收到的字符串!`);
logger.info(`重新尝试连接...`);
setTimeout(() => {
this._ReConnect();
}, RECONNECT_INTERVAL);
}
});
}
/**
* 处理连接错误
*/
_handleConnectionError(forceReconnect = false) {
// 清除心跳定时器
if (this.heart) {
clearInterval(this.heart);
this.heart = null;
}
if (!this.tryConnect && !forceReconnect) {
logger.warn("当前已取消自动重连,请检查后手动使用/huhobot reconnect重连");
return;
}
logger.info("正在尝试自动重连...");
this._attemptReconnect();
}
/**
* 自动重连
*/
_attemptReconnect() {
let reConnectCount = 0;
const reConnect = () => {
reConnectCount++;
if (reConnectCount >= MAX_RECONNECT_RETRIES) {
logger.warn(
`已尝试${MAX_RECONNECT_RETRIES}次自动重连失败,请检查后输入/huhobot reconnect重连`,
);
return;
}
setTimeout(() => {
this._ReConnect().then((success) => {
if (!success) {
logger.warn(`第${reConnectCount}次重连失败,继续尝试...`);
reConnect();
}
});
}, RECONNECT_INTERVAL);
};
reConnect();
}
/**
* 向服务器发送响应
* @param {object} msg
* @param {Array} groupId
* @param {"success"|"error"} type
* @param {string} uuid
*/
_Respone(msg, groupId, type, uuid = "") {
let config = getConfig();
let callbackConvertImg = config.callbackConvertImg;
this._sendMsg(
type,
{ msg: msg, group: groupId, callbackConvert: callbackConvertImg },
uuid,
);
}
/**
* 执行命令并发送响应
* @param {string} cmd 要执行的命令
* @param {Array} groupId 群组ID
* @param {string} id 消息ID
* @param {string} successPrefix 成功时的前缀
* @param {string} failPrefix 失败时的前缀
* @returns {object} 命令执行结果
*/
_executeAndRespond(cmd, groupId, id, successPrefix, failPrefix) {
let output = mc.runcmdEx(cmd);
let msg = (output.success ? successPrefix : failPrefix) + output.output;
this._Respone(msg, groupId, output.success ? "success" : "error", id);
return output;
}
/**
* 运行事件
* @param {"shaked"|"chat"|"success"|"add"|"delete"|"cmd"|"queryList"|"queryOnline"|"shutdown"} type
* @param {string} id
* @param {object} body
*/
_runEvent(type, id, body) {
if (this.Events[type] == null) {
throw new Error(`事件[${type}]不存在!`);
}
try {
let res = this.Events[type](id, body);
} catch (e) {
logger.error(`在运行事件[${type}]时遇到错误: ${e}\n${e.stack}`);
if (type != "shutdown") {
logger.info(`正在重新连接...`);
setTimeout(() => {
this._ReConnect();
}, RECONNECT_INTERVAL);
}
}
}
/**
* 消息处理
* @param {{"type":string,"id":string}} header
* @param {object} body
*/
_processMessage(header, body) {
if (header.id == null) {
logger.info(`收到特殊消息: ${body.msg}, 正在尝试重新连接...`);
setTimeout(() => {
this._ReConnect();
}, RECONNECT_INTERVAL);
return;
}
try {
switch (header.type) {
case "shaked":
this.onShaked(header.id, body);
break;
case "chat":
this.onChat(header.id, body);
break;
case "add":
this.onAddAllowList(header.id, body);
break;
case "delete":
this.onDelAllowList(header.id, body);
break;
case "cmd":
this.onRunCmd(header.id, body);
break;
case "queryList":
this.onQueryAllowList(header.id, body);
break;
case "queryOnline":
this.onQueryOnline(header.id, body);
break;
case "shutdown":
this.onShutDown(header.id, body);
break;
case "sendConfig":
this.onSendConfig(header.id, body);
break;
case "run":
this.onRun(header.id, body, header.type, false);
break;
case "runAdmin":
this.onRun(header.id, body, header.type, true);
break;
case "bindRequest":
this.onBindRequest(header.id, body, header.type);
break;
case "groupMember":
this.onGroupMember(header.id, body);
break;
}
} catch (e) {
logger.error(`在处理消息是遇到错误: ${e.stack}`);
logger.error(`此错误具有不可容错性!请检查插件是否为最新!`);
logger.info(`正在断开连接...`);
this._Close();
}
}
_shakedProcess() {
this.continueHeart = 0;
this.isShakeHand = true;
this.tryConnect = true;
this.heart = setInterval(() => {
this._sendMsg("heart", {});
}, HEARTBEAT_INTERVAL);
//记录时间自己重连
this.autoReconnect = setTimeout(() => {
logger.info("连接超时,尝试自动重连...");
this._attemptReconnect();
}, AUTO_RECONNECT_TIMEOUT);
}
/**
* 发送消息
* @param {"shaked"|"chat"|"success"|"add"|"delete"|"cmd"|"queryList"|"queryOnline"|"shutdown"} type
* @param {object} body
* @param {string} uuid
* @returns
*/
_sendMsg(type, body, uuid = system.randomGuid()) {
if (this.WSC.status != 0 && this.isShakeHand) {
//cb(null);
return;
}
let response = {
header: {
type: type,
id: uuid,
},
body: body,
};
let jsonStr = JSON.stringify(response);
this.WSC.send(jsonStr);
}
/**
* 向服务端握手
*/
_sendShakeHand() {
let config = getConfig();
this._sendMsg("shakeHand", {
serverId: config.serverId,
hashKey: config.hashKey,
name: this.name,
version: VERSION,
platform: "bds",
});
}
/**
* 回复消息
* @param {string} msg
*/
_postChat(msg, msgType = "聊天") {
let serverId = getConfig().serverId;
this._sendMsg("chat", {
serverId: serverId,
msg: msg,
msgType: msgType,
});
}
_bindConfirm(code) {
let bindId = this.bindMap[code];
this._sendMsg("bindConfirm", {}, bindId);
}
/**
* 执行自定义命令
* @param {string} id
* @param {object} body
* @param {string} type
*/
onBindRequest(id, body, type) {
let bindCode = body.bindCode;
logger.info(
`收到一个新的绑定请求,如确认绑定,请输入"/huhobot bind ${bindCode}"来进行确认`,
);
this.bindMap[bindCode] = id;
}
/**
* 群成员变更事件
* @param {string} id
* @param {{action:"add"|"remove",groupId:string,memberId:string,nick:string,bind_qq:string}} body
*/
onGroupMember(id, body) {
let keyWord;
if (body.action == "add") {
keyWord = "#MemberAdd";
} else if (body.action == "remove") {
keyWord = "#MemberRemove";
} else {
logger.warn(`未知的群成员变更类型: ${body.action}`);
return;
}
callInlineEvent(keyWord, body);
}
/**
* 执行自定义命令
* @param {string} id
* @param {object} body
* @param {string} type
* @param {boolean} isAdmin
*/
onRun(id, body, type, isAdmin) {
let keyWord = body.key;
let params = body.runParams;
//配置文件自定义命令
let config = getConfig();
let customCommand = config.customCommand;
for (let i = 0; i < customCommand.length; i++) {
let command = customCommand[i];
if (command.key == keyWord) {
//判断是否是管理员
if (command.permission > 0 && !isAdmin) {
this._Respone(
`权限不足,若您是管理员,请使用/管理员执行`,
body.groupId,
"error",
id,
);
return;
}
//格式化参数
let cmd = command.command;
for (let j = 0; j < params.length; j++) {
let param = params[j];
cmd = cmd.replace(`&${j + 1}`, param);
}
//执行
this._executeAndRespond(
cmd,
body.groupId,
id,
"执行成功:\n",
"执行失败:\n",
);
return;
}
}
//插件自定义命令
let data = JSON.stringify(body);
if (keyWord in callbackEvent[type]) {
let ret = callbackEvent[type][keyWord](data);
if (typeof ret === "string") {
this._Respone(ret, body.groupId, "success", id);
} else {
throw new Error(`自定义命令返回值必须为字符串!`);
}
return;
} else {
let ret = `未找到自定义命令:${keyWord}`;
this._Respone(ret, body.groupId, "error", id);
}
}
/**
* 下发配置文件
* @param {string} id
* @param {object} body
*/
onSendConfig(id, body) {
//writeFile(CONFIGPATH, body);
let serverId = body.serverId;
let hashKey = body.hashKey;
let config = getConfig();
config.serverId = serverId;
config.hashKey = hashKey;
writeFile(CONFIGPATH, config);
getConfig(true);
this._Respone(`服务器已接受下发配置文件`, body.groupId, "success", id);
logger.info(
`服务器已接受下发配置文件,正在自动重连,若重连失败请重启服务器`,
);
logger.info(`正在重新连接...`);
setTimeout(() => {
this._ReConnect();
}, RECONNECT_INTERVAL);
}
/**
* 握手成功
* @param {string} id
* @param {object} body
*/
onShaked(id, body) {
let code = body.code;
switch (code) {
case 1:
logger.info(`握手完成!`);
this._shakedProcess();
break;
case 2:
logger.info(`握手完成!,附加消息:${body.msg}`);
this._shakedProcess();
break;
case 3:
logger.error(`握手失败!原因: ${body.msg}`);
this.tryConnect = false;
break;
case 4:
logger.error(`握手失败!原因: ${body.msg}`);
logger.info(`正在尝试更新到最新版本...`);
updateVersion();
this.tryConnect = false;
break;
case 6:
logger.info(`握手完成,等待绑定....`);
this._shakedProcess();
let config = getConfig();
if (config.hashKey == null || config.hashKey == "") {
logger.warn(
`服务器尚未在机器人进行绑定,请在群内输入"/绑定 ${config.serverId}"来绑定`,
);
}
break;
default:
logger.error(`握手失败!原因: ${body.msg}`);
}
}
/**
* 聊天信息
* @param {string} id
* @param {object} body
*/
onChat(id, body) {
let config = getConfig();
if (!config.chatFormat.post_chat) return; // 总开关关闭时不处理
let chatMsg = config.chatFormat.group
.replace("{nick}", body.nick)
.replace("{msg}", body.msg);
mc.broadcast(chatMsg);
}
/**
* 添加白名单请求
* @param {string} id
* @param {object} body
*/
onAddAllowList(id, body) {
this._executeAndRespond(
`allowlist add ${body.xboxid}`,
body.groupId,
id,
`${this.name}已接受添加名为${body.xboxid}的白名单请求\n返回如下:`,
`${this.name}已拒绝添加名为${body.xboxid}的白名单请求\n返回如下:`,
);
}
/**
* 删除白名单请求
* @param {string} id
* @param {object} body
*/
onDelAllowList(id, body) {
this._executeAndRespond(
`allowlist remove ${body.xboxid}`,
body.groupId,
id,
`${this.name}已接受删除名为${body.xboxid}的白名单请求\n返回如下:`,
`${this.name}已拒绝删除名为${body.xboxid}的白名单请求\n返回如下:`,
);
}
/**
* 执行命令请求
* @param {string} id
* @param {object} body
*/
onRunCmd(id, body) {
this._executeAndRespond(
body.cmd,
body.groupId,
id,
"执行成功:\n",
"执行失败:\n",
);
}
/**
* 查询白名单请求
* @param {string} id
* @param {object} body
*/
onQueryAllowList(id, body) {
let BDSAllowlist = {};
try {
BDSAllowlist = readFile(BDSALLOWLISTPATH);
} catch (err) {
logger.error("读取白名单文件失败,请检查白名单文件是否正确!");
logger.error(err);
this._sendMsg(
"queryWl",
{ list: "读取白名单文件失败,请检查白名单文件是否正确!" },
id,
);
return;
}
let nameList = [];
for (let i = 0; i < BDSAllowlist.length; i++) {
nameList.push(BDSAllowlist[i]["name"]);
}
const formatNameList = (names) => names.map((n) => n + "\n").join("");
if ("key" in body) {
if (body.key.length < 2) {
this._sendMsg(
"queryWl",
{
list: `查询白名单关键词:${body.key}结果如下:\n请使用两个字母及以上的关键词进行查询!`,
},
id,
);
return;
}
let filterList = filterByKeyword(nameList, body.key);
let result = `查询白名单关键词:${body.key}结果如下:\n`;
result +=
filterList.length == 0
? "无结果"
: formatNameList(filterList) + `共有${filterList.length}个结果`;
this._sendMsg("queryWl", { list: result }, id);
} else {
let page = "page" in body ? body.page : 1;
let splitedNameList = paginateArray(nameList, ALLOWLIST_PAGE_SIZE);
let result = "服内白名单如下:\n";
if (page - 1 >= splitedNameList.length) {
result += `没有该页码\n`;
result += `共有${splitedNameList.length}页\n请使用/查白名单 {页码}来翻页`;
} else {
result += formatNameList(splitedNameList[page - 1]);
result += `共有${splitedNameList.length}页,当前为第${page}页\n请使用/查白名单 {页码}来翻页`;
}
this._sendMsg("queryWl", { list: result }, id);
}
}
/**
* 查询在线列表请求
* @param {string} id
* @param {object} body
*/
onQueryOnline(id, body) {
let config = getConfig();
let motd = config.motd || {};
let server_ip = motd.server_ip;
let server_port = motd.server_port;
let api = motd.api;
let post_img = motd.post_img;
let playerNames = getOnlinePlayerNames(config);
let useMarkdown = motd.markdown === true;
let list = {
msg: motdMsgBuilder(playerNames),
url: `${server_ip}:${server_port}`,
imgUrl: api
.replace("{server_ip}", server_ip)
.replace("{server_port}", server_port),
post_img: post_img,
serverType: "bedrock",
useMarkdown: useMarkdown,
serverName: config.serverName,
currentOnline: playerNames.length.toString(),
};
if (motd.customMarkdown === true) {
list.customMarkdown = readCustomMarkdown();
}
this._sendMsg(
"queryOnline",
{
list: list,
},
id,
);
}
/**
* 服务端断开连接
* @param {string} id
* @param {object} body