discord.js-selfv13 13.0.1

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of discord.js-selfv13 might be problematic. Click here for more details.

Files changed (188) hide show
  1. package/.dccache +1 -0
  2. package/LICENSE +190 -0
  3. package/README.md +87 -0
  4. package/browser.js +9 -0
  5. package/deploy/deploy-key.enc +0 -0
  6. package/deploy/deploy.sh +90 -0
  7. package/deploy/test.sh +34 -0
  8. package/docs/README.md +1 -0
  9. package/docs/examples/attachments.md +163 -0
  10. package/docs/examples/avatars.js +29 -0
  11. package/docs/examples/embed.js +38 -0
  12. package/docs/examples/greeting.js +30 -0
  13. package/docs/examples/moderation.md +145 -0
  14. package/docs/examples/ping.js +29 -0
  15. package/docs/examples/webhook.js +12 -0
  16. package/docs/general/faq.md +23 -0
  17. package/docs/general/updating.md +181 -0
  18. package/docs/general/welcome.md +95 -0
  19. package/docs/index.yml +30 -0
  20. package/docs/logo.svg +19 -0
  21. package/docs/topics/voice.md +113 -0
  22. package/docs/topics/web.md +38 -0
  23. package/package.json +147 -0
  24. package/src/client/Client.js +564 -0
  25. package/src/client/ClientDataManager.js +150 -0
  26. package/src/client/ClientDataResolver.js +376 -0
  27. package/src/client/ClientManager.js +74 -0
  28. package/src/client/WebhookClient.js +118 -0
  29. package/src/client/actions/Action.js +23 -0
  30. package/src/client/actions/ActionsManager.js +40 -0
  31. package/src/client/actions/ChannelCreate.js +11 -0
  32. package/src/client/actions/ChannelDelete.js +30 -0
  33. package/src/client/actions/ChannelUpdate.js +74 -0
  34. package/src/client/actions/GuildBanRemove.js +13 -0
  35. package/src/client/actions/GuildChannelsPositionUpdate.js +19 -0
  36. package/src/client/actions/GuildDelete.js +57 -0
  37. package/src/client/actions/GuildEmojiCreate.js +17 -0
  38. package/src/client/actions/GuildEmojiDelete.js +18 -0
  39. package/src/client/actions/GuildEmojiUpdate.js +17 -0
  40. package/src/client/actions/GuildEmojisUpdate.js +38 -0
  41. package/src/client/actions/GuildMemberGet.js +10 -0
  42. package/src/client/actions/GuildMemberRemove.js +41 -0
  43. package/src/client/actions/GuildRoleCreate.js +26 -0
  44. package/src/client/actions/GuildRoleDelete.js +42 -0
  45. package/src/client/actions/GuildRoleUpdate.js +41 -0
  46. package/src/client/actions/GuildRolesPositionUpdate.js +19 -0
  47. package/src/client/actions/GuildSync.js +29 -0
  48. package/src/client/actions/GuildUpdate.js +34 -0
  49. package/src/client/actions/MessageCreate.js +53 -0
  50. package/src/client/actions/MessageDelete.js +35 -0
  51. package/src/client/actions/MessageDeleteBulk.js +26 -0
  52. package/src/client/actions/MessageReactionAdd.js +37 -0
  53. package/src/client/actions/MessageReactionRemove.js +37 -0
  54. package/src/client/actions/MessageReactionRemoveAll.js +25 -0
  55. package/src/client/actions/MessageUpdate.js +40 -0
  56. package/src/client/actions/Ready.js +1 -0
  57. package/src/client/actions/Ready.js.bak +65 -0
  58. package/src/client/actions/UserGet.js +11 -0
  59. package/src/client/actions/UserNoteUpdate.js +30 -0
  60. package/src/client/actions/UserUpdate.js +33 -0
  61. package/src/client/rest/APIRequest.js +56 -0
  62. package/src/client/rest/DiscordAPIError.js +60 -0
  63. package/src/client/rest/RESTManager.js +58 -0
  64. package/src/client/rest/RESTMethods.js +1006 -0
  65. package/src/client/rest/RequestHandlers/Burst.js +90 -0
  66. package/src/client/rest/RequestHandlers/RequestHandler.js +54 -0
  67. package/src/client/rest/RequestHandlers/Sequential.js +132 -0
  68. package/src/client/rest/UserAgentManager.js +25 -0
  69. package/src/client/voice/ClientVoiceManager.js +81 -0
  70. package/src/client/voice/VoiceBroadcast.js +366 -0
  71. package/src/client/voice/VoiceConnection.js +530 -0
  72. package/src/client/voice/VoiceUDPClient.js +127 -0
  73. package/src/client/voice/VoiceWebSocket.js +246 -0
  74. package/src/client/voice/dispatcher/StreamDispatcher.js +331 -0
  75. package/src/client/voice/opus/BaseOpusEngine.js +60 -0
  76. package/src/client/voice/opus/NodeOpusEngine.js +40 -0
  77. package/src/client/voice/opus/OpusEngineList.js +28 -0
  78. package/src/client/voice/opus/OpusScriptEngine.js +45 -0
  79. package/src/client/voice/player/AudioPlayer.js +170 -0
  80. package/src/client/voice/receiver/VoiceReadable.js +17 -0
  81. package/src/client/voice/receiver/VoiceReceiver.js +219 -0
  82. package/src/client/voice/util/SecretKey.js +16 -0
  83. package/src/client/voice/util/Secretbox.js +33 -0
  84. package/src/client/voice/util/VolumeInterface.js +86 -0
  85. package/src/client/websocket/WebSocketConnection.js +506 -0
  86. package/src/client/websocket/WebSocketManager.js +90 -0
  87. package/src/client/websocket/packets/WebSocketPacketManager.js +110 -0
  88. package/src/client/websocket/packets/handlers/AbstractHandler.js +11 -0
  89. package/src/client/websocket/packets/handlers/ChannelCreate.js +17 -0
  90. package/src/client/websocket/packets/handlers/ChannelDelete.js +20 -0
  91. package/src/client/websocket/packets/handlers/ChannelPinsUpdate.js +37 -0
  92. package/src/client/websocket/packets/handlers/ChannelUpdate.js +11 -0
  93. package/src/client/websocket/packets/handlers/GuildBanAdd.js +23 -0
  94. package/src/client/websocket/packets/handlers/GuildBanRemove.js +20 -0
  95. package/src/client/websocket/packets/handlers/GuildCreate.js +22 -0
  96. package/src/client/websocket/packets/handlers/GuildDelete.js +19 -0
  97. package/src/client/websocket/packets/handlers/GuildEmojisUpdate.js +11 -0
  98. package/src/client/websocket/packets/handlers/GuildIntegrationsUpdate.js +19 -0
  99. package/src/client/websocket/packets/handlers/GuildMemberAdd.js +17 -0
  100. package/src/client/websocket/packets/handlers/GuildMemberRemove.js +13 -0
  101. package/src/client/websocket/packets/handlers/GuildMemberUpdate.js +18 -0
  102. package/src/client/websocket/packets/handlers/GuildMembersChunk.js +33 -0
  103. package/src/client/websocket/packets/handlers/GuildRoleCreate.js +11 -0
  104. package/src/client/websocket/packets/handlers/GuildRoleDelete.js +11 -0
  105. package/src/client/websocket/packets/handlers/GuildRoleUpdate.js +11 -0
  106. package/src/client/websocket/packets/handlers/GuildSync.js +11 -0
  107. package/src/client/websocket/packets/handlers/GuildUpdate.js +11 -0
  108. package/src/client/websocket/packets/handlers/MessageCreate.js +19 -0
  109. package/src/client/websocket/packets/handlers/MessageDelete.js +19 -0
  110. package/src/client/websocket/packets/handlers/MessageDeleteBulk.js +17 -0
  111. package/src/client/websocket/packets/handlers/MessageReactionAdd.js +11 -0
  112. package/src/client/websocket/packets/handlers/MessageReactionRemove.js +11 -0
  113. package/src/client/websocket/packets/handlers/MessageReactionRemoveAll.js +11 -0
  114. package/src/client/websocket/packets/handlers/MessageUpdate.js +11 -0
  115. package/src/client/websocket/packets/handlers/PresenceUpdate.js +76 -0
  116. package/src/client/websocket/packets/handlers/Ready.js +83 -0
  117. package/src/client/websocket/packets/handlers/RelationshipAdd.js +19 -0
  118. package/src/client/websocket/packets/handlers/RelationshipRemove.js +19 -0
  119. package/src/client/websocket/packets/handlers/Resumed.js +28 -0
  120. package/src/client/websocket/packets/handlers/TypingStart.js +68 -0
  121. package/src/client/websocket/packets/handlers/UserGuildSettingsUpdate.js +21 -0
  122. package/src/client/websocket/packets/handlers/UserNoteUpdate.js +12 -0
  123. package/src/client/websocket/packets/handlers/UserSettingsUpdate.js +18 -0
  124. package/src/client/websocket/packets/handlers/UserUpdate.js +11 -0
  125. package/src/client/websocket/packets/handlers/VoiceServerUpdate.js +19 -0
  126. package/src/client/websocket/packets/handlers/VoiceStateUpdate.js +52 -0
  127. package/src/client/websocket/packets/handlers/WebhooksUpdate.js +19 -0
  128. package/src/index.js +66 -0
  129. package/src/sharding/Shard.js +282 -0
  130. package/src/sharding/ShardClientUtil.js +146 -0
  131. package/src/sharding/ShardingManager.js +220 -0
  132. package/src/structures/Attachment.js +75 -0
  133. package/src/structures/CategoryChannel.js +22 -0
  134. package/src/structures/Channel.js +78 -0
  135. package/src/structures/ClientUser.js +447 -0
  136. package/src/structures/ClientUserChannelOverride.js +30 -0
  137. package/src/structures/ClientUserGuildSettings.js +60 -0
  138. package/src/structures/ClientUserSettings.js +80 -0
  139. package/src/structures/DMChannel.js +76 -0
  140. package/src/structures/Emoji.js +256 -0
  141. package/src/structures/GroupDMChannel.js +246 -0
  142. package/src/structures/Guild.js +1461 -0
  143. package/src/structures/GuildAuditLogs.js +371 -0
  144. package/src/structures/GuildChannel.js +537 -0
  145. package/src/structures/GuildMember.js +613 -0
  146. package/src/structures/Invite.js +164 -0
  147. package/src/structures/Message.js +605 -0
  148. package/src/structures/MessageAttachment.js +68 -0
  149. package/src/structures/MessageCollector.js +100 -0
  150. package/src/structures/MessageEmbed.js +386 -0
  151. package/src/structures/MessageMentions.js +144 -0
  152. package/src/structures/MessageReaction.js +96 -0
  153. package/src/structures/NewsChannel.js +24 -0
  154. package/src/structures/OAuth2Application.js +148 -0
  155. package/src/structures/PartialGuild.js +51 -0
  156. package/src/structures/PartialGuildChannel.js +44 -0
  157. package/src/structures/PermissionOverwrites.js +69 -0
  158. package/src/structures/Presence.js +241 -0
  159. package/src/structures/ReactionCollector.js +85 -0
  160. package/src/structures/ReactionEmoji.js +49 -0
  161. package/src/structures/RichEmbed.js +295 -0
  162. package/src/structures/Role.js +376 -0
  163. package/src/structures/StoreChannel.js +25 -0
  164. package/src/structures/TextChannel.js +154 -0
  165. package/src/structures/User.js +329 -0
  166. package/src/structures/UserConnection.js +48 -0
  167. package/src/structures/UserProfile.js +62 -0
  168. package/src/structures/VoiceChannel.js +146 -0
  169. package/src/structures/VoiceRegion.js +50 -0
  170. package/src/structures/Webhook.js +304 -0
  171. package/src/structures/interfaces/Collector.js +179 -0
  172. package/src/structures/interfaces/TextBasedChannel.js +635 -0
  173. package/src/structures/shared/resolvePermissions.js +26 -0
  174. package/src/util/Collection.js +532 -0
  175. package/src/util/Constants.js +845 -0
  176. package/src/util/Permissions.js +306 -0
  177. package/src/util/Snowflake.js +82 -0
  178. package/src/util/Util.js +221 -0
  179. package/test/random.js +207 -0
  180. package/test/shard.js +31 -0
  181. package/test/sharder.js +7 -0
  182. package/test/voice.js +78 -0
  183. package/test/webpack.html +31 -0
  184. package/tsconfig.json +13 -0
  185. package/tslint.json +62 -0
  186. package/typings/discord.js-test.ts +69 -0
  187. package/typings/index.d.ts +2190 -0
  188. package/webpack.config.js +62 -0
