woodenfish-bot 2.0.7

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/lib/index.js ADDED
@@ -0,0 +1,3203 @@
1
+ 'use strict';
2
+
3
+ var resty = require('resty-client');
4
+ var fs = require('fs');
5
+ var https = require('https');
6
+ var WebSocket = require('ws');
7
+
8
+ function _classCallCheck(instance, Constructor) {
9
+ if (!(instance instanceof Constructor)) {
10
+ throw new TypeError("Cannot call a class as a function");
11
+ }
12
+ }
13
+
14
+ function _typeof$1(o) {
15
+ "@babel/helpers - typeof";
16
+
17
+ return _typeof$1 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
18
+ return typeof o;
19
+ } : function (o) {
20
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
21
+ }, _typeof$1(o);
22
+ }
23
+
24
+ function toPrimitive(t, r) {
25
+ if ("object" != _typeof$1(t) || !t) return t;
26
+ var e = t[Symbol.toPrimitive];
27
+ if (void 0 !== e) {
28
+ var i = e.call(t, r || "default");
29
+ if ("object" != _typeof$1(i)) return i;
30
+ throw new TypeError("@@toPrimitive must return a primitive value.");
31
+ }
32
+ return ("string" === r ? String : Number)(t);
33
+ }
34
+
35
+ function toPropertyKey(t) {
36
+ var i = toPrimitive(t, "string");
37
+ return "symbol" == _typeof$1(i) ? i : i + "";
38
+ }
39
+
40
+ function _defineProperties(target, props) {
41
+ for (var i = 0; i < props.length; i++) {
42
+ var descriptor = props[i];
43
+ descriptor.enumerable = descriptor.enumerable || false;
44
+ descriptor.configurable = true;
45
+ if ("value" in descriptor) descriptor.writable = true;
46
+ Object.defineProperty(target, toPropertyKey(descriptor.key), descriptor);
47
+ }
48
+ }
49
+ function _createClass(Constructor, protoProps, staticProps) {
50
+ if (protoProps) _defineProperties(Constructor.prototype, protoProps);
51
+ if (staticProps) _defineProperties(Constructor, staticProps);
52
+ Object.defineProperty(Constructor, "prototype", {
53
+ writable: false
54
+ });
55
+ return Constructor;
56
+ }
57
+
58
+ function _defineProperty(obj, key, value) {
59
+ key = toPropertyKey(key);
60
+ if (key in obj) {
61
+ Object.defineProperty(obj, key, {
62
+ value: value,
63
+ enumerable: true,
64
+ configurable: true,
65
+ writable: true
66
+ });
67
+ } else {
68
+ obj[key] = value;
69
+ }
70
+ return obj;
71
+ }
72
+
73
+ var versionMapping = Object.create(null);
74
+ function register(version, api) {
75
+ versionMapping[version] = api;
76
+ }
77
+
78
+ var apiMap = {
79
+ guildURI: '/guilds/:guildID',
80
+ guildMembersURI: '/guilds/:guildID/members',
81
+ guildMemberURI: '/guilds/:guildID/members/:userID',
82
+ channelsURI: '/guilds/:guildID/channels',
83
+ channelURI: '/channels/:channelID',
84
+ guildAnnouncesURI: '/guilds/:guildID/announces',
85
+ guildAnnounceURI: '/guilds/:guildID/announces/:messageID',
86
+ channelAnnouncesURI: '/channels/:channelID/announces',
87
+ channelAnnounceURI: '/channels/:channelID/announces/:messageID',
88
+ messagesURI: '/channels/:channelID/messages',
89
+ messageURI: '/channels/:channelID/messages/:messageID',
90
+ userMeURI: '/users/@me',
91
+ userMeGuildsURI: '/users/@me/guilds',
92
+ muteURI: '/guilds/:guildID/mute',
93
+ muteMemberURI: '/guilds/:guildID/members/:userID/mute',
94
+ muteMembersURI: '/guilds/:guildID/mute',
95
+ gatewayURI: '/gateway',
96
+ gatewayBotURI: '/gateway/bot',
97
+ audioControlURI: '/channels/:channelID/audio',
98
+ rolesURI: '/guilds/:guildID/roles',
99
+ roleURI: '/guilds/:guildID/roles/:roleID',
100
+ memberRoleURI: '/guilds/:guildID/members/:userID/roles/:roleID',
101
+ userMeDMURI: '/users/@me/dms',
102
+ dmsURI: '/dms/:guildID/messages',
103
+ channelPermissionsURI: '/channels/:channelID/members/:userID/permissions',
104
+ channelRolePermissionsURI: '/channels/:channelID/roles/:roleID/permissions',
105
+ schedulesURI: '/channels/:channelID/schedules',
106
+ scheduleURI: '/channels/:channelID/schedules/:scheduleID',
107
+ guildPermissionURI: '/guilds/:guildID/api_permission',
108
+ guildPermissionDemandURI: '/guilds/:guildID/api_permission/demand',
109
+ wsInfo: '/gateway/bot',
110
+ reactionURI: '/channels/:channelID/messages/:messageID/reactions/:emojiType/:emojiID',
111
+ pinsMessageIdURI: '/channels/:channelID/pins/:messageID',
112
+ pinsMessageURI: '/channels/:channelID/pins',
113
+ interactionURI: '/interactions/:interactionID',
114
+ guildRolesMembersURI: '/guilds/:guildID/roles/:roleID/members',
115
+ // 获取身份组成员列表
116
+ guildVoiceMembersURI: '/channels/:channelID/voice/members',
117
+ // 语音子频道在线成员车查询
118
+ botMic: '/channels/:channelID/mic',
119
+ // 机器人上麦|下麦
120
+ groupMessagesURI: '/v2/groups/:groupID/messages',
121
+ // 群组消息
122
+ groupRichMediaURI: '/v2/groups/:groupID/files',
123
+ // 群组富媒体消息
124
+ groupMessageURI: '/v2/groups/:groupID/messages/:messageID',
125
+ // 群组撤回消息
126
+ c2cMessagesURI: '/v2/users/:userID/messages',
127
+ // C2C消息
128
+ c2cRichMediaURI: '/v2/users/:userID/files',
129
+ // C2C富媒体消息
130
+ c2cMessageURI: '/v2/users/:userID/messages/:messageID' // C2C撤回消息
131
+ };
132
+ var getURL = function getURL(endpoint) {
133
+ return apiMap[endpoint];
134
+ };
135
+
136
+ var PinsMessage = /*#__PURE__*/function () {
137
+ function PinsMessage(request, config) {
138
+ _classCallCheck(this, PinsMessage);
139
+ _defineProperty(this, "request", void 0);
140
+ _defineProperty(this, "config", void 0);
141
+ this.request = request;
142
+ this.config = config;
143
+ }
144
+
145
+ // 获取精华消息
146
+ return _createClass(PinsMessage, [{
147
+ key: "pinsMessage",
148
+ value: function pinsMessage(channelID) {
149
+ var options = {
150
+ method: 'GET',
151
+ url: getURL('pinsMessageURI'),
152
+ rest: {
153
+ channelID: channelID
154
+ }
155
+ };
156
+ return this.request(options);
157
+ }
158
+
159
+ // 发送精华消息
160
+ }, {
161
+ key: "putPinsMessage",
162
+ value: function putPinsMessage(channelID, messageID) {
163
+ var options = {
164
+ method: 'PUT',
165
+ url: getURL('pinsMessageIdURI'),
166
+ headers: {
167
+ 'Content-Type': 'application/json;'
168
+ },
169
+ rest: {
170
+ channelID: channelID,
171
+ messageID: messageID
172
+ }
173
+ };
174
+ return this.request(options);
175
+ }
176
+
177
+ // 删除精华消息
178
+ }, {
179
+ key: "deletePinsMessage",
180
+ value: function deletePinsMessage(channelID, messageID) {
181
+ var options = {
182
+ method: 'DELETE',
183
+ url: getURL('pinsMessageIdURI'),
184
+ rest: {
185
+ channelID: channelID,
186
+ messageID: messageID
187
+ }
188
+ };
189
+ return this.request(options);
190
+ }
191
+ }]);
192
+ }();
193
+
194
+ var Reaction = /*#__PURE__*/function () {
195
+ function Reaction(request, config) {
196
+ _classCallCheck(this, Reaction);
197
+ _defineProperty(this, "request", void 0);
198
+ _defineProperty(this, "config", void 0);
199
+ this.request = request;
200
+ this.config = config;
201
+ }
202
+
203
+ // 发表表情表态
204
+ return _createClass(Reaction, [{
205
+ key: "postReaction",
206
+ value: function postReaction(channelId, reactionToCreate) {
207
+ var options = {
208
+ method: 'PUT',
209
+ url: getURL('reactionURI'),
210
+ rest: {
211
+ channelID: channelId,
212
+ messageID: reactionToCreate === null || reactionToCreate === void 0 ? void 0 : reactionToCreate.message_id,
213
+ emojiType: reactionToCreate === null || reactionToCreate === void 0 ? void 0 : reactionToCreate.emoji_type,
214
+ emojiID: reactionToCreate === null || reactionToCreate === void 0 ? void 0 : reactionToCreate.emoji_id
215
+ }
216
+ };
217
+ return this.request(options);
218
+ }
219
+
220
+ // 删除表情表态
221
+ }, {
222
+ key: "deleteReaction",
223
+ value: function deleteReaction(channelId, reactionToDelete) {
224
+ var options = {
225
+ method: 'DELETE',
226
+ url: getURL('reactionURI'),
227
+ rest: {
228
+ channelID: channelId,
229
+ messageID: reactionToDelete === null || reactionToDelete === void 0 ? void 0 : reactionToDelete.message_id,
230
+ emojiType: reactionToDelete === null || reactionToDelete === void 0 ? void 0 : reactionToDelete.emoji_type,
231
+ emojiID: reactionToDelete === null || reactionToDelete === void 0 ? void 0 : reactionToDelete.emoji_id
232
+ }
233
+ };
234
+ return this.request(options);
235
+ }
236
+
237
+ // 拉取表情表态用户列表
238
+ }, {
239
+ key: "getReactionUserList",
240
+ value: function getReactionUserList(channelId, reactionToCreate, options) {
241
+ if (!options) {
242
+ return Promise.reject(new Error("'options' required!"));
243
+ }
244
+ var reqOptions = {
245
+ method: 'GET',
246
+ url: getURL('reactionURI'),
247
+ rest: {
248
+ channelID: channelId,
249
+ messageID: reactionToCreate === null || reactionToCreate === void 0 ? void 0 : reactionToCreate.message_id,
250
+ emojiType: reactionToCreate === null || reactionToCreate === void 0 ? void 0 : reactionToCreate.emoji_type,
251
+ emojiID: reactionToCreate === null || reactionToCreate === void 0 ? void 0 : reactionToCreate.emoji_id
252
+ },
253
+ params: options
254
+ };
255
+ return this.request(reqOptions);
256
+ }
257
+ }]);
258
+ }();
259
+
260
+ var Guild = /*#__PURE__*/function () {
261
+ function Guild(request, config) {
262
+ _classCallCheck(this, Guild);
263
+ _defineProperty(this, "request", void 0);
264
+ _defineProperty(this, "config", void 0);
265
+ this.request = request;
266
+ this.config = config;
267
+ }
268
+
269
+ // 获取频道信息
270
+ return _createClass(Guild, [{
271
+ key: "guild",
272
+ value: function guild(guildID) {
273
+ var options = {
274
+ method: 'GET',
275
+ url: getURL('guildURI'),
276
+ rest: {
277
+ guildID: guildID
278
+ }
279
+ };
280
+ return this.request(options);
281
+ }
282
+
283
+ // 获取某个成员信息
284
+ }, {
285
+ key: "guildMember",
286
+ value: function guildMember(guildID, userID) {
287
+ var options = {
288
+ method: 'GET',
289
+ url: getURL('guildMemberURI'),
290
+ rest: {
291
+ guildID: guildID,
292
+ userID: userID
293
+ }
294
+ };
295
+ return this.request(options);
296
+ }
297
+
298
+ // 获取频道成员列表
299
+ }, {
300
+ key: "guildMembers",
301
+ value: function guildMembers(guildID, pager) {
302
+ pager = pager || {
303
+ after: '0',
304
+ limit: 1
305
+ };
306
+ var options = {
307
+ method: 'GET',
308
+ url: getURL('guildMembersURI'),
309
+ rest: {
310
+ guildID: guildID
311
+ },
312
+ params: pager
313
+ };
314
+ return this.request(options);
315
+ }
316
+
317
+ // 删除指定频道成员
318
+ }, {
319
+ key: "deleteGuildMember",
320
+ value: function deleteGuildMember(guildID, userID, add_blacklist, delete_history_msg_days) {
321
+ var json = {};
322
+ if (add_blacklist) {
323
+ json.add_blacklist = add_blacklist;
324
+ }
325
+ if (delete_history_msg_days) {
326
+ json.delete_history_msg_days = delete_history_msg_days;
327
+ }
328
+ var options = {
329
+ method: 'DELETE',
330
+ url: getURL('guildMemberURI'),
331
+ rest: {
332
+ guildID: guildID,
333
+ userID: userID
334
+ },
335
+ data: json
336
+ };
337
+ return this.request(options);
338
+ }
339
+
340
+ // 语音子频道在线成员列表
341
+ }, {
342
+ key: "guildVoiceMembers",
343
+ value: function guildVoiceMembers(channelID) {
344
+ var options = {
345
+ method: 'GET',
346
+ url: getURL('guildVoiceMembersURI'),
347
+ rest: {
348
+ channelID: channelID
349
+ }
350
+ };
351
+ return this.request(options);
352
+ }
353
+ }]);
354
+ }();
355
+
356
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
357
+ try {
358
+ var info = gen[key](arg);
359
+ var value = info.value;
360
+ } catch (error) {
361
+ reject(error);
362
+ return;
363
+ }
364
+ if (info.done) {
365
+ resolve(value);
366
+ } else {
367
+ Promise.resolve(value).then(_next, _throw);
368
+ }
369
+ }
370
+ function _asyncToGenerator(fn) {
371
+ return function () {
372
+ var self = this,
373
+ args = arguments;
374
+ return new Promise(function (resolve, reject) {
375
+ var gen = fn.apply(self, args);
376
+ function _next(value) {
377
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
378
+ }
379
+ function _throw(err) {
380
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
381
+ }
382
+ _next(undefined);
383
+ });
384
+ };
385
+ }
386
+
387
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
388
+
389
+ function getDefaultExportFromCjs (x) {
390
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
391
+ }
392
+
393
+ var regeneratorRuntime$1 = {exports: {}};
394
+
395
+ var _typeof = {exports: {}};
396
+
397
+ (function (module) {
398
+ function _typeof(o) {
399
+ "@babel/helpers - typeof";
400
+
401
+ return (module.exports = _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
402
+ return typeof o;
403
+ } : function (o) {
404
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
405
+ }, module.exports.__esModule = true, module.exports["default"] = module.exports), _typeof(o);
406
+ }
407
+ module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports;
408
+ } (_typeof));
409
+
410
+ var _typeofExports = _typeof.exports;
411
+
412
+ (function (module) {
413
+ var _typeof = _typeofExports["default"];
414
+ function _regeneratorRuntime() {
415
+ module.exports = _regeneratorRuntime = function _regeneratorRuntime() {
416
+ return e;
417
+ }, module.exports.__esModule = true, module.exports["default"] = module.exports;
418
+ var t,
419
+ e = {},
420
+ r = Object.prototype,
421
+ n = r.hasOwnProperty,
422
+ o = Object.defineProperty || function (t, e, r) {
423
+ t[e] = r.value;
424
+ },
425
+ i = "function" == typeof Symbol ? Symbol : {},
426
+ a = i.iterator || "@@iterator",
427
+ c = i.asyncIterator || "@@asyncIterator",
428
+ u = i.toStringTag || "@@toStringTag";
429
+ function define(t, e, r) {
430
+ return Object.defineProperty(t, e, {
431
+ value: r,
432
+ enumerable: !0,
433
+ configurable: !0,
434
+ writable: !0
435
+ }), t[e];
436
+ }
437
+ try {
438
+ define({}, "");
439
+ } catch (t) {
440
+ define = function define(t, e, r) {
441
+ return t[e] = r;
442
+ };
443
+ }
444
+ function wrap(t, e, r, n) {
445
+ var i = e && e.prototype instanceof Generator ? e : Generator,
446
+ a = Object.create(i.prototype),
447
+ c = new Context(n || []);
448
+ return o(a, "_invoke", {
449
+ value: makeInvokeMethod(t, r, c)
450
+ }), a;
451
+ }
452
+ function tryCatch(t, e, r) {
453
+ try {
454
+ return {
455
+ type: "normal",
456
+ arg: t.call(e, r)
457
+ };
458
+ } catch (t) {
459
+ return {
460
+ type: "throw",
461
+ arg: t
462
+ };
463
+ }
464
+ }
465
+ e.wrap = wrap;
466
+ var h = "suspendedStart",
467
+ l = "suspendedYield",
468
+ f = "executing",
469
+ s = "completed",
470
+ y = {};
471
+ function Generator() {}
472
+ function GeneratorFunction() {}
473
+ function GeneratorFunctionPrototype() {}
474
+ var p = {};
475
+ define(p, a, function () {
476
+ return this;
477
+ });
478
+ var d = Object.getPrototypeOf,
479
+ v = d && d(d(values([])));
480
+ v && v !== r && n.call(v, a) && (p = v);
481
+ var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p);
482
+ function defineIteratorMethods(t) {
483
+ ["next", "throw", "return"].forEach(function (e) {
484
+ define(t, e, function (t) {
485
+ return this._invoke(e, t);
486
+ });
487
+ });
488
+ }
489
+ function AsyncIterator(t, e) {
490
+ function invoke(r, o, i, a) {
491
+ var c = tryCatch(t[r], t, o);
492
+ if ("throw" !== c.type) {
493
+ var u = c.arg,
494
+ h = u.value;
495
+ return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) {
496
+ invoke("next", t, i, a);
497
+ }, function (t) {
498
+ invoke("throw", t, i, a);
499
+ }) : e.resolve(h).then(function (t) {
500
+ u.value = t, i(u);
501
+ }, function (t) {
502
+ return invoke("throw", t, i, a);
503
+ });
504
+ }
505
+ a(c.arg);
506
+ }
507
+ var r;
508
+ o(this, "_invoke", {
509
+ value: function value(t, n) {
510
+ function callInvokeWithMethodAndArg() {
511
+ return new e(function (e, r) {
512
+ invoke(t, n, e, r);
513
+ });
514
+ }
515
+ return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
516
+ }
517
+ });
518
+ }
519
+ function makeInvokeMethod(e, r, n) {
520
+ var o = h;
521
+ return function (i, a) {
522
+ if (o === f) throw Error("Generator is already running");
523
+ if (o === s) {
524
+ if ("throw" === i) throw a;
525
+ return {
526
+ value: t,
527
+ done: !0
528
+ };
529
+ }
530
+ for (n.method = i, n.arg = a;;) {
531
+ var c = n.delegate;
532
+ if (c) {
533
+ var u = maybeInvokeDelegate(c, n);
534
+ if (u) {
535
+ if (u === y) continue;
536
+ return u;
537
+ }
538
+ }
539
+ if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) {
540
+ if (o === h) throw o = s, n.arg;
541
+ n.dispatchException(n.arg);
542
+ } else "return" === n.method && n.abrupt("return", n.arg);
543
+ o = f;
544
+ var p = tryCatch(e, r, n);
545
+ if ("normal" === p.type) {
546
+ if (o = n.done ? s : l, p.arg === y) continue;
547
+ return {
548
+ value: p.arg,
549
+ done: n.done
550
+ };
551
+ }
552
+ "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg);
553
+ }
554
+ };
555
+ }
556
+ function maybeInvokeDelegate(e, r) {
557
+ var n = r.method,
558
+ o = e.iterator[n];
559
+ if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y;
560
+ var i = tryCatch(o, e.iterator, r.arg);
561
+ if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y;
562
+ var a = i.arg;
563
+ return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y);
564
+ }
565
+ function pushTryEntry(t) {
566
+ var e = {
567
+ tryLoc: t[0]
568
+ };
569
+ 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e);
570
+ }
571
+ function resetTryEntry(t) {
572
+ var e = t.completion || {};
573
+ e.type = "normal", delete e.arg, t.completion = e;
574
+ }
575
+ function Context(t) {
576
+ this.tryEntries = [{
577
+ tryLoc: "root"
578
+ }], t.forEach(pushTryEntry, this), this.reset(!0);
579
+ }
580
+ function values(e) {
581
+ if (e || "" === e) {
582
+ var r = e[a];
583
+ if (r) return r.call(e);
584
+ if ("function" == typeof e.next) return e;
585
+ if (!isNaN(e.length)) {
586
+ var o = -1,
587
+ i = function next() {
588
+ for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next;
589
+ return next.value = t, next.done = !0, next;
590
+ };
591
+ return i.next = i;
592
+ }
593
+ }
594
+ throw new TypeError(_typeof(e) + " is not iterable");
595
+ }
596
+ return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", {
597
+ value: GeneratorFunctionPrototype,
598
+ configurable: !0
599
+ }), o(GeneratorFunctionPrototype, "constructor", {
600
+ value: GeneratorFunction,
601
+ configurable: !0
602
+ }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) {
603
+ var e = "function" == typeof t && t.constructor;
604
+ return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name));
605
+ }, e.mark = function (t) {
606
+ return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t;
607
+ }, e.awrap = function (t) {
608
+ return {
609
+ __await: t
610
+ };
611
+ }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () {
612
+ return this;
613
+ }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) {
614
+ void 0 === i && (i = Promise);
615
+ var a = new AsyncIterator(wrap(t, r, n, o), i);
616
+ return e.isGeneratorFunction(r) ? a : a.next().then(function (t) {
617
+ return t.done ? t.value : a.next();
618
+ });
619
+ }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () {
620
+ return this;
621
+ }), define(g, "toString", function () {
622
+ return "[object Generator]";
623
+ }), e.keys = function (t) {
624
+ var e = Object(t),
625
+ r = [];
626
+ for (var n in e) r.push(n);
627
+ return r.reverse(), function next() {
628
+ for (; r.length;) {
629
+ var t = r.pop();
630
+ if (t in e) return next.value = t, next.done = !1, next;
631
+ }
632
+ return next.done = !0, next;
633
+ };
634
+ }, e.values = values, Context.prototype = {
635
+ constructor: Context,
636
+ reset: function reset(e) {
637
+ if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t);
638
+ },
639
+ stop: function stop() {
640
+ this.done = !0;
641
+ var t = this.tryEntries[0].completion;
642
+ if ("throw" === t.type) throw t.arg;
643
+ return this.rval;
644
+ },
645
+ dispatchException: function dispatchException(e) {
646
+ if (this.done) throw e;
647
+ var r = this;
648
+ function handle(n, o) {
649
+ return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o;
650
+ }
651
+ for (var o = this.tryEntries.length - 1; o >= 0; --o) {
652
+ var i = this.tryEntries[o],
653
+ a = i.completion;
654
+ if ("root" === i.tryLoc) return handle("end");
655
+ if (i.tryLoc <= this.prev) {
656
+ var c = n.call(i, "catchLoc"),
657
+ u = n.call(i, "finallyLoc");
658
+ if (c && u) {
659
+ if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
660
+ if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
661
+ } else if (c) {
662
+ if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
663
+ } else {
664
+ if (!u) throw Error("try statement without catch or finally");
665
+ if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
666
+ }
667
+ }
668
+ }
669
+ },
670
+ abrupt: function abrupt(t, e) {
671
+ for (var r = this.tryEntries.length - 1; r >= 0; --r) {
672
+ var o = this.tryEntries[r];
673
+ if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) {
674
+ var i = o;
675
+ break;
676
+ }
677
+ }
678
+ i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null);
679
+ var a = i ? i.completion : {};
680
+ return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a);
681
+ },
682
+ complete: function complete(t, e) {
683
+ if ("throw" === t.type) throw t.arg;
684
+ return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y;
685
+ },
686
+ finish: function finish(t) {
687
+ for (var e = this.tryEntries.length - 1; e >= 0; --e) {
688
+ var r = this.tryEntries[e];
689
+ if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y;
690
+ }
691
+ },
692
+ "catch": function _catch(t) {
693
+ for (var e = this.tryEntries.length - 1; e >= 0; --e) {
694
+ var r = this.tryEntries[e];
695
+ if (r.tryLoc === t) {
696
+ var n = r.completion;
697
+ if ("throw" === n.type) {
698
+ var o = n.arg;
699
+ resetTryEntry(r);
700
+ }
701
+ return o;
702
+ }
703
+ }
704
+ throw Error("illegal catch attempt");
705
+ },
706
+ delegateYield: function delegateYield(e, r, n) {
707
+ return this.delegate = {
708
+ iterator: values(e),
709
+ resultName: r,
710
+ nextLoc: n
711
+ }, "next" === this.method && (this.arg = t), y;
712
+ }
713
+ }, e;
714
+ }
715
+ module.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports["default"] = module.exports;
716
+ } (regeneratorRuntime$1));
717
+
718
+ var regeneratorRuntimeExports = regeneratorRuntime$1.exports;
719
+
720
+ // TODO(Babel 8): Remove this file.
721
+
722
+ var runtime = regeneratorRuntimeExports();
723
+ var regenerator = runtime;
724
+
725
+ // Copied from https://github.com/facebook/regenerator/blob/main/packages/runtime/runtime.js#L736=
726
+ try {
727
+ regeneratorRuntime = runtime;
728
+ } catch (accidentalStrictMode) {
729
+ if (typeof globalThis === "object") {
730
+ globalThis.regeneratorRuntime = runtime;
731
+ } else {
732
+ Function("r", "regeneratorRuntime = r")(runtime);
733
+ }
734
+ }
735
+
736
+ var _regeneratorRuntime = /*@__PURE__*/getDefaultExportFromCjs(regenerator);
737
+
738
+ var version = "2.0.7";
739
+
740
+ var loglevel = {exports: {}};
741
+
742
+ /*
743
+ * loglevel - https://github.com/pimterry/loglevel
744
+ *
745
+ * Copyright (c) 2013 Tim Perry
746
+ * Licensed under the MIT license.
747
+ */
748
+
749
+ (function (module) {
750
+ (function (root, definition) {
751
+ if (module.exports) {
752
+ module.exports = definition();
753
+ } else {
754
+ root.log = definition();
755
+ }
756
+ }(commonjsGlobal, function () {
757
+
758
+ // Slightly dubious tricks to cut down minimized file size
759
+ var noop = function() {};
760
+ var undefinedType = "undefined";
761
+ var isIE = (typeof window !== undefinedType) && (typeof window.navigator !== undefinedType) && (
762
+ /Trident\/|MSIE /.test(window.navigator.userAgent)
763
+ );
764
+
765
+ var logMethods = [
766
+ "trace",
767
+ "debug",
768
+ "info",
769
+ "warn",
770
+ "error"
771
+ ];
772
+
773
+ var _loggersByName = {};
774
+ var defaultLogger = null;
775
+
776
+ // Cross-browser bind equivalent that works at least back to IE6
777
+ function bindMethod(obj, methodName) {
778
+ var method = obj[methodName];
779
+ if (typeof method.bind === 'function') {
780
+ return method.bind(obj);
781
+ } else {
782
+ try {
783
+ return Function.prototype.bind.call(method, obj);
784
+ } catch (e) {
785
+ // Missing bind shim or IE8 + Modernizr, fallback to wrapping
786
+ return function() {
787
+ return Function.prototype.apply.apply(method, [obj, arguments]);
788
+ };
789
+ }
790
+ }
791
+ }
792
+
793
+ // Trace() doesn't print the message in IE, so for that case we need to wrap it
794
+ function traceForIE() {
795
+ if (console.log) {
796
+ if (console.log.apply) {
797
+ console.log.apply(console, arguments);
798
+ } else {
799
+ // In old IE, native console methods themselves don't have apply().
800
+ Function.prototype.apply.apply(console.log, [console, arguments]);
801
+ }
802
+ }
803
+ if (console.trace) console.trace();
804
+ }
805
+
806
+ // Build the best logging method possible for this env
807
+ // Wherever possible we want to bind, not wrap, to preserve stack traces
808
+ function realMethod(methodName) {
809
+ if (methodName === 'debug') {
810
+ methodName = 'log';
811
+ }
812
+
813
+ if (typeof console === undefinedType) {
814
+ return false; // No method possible, for now - fixed later by enableLoggingWhenConsoleArrives
815
+ } else if (methodName === 'trace' && isIE) {
816
+ return traceForIE;
817
+ } else if (console[methodName] !== undefined) {
818
+ return bindMethod(console, methodName);
819
+ } else if (console.log !== undefined) {
820
+ return bindMethod(console, 'log');
821
+ } else {
822
+ return noop;
823
+ }
824
+ }
825
+
826
+ // These private functions always need `this` to be set properly
827
+
828
+ function replaceLoggingMethods() {
829
+ /*jshint validthis:true */
830
+ var level = this.getLevel();
831
+
832
+ // Replace the actual methods.
833
+ for (var i = 0; i < logMethods.length; i++) {
834
+ var methodName = logMethods[i];
835
+ this[methodName] = (i < level) ?
836
+ noop :
837
+ this.methodFactory(methodName, level, this.name);
838
+ }
839
+
840
+ // Define log.log as an alias for log.debug
841
+ this.log = this.debug;
842
+
843
+ // Return any important warnings.
844
+ if (typeof console === undefinedType && level < this.levels.SILENT) {
845
+ return "No console available for logging";
846
+ }
847
+ }
848
+
849
+ // In old IE versions, the console isn't present until you first open it.
850
+ // We build realMethod() replacements here that regenerate logging methods
851
+ function enableLoggingWhenConsoleArrives(methodName) {
852
+ return function () {
853
+ if (typeof console !== undefinedType) {
854
+ replaceLoggingMethods.call(this);
855
+ this[methodName].apply(this, arguments);
856
+ }
857
+ };
858
+ }
859
+
860
+ // By default, we use closely bound real methods wherever possible, and
861
+ // otherwise we wait for a console to appear, and then try again.
862
+ function defaultMethodFactory(methodName, _level, _loggerName) {
863
+ /*jshint validthis:true */
864
+ return realMethod(methodName) ||
865
+ enableLoggingWhenConsoleArrives.apply(this, arguments);
866
+ }
867
+
868
+ function Logger(name, factory) {
869
+ // Private instance variables.
870
+ var self = this;
871
+ /**
872
+ * The level inherited from a parent logger (or a global default). We
873
+ * cache this here rather than delegating to the parent so that it stays
874
+ * in sync with the actual logging methods that we have installed (the
875
+ * parent could change levels but we might not have rebuilt the loggers
876
+ * in this child yet).
877
+ * @type {number}
878
+ */
879
+ var inheritedLevel;
880
+ /**
881
+ * The default level for this logger, if any. If set, this overrides
882
+ * `inheritedLevel`.
883
+ * @type {number|null}
884
+ */
885
+ var defaultLevel;
886
+ /**
887
+ * A user-specific level for this logger. If set, this overrides
888
+ * `defaultLevel`.
889
+ * @type {number|null}
890
+ */
891
+ var userLevel;
892
+
893
+ var storageKey = "loglevel";
894
+ if (typeof name === "string") {
895
+ storageKey += ":" + name;
896
+ } else if (typeof name === "symbol") {
897
+ storageKey = undefined;
898
+ }
899
+
900
+ function persistLevelIfPossible(levelNum) {
901
+ var levelName = (logMethods[levelNum] || 'silent').toUpperCase();
902
+
903
+ if (typeof window === undefinedType || !storageKey) return;
904
+
905
+ // Use localStorage if available
906
+ try {
907
+ window.localStorage[storageKey] = levelName;
908
+ return;
909
+ } catch (ignore) {}
910
+
911
+ // Use session cookie as fallback
912
+ try {
913
+ window.document.cookie =
914
+ encodeURIComponent(storageKey) + "=" + levelName + ";";
915
+ } catch (ignore) {}
916
+ }
917
+
918
+ function getPersistedLevel() {
919
+ var storedLevel;
920
+
921
+ if (typeof window === undefinedType || !storageKey) return;
922
+
923
+ try {
924
+ storedLevel = window.localStorage[storageKey];
925
+ } catch (ignore) {}
926
+
927
+ // Fallback to cookies if local storage gives us nothing
928
+ if (typeof storedLevel === undefinedType) {
929
+ try {
930
+ var cookie = window.document.cookie;
931
+ var cookieName = encodeURIComponent(storageKey);
932
+ var location = cookie.indexOf(cookieName + "=");
933
+ if (location !== -1) {
934
+ storedLevel = /^([^;]+)/.exec(
935
+ cookie.slice(location + cookieName.length + 1)
936
+ )[1];
937
+ }
938
+ } catch (ignore) {}
939
+ }
940
+
941
+ // If the stored level is not valid, treat it as if nothing was stored.
942
+ if (self.levels[storedLevel] === undefined) {
943
+ storedLevel = undefined;
944
+ }
945
+
946
+ return storedLevel;
947
+ }
948
+
949
+ function clearPersistedLevel() {
950
+ if (typeof window === undefinedType || !storageKey) return;
951
+
952
+ // Use localStorage if available
953
+ try {
954
+ window.localStorage.removeItem(storageKey);
955
+ } catch (ignore) {}
956
+
957
+ // Use session cookie as fallback
958
+ try {
959
+ window.document.cookie =
960
+ encodeURIComponent(storageKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
961
+ } catch (ignore) {}
962
+ }
963
+
964
+ function normalizeLevel(input) {
965
+ var level = input;
966
+ if (typeof level === "string" && self.levels[level.toUpperCase()] !== undefined) {
967
+ level = self.levels[level.toUpperCase()];
968
+ }
969
+ if (typeof level === "number" && level >= 0 && level <= self.levels.SILENT) {
970
+ return level;
971
+ } else {
972
+ throw new TypeError("log.setLevel() called with invalid level: " + input);
973
+ }
974
+ }
975
+
976
+ /*
977
+ *
978
+ * Public logger API - see https://github.com/pimterry/loglevel for details
979
+ *
980
+ */
981
+
982
+ self.name = name;
983
+
984
+ self.levels = { "TRACE": 0, "DEBUG": 1, "INFO": 2, "WARN": 3,
985
+ "ERROR": 4, "SILENT": 5};
986
+
987
+ self.methodFactory = factory || defaultMethodFactory;
988
+
989
+ self.getLevel = function () {
990
+ if (userLevel != null) {
991
+ return userLevel;
992
+ } else if (defaultLevel != null) {
993
+ return defaultLevel;
994
+ } else {
995
+ return inheritedLevel;
996
+ }
997
+ };
998
+
999
+ self.setLevel = function (level, persist) {
1000
+ userLevel = normalizeLevel(level);
1001
+ if (persist !== false) { // defaults to true
1002
+ persistLevelIfPossible(userLevel);
1003
+ }
1004
+
1005
+ // NOTE: in v2, this should call rebuild(), which updates children.
1006
+ return replaceLoggingMethods.call(self);
1007
+ };
1008
+
1009
+ self.setDefaultLevel = function (level) {
1010
+ defaultLevel = normalizeLevel(level);
1011
+ if (!getPersistedLevel()) {
1012
+ self.setLevel(level, false);
1013
+ }
1014
+ };
1015
+
1016
+ self.resetLevel = function () {
1017
+ userLevel = null;
1018
+ clearPersistedLevel();
1019
+ replaceLoggingMethods.call(self);
1020
+ };
1021
+
1022
+ self.enableAll = function(persist) {
1023
+ self.setLevel(self.levels.TRACE, persist);
1024
+ };
1025
+
1026
+ self.disableAll = function(persist) {
1027
+ self.setLevel(self.levels.SILENT, persist);
1028
+ };
1029
+
1030
+ self.rebuild = function () {
1031
+ if (defaultLogger !== self) {
1032
+ inheritedLevel = normalizeLevel(defaultLogger.getLevel());
1033
+ }
1034
+ replaceLoggingMethods.call(self);
1035
+
1036
+ if (defaultLogger === self) {
1037
+ for (var childName in _loggersByName) {
1038
+ _loggersByName[childName].rebuild();
1039
+ }
1040
+ }
1041
+ };
1042
+
1043
+ // Initialize all the internal levels.
1044
+ inheritedLevel = normalizeLevel(
1045
+ defaultLogger ? defaultLogger.getLevel() : "WARN"
1046
+ );
1047
+ var initialLevel = getPersistedLevel();
1048
+ if (initialLevel != null) {
1049
+ userLevel = normalizeLevel(initialLevel);
1050
+ }
1051
+ replaceLoggingMethods.call(self);
1052
+ }
1053
+
1054
+ /*
1055
+ *
1056
+ * Top-level API
1057
+ *
1058
+ */
1059
+
1060
+ defaultLogger = new Logger();
1061
+
1062
+ defaultLogger.getLogger = function getLogger(name) {
1063
+ if ((typeof name !== "symbol" && typeof name !== "string") || name === "") {
1064
+ throw new TypeError("You must supply a name when creating a logger.");
1065
+ }
1066
+
1067
+ var logger = _loggersByName[name];
1068
+ if (!logger) {
1069
+ logger = _loggersByName[name] = new Logger(
1070
+ name,
1071
+ defaultLogger.methodFactory
1072
+ );
1073
+ }
1074
+ return logger;
1075
+ };
1076
+
1077
+ // Grab the current global log variable in case of overwrite
1078
+ var _log = (typeof window !== undefinedType) ? window.log : undefined;
1079
+ defaultLogger.noConflict = function() {
1080
+ if (typeof window !== undefinedType &&
1081
+ window.log === defaultLogger) {
1082
+ window.log = _log;
1083
+ }
1084
+
1085
+ return defaultLogger;
1086
+ };
1087
+
1088
+ defaultLogger.getLoggers = function getLoggers() {
1089
+ return _loggersByName;
1090
+ };
1091
+
1092
+ // ES6 default export, for compatibility
1093
+ defaultLogger['default'] = defaultLogger;
1094
+
1095
+ return defaultLogger;
1096
+ }));
1097
+ } (loglevel));
1098
+
1099
+ var loglevelExports = loglevel.exports;
1100
+ var log = /*@__PURE__*/getDefaultExportFromCjs(loglevelExports);
1101
+
1102
+ log.setLevel('info');
1103
+ log.setLevel('trace');
1104
+ var BotLogger = log;
1105
+
1106
+ // 转为对象
1107
+ var toObject = function toObject(data) {
1108
+ if (Buffer.isBuffer(data)) return JSON.parse(data.toString());
1109
+ if (_typeof$1(data) === 'object') return data;
1110
+ if (typeof data === 'string') return JSON.parse(data);
1111
+ // return String(data);
1112
+ };
1113
+
1114
+ // 获取number类型的10位时间戳
1115
+ // export const getTimeStampNumber = () => Number(new Date().getTime().toString().substr(0, 10));
1116
+ var getTimeStampNumber = function getTimeStampNumber() {
1117
+ return Math.floor(new Date().getTime() / 1000);
1118
+ };
1119
+
1120
+ // 添加 User-Agent
1121
+ var addUserAgent = function addUserAgent(header, appID, apiVersion) {
1122
+ var sdkVersion = version;
1123
+ header['User-Agent'] = "BotNodeSDK/v".concat(sdkVersion);
1124
+ if (apiVersion == 'v2') {
1125
+ header['X-Union-Appid'] = "".concat(appID);
1126
+ }
1127
+ };
1128
+ function getAccessToken(file_token, url, data, appID, token) {
1129
+ var now_time = getTimeStampNumber();
1130
+ var requestData = JSON.stringify(data);
1131
+ var options = {
1132
+ method: 'POST',
1133
+ headers: {
1134
+ 'Content-Type': 'application/json',
1135
+ 'Content-Length': requestData.length
1136
+ }
1137
+ };
1138
+ return new Promise(function (resolve, reject) {
1139
+ var req = https.request(url, options, function (res) {
1140
+ var responseData = '';
1141
+ res.on('data', function (chunk) {
1142
+ responseData += chunk;
1143
+ });
1144
+ res.on('end', function () {
1145
+ if (res.statusCode >= 200 && res.statusCode <= 299) {
1146
+ try {
1147
+ var parsedData = JSON.parse(responseData);
1148
+ console.log('response_access_token', JSON.stringify(parsedData));
1149
+ var access_token = parsedData.access_token;
1150
+ var expires_in = now_time + parseInt(parsedData.expires_in);
1151
+ // 修改access_token字段的值
1152
+ token['bot'][appID]['access_token'] = access_token;
1153
+ token['bot'][appID]['expires_in'] = expires_in.toString();
1154
+ // 将修改后的配置写入json文件,保留原有格式
1155
+ var token_new = JSON.stringify(token, null, 2);
1156
+ // 写入配置文件,utf-8格式,如果文件不存在会自动创建
1157
+ fs.writeFileSync(file_token, token_new, 'utf-8');
1158
+ console.log('配置已成功写入到access_token.json文件中。');
1159
+ resolve(access_token);
1160
+ } catch (error) {
1161
+ reject(error);
1162
+ }
1163
+ } else {
1164
+ reject(new Error("Request failed with status code ".concat(res.statusCode)));
1165
+ }
1166
+ });
1167
+ });
1168
+ req.on('error', function (error) {
1169
+ reject(error);
1170
+ });
1171
+ req.write(requestData);
1172
+ req.end();
1173
+ });
1174
+ }
1175
+
1176
+ // 添加 User-Agent
1177
+ var addAuthorization = /*#__PURE__*/function () {
1178
+ var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(header, appID, token, clientSecret, apiVersion) {
1179
+ var now_time, url, data, file_token, _token, access_token, expires_in;
1180
+ return _regeneratorRuntime.wrap(function _callee$(_context) {
1181
+ while (1) switch (_context.prev = _context.next) {
1182
+ case 0:
1183
+ if (!(apiVersion == 'v2')) {
1184
+ _context.next = 17;
1185
+ break;
1186
+ }
1187
+ now_time = getTimeStampNumber();
1188
+ url = 'https://bots.qq.com/app/getAppAccessToken';
1189
+ data = {
1190
+ appId: appID,
1191
+ clientSecret: clientSecret
1192
+ };
1193
+ file_token = './access_token.json';
1194
+ _token = {
1195
+ "bot": _defineProperty({}, appID, {
1196
+ "access_token": "",
1197
+ "expires_in": ""
1198
+ })
1199
+ };
1200
+ access_token = '';
1201
+ expires_in = 0;
1202
+ try {
1203
+ // 判断文件是否存在
1204
+ if (fs.existsSync(file_token)) {
1205
+ // 执行文件存在时的处理逻辑
1206
+ _token = JSON.parse(fs.readFileSync(file_token).toString());
1207
+ // 判断是否存在appID
1208
+ if (_token.hasOwnProperty('bot') && _token['bot'].hasOwnProperty(appID)) {
1209
+ access_token = _token['bot'][appID]['access_token'];
1210
+ expires_in = parseInt(_token['bot'][appID]['expires_in']);
1211
+ } else {
1212
+ // 不存在appID时的处理逻辑
1213
+ fs.writeFileSync(file_token, JSON.stringify(_token, null, 2), 'utf-8');
1214
+ }
1215
+ } else {
1216
+ // 执行文件不存在时的处理逻辑
1217
+ fs.writeFileSync(file_token, JSON.stringify(_token, null, 2), 'utf-8');
1218
+ }
1219
+ } catch (err) {
1220
+ console.error('读取文件时发生错误:', err);
1221
+ }
1222
+ // 判断access_token是否存在,不存在或者已经过期就重新获取
1223
+ if (!(access_token === '' || now_time > expires_in - 50)) {
1224
+ _context.next = 14;
1225
+ break;
1226
+ }
1227
+ console.log('access_token', access_token, 'expire_time', expires_in);
1228
+ _context.next = 13;
1229
+ return getAccessToken(file_token, url, data, appID, _token);
1230
+ case 13:
1231
+ access_token = _context.sent;
1232
+ case 14:
1233
+ // 更新header['Authorization']
1234
+ header['Authorization'] = "QQBot ".concat(access_token);
1235
+ _context.next = 18;
1236
+ break;
1237
+ case 17:
1238
+ header['Authorization'] = "Bot ".concat(appID, ".").concat(token);
1239
+ case 18:
1240
+ case "end":
1241
+ return _context.stop();
1242
+ }
1243
+ }, _callee);
1244
+ }));
1245
+ return function addAuthorization(_x, _x2, _x3, _x4, _x5) {
1246
+ return _ref.apply(this, arguments);
1247
+ };
1248
+ }();
1249
+ // 组装完整Url
1250
+ var buildUrl = function buildUrl() {
1251
+ var path = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
1252
+ var isSandbox = arguments.length > 1 ? arguments[1] : undefined;
1253
+ return "".concat(isSandbox ? 'https://sandbox.api.sgroup.qq.com' : 'https://api.sgroup.qq.com').concat(path);
1254
+ };
1255
+
1256
+ var Channel = /*#__PURE__*/function () {
1257
+ function Channel(request, config) {
1258
+ _classCallCheck(this, Channel);
1259
+ _defineProperty(this, "request", void 0);
1260
+ _defineProperty(this, "config", void 0);
1261
+ this.request = request;
1262
+ this.config = config;
1263
+ }
1264
+ // 获取子频道信息
1265
+ return _createClass(Channel, [{
1266
+ key: "channel",
1267
+ value: function channel(channelID) {
1268
+ var options = {
1269
+ method: 'GET',
1270
+ url: getURL('channelURI'),
1271
+ rest: {
1272
+ channelID: channelID
1273
+ }
1274
+ };
1275
+ return this.request(options);
1276
+ }
1277
+
1278
+ // 获取频道下的子频道列表
1279
+ }, {
1280
+ key: "channels",
1281
+ value: function channels(guildID) {
1282
+ var options = {
1283
+ method: 'GET',
1284
+ url: getURL('channelsURI'),
1285
+ rest: {
1286
+ guildID: guildID
1287
+ }
1288
+ };
1289
+ return this.request(options);
1290
+ }
1291
+
1292
+ // 创建子频道
1293
+ }, {
1294
+ key: "postChannel",
1295
+ value: function postChannel(guildID, channel) {
1296
+ if (channel.position === 0) {
1297
+ channel.position = getTimeStampNumber();
1298
+ }
1299
+ var options = {
1300
+ method: 'POST',
1301
+ url: getURL('channelsURI'),
1302
+ rest: {
1303
+ guildID: guildID
1304
+ },
1305
+ data: channel
1306
+ };
1307
+ return this.request(options);
1308
+ }
1309
+
1310
+ // 修改子频道信息
1311
+ }, {
1312
+ key: "patchChannel",
1313
+ value: function patchChannel(channelID, channel) {
1314
+ if (channel.position === 0) {
1315
+ channel.position = getTimeStampNumber();
1316
+ }
1317
+ var options = {
1318
+ method: 'PATCH',
1319
+ url: getURL('channelURI'),
1320
+ rest: {
1321
+ channelID: channelID
1322
+ },
1323
+ data: channel
1324
+ };
1325
+ return this.request(options);
1326
+ }
1327
+ // 删除指定子频道
1328
+ }, {
1329
+ key: "deleteChannel",
1330
+ value: function deleteChannel(channelID) {
1331
+ var options = {
1332
+ method: 'DELETE',
1333
+ url: getURL('channelURI'),
1334
+ rest: {
1335
+ channelID: channelID
1336
+ }
1337
+ };
1338
+ return this.request(options);
1339
+ }
1340
+ }]);
1341
+ }();
1342
+
1343
+ var Me = /*#__PURE__*/function () {
1344
+ function Me(request, config) {
1345
+ _classCallCheck(this, Me);
1346
+ _defineProperty(this, "request", void 0);
1347
+ _defineProperty(this, "config", void 0);
1348
+ this.request = request;
1349
+ this.config = config;
1350
+ }
1351
+
1352
+ // 获取当前用户信息
1353
+ return _createClass(Me, [{
1354
+ key: "me",
1355
+ value: function me() {
1356
+ var options = {
1357
+ method: 'GET',
1358
+ url: getURL('userMeURI')
1359
+ };
1360
+ return this.request(options);
1361
+ }
1362
+
1363
+ // 获取当前用户频道列表
1364
+ }, {
1365
+ key: "meGuilds",
1366
+ value: function meGuilds(options) {
1367
+ var reqOptions = {
1368
+ method: 'GET',
1369
+ url: getURL('userMeGuildsURI'),
1370
+ params: options
1371
+ };
1372
+ return this.request(reqOptions);
1373
+ }
1374
+ }]);
1375
+ }();
1376
+
1377
+ var Message = /*#__PURE__*/function () {
1378
+ function Message(request, config) {
1379
+ _classCallCheck(this, Message);
1380
+ _defineProperty(this, "request", void 0);
1381
+ _defineProperty(this, "config", void 0);
1382
+ this.request = request;
1383
+ this.config = config;
1384
+ }
1385
+
1386
+ // 获取指定消息
1387
+ return _createClass(Message, [{
1388
+ key: "message",
1389
+ value: function message(channelID, messageID) {
1390
+ var options = {
1391
+ method: 'GET',
1392
+ url: getURL('messageURI'),
1393
+ rest: {
1394
+ channelID: channelID,
1395
+ messageID: messageID
1396
+ }
1397
+ };
1398
+ return this.request(options);
1399
+ }
1400
+
1401
+ // 获取消息列表
1402
+ }, {
1403
+ key: "messages",
1404
+ value: function messages(channelID, pager) {
1405
+ var params = Object.create(null);
1406
+ if (pager && pager.type && pager.id) {
1407
+ params[pager.type] = pager.id;
1408
+ params.limit = pager.limit || 20;
1409
+ }
1410
+ var options = {
1411
+ method: 'GET',
1412
+ url: getURL('messagesURI'),
1413
+ rest: {
1414
+ channelID: channelID
1415
+ },
1416
+ params: params
1417
+ };
1418
+ return this.request(options);
1419
+ }
1420
+
1421
+ // 发送消息
1422
+ }, {
1423
+ key: "postMessage",
1424
+ value: function postMessage(channelID, message) {
1425
+ var options = {
1426
+ method: 'POST',
1427
+ url: getURL('messagesURI'),
1428
+ rest: {
1429
+ channelID: channelID
1430
+ },
1431
+ data: message
1432
+ };
1433
+ return this.request(options);
1434
+ }
1435
+
1436
+ // 修改消息
1437
+ }, {
1438
+ key: "patchMessage",
1439
+ value: function patchMessage(channelID, messageID, message) {
1440
+ var options = {
1441
+ method: 'PATCH',
1442
+ url: getURL('messageURI'),
1443
+ rest: {
1444
+ channelID: channelID,
1445
+ messageID: messageID
1446
+ },
1447
+ data: message
1448
+ };
1449
+ return this.request(options);
1450
+ }
1451
+
1452
+ // 频道撤回消息
1453
+ }, {
1454
+ key: "deleteMessage",
1455
+ value: function deleteMessage(channelID, messageID, hideTip) {
1456
+ var params = Object.create(null);
1457
+ if (hideTip) {
1458
+ params.hidetip = hideTip;
1459
+ }
1460
+ var options = {
1461
+ method: 'DELETE',
1462
+ url: getURL('messageURI'),
1463
+ rest: {
1464
+ channelID: channelID,
1465
+ messageID: messageID
1466
+ },
1467
+ params: params
1468
+ };
1469
+ return this.request(options);
1470
+ }
1471
+
1472
+ // C2C撤回消息
1473
+ }, {
1474
+ key: "deleteC2CMessage",
1475
+ value: function deleteC2CMessage(userID, messageID, hideTip) {
1476
+ var params = Object.create(null);
1477
+ if (hideTip) {
1478
+ params.hidetip = hideTip;
1479
+ }
1480
+ var options = {
1481
+ method: 'DELETE',
1482
+ url: getURL('c2cMessageURI'),
1483
+ rest: {
1484
+ userID: userID,
1485
+ messageID: messageID
1486
+ },
1487
+ params: params
1488
+ };
1489
+ return this.request(options);
1490
+ }
1491
+
1492
+ // 群组撤回消息
1493
+ }, {
1494
+ key: "deleteGroupMessage",
1495
+ value: function deleteGroupMessage(groupID, messageID, hideTip) {
1496
+ var params = Object.create(null);
1497
+ if (hideTip) {
1498
+ params.hidetip = hideTip;
1499
+ }
1500
+ var options = {
1501
+ method: 'DELETE',
1502
+ url: getURL('groupMessageURI'),
1503
+ rest: {
1504
+ groupID: groupID,
1505
+ messageID: messageID
1506
+ },
1507
+ params: params
1508
+ };
1509
+ return this.request(options);
1510
+ }
1511
+
1512
+ // 发送群消息
1513
+ }, {
1514
+ key: "postGroupMessage",
1515
+ value: function postGroupMessage(groupID, message) {
1516
+ message.timestamp = Date.now();
1517
+ var options = {
1518
+ method: 'POST',
1519
+ url: getURL('groupMessagesURI'),
1520
+ rest: {
1521
+ groupID: groupID
1522
+ },
1523
+ data: message,
1524
+ apiVersion: 'v2'
1525
+ };
1526
+ return this.request(options);
1527
+ }
1528
+
1529
+ // 发送C2C消息
1530
+ }, {
1531
+ key: "postC2CMessage",
1532
+ value: function postC2CMessage(userID, message) {
1533
+ message.timestamp = Date.now();
1534
+ var options = {
1535
+ method: 'POST',
1536
+ url: getURL('c2cMessagesURI'),
1537
+ rest: {
1538
+ userID: userID
1539
+ },
1540
+ data: message,
1541
+ apiVersion: 'v2'
1542
+ };
1543
+ return this.request(options);
1544
+ }
1545
+
1546
+ // 发送群富媒体消息
1547
+ }, {
1548
+ key: "postGroupMedia",
1549
+ value: function postGroupMedia(groupID, message) {
1550
+ var options = {
1551
+ method: 'POST',
1552
+ url: getURL('groupRichMediaURI'),
1553
+ rest: {
1554
+ groupID: groupID
1555
+ },
1556
+ data: message,
1557
+ apiVersion: 'v2'
1558
+ };
1559
+ return this.request(options);
1560
+ }
1561
+
1562
+ // 发送C2C消息
1563
+ }, {
1564
+ key: "postC2CMedia",
1565
+ value: function postC2CMedia(userID, message) {
1566
+ var options = {
1567
+ method: 'POST',
1568
+ url: getURL('c2cRichMediaURI'),
1569
+ rest: {
1570
+ userID: userID
1571
+ },
1572
+ data: message,
1573
+ apiVersion: 'v2'
1574
+ };
1575
+ return this.request(options);
1576
+ }
1577
+ }]);
1578
+ }();
1579
+
1580
+ var Member = /*#__PURE__*/function () {
1581
+ function Member(request, config) {
1582
+ _classCallCheck(this, Member);
1583
+ _defineProperty(this, "request", void 0);
1584
+ _defineProperty(this, "config", void 0);
1585
+ this.request = request;
1586
+ this.config = config;
1587
+ }
1588
+
1589
+ // 增加频道身份组成员
1590
+ return _createClass(Member, [{
1591
+ key: "memberAddRole",
1592
+ value: function memberAddRole(guildID, roleID, userID, channel // 兼容原来传递 channel 对象的逻辑,后续仅支持 string
1593
+ ) {
1594
+ var channelObj = typeof channel === 'string' ? {
1595
+ channel: {
1596
+ id: channel
1597
+ }
1598
+ } : channel;
1599
+ var options = {
1600
+ method: 'PUT',
1601
+ url: getURL('memberRoleURI'),
1602
+ rest: {
1603
+ guildID: guildID,
1604
+ userID: userID,
1605
+ roleID: roleID
1606
+ },
1607
+ data: channelObj
1608
+ };
1609
+ return this.request(options);
1610
+ }
1611
+
1612
+ // 删除频道身份组成员
1613
+ }, {
1614
+ key: "memberDeleteRole",
1615
+ value: function memberDeleteRole(guildID, roleID, userID, channel // 兼容原来传递 channel 对象的逻辑,后续仅支持 string
1616
+ ) {
1617
+ var channelObj = typeof channel === 'string' ? {
1618
+ channel: {
1619
+ id: channel
1620
+ }
1621
+ } : channel;
1622
+ var options = {
1623
+ method: 'DELETE',
1624
+ url: getURL('memberRoleURI'),
1625
+ rest: {
1626
+ guildID: guildID,
1627
+ userID: userID,
1628
+ roleID: roleID
1629
+ },
1630
+ data: channelObj
1631
+ };
1632
+ return this.request(options);
1633
+ }
1634
+
1635
+ // 获取身份组成员列表
1636
+ }, {
1637
+ key: "guildRolesMembers",
1638
+ value: function guildRolesMembers(guildID, roleID, pager) {
1639
+ pager = pager || {
1640
+ start_index: '0',
1641
+ limit: 1
1642
+ };
1643
+ var options = {
1644
+ method: 'GET',
1645
+ url: getURL('guildRolesMembersURI'),
1646
+ rest: {
1647
+ guildID: guildID,
1648
+ roleID: roleID
1649
+ },
1650
+ params: pager
1651
+ };
1652
+ return this.request(options);
1653
+ }
1654
+ }]);
1655
+ }();
1656
+
1657
+ // 默认的filter:0 1 代表是否设置 0-否 1-是
1658
+ var defaultFilter = {
1659
+ name: 1,
1660
+ color: 1,
1661
+ hoist: 1
1662
+ };
1663
+
1664
+ // 用户组默认颜色值
1665
+ var defaultColor = 4278245297;
1666
+ var Role = /*#__PURE__*/function () {
1667
+ function Role(request, config) {
1668
+ _classCallCheck(this, Role);
1669
+ _defineProperty(this, "request", void 0);
1670
+ _defineProperty(this, "config", void 0);
1671
+ this.request = request;
1672
+ this.config = config;
1673
+ }
1674
+ // 获取频道身份组列表
1675
+ return _createClass(Role, [{
1676
+ key: "roles",
1677
+ value: function roles(guildID) {
1678
+ var options = {
1679
+ method: 'GET',
1680
+ url: getURL('rolesURI'),
1681
+ rest: {
1682
+ guildID: guildID
1683
+ }
1684
+ };
1685
+ return this.request(options);
1686
+ }
1687
+
1688
+ // 创建频道身份组
1689
+ }, {
1690
+ key: "postRole",
1691
+ value: function postRole(guildID, role) {
1692
+ var filter = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : defaultFilter;
1693
+ if (role.color === 0) {
1694
+ role.color = defaultColor;
1695
+ }
1696
+ var options = {
1697
+ method: 'POST',
1698
+ url: getURL('rolesURI'),
1699
+ rest: {
1700
+ guildID: guildID
1701
+ },
1702
+ data: {
1703
+ guild_id: guildID,
1704
+ filter: filter,
1705
+ info: role
1706
+ }
1707
+ };
1708
+ return this.request(options);
1709
+ }
1710
+
1711
+ // 修改频道身份组
1712
+ }, {
1713
+ key: "patchRole",
1714
+ value: function patchRole(guildID, roleID, role) {
1715
+ var filter = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : defaultFilter;
1716
+ if (role.color === 0) {
1717
+ role.color = defaultColor;
1718
+ }
1719
+ var options = {
1720
+ method: 'PATCH',
1721
+ url: getURL('roleURI'),
1722
+ rest: {
1723
+ guildID: guildID,
1724
+ roleID: roleID
1725
+ },
1726
+ data: {
1727
+ guild_id: guildID,
1728
+ filter: filter,
1729
+ info: role
1730
+ }
1731
+ };
1732
+ return this.request(options);
1733
+ }
1734
+
1735
+ // 删除频道身份组
1736
+ }, {
1737
+ key: "deleteRole",
1738
+ value: function deleteRole(guildID, roleID) {
1739
+ var options = {
1740
+ method: 'DELETE',
1741
+ url: getURL('roleURI'),
1742
+ rest: {
1743
+ guildID: guildID,
1744
+ roleID: roleID
1745
+ }
1746
+ };
1747
+ return this.request(options);
1748
+ }
1749
+ }]);
1750
+ }();
1751
+
1752
+ var DirectMessage = /*#__PURE__*/function () {
1753
+ function DirectMessage(request, config) {
1754
+ _classCallCheck(this, DirectMessage);
1755
+ _defineProperty(this, "request", void 0);
1756
+ _defineProperty(this, "config", void 0);
1757
+ this.request = request;
1758
+ this.config = config;
1759
+ }
1760
+ // 创建私信频道
1761
+ return _createClass(DirectMessage, [{
1762
+ key: "createDirectMessage",
1763
+ value: function createDirectMessage(dm) {
1764
+ var options = {
1765
+ method: 'POST',
1766
+ url: getURL('userMeDMURI'),
1767
+ data: dm
1768
+ };
1769
+ return this.request(options);
1770
+ }
1771
+
1772
+ // 在私信频道内发消息
1773
+ }, {
1774
+ key: "postDirectMessage",
1775
+ value: function postDirectMessage(guildID, msg) {
1776
+ var options = {
1777
+ method: 'POST',
1778
+ url: getURL('dmsURI'),
1779
+ rest: {
1780
+ guildID: guildID
1781
+ },
1782
+ data: msg
1783
+ };
1784
+ return this.request(options);
1785
+ }
1786
+ }]);
1787
+ }();
1788
+
1789
+ var ChannelPermissions = /*#__PURE__*/function () {
1790
+ function ChannelPermissions(request, config) {
1791
+ _classCallCheck(this, ChannelPermissions);
1792
+ _defineProperty(this, "request", void 0);
1793
+ _defineProperty(this, "config", void 0);
1794
+ this.request = request;
1795
+ this.config = config;
1796
+ }
1797
+
1798
+ // 获取指定子频道的权限
1799
+ return _createClass(ChannelPermissions, [{
1800
+ key: "channelPermissions",
1801
+ value: function channelPermissions(channelID, userID) {
1802
+ var options = {
1803
+ method: 'GET',
1804
+ url: getURL('channelPermissionsURI'),
1805
+ rest: {
1806
+ channelID: channelID,
1807
+ userID: userID
1808
+ }
1809
+ };
1810
+ return this.request(options);
1811
+ }
1812
+
1813
+ // 修改指定子频道的权限
1814
+ }, {
1815
+ key: "putChannelPermissions",
1816
+ value: function putChannelPermissions(channelID, userID, p) {
1817
+ try {
1818
+ // 校验参数
1819
+ parseInt(p.add, 10);
1820
+ parseInt(p.remove, 10);
1821
+ } catch (error) {
1822
+ return Promise.reject(new Error('invalid parameter'));
1823
+ }
1824
+ var options = {
1825
+ method: 'PUT',
1826
+ url: getURL('channelPermissionsURI'),
1827
+ rest: {
1828
+ channelID: channelID,
1829
+ userID: userID
1830
+ },
1831
+ data: p
1832
+ };
1833
+ return this.request(options);
1834
+ }
1835
+
1836
+ // 获取指定子频道身份组的权限
1837
+ }, {
1838
+ key: "channelRolePermissions",
1839
+ value: function channelRolePermissions(channelID, roleID) {
1840
+ var options = {
1841
+ method: 'GET',
1842
+ url: getURL('channelRolePermissionsURI'),
1843
+ rest: {
1844
+ channelID: channelID,
1845
+ roleID: roleID
1846
+ }
1847
+ };
1848
+ return this.request(options);
1849
+ }
1850
+
1851
+ // 修改指定子频道身份组的权限
1852
+ }, {
1853
+ key: "putChannelRolePermissions",
1854
+ value: function putChannelRolePermissions(channelID, roleID, p) {
1855
+ try {
1856
+ // 校验参数
1857
+ parseInt(p.add, 10);
1858
+ parseInt(p.remove, 10);
1859
+ } catch (error) {
1860
+ return Promise.reject(new Error('invalid parameter'));
1861
+ }
1862
+ var options = {
1863
+ method: 'PUT',
1864
+ url: getURL('channelRolePermissionsURI'),
1865
+ rest: {
1866
+ channelID: channelID,
1867
+ roleID: roleID
1868
+ },
1869
+ data: p
1870
+ };
1871
+ return this.request(options);
1872
+ }
1873
+ }]);
1874
+ }();
1875
+
1876
+ var Audio = /*#__PURE__*/function () {
1877
+ function Audio(request, config) {
1878
+ _classCallCheck(this, Audio);
1879
+ _defineProperty(this, "request", void 0);
1880
+ _defineProperty(this, "config", void 0);
1881
+ this.request = request;
1882
+ this.config = config;
1883
+ }
1884
+ // 执行音频播放,暂停等操作
1885
+ return _createClass(Audio, [{
1886
+ key: "postAudio",
1887
+ value: function postAudio(channelID, audioControl) {
1888
+ var options = {
1889
+ method: 'POST',
1890
+ url: getURL('audioControlURI'),
1891
+ rest: {
1892
+ channelID: channelID
1893
+ },
1894
+ data: audioControl
1895
+ };
1896
+ return this.request(options);
1897
+ }
1898
+ // 机器人上麦
1899
+ }, {
1900
+ key: "botOnMic",
1901
+ value: function botOnMic(channelID) {
1902
+ var options = {
1903
+ method: 'PUT',
1904
+ url: getURL('botMic'),
1905
+ rest: {
1906
+ channelID: channelID
1907
+ },
1908
+ data: {}
1909
+ };
1910
+ return this.request(options);
1911
+ }
1912
+ // 机器人下麦
1913
+ }, {
1914
+ key: "botOffMic",
1915
+ value: function botOffMic(channelID) {
1916
+ var options = {
1917
+ method: 'DELETE',
1918
+ url: getURL('botMic'),
1919
+ rest: {
1920
+ channelID: channelID
1921
+ },
1922
+ data: {}
1923
+ };
1924
+ return this.request(options);
1925
+ }
1926
+ }]);
1927
+ }();
1928
+
1929
+ function ownKeys$1(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
1930
+ function _objectSpread$1(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$1(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
1931
+ var Mute = /*#__PURE__*/function () {
1932
+ function Mute(request, config) {
1933
+ _classCallCheck(this, Mute);
1934
+ _defineProperty(this, "request", void 0);
1935
+ _defineProperty(this, "config", void 0);
1936
+ this.request = request;
1937
+ this.config = config;
1938
+ }
1939
+
1940
+ // 禁言某个member
1941
+ return _createClass(Mute, [{
1942
+ key: "muteMember",
1943
+ value: function muteMember(guildID, userID, options) {
1944
+ if (!options) {
1945
+ return Promise.reject(new Error("'options' required!"));
1946
+ }
1947
+ var reqOptions = {
1948
+ method: 'PATCH',
1949
+ url: getURL('muteMemberURI'),
1950
+ rest: {
1951
+ guildID: guildID,
1952
+ userID: userID
1953
+ },
1954
+ data: options
1955
+ };
1956
+ return this.request(reqOptions);
1957
+ }
1958
+
1959
+ // 禁言所有人
1960
+ }, {
1961
+ key: "muteAll",
1962
+ value: function muteAll(guildID, options) {
1963
+ if (!options) {
1964
+ return Promise.reject(new Error("'options' required!"));
1965
+ }
1966
+ var reqOptions = {
1967
+ method: 'PATCH',
1968
+ url: getURL('muteURI'),
1969
+ rest: {
1970
+ guildID: guildID
1971
+ },
1972
+ data: options
1973
+ };
1974
+ return this.request(reqOptions);
1975
+ }
1976
+
1977
+ // 禁言批量member
1978
+ }, {
1979
+ key: "muteMembers",
1980
+ value: function muteMembers(guildID, userIDList, options) {
1981
+ if (!options) {
1982
+ return Promise.reject(new Error("'options' required!"));
1983
+ }
1984
+ var reqOptions = {
1985
+ method: 'PATCH',
1986
+ url: getURL('muteMembersURI'),
1987
+ rest: {
1988
+ guildID: guildID
1989
+ },
1990
+ // 将options和userIDList合并到一起
1991
+ data: _objectSpread$1(_objectSpread$1({}, options), {}, {
1992
+ user_ids: userIDList
1993
+ })
1994
+ };
1995
+ return this.request(reqOptions);
1996
+ }
1997
+ }]);
1998
+ }();
1999
+
2000
+ var Announce = /*#__PURE__*/function () {
2001
+ function Announce(request, config) {
2002
+ _classCallCheck(this, Announce);
2003
+ _defineProperty(this, "request", void 0);
2004
+ _defineProperty(this, "config", void 0);
2005
+ this.request = request;
2006
+ this.config = config;
2007
+ }
2008
+
2009
+ // 创建guild公告
2010
+ return _createClass(Announce, [{
2011
+ key: "postGuildAnnounce",
2012
+ value: function postGuildAnnounce(guildID, channelID, messageID) {
2013
+ var options = {
2014
+ method: 'POST',
2015
+ url: getURL('guildAnnouncesURI'),
2016
+ rest: {
2017
+ guildID: guildID
2018
+ },
2019
+ data: {
2020
+ channel_id: channelID,
2021
+ message_id: messageID
2022
+ }
2023
+ };
2024
+ return this.request(options);
2025
+ }
2026
+
2027
+ // 删除guild公告
2028
+ }, {
2029
+ key: "deleteGuildAnnounce",
2030
+ value: function deleteGuildAnnounce(guildID, messageID) {
2031
+ var options = {
2032
+ method: 'DELETE',
2033
+ url: getURL('guildAnnounceURI'),
2034
+ rest: {
2035
+ guildID: guildID,
2036
+ messageID: messageID
2037
+ }
2038
+ };
2039
+ return this.request(options);
2040
+ }
2041
+
2042
+ // 创建频道公告推荐子频道
2043
+ }, {
2044
+ key: "postGuildRecommend",
2045
+ value: function postGuildRecommend(guildID, recommendObj) {
2046
+ var options = {
2047
+ method: 'POST',
2048
+ url: getURL('guildAnnouncesURI'),
2049
+ rest: {
2050
+ guildID: guildID
2051
+ },
2052
+ data: recommendObj
2053
+ };
2054
+ return this.request(options);
2055
+ }
2056
+
2057
+ // 创建channel公告
2058
+ }, {
2059
+ key: "postChannelAnnounce",
2060
+ value: function postChannelAnnounce(channelID, messageID) {
2061
+ var options = {
2062
+ method: 'POST',
2063
+ url: getURL('channelAnnouncesURI'),
2064
+ rest: {
2065
+ channelID: channelID
2066
+ },
2067
+ data: {
2068
+ message_id: messageID
2069
+ }
2070
+ };
2071
+ return this.request(options);
2072
+ }
2073
+
2074
+ // 删除channel公告
2075
+ }, {
2076
+ key: "deleteChannelAnnounce",
2077
+ value: function deleteChannelAnnounce(channelID, messageID) {
2078
+ var options = {
2079
+ method: 'DELETE',
2080
+ url: getURL('channelAnnounceURI'),
2081
+ rest: {
2082
+ channelID: channelID,
2083
+ messageID: messageID
2084
+ }
2085
+ };
2086
+ return this.request(options);
2087
+ }
2088
+ }]);
2089
+ }();
2090
+
2091
+ var Schedule = /*#__PURE__*/function () {
2092
+ function Schedule(request, config) {
2093
+ _classCallCheck(this, Schedule);
2094
+ _defineProperty(this, "request", void 0);
2095
+ _defineProperty(this, "config", void 0);
2096
+ this.request = request;
2097
+ this.config = config;
2098
+ }
2099
+
2100
+ // 获取日程列表
2101
+ return _createClass(Schedule, [{
2102
+ key: "schedules",
2103
+ value: function schedules(channelID, since) {
2104
+ if (since && since.length !== 13) {
2105
+ return Promise.reject(new Error("Param 'since' is invalid, millisecond timestamp expected!"));
2106
+ }
2107
+ var options = {
2108
+ method: 'GET',
2109
+ url: getURL('schedulesURI'),
2110
+ rest: {
2111
+ channelID: channelID
2112
+ },
2113
+ params: {
2114
+ since: since
2115
+ }
2116
+ };
2117
+ return this.request(options);
2118
+ }
2119
+
2120
+ // 获取日程
2121
+ }, {
2122
+ key: "schedule",
2123
+ value: function schedule(channelID, scheduleID) {
2124
+ var options = {
2125
+ method: 'GET',
2126
+ url: getURL('scheduleURI'),
2127
+ rest: {
2128
+ channelID: channelID,
2129
+ scheduleID: scheduleID
2130
+ }
2131
+ };
2132
+ return this.request(options);
2133
+ }
2134
+
2135
+ // 创建日程
2136
+ }, {
2137
+ key: "postSchedule",
2138
+ value: function postSchedule(channelID, schedule) {
2139
+ var options = {
2140
+ method: 'POST',
2141
+ url: getURL('schedulesURI'),
2142
+ rest: {
2143
+ channelID: channelID
2144
+ },
2145
+ data: {
2146
+ schedule: schedule
2147
+ }
2148
+ };
2149
+ return this.request(options);
2150
+ }
2151
+
2152
+ // 修改日程
2153
+ }, {
2154
+ key: "patchSchedule",
2155
+ value: function patchSchedule(channelID, scheduleID, schedule) {
2156
+ var options = {
2157
+ method: 'PATCH',
2158
+ url: getURL('scheduleURI'),
2159
+ rest: {
2160
+ channelID: channelID,
2161
+ scheduleID: scheduleID
2162
+ },
2163
+ data: {
2164
+ schedule: schedule
2165
+ }
2166
+ };
2167
+ return this.request(options);
2168
+ }
2169
+
2170
+ // 删除日程
2171
+ }, {
2172
+ key: "deleteSchedule",
2173
+ value: function deleteSchedule(channelID, scheduleID) {
2174
+ var options = {
2175
+ method: 'DELETE',
2176
+ url: getURL('scheduleURI'),
2177
+ rest: {
2178
+ channelID: channelID,
2179
+ scheduleID: scheduleID
2180
+ }
2181
+ };
2182
+ return this.request(options);
2183
+ }
2184
+ }]);
2185
+ }();
2186
+
2187
+ var GuildPermissions = /*#__PURE__*/function () {
2188
+ function GuildPermissions(request, config) {
2189
+ _classCallCheck(this, GuildPermissions);
2190
+ _defineProperty(this, "request", void 0);
2191
+ _defineProperty(this, "config", void 0);
2192
+ this.request = request;
2193
+ this.config = config;
2194
+ }
2195
+
2196
+ // 获取频道可用权限列表
2197
+ return _createClass(GuildPermissions, [{
2198
+ key: "permissions",
2199
+ value: function permissions(guildID) {
2200
+ var options = {
2201
+ method: 'GET',
2202
+ url: getURL('guildPermissionURI'),
2203
+ rest: {
2204
+ guildID: guildID
2205
+ }
2206
+ };
2207
+ return this.request(options);
2208
+ }
2209
+
2210
+ // 创建频道 API 接口权限授权链接
2211
+ }, {
2212
+ key: "postPermissionDemand",
2213
+ value: function postPermissionDemand(guildID, permissionDemandObj) {
2214
+ var options = {
2215
+ method: 'POST',
2216
+ url: getURL('guildPermissionDemandURI'),
2217
+ rest: {
2218
+ guildID: guildID
2219
+ },
2220
+ data: permissionDemandObj
2221
+ };
2222
+ return this.request(options);
2223
+ }
2224
+ }]);
2225
+ }();
2226
+
2227
+ var Interaction = /*#__PURE__*/function () {
2228
+ function Interaction(request, config) {
2229
+ _classCallCheck(this, Interaction);
2230
+ _defineProperty(this, "request", void 0);
2231
+ _defineProperty(this, "config", void 0);
2232
+ this.request = request;
2233
+ this.config = config;
2234
+ }
2235
+
2236
+ // 异步更新交互数据
2237
+ return _createClass(Interaction, [{
2238
+ key: "putInteraction",
2239
+ value: function putInteraction(interactionID, interactionData) {
2240
+ var options = {
2241
+ method: 'PUT',
2242
+ url: getURL('interactionURI'),
2243
+ headers: {
2244
+ 'Content-Type': 'none'
2245
+ },
2246
+ rest: {
2247
+ interactionID: interactionID
2248
+ },
2249
+ data: interactionData
2250
+ };
2251
+ return this.request(options);
2252
+ }
2253
+ }]);
2254
+ }();
2255
+
2256
+ function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
2257
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
2258
+ var apiVersion = 'v1';
2259
+ var OpenAPI = /*#__PURE__*/function () {
2260
+ function OpenAPI(config) {
2261
+ _classCallCheck(this, OpenAPI);
2262
+ _defineProperty(this, "config", {
2263
+ appID: '',
2264
+ token: ''
2265
+ });
2266
+ _defineProperty(this, "guildApi", void 0);
2267
+ _defineProperty(this, "channelApi", void 0);
2268
+ _defineProperty(this, "meApi", void 0);
2269
+ _defineProperty(this, "messageApi", void 0);
2270
+ _defineProperty(this, "memberApi", void 0);
2271
+ _defineProperty(this, "roleApi", void 0);
2272
+ _defineProperty(this, "muteApi", void 0);
2273
+ _defineProperty(this, "announceApi", void 0);
2274
+ _defineProperty(this, "scheduleApi", void 0);
2275
+ _defineProperty(this, "directMessageApi", void 0);
2276
+ _defineProperty(this, "channelPermissionsApi", void 0);
2277
+ _defineProperty(this, "audioApi", void 0);
2278
+ _defineProperty(this, "reactionApi", void 0);
2279
+ _defineProperty(this, "interactionApi", void 0);
2280
+ _defineProperty(this, "pinsMessageApi", void 0);
2281
+ _defineProperty(this, "guildPermissionsApi", void 0);
2282
+ this.config = config;
2283
+ this.register(this);
2284
+ }
2285
+ return _createClass(OpenAPI, [{
2286
+ key: "register",
2287
+ value: function register(client) {
2288
+ // 注册聚合client
2289
+ client.guildApi = new Guild(this.request, this.config);
2290
+ client.channelApi = new Channel(this.request, this.config);
2291
+ client.meApi = new Me(this.request, this.config);
2292
+ client.messageApi = new Message(this.request, this.config);
2293
+ client.memberApi = new Member(this.request, this.config);
2294
+ client.roleApi = new Role(this.request, this.config);
2295
+ client.muteApi = new Mute(this.request, this.config);
2296
+ client.announceApi = new Announce(this.request, this.config);
2297
+ client.scheduleApi = new Schedule(this.request, this.config);
2298
+ client.directMessageApi = new DirectMessage(this.request, this.config);
2299
+ client.channelPermissionsApi = new ChannelPermissions(this.request, this.config);
2300
+ client.audioApi = new Audio(this.request, this.config);
2301
+ client.guildPermissionsApi = new GuildPermissions(this.request, this.config);
2302
+ client.reactionApi = new Reaction(this.request, this.config);
2303
+ client.interactionApi = new Interaction(this.request, this.config);
2304
+ client.pinsMessageApi = new PinsMessage(this.request, this.config);
2305
+ }
2306
+
2307
+ // 基础rest请求
2308
+ }, {
2309
+ key: "request",
2310
+ value: function request(options) {
2311
+ var _this$config = this.config,
2312
+ appID = _this$config.appID,
2313
+ token = _this$config.token,
2314
+ clientSecret = _this$config.clientSecret;
2315
+ options.headers = _objectSpread({}, options.headers);
2316
+ var apiVersion = options.apiVersion || '';
2317
+ // 添加 UA
2318
+ addUserAgent(options.headers, appID, apiVersion);
2319
+ // 添加鉴权信息
2320
+ addAuthorization(options.headers, appID, token, clientSecret, apiVersion);
2321
+ // 组装完整Url
2322
+ var botUrl = buildUrl(options.url, this.config.sandbox);
2323
+
2324
+ // 简化错误信息,后续可考虑通过中间件形式暴露给用户自行处理
2325
+ resty.useRes(function (result) {
2326
+ return result;
2327
+ }, function (error) {
2328
+ var _error$response, _error$response2;
2329
+ var traceid = error === null || error === void 0 || (_error$response = error.response) === null || _error$response === void 0 || (_error$response = _error$response.headers) === null || _error$response === void 0 ? void 0 : _error$response['x-tps-trace-id'];
2330
+ if (error !== null && error !== void 0 && (_error$response2 = error.response) !== null && _error$response2 !== void 0 && _error$response2.data) {
2331
+ return Promise.reject(_objectSpread(_objectSpread({}, error.response.data), {}, {
2332
+ traceid: traceid
2333
+ }));
2334
+ }
2335
+ if (error !== null && error !== void 0 && error.response) {
2336
+ return Promise.reject(_objectSpread(_objectSpread({}, error.response), {}, {
2337
+ traceid: traceid
2338
+ }));
2339
+ }
2340
+ return Promise.reject(error);
2341
+ });
2342
+ var client = resty.create(options);
2343
+ return client.request(botUrl, options);
2344
+ }
2345
+ }], [{
2346
+ key: "newClient",
2347
+ value: function newClient(config) {
2348
+ return new OpenAPI(config);
2349
+ }
2350
+ }]);
2351
+ }();
2352
+ function v1Setup() {
2353
+ register(apiVersion, OpenAPI);
2354
+ }
2355
+
2356
+ function _assertThisInitialized(self) {
2357
+ if (self === void 0) {
2358
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
2359
+ }
2360
+ return self;
2361
+ }
2362
+
2363
+ function _possibleConstructorReturn(self, call) {
2364
+ if (call && (_typeof$1(call) === "object" || typeof call === "function")) {
2365
+ return call;
2366
+ } else if (call !== void 0) {
2367
+ throw new TypeError("Derived constructors may only return object or undefined");
2368
+ }
2369
+ return _assertThisInitialized(self);
2370
+ }
2371
+
2372
+ function _getPrototypeOf(o) {
2373
+ _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
2374
+ return o.__proto__ || Object.getPrototypeOf(o);
2375
+ };
2376
+ return _getPrototypeOf(o);
2377
+ }
2378
+
2379
+ function _setPrototypeOf(o, p) {
2380
+ _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
2381
+ o.__proto__ = p;
2382
+ return o;
2383
+ };
2384
+ return _setPrototypeOf(o, p);
2385
+ }
2386
+
2387
+ function _inherits(subClass, superClass) {
2388
+ if (typeof superClass !== "function" && superClass !== null) {
2389
+ throw new TypeError("Super expression must either be null or a function");
2390
+ }
2391
+ subClass.prototype = Object.create(superClass && superClass.prototype, {
2392
+ constructor: {
2393
+ value: subClass,
2394
+ writable: true,
2395
+ configurable: true
2396
+ }
2397
+ });
2398
+ Object.defineProperty(subClass, "prototype", {
2399
+ writable: false
2400
+ });
2401
+ if (superClass) _setPrototypeOf(subClass, superClass);
2402
+ }
2403
+
2404
+ // websocket建立成功回包
2405
+
2406
+ // 发送心跳入参
2407
+
2408
+ // 事件分发类型
2409
+
2410
+ // 请求得到ws地址的参数
2411
+
2412
+ // 请求ws地址回包对象
2413
+
2414
+ // ws信息
2415
+
2416
+ // 会话记录
2417
+
2418
+ // 心跳参数
2419
+ var OpCode = /*#__PURE__*/function (OpCode) {
2420
+ OpCode[OpCode["DISPATCH"] = 0] = "DISPATCH";
2421
+ OpCode[OpCode["HEARTBEAT"] = 1] = "HEARTBEAT";
2422
+ OpCode[OpCode["IDENTIFY"] = 2] = "IDENTIFY";
2423
+ OpCode[OpCode["RESUME"] = 6] = "RESUME";
2424
+ OpCode[OpCode["RECONNECT"] = 7] = "RECONNECT";
2425
+ OpCode[OpCode["INVALID_SESSION"] = 9] = "INVALID_SESSION";
2426
+ OpCode[OpCode["HELLO"] = 10] = "HELLO";
2427
+ OpCode[OpCode["HEARTBEAT_ACK"] = 11] = "HEARTBEAT_ACK";
2428
+ return OpCode;
2429
+ }({}); // 当发送心跳成功之后,就会收到该消息
2430
+
2431
+ // 可使用的intents事件类型
2432
+ var AvailableIntentsEventsEnum = /*#__PURE__*/function (AvailableIntentsEventsEnum) {
2433
+ AvailableIntentsEventsEnum["GUILDS"] = "GUILDS";
2434
+ AvailableIntentsEventsEnum["GUILD_MEMBERS"] = "GUILD_MEMBERS";
2435
+ AvailableIntentsEventsEnum["GUILD_MESSAGES"] = "GUILD_MESSAGES";
2436
+ AvailableIntentsEventsEnum["GUILD_MESSAGE_REACTIONS"] = "GUILD_MESSAGE_REACTIONS";
2437
+ AvailableIntentsEventsEnum["DIRECT_MESSAGE"] = "DIRECT_MESSAGE";
2438
+ AvailableIntentsEventsEnum["FORUM_EVENT"] = "FORUM_EVENT";
2439
+ AvailableIntentsEventsEnum["AUDIO_ACTION"] = "AUDIO_ACTION";
2440
+ AvailableIntentsEventsEnum["OPEN_FORUM_EVENT"] = "OPEN_FORUM_EVENT";
2441
+ AvailableIntentsEventsEnum["AUDIO_OR_LIVE_CHANNEL_MEMBER"] = "AUDIO_OR_LIVE_CHANNEL_MEMBER";
2442
+ AvailableIntentsEventsEnum["PUBLIC_GUILD_MESSAGES"] = "PUBLIC_GUILD_MESSAGES";
2443
+ AvailableIntentsEventsEnum["MESSAGE_AUDIT"] = "MESSAGE_AUDIT";
2444
+ AvailableIntentsEventsEnum["INTERACTION"] = "INTERACTION";
2445
+ AvailableIntentsEventsEnum["GROUP_C2C_EVENT"] = "GROUP_C2C_EVENT";
2446
+ return AvailableIntentsEventsEnum;
2447
+ }({});
2448
+
2449
+ // OpenAPI传过来的事件类型
2450
+ var WsEventType = {
2451
+ // ======= GUILDS ======
2452
+ GUILD_CREATE: AvailableIntentsEventsEnum.GUILDS,
2453
+ // 频道创建
2454
+ GUILD_UPDATE: AvailableIntentsEventsEnum.GUILDS,
2455
+ // 频道更新
2456
+ GUILD_DELETE: AvailableIntentsEventsEnum.GUILDS,
2457
+ // 频道删除
2458
+ CHANNEL_CREATE: AvailableIntentsEventsEnum.GUILDS,
2459
+ // 子频道创建
2460
+ CHANNEL_UPDATE: AvailableIntentsEventsEnum.GUILDS,
2461
+ // 子频道更新
2462
+ CHANNEL_DELETE: AvailableIntentsEventsEnum.GUILDS,
2463
+ // 子频道删除
2464
+
2465
+ // ======= GUILD_MEMBERS ======
2466
+ GUILD_MEMBER_ADD: AvailableIntentsEventsEnum.GUILD_MEMBERS,
2467
+ // 频道成员加入
2468
+ GUILD_MEMBER_UPDATE: AvailableIntentsEventsEnum.GUILD_MEMBERS,
2469
+ // 频道成员更新
2470
+ GUILD_MEMBER_REMOVE: AvailableIntentsEventsEnum.GUILD_MEMBERS,
2471
+ // 频道成员移除
2472
+
2473
+ // ======= GUILD_MESSAGES ======
2474
+ MESSAGE_CREATE: AvailableIntentsEventsEnum.GUILD_MESSAGES,
2475
+ // 机器人收到频道消息时触发
2476
+ MESSAGE_DELETE: AvailableIntentsEventsEnum.GUILD_MESSAGES,
2477
+ // 删除(撤回)消息事件
2478
+
2479
+ // ======= GUILD_MESSAGE_REACTIONS ======
2480
+ MESSAGE_REACTION_ADD: AvailableIntentsEventsEnum.GUILD_MESSAGE_REACTIONS,
2481
+ // 为消息添加表情表态
2482
+ MESSAGE_REACTION_REMOVE: AvailableIntentsEventsEnum.GUILD_MESSAGE_REACTIONS,
2483
+ // 为消息删除表情表态
2484
+
2485
+ // ======= DIRECT_MESSAGE ======
2486
+ DIRECT_MESSAGE_CREATE: AvailableIntentsEventsEnum.DIRECT_MESSAGE,
2487
+ // 当收到用户发给机器人的私信消息时
2488
+ DIRECT_MESSAGE_DELETE: AvailableIntentsEventsEnum.DIRECT_MESSAGE,
2489
+ // 删除(撤回)消息事件
2490
+
2491
+ // ======= INTERACTION ======
2492
+ INTERACTION_CREATE: AvailableIntentsEventsEnum.INTERACTION,
2493
+ // 互动事件创建时
2494
+
2495
+ // ======= MESSAGE_AUDIT ======
2496
+ MESSAGE_AUDIT_PASS: AvailableIntentsEventsEnum.MESSAGE_AUDIT,
2497
+ // 消息审核通过
2498
+ MESSAGE_AUDIT_REJECT: AvailableIntentsEventsEnum.MESSAGE_AUDIT,
2499
+ // 消息审核不通过
2500
+
2501
+ // ======= FORUM_EVENT ======
2502
+ FORUM_THREAD_CREATE: AvailableIntentsEventsEnum.FORUM_EVENT,
2503
+ // 当用户创建帖子时
2504
+ FORUM_THREAD_UPDATE: AvailableIntentsEventsEnum.FORUM_EVENT,
2505
+ // 当用户更新帖子时
2506
+ FORUM_THREAD_DELETE: AvailableIntentsEventsEnum.FORUM_EVENT,
2507
+ // 当用户删除帖子时
2508
+ FORUM_POST_CREATE: AvailableIntentsEventsEnum.FORUM_EVENT,
2509
+ // 当用户创建回帖时
2510
+ FORUM_POST_DELETE: AvailableIntentsEventsEnum.FORUM_EVENT,
2511
+ // 当用户删除回帖时
2512
+ FORUM_REPLY_CREATE: AvailableIntentsEventsEnum.FORUM_EVENT,
2513
+ // 当用户回复评论时
2514
+ FORUM_REPLY_DELETE: AvailableIntentsEventsEnum.FORUM_EVENT,
2515
+ // 当用户删除评论时
2516
+ FORUM_PUBLISH_AUDIT_RESULT: AvailableIntentsEventsEnum.FORUM_EVENT,
2517
+ // 当用户发表审核通过时
2518
+
2519
+ // ======= OPEN_FORUM_EVENT ======
2520
+ OPEN_FORUM_THREAD_CREATE: AvailableIntentsEventsEnum.OPEN_FORUM_EVENT,
2521
+ // 当用户创建帖子时
2522
+ OPEN_FORUM_THREAD_UPDATE: AvailableIntentsEventsEnum.OPEN_FORUM_EVENT,
2523
+ // 当用户更新帖子时
2524
+ OPEN_FORUM_THREAD_DELETE: AvailableIntentsEventsEnum.OPEN_FORUM_EVENT,
2525
+ // 当用户删除帖子时
2526
+ OPEN_FORUM_POST_CREATE: AvailableIntentsEventsEnum.OPEN_FORUM_EVENT,
2527
+ // 当用户创建回帖时
2528
+ OPEN_FORUM_POST_DELETE: AvailableIntentsEventsEnum.OPEN_FORUM_EVENT,
2529
+ // 当用户删除回帖时
2530
+ OPEN_FORUM_REPLY_CREATE: AvailableIntentsEventsEnum.OPEN_FORUM_EVENT,
2531
+ // 当用户回复评论时
2532
+ OPEN_FORUM_REPLY_DELETE: AvailableIntentsEventsEnum.OPEN_FORUM_EVENT,
2533
+ // 当用户删除评论时
2534
+
2535
+ // ======= AUDIO_ACTION ======
2536
+ AUDIO_START: AvailableIntentsEventsEnum.AUDIO_ACTION,
2537
+ // 音频开始播放
2538
+ AUDIO_FINISH: AvailableIntentsEventsEnum.AUDIO_ACTION,
2539
+ // 音频结束播放
2540
+ AUDIO_ON_MIC: AvailableIntentsEventsEnum.AUDIO_ACTION,
2541
+ // 机器人上麦
2542
+ AUDIO_OFF_MIC: AvailableIntentsEventsEnum.AUDIO_ACTION,
2543
+ // 机器人下麦
2544
+
2545
+ // ======= AUDIO_OR_LIVE_CHANNEL_MEMBER ======
2546
+ AUDIO_OR_LIVE_CHANNEL_MEMBER_ENTER: AvailableIntentsEventsEnum.AUDIO_OR_LIVE_CHANNEL_MEMBER,
2547
+ // 当用户进入音视频/直播子频道
2548
+ AUDIO_OR_LIVE_CHANNEL_MEMBER_EXIT: AvailableIntentsEventsEnum.AUDIO_OR_LIVE_CHANNEL_MEMBER,
2549
+ // 当用户离开音视频/直播子频道
2550
+
2551
+ // ======= PUBLIC_GUILD_MESSAGES ======
2552
+ AT_MESSAGE_CREATE: AvailableIntentsEventsEnum.PUBLIC_GUILD_MESSAGES,
2553
+ // 机器人被@时触发
2554
+ PUBLIC_MESSAGE_DELETE: AvailableIntentsEventsEnum.PUBLIC_GUILD_MESSAGES,
2555
+ // 当频道的消息被删除时
2556
+
2557
+ // ======= GROUP_C2C_EVENT ======
2558
+ GROUP_AT_MESSAGE_CREATE: AvailableIntentsEventsEnum.GROUP_C2C_EVENT,
2559
+ // 机器人在群聊被@时触发
2560
+ C2C_MESSAGE_CREATE: AvailableIntentsEventsEnum.GROUP_C2C_EVENT,
2561
+ // 机器人收到C2C消息时触发
2562
+ FRIEND_ADD: AvailableIntentsEventsEnum.GROUP_C2C_EVENT,
2563
+ // 机器人被加好友时触发
2564
+ FRIEND_DEL: AvailableIntentsEventsEnum.GROUP_C2C_EVENT,
2565
+ // 机器人被删除好友时触发
2566
+ C2C_MSG_RECEIVE: AvailableIntentsEventsEnum.GROUP_C2C_EVENT,
2567
+ // 用户在机器人资料卡手动开启"主动消息"推送
2568
+ C2C_MSG_REJECT: AvailableIntentsEventsEnum.GROUP_C2C_EVENT,
2569
+ // 用户在机器人资料卡手动关闭"主动消息"推送
2570
+ GROUP_ADD_ROBOT: AvailableIntentsEventsEnum.GROUP_C2C_EVENT,
2571
+ // 机器人被加入群聊时触发
2572
+ GROUP_DEL_ROBOT: AvailableIntentsEventsEnum.GROUP_C2C_EVENT,
2573
+ // 机器人被移出群聊时触发
2574
+ GROUP_MSG_RECEIVE: AvailableIntentsEventsEnum.GROUP_C2C_EVENT,
2575
+ // 群管理员主动在机器人资料页操作开启通知
2576
+ GROUP_MSG_REJECT: AvailableIntentsEventsEnum.GROUP_C2C_EVENT // 群管理员主动在机器人资料页操作关闭通知
2577
+ };
2578
+ var WSCodes = {
2579
+ 1000: 'WS_CLOSE_REQUESTED',
2580
+ 4004: 'TOKEN_INVALID',
2581
+ 4010: 'SHARDING_INVALID',
2582
+ 4011: 'SHARDING_REQUIRED',
2583
+ 4013: 'INVALID_INTENTS',
2584
+ 4014: 'DISALLOWED_INTENTS'
2585
+ };
2586
+
2587
+ // websocket错误码
2588
+ var WebsocketCode = /*#__PURE__*/function (WebsocketCode) {
2589
+ WebsocketCode[WebsocketCode["INVALID_OPCODE"] = 4001] = "INVALID_OPCODE";
2590
+ WebsocketCode[WebsocketCode["INVALID_PAYLOAD"] = 4002] = "INVALID_PAYLOAD";
2591
+ WebsocketCode[WebsocketCode["ERROR_SEQ"] = 4007] = "ERROR_SEQ";
2592
+ WebsocketCode[WebsocketCode["TOO_FAST_PAYLOAD"] = 4008] = "TOO_FAST_PAYLOAD";
2593
+ WebsocketCode[WebsocketCode["EXPIRED"] = 4009] = "EXPIRED";
2594
+ WebsocketCode[WebsocketCode["INVALID_SHARD"] = 4010] = "INVALID_SHARD";
2595
+ WebsocketCode[WebsocketCode["TOO_MACH_GUILD"] = 4011] = "TOO_MACH_GUILD";
2596
+ WebsocketCode[WebsocketCode["INVALID_VERSION"] = 4012] = "INVALID_VERSION";
2597
+ WebsocketCode[WebsocketCode["INVALID_INTENTS"] = 4013] = "INVALID_INTENTS";
2598
+ WebsocketCode[WebsocketCode["DISALLOWED_INTENTS"] = 4014] = "DISALLOWED_INTENTS";
2599
+ WebsocketCode[WebsocketCode["ERROR"] = 4900] = "ERROR";
2600
+ return WebsocketCode;
2601
+ }({}); // 内部错误,请重连
2602
+
2603
+ // websocket错误原因
2604
+ var WebsocketCloseReason = [{
2605
+ code: 4001,
2606
+ reason: '无效的opcode'
2607
+ }, {
2608
+ code: 4002,
2609
+ reason: '无效的payload'
2610
+ }, {
2611
+ code: 4007,
2612
+ reason: 'seq错误'
2613
+ }, {
2614
+ code: 4008,
2615
+ reason: '发送 payload 过快,请重新连接,并遵守连接后返回的频控信息',
2616
+ resume: true
2617
+ }, {
2618
+ code: 4009,
2619
+ reason: '连接过期,请重连',
2620
+ resume: true
2621
+ }, {
2622
+ code: 4010,
2623
+ reason: '无效的shard'
2624
+ }, {
2625
+ code: 4011,
2626
+ reason: '连接需要处理的guild过多,请进行合理分片'
2627
+ }, {
2628
+ code: 4012,
2629
+ reason: '无效的version'
2630
+ }, {
2631
+ code: 4013,
2632
+ reason: '无效的intent'
2633
+ }, {
2634
+ code: 4014,
2635
+ reason: 'intent无权限'
2636
+ }, {
2637
+ code: 4900,
2638
+ reason: '内部错误,请重连'
2639
+ }, {
2640
+ code: 4914,
2641
+ reason: '机器人已下架,只允许连接沙箱环境,请断开连接,检验当前连接环境'
2642
+ }, {
2643
+ code: 4915,
2644
+ reason: '机器人已封禁,不允许连接,请断开连接,申请解封后再连接'
2645
+ }];
2646
+ // 用户输入的intents类型
2647
+ var IntentEvents = {
2648
+ GUILDS: 1 << 0,
2649
+ GUILD_MEMBERS: 1 << 1,
2650
+ GUILD_MESSAGES: 1 << 9,
2651
+ GUILD_MESSAGE_REACTIONS: 1 << 10,
2652
+ DIRECT_MESSAGE: 1 << 12,
2653
+ OPEN_FORUM_EVENT: 1 << 18,
2654
+ AUDIO_OR_LIVE_CHANNEL_MEMBER: 1 << 19,
2655
+ GROUP_C2C_EVENT: 1 << 25,
2656
+ INTERACTION: 1 << 26,
2657
+ MESSAGE_AUDIT: 1 << 27,
2658
+ FORUM_EVENT: 1 << 28,
2659
+ AUDIO_ACTION: 1 << 29,
2660
+ PUBLIC_GUILD_MESSAGES: 1 << 30
2661
+ };
2662
+
2663
+ // intents
2664
+ var Intents = {
2665
+ GUILDS: 0,
2666
+ GUILD_MEMBERS: 1,
2667
+ GUILD_BANS: 2,
2668
+ GUILD_EMOJIS: 3,
2669
+ GUILD_INTEGRATIONS: 4,
2670
+ GUILD_WEBHOOKS: 5,
2671
+ GUILD_INVITES: 6,
2672
+ GUILD_VOICE_STATES: 7,
2673
+ GUILD_PRESENCES: 8,
2674
+ GUILD_MESSAGES: 9,
2675
+ GUILD_MESSAGE_REACTIONS: 10,
2676
+ GUILD_MESSAGE_TYPING: 11,
2677
+ DIRECT_MESSAGES: 12,
2678
+ DIRECT_MESSAGE_REACTIONS: 13,
2679
+ DIRECT_MESSAGE_TYPING: 14,
2680
+ OPEN_FORUM_EVENT: 18,
2681
+ AUDIO_OR_LIVE_CHANNEL_MEMBER: 19,
2682
+ GROUP_C2C_EVENT: 25,
2683
+ INTERACTION: 26,
2684
+ MESSAGE_AUDIT: 27,
2685
+ FORUM_EVENT: 28,
2686
+ AUDIO_ACTION: 29,
2687
+ PUBLIC_GUILD_MESSAGES: 30
2688
+ };
2689
+
2690
+ // Session事件
2691
+ var SessionEvents = {
2692
+ CLOSED: 'CLOSED',
2693
+ READY: 'READY',
2694
+ // 已经可以通信
2695
+ ERROR: 'ERROR',
2696
+ // 会话错误
2697
+ INVALID_SESSION: 'INVALID_SESSION',
2698
+ RECONNECT: 'RECONNECT',
2699
+ // 服务端通知重新连接
2700
+ DISCONNECT: 'DISCONNECT',
2701
+ // 断线
2702
+ EVENT_WS: 'EVENT_WS',
2703
+ // 内部通信
2704
+ RESUMED: 'RESUMED',
2705
+ // 重连
2706
+ DEAD: 'DEAD' // 连接已死亡,请检查网络或重启
2707
+ };
2708
+
2709
+ // ws地址配置
2710
+ var WsObjRequestOptions = function WsObjRequestOptions(sandbox) {
2711
+ return {
2712
+ method: 'GET',
2713
+ url: buildUrl(getURL('wsInfo'), sandbox),
2714
+ headers: {
2715
+ Accept: '*/*',
2716
+ 'Accept-Encoding': 'utf-8',
2717
+ 'Accept-Language': 'zh-CN,zh;q=0.8',
2718
+ 'Connection': 'keep-alive',
2719
+ 'User-Agent': apiVersion,
2720
+ 'Authorization': ''
2721
+ }
2722
+ };
2723
+ };
2724
+
2725
+ // 配置文件
2726
+ // 后台校验暂时用不到这块,所以给一个默认值
2727
+ var Properties = {
2728
+ os: 'linux',
2729
+ browser: 'my_library',
2730
+ device: 'my_library'
2731
+ };
2732
+
2733
+ // websocket连接
2734
+ var Ws = /*#__PURE__*/function () {
2735
+ function Ws(config, event, sessionRecord) {
2736
+ _classCallCheck(this, Ws);
2737
+ _defineProperty(this, "ws", void 0);
2738
+ _defineProperty(this, "event", void 0);
2739
+ _defineProperty(this, "config", void 0);
2740
+ _defineProperty(this, "heartbeatInterval", void 0);
2741
+ // 心跳参数,默认为心跳测试
2742
+ _defineProperty(this, "heartbeatParam", {
2743
+ op: OpCode.HEARTBEAT,
2744
+ d: null // 心跳唯一值
2745
+ });
2746
+ // 是否是断线重连,如果是断线重连的话,不需要走鉴权
2747
+ _defineProperty(this, "isReconnect", void 0);
2748
+ // 记录会话参数
2749
+ _defineProperty(this, "sessionRecord", {
2750
+ sessionID: '',
2751
+ seq: 0
2752
+ });
2753
+ _defineProperty(this, "alive", false);
2754
+ this.config = config;
2755
+ this.isReconnect = false;
2756
+ this.event = event;
2757
+ // 如果是重连,则拿到重新的会话记录,然后进入重连步骤
2758
+ if (sessionRecord) {
2759
+ this.sessionRecord.sessionID = sessionRecord.sessionID;
2760
+ this.sessionRecord.seq = sessionRecord.seq;
2761
+ this.isReconnect = true;
2762
+ }
2763
+ }
2764
+
2765
+ // 创建一个websocket连接
2766
+ return _createClass(Ws, [{
2767
+ key: "createWebsocket",
2768
+ value: function createWebsocket(wsData) {
2769
+ // 先链接到ws
2770
+ this.connectWs(wsData);
2771
+ // 对消息进行监听
2772
+ return this.createListening();
2773
+ }
2774
+
2775
+ // 创建监听
2776
+ }, {
2777
+ key: "createListening",
2778
+ value: function createListening() {
2779
+ var _this = this;
2780
+ // websocket连接已开启
2781
+ this.ws.on('open', function () {
2782
+ BotLogger.info("[CLIENT] \u5F00\u542F");
2783
+ });
2784
+
2785
+ // 接受消息
2786
+ this.ws.on('message', function (data) {
2787
+ var _wsRes$d;
2788
+ // BotLogger.info(`[CLIENT] 收到消息: ${data}`);
2789
+
2790
+ // 先将消息解析
2791
+ var wsRes = toObject(data);
2792
+ // 先判断websocket连接是否成功
2793
+ if ((wsRes === null || wsRes === void 0 ? void 0 : wsRes.op) === OpCode.HELLO && wsRes !== null && wsRes !== void 0 && (_wsRes$d = wsRes.d) !== null && _wsRes$d !== void 0 && _wsRes$d.heartbeat_interval) {
2794
+ var _wsRes$d2;
2795
+ // websocket连接成功,拿到心跳周期
2796
+ _this.heartbeatInterval = wsRes === null || wsRes === void 0 || (_wsRes$d2 = wsRes.d) === null || _wsRes$d2 === void 0 ? void 0 : _wsRes$d2.heartbeat_interval;
2797
+ // 非断线重连时,需要鉴权
2798
+ _this.isReconnect ? _this.reconnectWs() : _this.authWs();
2799
+ return;
2800
+ }
2801
+
2802
+ // 鉴权通过
2803
+ if (wsRes.t === SessionEvents.READY) {
2804
+ BotLogger.info("[CLIENT] \u9274\u6743\u901A\u8FC7");
2805
+ var d = wsRes.d,
2806
+ s = wsRes.s;
2807
+ var session_id = d.session_id;
2808
+ // 获取当前会话参数
2809
+ if (session_id && s) {
2810
+ _this.sessionRecord.sessionID = session_id;
2811
+ _this.sessionRecord.seq = s;
2812
+ _this.heartbeatParam.d = s;
2813
+ }
2814
+ _this.event.emit(SessionEvents.READY, {
2815
+ eventType: SessionEvents.READY,
2816
+ msg: d || ''
2817
+ });
2818
+ // 第一次发送心跳
2819
+ BotLogger.info("[CLIENT] \u53D1\u9001\u7B2C\u4E00\u6B21\u5FC3\u8DF3", _this.heartbeatParam);
2820
+ _this.sendWs(_this.heartbeatParam);
2821
+ return;
2822
+ }
2823
+
2824
+ // 心跳测试
2825
+ if (wsRes.op === OpCode.HEARTBEAT_ACK || wsRes.t === SessionEvents.RESUMED) {
2826
+ if (!_this.alive) {
2827
+ _this.alive = true;
2828
+ _this.event.emit(SessionEvents.EVENT_WS, {
2829
+ eventType: SessionEvents.READY
2830
+ });
2831
+ }
2832
+ BotLogger.info('[CLIENT] 心跳校验', _this.heartbeatParam);
2833
+ setTimeout(function () {
2834
+ _this.sendWs(_this.heartbeatParam);
2835
+ }, _this.heartbeatInterval);
2836
+ }
2837
+
2838
+ // 收到服务端锻炼重连的通知
2839
+ if (wsRes.op === OpCode.RECONNECT) {
2840
+ // 通知会话,当前已断线
2841
+ _this.event.emit(SessionEvents.EVENT_WS, {
2842
+ eventType: SessionEvents.RECONNECT
2843
+ });
2844
+ }
2845
+
2846
+ // 服务端主动推送的消息
2847
+ if (wsRes.op === OpCode.DISPATCH) {
2848
+ // 更新心跳唯一值
2849
+ var _s = wsRes.s;
2850
+ if (_s) {
2851
+ _this.sessionRecord.seq = _s;
2852
+ _this.heartbeatParam.d = _s;
2853
+ }
2854
+ // OpenAPI事件分发
2855
+ _this.dispatchEvent(wsRes.t, wsRes);
2856
+ }
2857
+ });
2858
+
2859
+ // 监听websocket关闭事件
2860
+ this.ws.on('close', function (data) {
2861
+ BotLogger.info('[CLIENT] 连接关闭', data);
2862
+ // 通知会话,当前已断线
2863
+ _this.alive = false;
2864
+ _this.event.emit(SessionEvents.EVENT_WS, {
2865
+ eventType: SessionEvents.DISCONNECT,
2866
+ eventMsg: _this.sessionRecord,
2867
+ code: data
2868
+ });
2869
+ if (data) {
2870
+ _this.handleWsCloseEvent(data);
2871
+ }
2872
+ });
2873
+
2874
+ // 监听websocket错误
2875
+ this.ws.on('error', function () {
2876
+ BotLogger.info("[CLIENT] \u8FDE\u63A5\u9519\u8BEF");
2877
+ _this.event.emit(SessionEvents.CLOSED, {
2878
+ eventType: SessionEvents.CLOSED
2879
+ });
2880
+ });
2881
+ return this.ws;
2882
+ }
2883
+
2884
+ // 连接ws
2885
+ }, {
2886
+ key: "connectWs",
2887
+ value: function connectWs(wsData) {
2888
+ // 创建websocket连接
2889
+ this.ws = new WebSocket(wsData.url);
2890
+ }
2891
+
2892
+ // 鉴权
2893
+ }, {
2894
+ key: "authWs",
2895
+ value: function authWs() {
2896
+ // 鉴权参数
2897
+ var authOp = {
2898
+ op: OpCode.IDENTIFY,
2899
+ // 鉴权参数
2900
+ d: {
2901
+ token: "Bot ".concat(this.config.appID, ".").concat(this.config.token),
2902
+ // 根据配置转换token
2903
+ intents: this.getValidIntents(),
2904
+ // todo 接受的类型
2905
+ shard: this.checkShards(this.config.shards) || [0, 1],
2906
+ // 分片信息,给一个默认值
2907
+ properties: {
2908
+ $os: Properties.os,
2909
+ $browser: Properties.browser,
2910
+ $device: Properties.device
2911
+ }
2912
+ }
2913
+ };
2914
+ // 发送鉴权请求
2915
+ this.sendWs(authOp);
2916
+ }
2917
+
2918
+ // 校验intents类型
2919
+ }, {
2920
+ key: "getValidIntents",
2921
+ value: function getValidIntents() {
2922
+ // 判断用户有没有给到需要监听的事件类型
2923
+ var intentsIn = this.getValidIntentsType();
2924
+ if (intentsIn.length > 0) {
2925
+ var intents = {
2926
+ value: 0
2927
+ };
2928
+ if (intentsIn.length === 1) {
2929
+ intents.value = IntentEvents[intentsIn[0]];
2930
+ return intents.value;
2931
+ }
2932
+ intentsIn.forEach(function (e) {
2933
+ intents.value = IntentEvents[e] | intents.value;
2934
+ });
2935
+ return intents.value;
2936
+ }
2937
+ }
2938
+
2939
+ // 校验intents格式
2940
+ }, {
2941
+ key: "getValidIntentsType",
2942
+ value: function getValidIntentsType() {
2943
+ var intentsIn = this.config.intents;
2944
+ // 全部可监听事件
2945
+ var defaultIntents = Object.keys(AvailableIntentsEventsEnum);
2946
+ // 如果开发者没传intents,我们默认给他开启全部监听事件
2947
+ if (!intentsIn) {
2948
+ BotLogger.info('[CLIENT] intents不存在,默认开启全部监听事件');
2949
+ return defaultIntents;
2950
+ }
2951
+ // 如果开发者传入intents为空数组,我们默认给他开启全部监听事件
2952
+ if (intentsIn.length === 0) {
2953
+ BotLogger.info('[CLIENT] intents为空,默认开启全部监听事件');
2954
+ return defaultIntents;
2955
+ }
2956
+ // 如果intents大于可监听数
2957
+ if (intentsIn.length > defaultIntents.length) {
2958
+ BotLogger.info('[CLIENT] intents中的监听事件大于可监听数,仅开启有效监听事件');
2959
+ }
2960
+ // 如果intents中数据格式不对
2961
+ var typeIn = intentsIn.every(function (item) {
2962
+ return typeof item === 'string';
2963
+ });
2964
+ if (!typeIn) {
2965
+ BotLogger.info('[CLIENT] intents中存在不合法类型,仅开启有效监听事件');
2966
+ return intentsIn.filter(function (item) {
2967
+ return typeof item === 'string';
2968
+ });
2969
+ }
2970
+ return intentsIn;
2971
+ }
2972
+
2973
+ // 校验shards
2974
+ }, {
2975
+ key: "checkShards",
2976
+ value: function checkShards(shardsArr) {
2977
+ // 没有传shards进来
2978
+ if (!shardsArr) {
2979
+ return BotLogger.info('shards 不存在');
2980
+ }
2981
+ // 传进来的符合要求
2982
+ if (Array.isArray(shardsArr) && shardsArr.length === 2 && shardsArr[0] < shardsArr[1]) {
2983
+ return shardsArr;
2984
+ }
2985
+ return BotLogger.info('shards 错误');
2986
+ }
2987
+
2988
+ // 发送websocket
2989
+ }, {
2990
+ key: "sendWs",
2991
+ value: function sendWs(msg) {
2992
+ try {
2993
+ // 先将消息转为字符串
2994
+ this.ws.send(typeof msg === 'string' ? msg : JSON.stringify(msg));
2995
+ } catch (e) {
2996
+ BotLogger.info(e);
2997
+ }
2998
+ }
2999
+
3000
+ // 重新连接
3001
+ }, {
3002
+ key: "reconnect",
3003
+ value: function reconnect() {
3004
+ BotLogger.info('[CLIENT] 等待断线重连');
3005
+ }
3006
+
3007
+ // 重新重连Ws
3008
+ }, {
3009
+ key: "reconnectWs",
3010
+ value: function reconnectWs() {
3011
+ var reconnectParam = {
3012
+ op: OpCode.RESUME,
3013
+ d: {
3014
+ token: "Bot ".concat(this.config.appID, ".").concat(this.config.token),
3015
+ session_id: this.sessionRecord.sessionID,
3016
+ seq: this.sessionRecord.seq
3017
+ }
3018
+ };
3019
+ this.sendWs(reconnectParam);
3020
+ }
3021
+
3022
+ // OpenAPI事件分发
3023
+ }, {
3024
+ key: "dispatchEvent",
3025
+ value: function dispatchEvent(eventType, wsRes) {
3026
+ var msg = wsRes.d;
3027
+ var eventId = wsRes.id || '';
3028
+ // 如果没有事件,即刻退出
3029
+ if (!msg || !eventType) return;
3030
+ this.event.emit(WsEventType[eventType], {
3031
+ eventType: eventType,
3032
+ eventId: eventId,
3033
+ msg: msg
3034
+ });
3035
+ }
3036
+
3037
+ // 主动关闭会话
3038
+ }, {
3039
+ key: "closeWs",
3040
+ value: function closeWs() {
3041
+ this.ws.close();
3042
+ }
3043
+
3044
+ // ws关闭的原因
3045
+ }, {
3046
+ key: "handleWsCloseEvent",
3047
+ value: function handleWsCloseEvent(code) {
3048
+ var _this2 = this;
3049
+ WebsocketCloseReason.forEach(function (e) {
3050
+ if (e.code === code) {
3051
+ _this2.event.emit(SessionEvents.ERROR, {
3052
+ eventType: SessionEvents.ERROR,
3053
+ msg: e.reason
3054
+ });
3055
+ }
3056
+ });
3057
+ }
3058
+ }]);
3059
+ }();
3060
+
3061
+ var Session = /*#__PURE__*/function () {
3062
+ function Session(config, event, sessionRecord) {
3063
+ _classCallCheck(this, Session);
3064
+ _defineProperty(this, "config", void 0);
3065
+ _defineProperty(this, "heartbeatInterval", void 0);
3066
+ _defineProperty(this, "ws", void 0);
3067
+ _defineProperty(this, "event", void 0);
3068
+ _defineProperty(this, "sessionRecord", void 0);
3069
+ this.config = config;
3070
+ this.event = event;
3071
+ // 如果会话记录存在的话,继续透传
3072
+ if (sessionRecord) {
3073
+ this.sessionRecord = sessionRecord;
3074
+ }
3075
+ this.createSession();
3076
+ }
3077
+
3078
+ // 新建会话
3079
+ return _createClass(Session, [{
3080
+ key: "createSession",
3081
+ value: function createSession() {
3082
+ var _this = this;
3083
+ this.ws = new Ws(this.config, this.event, this.sessionRecord || undefined);
3084
+ // 拿到 ws地址等信息
3085
+ var reqOptions = WsObjRequestOptions(this.config.sandbox);
3086
+ addAuthorization(reqOptions.headers, this.config.appID, this.config.token, this.config.clientSecret);
3087
+ resty.create(reqOptions).get(reqOptions.url, {}).then(function (r) {
3088
+ var wsData = r.data;
3089
+ if (!wsData) throw new Error('获取ws连接信息异常');
3090
+ _this.ws.createWebsocket(wsData);
3091
+ })["catch"](function (e) {
3092
+ BotLogger.info('[ERROR] createSession: ', e);
3093
+ _this.event.emit(SessionEvents.EVENT_WS, {
3094
+ eventType: SessionEvents.DISCONNECT,
3095
+ eventMsg: _this.sessionRecord
3096
+ });
3097
+ });
3098
+ }
3099
+
3100
+ // 关闭会话
3101
+ }, {
3102
+ key: "closeSession",
3103
+ value: function closeSession() {
3104
+ this.ws.closeWs();
3105
+ }
3106
+ }]);
3107
+ }();
3108
+
3109
+ function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
3110
+ function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3111
+ var MAX_RETRY = 10;
3112
+ var WebsocketClient = /*#__PURE__*/function (_EventEmitter) {
3113
+ function WebsocketClient(config) {
3114
+ var _this;
3115
+ _classCallCheck(this, WebsocketClient);
3116
+ _this = _callSuper(this, WebsocketClient);
3117
+ _defineProperty(_this, "session", void 0);
3118
+ _defineProperty(_this, "retry", 0);
3119
+ _this.connect(config);
3120
+ _this.on(SessionEvents.EVENT_WS, function (data) {
3121
+ switch (data.eventType) {
3122
+ case SessionEvents.RECONNECT:
3123
+ BotLogger.info('[CLIENT] 等待断线重连中...');
3124
+ break;
3125
+ case SessionEvents.DISCONNECT:
3126
+ if (_this.retry < (config.maxRetry || MAX_RETRY)) {
3127
+ var _WebsocketCloseReason;
3128
+ BotLogger.info('[CLIENT] 重新连接中,尝试次数:', _this.retry + 1);
3129
+ _this.connect(config, (_WebsocketCloseReason = WebsocketCloseReason.find(function (v) {
3130
+ return v.code === data.code;
3131
+ })) !== null && _WebsocketCloseReason !== void 0 && _WebsocketCloseReason.resume ? data.eventMsg : null);
3132
+ _this.retry += 1;
3133
+ } else {
3134
+ BotLogger.info('[CLIENT] 超过重试次数,连接终止');
3135
+ _this.emit(SessionEvents.DEAD, {
3136
+ eventType: SessionEvents.ERROR,
3137
+ msg: '连接已死亡,请检查网络或重启'
3138
+ });
3139
+ }
3140
+ break;
3141
+ case SessionEvents.READY:
3142
+ BotLogger.info('[CLIENT] 连接成功');
3143
+ _this.retry = 0;
3144
+ break;
3145
+ }
3146
+ });
3147
+ return _this;
3148
+ }
3149
+
3150
+ // 连接
3151
+ _inherits(WebsocketClient, _EventEmitter);
3152
+ return _createClass(WebsocketClient, [{
3153
+ key: "connect",
3154
+ value: function connect(config, sessionRecord) {
3155
+ var event = this;
3156
+ // 新建一个会话
3157
+ this.session = new Session(config, event, sessionRecord);
3158
+ return this.session;
3159
+ }
3160
+
3161
+ // 断开连接
3162
+ }, {
3163
+ key: "disconnect",
3164
+ value: function disconnect() {
3165
+ // 关闭会话
3166
+ this.session.closeSession();
3167
+ }
3168
+ }]);
3169
+ }(WebSocket.EventEmitter);
3170
+
3171
+ // 注册v1接口
3172
+ v1Setup();
3173
+ var defaultImpl = versionMapping[apiVersion];
3174
+
3175
+ // SelectOpenAPIVersion 指定使用哪个版本的 api 实现,如果不指定,sdk将默认使用第一个 setup 的 api 实现
3176
+ function selectOpenAPIVersion(version) {
3177
+ if (!versionMapping[version]) {
3178
+ return false;
3179
+ }
3180
+ defaultImpl = versionMapping[version];
3181
+ }
3182
+ // 如果需要使用其他版本的实现,需要在调用这个方法之前调用 SelectOpenAPIVersion 方法
3183
+ function createOpenAPI(config) {
3184
+ return defaultImpl.newClient(config);
3185
+ }
3186
+ // ws连接新建
3187
+ function createWebsocket(config) {
3188
+ return new WebsocketClient(config);
3189
+ }
3190
+
3191
+ exports.AvailableIntentsEventsEnum = AvailableIntentsEventsEnum;
3192
+ exports.IntentEvents = IntentEvents;
3193
+ exports.Intents = Intents;
3194
+ exports.OpCode = OpCode;
3195
+ exports.SessionEvents = SessionEvents;
3196
+ exports.WSCodes = WSCodes;
3197
+ exports.WebsocketCloseReason = WebsocketCloseReason;
3198
+ exports.WebsocketCode = WebsocketCode;
3199
+ exports.WsEventType = WsEventType;
3200
+ exports.WsObjRequestOptions = WsObjRequestOptions;
3201
+ exports.createOpenAPI = createOpenAPI;
3202
+ exports.createWebsocket = createWebsocket;
3203
+ exports.selectOpenAPIVersion = selectOpenAPIVersion;