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