@@ -0,0 +1,306 @@
1
+ const Constants = require('../util/Constants');
2
+ const util = require('util');
3
+
4
+ /**
5
+ * Data structure that makes it easy to interact with a permission bitfield. All {@link GuildMember}s have a set of
6
+ * permissions in their guild, and each channel in the guild may also have {@link PermissionOverwrites} for the member
7
+ * that override their default permissions.
8
+ */
9
+ class Permissions {
10
+ /**
11
+ * @param {GuildMember} [member] Member the permissions are for **(deprecated)**
12
+ * @param {number|PermissionResolvable} permissions Permissions or bitfield to read from
13
+ */
14
+ constructor(member, permissions) {
15
+ permissions = typeof member === 'object' && !(member instanceof Array) ? permissions : member;
16
+
17
+ /**
18
+ * Member the permissions are for
19
+ * @type {GuildMember}
20
+ * @deprecated
21
+ */
22
+ this._member = typeof member === 'object' ? member : null;
23
+
24
+ /**
25
+ * Bitfield of the packed permissions
26
+ * @type {number}
27
+ */
28
+ this.bitfield = typeof permissions === 'number' ? permissions : this.constructor.resolve(permissions);
29
+ }
30
+
31
+ get member() {
32
+ return this._member;
33
+ }
34
+
35
+ set member(value) {
36
+ this._member = value;
37
+ }
38
+
39
+ /**
40
+ * Bitfield of the packed permissions
41
+ * @type {number}
42
+ * @see {@link Permissions#bitfield}
43
+ * @deprecated
44
+ * @readonly
45
+ */
46
+ get raw() {
47
+ return this.bitfield;
48
+ }
49
+
50
+ set raw(raw) {
51
+ this.bitfield = raw;
52
+ }
53
+
54
+ /**
55
+ * Checks whether the bitfield has a permission, or multiple permissions.
56
+ * @param {PermissionResolvable} permission Permission(s) to check for
57
+ * @param {boolean} [checkAdmin=true] Whether to allow the administrator permission to override
58
+ * @returns {boolean}
59
+ */
60
+ has(permission, checkAdmin = true) {
61
+ if (permission instanceof Array) return permission.every(p => this.has(p, checkAdmin));
62
+ permission = this.constructor.resolve(permission);
63
+ if (checkAdmin && (this.bitfield & this.constructor.FLAGS.ADMINISTRATOR) > 0) return true;
64
+ return (this.bitfield & permission) === permission;
65
+ }
66
+
67
+ /**
68
+ * Gets all given permissions that are missing from the bitfield.
69
+ * @param {PermissionResolvable} permissions Permissions to check for
70
+ * @param {boolean} [checkAdmin=true] Whether to allow the administrator permission to override
71
+ * @returns {PermissionResolvable}
72
+ */
73
+ missing(permissions, checkAdmin = true) {
74
+ if (!(permissions instanceof Array)) permissions = [permissions];
75
+ return permissions.filter(p => !this.has(p, checkAdmin));
76
+ }
77
+
78
+ /**
79
+ * Adds permissions to this one, creating a new instance to represent the new bitfield.
80
+ * @param {...PermissionResolvable} permissions Permissions to add
81
+ * @returns {Permissions}
82
+ */
83
+ add(...permissions) {
84
+ let total = 0;
85
+ for (let p = permissions.length - 1; p >= 0; p--) {
86
+ const perm = this.constructor.resolve(permissions[p]);
87
+ total |= perm;
88
+ }
89
+ if (Object.isFrozen(this)) return new this.constructor(this.bitfield | total);
90
+ this.bitfield |= total;
91
+ return this;
92
+ }
93
+
94
+ /**
95
+ * Removes permissions to this one, creating a new instance to represent the new bitfield.
96
+ * @param {...PermissionResolvable} permissions Permissions to remove
97
+ * @returns {Permissions}
98
+ */
99
+ remove(...permissions) {
100
+ let total = 0;
101
+ for (let p = permissions.length - 1; p >= 0; p--) {
102
+ const perm = this.constructor.resolve(permissions[p]);
103
+ total |= perm;
104
+ }
105
+ if (Object.isFrozen(this)) return new this.constructor(this.bitfield & ~total);
106
+ this.bitfield &= ~total;
107
+ return this;
108
+ }
109
+
110
+ /**
111
+ * Gets an object mapping permission name (like `VIEW_CHANNEL`) to a {@link boolean} indicating whether the
112
+ * permission is available.
113
+ * @param {boolean} [checkAdmin=true] Whether to allow the administrator permission to override
114
+ * @returns {Object}
115
+ */
116
+ serialize(checkAdmin = true) {
117
+ const serialized = {};
118
+ for (const perm in this.constructor.FLAGS) serialized[perm] = this.has(perm, checkAdmin);
119
+ return serialized;
120
+ }
121
+
122
+ /**
123
+ * Checks whether the user has a certain permission, e.g. `READ_MESSAGES`.
124
+ * @param {PermissionResolvable} permission The permission to check for
125
+ * @param {boolean} [explicit=false] Whether to require the user to explicitly have the exact permission
126
+ * @returns {boolean}
127
+ * @see {@link Permissions#has}
128
+ * @deprecated
129
+ */
130
+ hasPermission(permission, explicit = false) {
131
+ return this.has(permission, !explicit);
132
+ }
133
+
134
+ /**
135
+ * Checks whether the user has all specified permissions.
136
+ * @param {PermissionResolvable} permissions The permissions to check for
137
+ * @param {boolean} [explicit=false] Whether to require the user to explicitly have the exact permissions
138
+ * @returns {boolean}
139
+ * @see {@link Permissions#has}
140
+ * @deprecated
141
+ */
142
+ hasPermissions(permissions, explicit = false) {
143
+ return this.has(permissions, !explicit);
144
+ }
145
+
146
+ /**
147
+ * Checks whether the user has all specified permissions, and lists any missing permissions.
148
+ * @param {PermissionResolvable} permissions The permissions to check for
149
+ * @param {boolean} [explicit=false] Whether to require the user to explicitly have the exact permissions
150
+ * @returns {PermissionResolvable}
151
+ * @see {@link Permissions#missing}
152
+ * @deprecated
153
+ */
154
+ missingPermissions(permissions, explicit = false) {
155
+ return this.missing(permissions, !explicit);
156
+ }
157
+
158
+ /**
159
+ * Gets an {@link Array} of permission names (such as `VIEW_CHANNEL`) based on the permissions available.
160
+ * @param {boolean} [checkAdmin=true] Whether to allow the administrator permission to override
161
+ * @returns {string[]}
162
+ */
163
+ toArray(checkAdmin = true) {
164
+ return Object.keys(this.constructor.FLAGS).filter(perm => this.has(perm, checkAdmin));
165
+ }
166
+
167
+ /**
168
+ * Freezes these permissions, making them immutable.
169
+ * @returns {Permissions} These permissions
170
+ */
171
+ freeze() {
172
+ return Object.freeze(this);
173
+ }
174
+
175
+ valueOf() {
176
+ return this.bitfield;
177
+ }
178
+
179
+ /**
180
+ * Data that can be resolved to give a permission number. This can be:
181
+ * * A string (see {@link Permissions.FLAGS})
182
+ * * A permission number
183
+ * @typedef {string|number|Permissions|PermissionResolvable[]} PermissionResolvable
184
+ */
185
+
186
+ /**
187
+ * Resolves permissions to their numeric form.
188
+ * @param {PermissionResolvable} permission - Permission(s) to resolve
189
+ * @returns {number}
190
+ */
191
+ static resolve(permission) {
192
+ if (permission instanceof Array) return permission.map(p => this.resolve(p)).reduce((prev, p) => prev | p, 0);
193
+ if (permission instanceof Permissions) return permission.bitfield;
194
+ if (typeof permission === 'string') permission = this.FLAGS[permission];
195
+ if (typeof permission !== 'number' || permission < 0) throw new RangeError(Constants.Errors.NOT_A_PERMISSION);
196
+ return permission;
197
+ }
198
+ }
199
+
200
+ /**
201
+ * Numeric permission flags. All available properties:
202
+ * - `ADMINISTRATOR` (implicitly has *all* permissions, and bypasses all channel overwrites)
203
+ * - `CREATE_INSTANT_INVITE` (create invitations to the guild)
204
+ * - `KICK_MEMBERS`
205
+ * - `BAN_MEMBERS`
206
+ * - `MANAGE_CHANNELS` (edit and reorder channels)
207
+ * - `MANAGE_GUILD` (edit the guild information, region, etc.)
208
+ * - `ADD_REACTIONS` (add new reactions to messages)
209
+ * - `VIEW_AUDIT_LOG`
210
+ * - `PRIORITY_SPEAKER`
211
+ * - `VIEW_CHANNEL`
212
+ * - `READ_MESSAGES` **(deprecated)**
213
+ * - `SEND_MESSAGES`
214
+ * - `SEND_TTS_MESSAGES`
215
+ * - `MANAGE_MESSAGES` (delete messages and reactions)
216
+ * - `EMBED_LINKS` (links posted will have a preview embedded)
217
+ * - `ATTACH_FILES`
218
+ * - `READ_MESSAGE_HISTORY` (view messages that were posted prior to opening Discord)
219
+ * - `MENTION_EVERYONE`
220
+ * - `USE_EXTERNAL_EMOJIS` (use emojis from different guilds)
221
+ * - `EXTERNAL_EMOJIS` **(deprecated)**
222
+ * - `CONNECT` (connect to a voice channel)
223
+ * - `SPEAK` (speak in a voice channel)
224
+ * - `MUTE_MEMBERS` (mute members across all voice channels)
225
+ * - `DEAFEN_MEMBERS` (deafen members across all voice channels)
226
+ * - `MOVE_MEMBERS` (move members between voice channels)
227
+ * - `USE_VAD` (use voice activity detection)
228
+ * - `CHANGE_NICKNAME`
229
+ * - `MANAGE_NICKNAMES` (change other members' nicknames)
230
+ * - `MANAGE_ROLES`
231
+ * - `MANAGE_ROLES_OR_PERMISSIONS` **(deprecated)**
232
+ * - `MANAGE_WEBHOOKS`
233
+ * - `MANAGE_EMOJIS`
234
+ * @type {Object}
235
+ * @see {@link https://discordapp.com/developers/docs/topics/permissions}
236
+ */
237
+ Permissions.FLAGS = {
238
+ CREATE_INSTANT_INVITE: 1 << 0,
239
+ KICK_MEMBERS: 1 << 1,
240
+ BAN_MEMBERS: 1 << 2,
241
+ ADMINISTRATOR: 1 << 3,
242
+ MANAGE_CHANNELS: 1 << 4,
243
+ MANAGE_GUILD: 1 << 5,
244
+ ADD_REACTIONS: 1 << 6,
245
+ VIEW_AUDIT_LOG: 1 << 7,
246
+ PRIORITY_SPEAKER: 1 << 8,
247
+
248
+ VIEW_CHANNEL: 1 << 10,
249
+ READ_MESSAGES: 1 << 10,
250
+ SEND_MESSAGES: 1 << 11,
251
+ SEND_TTS_MESSAGES: 1 << 12,
252
+ MANAGE_MESSAGES: 1 << 13,
253
+ EMBED_LINKS: 1 << 14,
254
+ ATTACH_FILES: 1 << 15,
255
+ READ_MESSAGE_HISTORY: 1 << 16,
256
+ MENTION_EVERYONE: 1 << 17,
257
+ EXTERNAL_EMOJIS: 1 << 18,
258
+ USE_EXTERNAL_EMOJIS: 1 << 18,
259
+
260
+ CONNECT: 1 << 20,
261
+ SPEAK: 1 << 21,
262
+ MUTE_MEMBERS: 1 << 22,
263
+ DEAFEN_MEMBERS: 1 << 23,
264
+ MOVE_MEMBERS: 1 << 24,
265
+ USE_VAD: 1 << 25,
266
+
267
+ CHANGE_NICKNAME: 1 << 26,
268
+ MANAGE_NICKNAMES: 1 << 27,
269
+ MANAGE_ROLES: 1 << 28,
270
+ MANAGE_ROLES_OR_PERMISSIONS: 1 << 28,
271
+ MANAGE_WEBHOOKS: 1 << 29,
272
+ MANAGE_EMOJIS: 1 << 30,
273
+ };
274
+
275
+ /**
276
+ * Bitfield representing every permission combined
277
+ * @type {number}
278
+ */
279
+ Permissions.ALL = Object.keys(Permissions.FLAGS).reduce((all, p) => all | Permissions.FLAGS[p], 0);
280
+
281
+ /**
282
+ * Bitfield representing the default permissions for users
283
+ * @type {number}
284
+ */
285
+ Permissions.DEFAULT = 104324097;
286
+
287
+ /**
288
+ * @class EvaluatedPermissions
289
+ * @classdesc The final evaluated permissions for a member in a channel
290
+ * @see {@link Permissions}
291
+ * @deprecated
292
+ */
293
+
294
+ Permissions.prototype.hasPermission = util.deprecate(Permissions.prototype.hasPermission,
295
+ 'EvaluatedPermissions#hasPermission is deprecated, use Permissions#has instead');
296
+ Permissions.prototype.hasPermissions = util.deprecate(Permissions.prototype.hasPermissions,
297
+ 'EvaluatedPermissions#hasPermissions is deprecated, use Permissions#has instead');
298
+ Permissions.prototype.missingPermissions = util.deprecate(Permissions.prototype.missingPermissions,
299
+ 'EvaluatedPermissions#missingPermissions is deprecated, use Permissions#missing instead');
300
+ Object.defineProperty(Permissions.prototype, 'member', {
301
+ get: util
302
+ .deprecate(Object.getOwnPropertyDescriptor(Permissions.prototype, 'member').get,
303
+ 'EvaluatedPermissions#member is deprecated'),
304
+ });
305
+
306
+ module.exports = Permissions;
@@ -0,0 +1,82 @@
1
+ const Long = require('long');
2
+
3
+ // Discord epoch (2015-01-01T00:00:00.000Z)
4
+ const EPOCH = 1420070400000;
5
+ let INCREMENT = 0;
6
+
7
+ /**
8
+ * A container for useful snowflake-related methods.
9
+ */
10
+ class SnowflakeUtil {
11
+ constructor() {
12
+ throw new Error(`The ${this.constructor.name} class may not be instantiated.`);
13
+ }
14
+
15
+ /**
16
+ * A Twitter snowflake, except the epoch is 2015-01-01T00:00:00.000Z
17
+ * ```
18
+ * If we have a snowflake '266241948824764416' we can represent it as binary:
19
+ *
20
+ * 64 22 17 12 0
21
+ * 000000111011000111100001101001000101000000 00001 00000 000000000000
22
+ * number of ms since Discord epoch worker pid increment
23
+ * ```
24
+ * @typedef {string} Snowflake
25
+ */
26
+
27
+ /**
28
+ * Generates a Discord snowflake.
29
+ * <info>This hardcodes the worker ID as 1 and the process ID as 0.</info>
30
+ * @param {number|Date} [timestamp=Date.now()] Timestamp or date of the snowflake to generate
31
+ * @returns {Snowflake} The generated snowflake
32
+ */
33
+ static generate(timestamp = Date.now()) {
34
+ if (timestamp instanceof Date) timestamp = timestamp.getTime();
35
+ if (typeof timestamp !== 'number' || isNaN(timestamp)) {
36
+ throw new TypeError(
37
+ `"timestamp" argument must be a number (received ${isNaN(timestamp) ? 'NaN' : typeof timestamp})`
38
+ );
39
+ }
40
+ if (INCREMENT >= 4095) INCREMENT = 0;
41
+ const BINARY = `${pad((timestamp - EPOCH).toString(2), 42)}0000100000${pad((INCREMENT++).toString(2), 12)}`;
42
+ return Long.fromString(BINARY, 2).toString();
43
+ }
44
+
45
+ /**
46
+ * A deconstructed snowflake.
47
+ * @typedef {Object} DeconstructedSnowflake
48
+ * @property {number} timestamp Timestamp the snowflake was created
49
+ * @property {Date} date Date the snowflake was created
50
+ * @property {number} workerID Worker ID in the snowflake
51
+ * @property {number} processID Process ID in the snowflake
52
+ * @property {number} increment Increment in the snowflake
53
+ * @property {string} binary Binary representation of the snowflake
54
+ */
55
+
56
+ /**
57
+ * Deconstructs a Discord snowflake.
58
+ * @param {Snowflake} snowflake Snowflake to deconstruct
59
+ * @returns {DeconstructedSnowflake} Deconstructed snowflake
60
+ */
61
+ static deconstruct(snowflake) {
62
+ const BINARY = pad(Long.fromString(snowflake).toString(2), 64);
63
+ const res = {
64
+ timestamp: parseInt(BINARY.substring(0, 42), 2) + EPOCH,
65
+ workerID: parseInt(BINARY.substring(42, 47), 2),
66
+ processID: parseInt(BINARY.substring(47, 52), 2),
67
+ increment: parseInt(BINARY.substring(52, 64), 2),
68
+ binary: BINARY,
69
+ };
70
+ Object.defineProperty(res, 'date', {
71
+ get: function get() { return new Date(this.timestamp); },
72
+ enumerable: true,
73
+ });
74
+ return res;
75
+ }
76
+ }
77
+
78
+ function pad(v, n, c = '0') {
79
+ return String(v).length >= n ? String(v) : (String(c).repeat(n) + v).slice(-n);
80
+ }
81
+
82
+ module.exports = SnowflakeUtil;
@@ -0,0 +1,221 @@
1
+ const snekfetch = require('snekfetch');
2
+ const Constants = require('./Constants');
3
+ const ConstantsHttp = Constants.DefaultOptions.http;
4
+
5
+ /**
6
+ * Contains various general-purpose utility methods. These functions are also available on the base `Discord` object.
7
+ */
8
+ class Util {
9
+ constructor() {
10
+ throw new Error(`The ${this.constructor.name} class may not be instantiated.`);
11
+ }
12
+
13
+ /**
14
+ * Splits a string into multiple chunks at a designated character that do not exceed a specific length.
15
+ * @param {string} text Content to split
16
+ * @param {SplitOptions} [options] Options controlling the behaviour of the split
17
+ * @returns {string|string[]}
18
+ */
19
+ static splitMessage(text, { maxLength = 1950, char = '\n', prepend = '', append = '' } = {}) {
20
+ if (text.length <= maxLength) return text;
21
+ const splitText = text.split(char);
22
+ if (splitText.some(chunk => chunk.length > maxLength)) {
23
+ throw new Error('Message exceeds the max length and contains no split characters.');
24
+ }
25
+ const messages = [''];
26
+ let msg = 0;
27
+ for (let i = 0; i < splitText.length; i++) {
28
+ if (messages[msg].length + splitText[i].length + 1 > maxLength) {
29
+ messages[msg] += append;
30
+ messages.push(prepend);
31
+ msg++;
32
+ }
33
+ messages[msg] += (messages[msg].length > 0 && messages[msg] !== prepend ? char : '') + splitText[i];
34
+ }
35
+ return messages;
36
+ }
37
+
38
+ /**
39
+ * Escapes any Discord-flavour markdown in a string.
40
+ * @param {string} text Content to escape
41
+ * @param {boolean} [onlyCodeBlock=false] Whether to only escape codeblocks (takes priority)
42
+ * @param {boolean} [onlyInlineCode=false] Whether to only escape inline code
43
+ * @returns {string}
44
+ */
45
+ static escapeMarkdown(text, onlyCodeBlock = false, onlyInlineCode = false) {
46
+ if (onlyCodeBlock) return text.replace(/```/g, '`\u200b``');
47
+ if (onlyInlineCode) return text.replace(/\\(`|\\)/g, '$1').replace(/(`|\\)/g, '\\$1');
48
+ return text.replace(/\\(\*|_|`|~|\\)/g, '$1').replace(/(\*|_|`|~|\\)/g, '\\$1');
49
+ }
50
+
51
+ /**
52
+ * Gets the recommended shard count from Discord.
53
+ * @param {string} token Discord auth token
54
+ * @param {number} [guildsPerShard=1000] Number of guilds per shard
55
+ * @returns {Promise<number>} The recommended number of shards
56
+ */
57
+ static fetchRecommendedShards(token, guildsPerShard = 1000) {
58
+ return new Promise((resolve, reject) => {
59
+ if (!token) throw new Error('A token must be provided.');
60
+ snekfetch.get(`${ConstantsHttp.host}/api/v${ConstantsHttp.version}${Constants.Endpoints.gateway.bot}`)
61
+ .set('Authorization', `Bot ${token.replace(/^Bot\s*/i, '')}`)
62
+ .end((err, res) => {
63
+ if (err) reject(err);
64
+ resolve(res.body.shards * (1000 / guildsPerShard));
65
+ });
66
+ });
67
+ }
68
+
69
+ /**
70
+ * Parses emoji info out of a string. The string must be one of:
71
+ * * A UTF-8 emoji (no ID)
72
+ * * A URL-encoded UTF-8 emoji (no ID)
73
+ * * A Discord custom emoji (`<:name:id>` or `<a:name:id>`)
74
+ * @param {string} text Emoji string to parse
75
+ * @returns {?Object} Object with `animated`, `name`, and `id` properties
76
+ * @private
77
+ */
78
+ static parseEmoji(text) {
79
+ if (text.includes('%')) text = decodeURIComponent(text);
80
+ if (!text.includes(':')) return { animated: false, name: text, id: null };
81
+ const m = text.match(/<?(a:)?(\w{2,32}):(\d{17,19})>?/);
82
+ if (!m) return null;
83
+ return { animated: Boolean(m[1]), name: m[2], id: m[3] };
84
+ }
85
+
86
+ /**
87
+ * Checks whether the arrays are equal, also removes duplicated entries from b.
88
+ * @param {Array<*>} a Array which will not be modified.
89
+ * @param {Array<*>} b Array to remove duplicated entries from.
90
+ * @returns {boolean} Whether the arrays are equal.
91
+ * @private
92
+ */
93
+ static arraysEqual(a, b) {
94
+ if (a === b) return true;
95
+ if (a.length !== b.length) return false;
96
+
97
+ for (const item of a) {
98
+ const ind = b.indexOf(item);
99
+ if (ind !== -1) b.splice(ind, 1);
100
+ }
101
+
102
+ return b.length === 0;
103
+ }
104
+
105
+ /**
106
+ * Shallow-copies an object with its class/prototype intact.
107
+ * @param {Object} obj Object to clone
108
+ * @returns {Object}
109
+ * @private
110
+ */
111
+ static cloneObject(obj) {
112
+ return Object.assign(Object.create(obj), obj);
113
+ }
114
+
115
+ /**
116
+ * Sets default properties on an object that aren't already specified.
117
+ * @param {Object} def Default properties
118
+ * @param {Object} given Object to assign defaults to
119
+ * @returns {Object}
120
+ * @private
121
+ */
122
+ static mergeDefault(def, given) {
123
+ if (!given) return def;
124
+ for (const key in def) {
125
+ if (!{}.hasOwnProperty.call(given, key)) {
126
+ given[key] = def[key];
127
+ } else if (given[key] === Object(given[key])) {
128
+ given[key] = this.mergeDefault(def[key], given[key]);
129
+ }
130
+ }
131
+
132
+ return given;
133
+ }
134
+
135
+ /**
136
+ * Converts an ArrayBuffer or string to a Buffer.
137
+ * @param {ArrayBuffer|string} ab ArrayBuffer to convert
138
+ * @returns {Buffer}
139
+ * @private
140
+ */
141
+ static convertToBuffer(ab) {
142
+ if (typeof ab === 'string') ab = this.str2ab(ab);
143
+ return Buffer.from(ab);
144
+ }
145
+
146
+ /**
147
+ * Converts a string to an ArrayBuffer.
148
+ * @param {string} str String to convert
149
+ * @returns {ArrayBuffer}
150
+ * @private
151
+ */
152
+ static str2ab(str) {
153
+ const buffer = new ArrayBuffer(str.length * 2);
154
+ const view = new Uint16Array(buffer);
155
+ for (var i = 0, strLen = str.length; i < strLen; i++) view[i] = str.charCodeAt(i);
156
+ return buffer;
157
+ }
158
+
159
+ /**
160
+ * Makes an Error from a plain info object.
161
+ * @param {Object} obj Error info
162
+ * @param {string} obj.name Error type
163
+ * @param {string} obj.message Message for the error
164
+ * @param {string} obj.stack Stack for the error
165
+ * @returns {Error}
166
+ * @private
167
+ */
168
+ static makeError(obj) {
169
+ const err = new Error(obj.message);
170
+ err.name = obj.name;
171
+ err.stack = obj.stack;
172
+ return err;
173
+ }
174
+
175
+ /**
176
+ * Makes a plain error info object from an Error.
177
+ * @param {Error} err Error to get info from
178
+ * @returns {Object}
179
+ * @private
180
+ */
181
+ static makePlainError(err) {
182
+ const obj = {};
183
+ obj.name = err.name;
184
+ obj.message = err.message;
185
+ obj.stack = err.stack;
186
+ return obj;
187
+ }
188
+
189
+ /**
190
+ * Moves an element in an array *in place*.
191
+ * @param {Array<*>} array Array to modify
192
+ * @param {*} element Element to move
193
+ * @param {number} newIndex Index or offset to move the element to
194
+ * @param {boolean} [offset=false] Move the element by an offset amount rather than to a set index
195
+ * @returns {number}
196
+ * @private
197
+ */
198
+ static moveElementInArray(array, element, newIndex, offset = false) {
199
+ const index = array.indexOf(element);
200
+ newIndex = (offset ? index : 0) + newIndex;
201
+ if (newIndex > -1 && newIndex < array.length) {
202
+ const removedElement = array.splice(index, 1)[0];
203
+ array.splice(newIndex, 0, removedElement);
204
+ }
205
+ return array.indexOf(element);
206
+ }
207
+
208
+ /**
209
+ * Creates a Promise that resolves after a specified duration.
210
+ * @param {number} ms How long to wait before resolving (in milliseconds)
211
+ * @returns {Promise<void>}
212
+ * @private
213
+ */
214
+ static delayFor(ms) {
215
+ return new Promise(resolve => {
216
+ setTimeout(resolve, ms);
217
+ });
218
+ }
219
+ }
220
+
221
+ module.exports = Util;