djs-selfbot-v13 3.1.8 → 3.7.1

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.
Files changed (364) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +48 -37
  3. package/package.json +44 -26
  4. package/src/WebSocket.js +39 -39
  5. package/src/client/BaseClient.js +86 -86
  6. package/src/client/Client.js +934 -765
  7. package/src/client/WebhookClient.js +61 -61
  8. package/src/client/actions/Action.js +116 -120
  9. package/src/client/actions/ActionsManager.js +80 -78
  10. package/src/client/actions/ApplicationCommandPermissionsUpdate.js +34 -34
  11. package/src/client/actions/AutoModerationActionExecution.js +27 -27
  12. package/src/client/actions/AutoModerationRuleCreate.js +28 -28
  13. package/src/client/actions/AutoModerationRuleDelete.js +32 -32
  14. package/src/client/actions/AutoModerationRuleUpdate.js +30 -30
  15. package/src/client/actions/ChannelCreate.js +23 -23
  16. package/src/client/actions/ChannelDelete.js +39 -39
  17. package/src/client/actions/ChannelUpdate.js +43 -43
  18. package/src/client/actions/GuildAuditLogEntryCreate.js +29 -29
  19. package/src/client/actions/GuildBanAdd.js +20 -20
  20. package/src/client/actions/GuildBanRemove.js +25 -25
  21. package/src/client/actions/GuildChannelsPositionUpdate.js +21 -21
  22. package/src/client/actions/GuildDelete.js +65 -65
  23. package/src/client/actions/GuildEmojiCreate.js +20 -20
  24. package/src/client/actions/GuildEmojiDelete.js +21 -21
  25. package/src/client/actions/GuildEmojiUpdate.js +20 -20
  26. package/src/client/actions/GuildEmojisUpdate.js +34 -34
  27. package/src/client/actions/GuildIntegrationsUpdate.js +19 -19
  28. package/src/client/actions/GuildMemberRemove.js +33 -33
  29. package/src/client/actions/GuildMemberUpdate.js +44 -44
  30. package/src/client/actions/GuildRoleCreate.js +25 -25
  31. package/src/client/actions/GuildRoleDelete.js +31 -31
  32. package/src/client/actions/GuildRoleUpdate.js +39 -39
  33. package/src/client/actions/GuildRolesPositionUpdate.js +21 -21
  34. package/src/client/actions/GuildScheduledEventCreate.js +27 -27
  35. package/src/client/actions/GuildScheduledEventDelete.js +31 -31
  36. package/src/client/actions/GuildScheduledEventUpdate.js +30 -30
  37. package/src/client/actions/GuildScheduledEventUserAdd.js +32 -32
  38. package/src/client/actions/GuildScheduledEventUserRemove.js +32 -32
  39. package/src/client/actions/GuildStickerCreate.js +20 -20
  40. package/src/client/actions/GuildStickerDelete.js +21 -21
  41. package/src/client/actions/GuildStickerUpdate.js +20 -20
  42. package/src/client/actions/GuildStickersUpdate.js +34 -34
  43. package/src/client/actions/GuildUpdate.js +33 -33
  44. package/src/client/actions/InviteCreate.js +28 -28
  45. package/src/client/actions/InviteDelete.js +30 -30
  46. package/src/client/actions/MessageCreate.js +50 -46
  47. package/src/client/actions/MessageDelete.js +32 -32
  48. package/src/client/actions/MessageDeleteBulk.js +46 -46
  49. package/src/client/actions/MessagePollVoteAdd.js +33 -0
  50. package/src/client/actions/MessagePollVoteRemove.js +33 -0
  51. package/src/client/actions/MessageReactionAdd.js +68 -56
  52. package/src/client/actions/MessageReactionRemove.js +50 -45
  53. package/src/client/actions/MessageReactionRemoveAll.js +33 -33
  54. package/src/client/actions/MessageReactionRemoveEmoji.js +28 -28
  55. package/src/client/actions/MessageUpdate.js +26 -26
  56. package/src/client/actions/PresenceUpdate.js +50 -46
  57. package/src/client/actions/StageInstanceCreate.js +28 -28
  58. package/src/client/actions/StageInstanceDelete.js +33 -33
  59. package/src/client/actions/StageInstanceUpdate.js +30 -30
  60. package/src/client/actions/ThreadCreate.js +24 -24
  61. package/src/client/actions/ThreadDelete.js +32 -32
  62. package/src/client/actions/ThreadListSync.js +59 -59
  63. package/src/client/actions/ThreadMemberUpdate.js +30 -30
  64. package/src/client/actions/ThreadMembersUpdate.js +34 -34
  65. package/src/client/actions/TypingStart.js +29 -29
  66. package/src/client/actions/UserUpdate.js +35 -35
  67. package/src/client/actions/VoiceStateUpdate.js +50 -57
  68. package/src/client/actions/WebhooksUpdate.js +20 -20
  69. package/src/client/voice/ClientVoiceManager.js +151 -51
  70. package/src/client/voice/VoiceConnection.js +1249 -0
  71. package/src/client/voice/dispatcher/AnnexBDispatcher.js +120 -0
  72. package/src/client/voice/dispatcher/AudioDispatcher.js +145 -0
  73. package/src/client/voice/dispatcher/BaseDispatcher.js +459 -0
  74. package/src/client/voice/dispatcher/VPxDispatcher.js +54 -0
  75. package/src/client/voice/dispatcher/VideoDispatcher.js +68 -0
  76. package/src/client/voice/networking/VoiceUDPClient.js +173 -0
  77. package/src/client/voice/networking/VoiceWebSocket.js +286 -0
  78. package/src/client/voice/player/MediaPlayer.js +321 -0
  79. package/src/client/voice/player/processing/AnnexBNalSplitter.js +244 -0
  80. package/src/client/voice/player/processing/IvfSplitter.js +106 -0
  81. package/src/client/voice/player/processing/PCMInsertSilence.js +37 -0
  82. package/src/client/voice/receiver/PacketHandler.js +260 -0
  83. package/src/client/voice/receiver/Receiver.js +96 -0
  84. package/src/client/voice/receiver/Recorder.js +173 -0
  85. package/src/client/voice/util/Function.js +116 -0
  86. package/src/client/voice/util/PlayInterface.js +122 -0
  87. package/src/client/voice/util/Secretbox.js +64 -0
  88. package/src/client/voice/util/Silence.js +16 -0
  89. package/src/client/voice/util/Socket.js +62 -0
  90. package/src/client/voice/util/VolumeInterface.js +104 -0
  91. package/src/client/websocket/WebSocketManager.js +392 -392
  92. package/src/client/websocket/WebSocketShard.js +907 -906
  93. package/src/client/websocket/handlers/APPLICATION_COMMAND_CREATE.js +18 -18
  94. package/src/client/websocket/handlers/APPLICATION_COMMAND_DELETE.js +20 -20
  95. package/src/client/websocket/handlers/APPLICATION_COMMAND_PERMISSIONS_UPDATE.js +5 -5
  96. package/src/client/websocket/handlers/APPLICATION_COMMAND_UPDATE.js +20 -20
  97. package/src/client/websocket/handlers/AUTO_MODERATION_ACTION_EXECUTION.js +5 -5
  98. package/src/client/websocket/handlers/AUTO_MODERATION_RULE_CREATE.js +5 -5
  99. package/src/client/websocket/handlers/AUTO_MODERATION_RULE_DELETE.js +5 -5
  100. package/src/client/websocket/handlers/AUTO_MODERATION_RULE_UPDATE.js +5 -5
  101. package/src/client/websocket/handlers/CALL_CREATE.js +14 -14
  102. package/src/client/websocket/handlers/CALL_DELETE.js +11 -11
  103. package/src/client/websocket/handlers/CALL_UPDATE.js +11 -11
  104. package/src/client/websocket/handlers/CHANNEL_CREATE.js +5 -5
  105. package/src/client/websocket/handlers/CHANNEL_DELETE.js +5 -5
  106. package/src/client/websocket/handlers/CHANNEL_PINS_UPDATE.js +22 -22
  107. package/src/client/websocket/handlers/CHANNEL_RECIPIENT_ADD.js +19 -19
  108. package/src/client/websocket/handlers/CHANNEL_RECIPIENT_REMOVE.js +16 -16
  109. package/src/client/websocket/handlers/CHANNEL_UPDATE.js +16 -16
  110. package/src/client/websocket/handlers/GUILD_AUDIT_LOG_ENTRY_CREATE.js +5 -5
  111. package/src/client/websocket/handlers/GUILD_BAN_ADD.js +5 -5
  112. package/src/client/websocket/handlers/GUILD_BAN_REMOVE.js +5 -5
  113. package/src/client/websocket/handlers/GUILD_CREATE.js +52 -53
  114. package/src/client/websocket/handlers/GUILD_DELETE.js +5 -5
  115. package/src/client/websocket/handlers/GUILD_EMOJIS_UPDATE.js +5 -5
  116. package/src/client/websocket/handlers/GUILD_INTEGRATIONS_UPDATE.js +5 -5
  117. package/src/client/websocket/handlers/GUILD_MEMBERS_CHUNK.js +39 -39
  118. package/src/client/websocket/handlers/GUILD_MEMBER_ADD.js +20 -20
  119. package/src/client/websocket/handlers/GUILD_MEMBER_REMOVE.js +5 -5
  120. package/src/client/websocket/handlers/GUILD_MEMBER_UPDATE.js +5 -5
  121. package/src/client/websocket/handlers/GUILD_ROLE_CREATE.js +5 -5
  122. package/src/client/websocket/handlers/GUILD_ROLE_DELETE.js +5 -5
  123. package/src/client/websocket/handlers/GUILD_ROLE_UPDATE.js +5 -5
  124. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_CREATE.js +5 -5
  125. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_DELETE.js +5 -5
  126. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_UPDATE.js +5 -5
  127. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_USER_ADD.js +5 -5
  128. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_USER_REMOVE.js +5 -5
  129. package/src/client/websocket/handlers/GUILD_STICKERS_UPDATE.js +5 -5
  130. package/src/client/websocket/handlers/GUILD_UPDATE.js +5 -5
  131. package/src/client/websocket/handlers/INTERACTION_MODAL_CREATE.js +12 -12
  132. package/src/client/websocket/handlers/INVITE_CREATE.js +5 -5
  133. package/src/client/websocket/handlers/INVITE_DELETE.js +5 -5
  134. package/src/client/websocket/handlers/MESSAGE_CREATE.js +5 -5
  135. package/src/client/websocket/handlers/MESSAGE_DELETE.js +5 -5
  136. package/src/client/websocket/handlers/MESSAGE_DELETE_BULK.js +5 -5
  137. package/src/client/websocket/handlers/MESSAGE_POLL_VOTE_ADD.js +5 -0
  138. package/src/client/websocket/handlers/MESSAGE_POLL_VOTE_REMOVE.js +5 -0
  139. package/src/client/websocket/handlers/MESSAGE_REACTION_ADD.js +5 -5
  140. package/src/client/websocket/handlers/MESSAGE_REACTION_REMOVE.js +5 -5
  141. package/src/client/websocket/handlers/MESSAGE_REACTION_REMOVE_ALL.js +5 -5
  142. package/src/client/websocket/handlers/MESSAGE_REACTION_REMOVE_EMOJI.js +5 -5
  143. package/src/client/websocket/handlers/MESSAGE_UPDATE.js +16 -16
  144. package/src/client/websocket/handlers/PRESENCE_UPDATE.js +5 -5
  145. package/src/client/websocket/handlers/READY.js +121 -80
  146. package/src/client/websocket/handlers/RELATIONSHIP_ADD.js +19 -19
  147. package/src/client/websocket/handlers/RELATIONSHIP_REMOVE.js +17 -17
  148. package/src/client/websocket/handlers/RELATIONSHIP_UPDATE.js +41 -41
  149. package/src/client/websocket/handlers/RESUMED.js +14 -14
  150. package/src/client/websocket/handlers/STAGE_INSTANCE_CREATE.js +5 -5
  151. package/src/client/websocket/handlers/STAGE_INSTANCE_DELETE.js +5 -5
  152. package/src/client/websocket/handlers/STAGE_INSTANCE_UPDATE.js +5 -5
  153. package/src/client/websocket/handlers/THREAD_CREATE.js +5 -5
  154. package/src/client/websocket/handlers/THREAD_DELETE.js +5 -5
  155. package/src/client/websocket/handlers/THREAD_LIST_SYNC.js +5 -5
  156. package/src/client/websocket/handlers/THREAD_MEMBERS_UPDATE.js +5 -5
  157. package/src/client/websocket/handlers/THREAD_MEMBER_UPDATE.js +5 -5
  158. package/src/client/websocket/handlers/THREAD_UPDATE.js +16 -16
  159. package/src/client/websocket/handlers/TYPING_START.js +5 -5
  160. package/src/client/websocket/handlers/USER_GUILD_SETTINGS_UPDATE.js +6 -6
  161. package/src/client/websocket/handlers/USER_NOTE_UPDATE.js +5 -5
  162. package/src/client/websocket/handlers/USER_REQUIRED_ACTION_UPDATE.js +78 -78
  163. package/src/client/websocket/handlers/USER_SETTINGS_UPDATE.js +5 -5
  164. package/src/client/websocket/handlers/USER_UPDATE.js +5 -5
  165. package/src/client/websocket/handlers/VOICE_CHANNEL_EFFECT_SEND.js +16 -0
  166. package/src/client/websocket/handlers/VOICE_CHANNEL_STATUS_UPDATE.js +12 -12
  167. package/src/client/websocket/handlers/VOICE_SERVER_UPDATE.js +6 -6
  168. package/src/client/websocket/handlers/VOICE_STATE_UPDATE.js +5 -5
  169. package/src/client/websocket/handlers/WEBHOOKS_UPDATE.js +5 -5
  170. package/src/client/websocket/handlers/index.js +84 -81
  171. package/src/errors/DJSError.js +61 -61
  172. package/src/errors/Messages.js +217 -182
  173. package/src/errors/index.js +4 -4
  174. package/src/index.js +172 -158
  175. package/src/managers/ApplicationCommandManager.js +264 -264
  176. package/src/managers/ApplicationCommandPermissionsManager.js +417 -417
  177. package/src/managers/AutoModerationRuleManager.js +296 -296
  178. package/src/managers/BaseGuildEmojiManager.js +80 -80
  179. package/src/managers/BaseManager.js +19 -19
  180. package/src/managers/BillingManager.js +66 -66
  181. package/src/managers/CachedManager.js +71 -71
  182. package/src/managers/ChannelManager.js +148 -138
  183. package/src/managers/ClientUserSettingManager.js +372 -372
  184. package/src/managers/DataManager.js +61 -61
  185. package/src/managers/GuildBanManager.js +250 -204
  186. package/src/managers/GuildChannelManager.js +488 -504
  187. package/src/managers/GuildEmojiManager.js +171 -171
  188. package/src/managers/GuildEmojiRoleManager.js +118 -118
  189. package/src/managers/GuildForumThreadManager.js +108 -108
  190. package/src/managers/GuildInviteManager.js +213 -213
  191. package/src/managers/GuildManager.js +338 -304
  192. package/src/managers/GuildMemberManager.js +599 -593
  193. package/src/managers/GuildMemberRoleManager.js +195 -191
  194. package/src/managers/GuildScheduledEventManager.js +314 -296
  195. package/src/managers/GuildSettingManager.js +155 -155
  196. package/src/managers/GuildStickerManager.js +179 -179
  197. package/src/managers/GuildTextThreadManager.js +98 -98
  198. package/src/managers/InteractionManager.js +39 -39
  199. package/src/managers/MessageManager.js +423 -391
  200. package/src/managers/PermissionOverwriteManager.js +164 -166
  201. package/src/managers/PresenceManager.js +71 -58
  202. package/src/managers/ReactionManager.js +67 -67
  203. package/src/managers/ReactionUserManager.js +73 -71
  204. package/src/managers/RelationshipManager.js +278 -265
  205. package/src/managers/RoleManager.js +448 -352
  206. package/src/managers/SessionManager.js +66 -0
  207. package/src/managers/StageInstanceManager.js +162 -162
  208. package/src/managers/ThreadManager.js +175 -174
  209. package/src/managers/ThreadMemberManager.js +186 -186
  210. package/src/managers/UserManager.js +136 -146
  211. package/src/managers/UserNoteManager.js +53 -53
  212. package/src/managers/VoiceStateManager.js +59 -37
  213. package/src/rest/APIRequest.js +154 -154
  214. package/src/rest/APIRouter.js +53 -53
  215. package/src/rest/DiscordAPIError.js +119 -104
  216. package/src/rest/HTTPError.js +62 -62
  217. package/src/rest/RESTManager.js +67 -62
  218. package/src/rest/RateLimitError.js +55 -55
  219. package/src/rest/RequestHandler.js +466 -444
  220. package/src/sharding/Shard.js +444 -443
  221. package/src/sharding/ShardClientUtil.js +279 -275
  222. package/src/sharding/ShardingManager.js +319 -318
  223. package/src/structures/AnonymousGuild.js +98 -98
  224. package/src/structures/ApplicationCommand.js +593 -593
  225. package/src/structures/ApplicationRoleConnectionMetadata.js +48 -48
  226. package/src/structures/AutoModerationActionExecution.js +89 -89
  227. package/src/structures/AutoModerationRule.js +294 -294
  228. package/src/structures/AutocompleteInteraction.js +107 -107
  229. package/src/structures/Base.js +43 -43
  230. package/src/structures/BaseCommandInteraction.js +211 -211
  231. package/src/structures/BaseGuild.js +116 -116
  232. package/src/structures/BaseGuildEmoji.js +56 -56
  233. package/src/structures/BaseGuildTextChannel.js +191 -191
  234. package/src/structures/BaseGuildVoiceChannel.js +241 -241
  235. package/src/structures/BaseMessageComponent.js +181 -114
  236. package/src/structures/ButtonInteraction.js +11 -11
  237. package/src/structures/CallState.js +63 -63
  238. package/src/structures/CategoryChannel.js +85 -85
  239. package/src/structures/Channel.js +284 -270
  240. package/src/structures/ClientPresence.js +77 -88
  241. package/src/structures/ClientUser.js +479 -450
  242. package/src/structures/CommandInteraction.js +41 -41
  243. package/src/structures/CommandInteractionOptionResolver.js +276 -276
  244. package/src/structures/ContainerComponent.js +68 -0
  245. package/src/structures/ContextMenuInteraction.js +65 -65
  246. package/src/structures/DMChannel.js +219 -217
  247. package/src/structures/DirectoryChannel.js +20 -20
  248. package/src/structures/Emoji.js +148 -148
  249. package/src/structures/FileComponent.js +49 -0
  250. package/src/structures/ForumChannel.js +31 -261
  251. package/src/structures/GroupDMChannel.js +394 -387
  252. package/src/structures/Guild.js +1643 -1608
  253. package/src/structures/GuildAuditLogs.js +746 -729
  254. package/src/structures/GuildBan.js +59 -59
  255. package/src/structures/GuildBoost.js +108 -108
  256. package/src/structures/GuildChannel.js +470 -468
  257. package/src/structures/GuildEmoji.js +161 -161
  258. package/src/structures/GuildMember.js +636 -568
  259. package/src/structures/GuildPreview.js +191 -191
  260. package/src/structures/GuildPreviewEmoji.js +27 -27
  261. package/src/structures/GuildScheduledEvent.js +536 -441
  262. package/src/structures/GuildTemplate.js +236 -236
  263. package/src/structures/Integration.js +188 -188
  264. package/src/structures/IntegrationApplication.js +96 -96
  265. package/src/structures/Interaction.js +290 -290
  266. package/src/structures/InteractionCollector.js +248 -248
  267. package/src/structures/InteractionWebhook.js +43 -43
  268. package/src/structures/Invite.js +358 -358
  269. package/src/structures/InviteGuild.js +23 -23
  270. package/src/structures/InviteStageInstance.js +86 -86
  271. package/src/structures/MediaChannel.js +11 -0
  272. package/src/structures/MediaGalleryComponent.js +41 -0
  273. package/src/structures/MediaGalleryItem.js +47 -0
  274. package/src/structures/Message.js +1252 -1236
  275. package/src/structures/MessageActionRow.js +105 -103
  276. package/src/structures/MessageAttachment.js +216 -204
  277. package/src/structures/MessageButton.js +166 -165
  278. package/src/structures/MessageCollector.js +146 -146
  279. package/src/structures/MessageComponentInteraction.js +120 -120
  280. package/src/structures/MessageContextMenuInteraction.js +20 -20
  281. package/src/structures/MessageEmbed.js +596 -586
  282. package/src/structures/MessageMentions.js +273 -273
  283. package/src/structures/MessagePayload.js +354 -316
  284. package/src/structures/MessageReaction.js +181 -171
  285. package/src/structures/MessageSelectMenu.js +141 -140
  286. package/src/structures/Modal.js +161 -174
  287. package/src/structures/ModalSubmitFieldsResolver.js +53 -53
  288. package/src/structures/ModalSubmitInteraction.js +119 -119
  289. package/src/structures/NewsChannel.js +32 -32
  290. package/src/structures/OAuth2Guild.js +28 -28
  291. package/src/structures/PermissionOverwrites.js +198 -196
  292. package/src/structures/Poll.js +108 -0
  293. package/src/structures/PollAnswer.js +88 -0
  294. package/src/structures/Presence.js +1105 -443
  295. package/src/structures/ReactionCollector.js +229 -229
  296. package/src/structures/ReactionEmoji.js +31 -31
  297. package/src/structures/Role.js +590 -531
  298. package/src/structures/SectionComponent.js +48 -0
  299. package/src/structures/SelectMenuInteraction.js +21 -21
  300. package/src/structures/SeparatorComponent.js +48 -0
  301. package/src/structures/Session.js +81 -0
  302. package/src/structures/StageChannel.js +104 -104
  303. package/src/structures/StageInstance.js +208 -208
  304. package/src/structures/Sticker.js +310 -310
  305. package/src/structures/StickerPack.js +95 -95
  306. package/src/structures/StoreChannel.js +56 -56
  307. package/src/structures/Team.js +118 -118
  308. package/src/structures/TeamMember.js +80 -71
  309. package/src/structures/TextChannel.js +33 -33
  310. package/src/structures/TextDisplayComponent.js +40 -0
  311. package/src/structures/TextInputComponent.js +132 -131
  312. package/src/structures/ThreadChannel.js +605 -607
  313. package/src/structures/ThreadMember.js +105 -105
  314. package/src/structures/ThreadOnlyChannel.js +249 -0
  315. package/src/structures/ThumbnailComponent.js +57 -0
  316. package/src/structures/Typing.js +74 -74
  317. package/src/structures/UnfurledMediaItem.js +29 -0
  318. package/src/structures/User.js +640 -509
  319. package/src/structures/UserContextMenuInteraction.js +29 -29
  320. package/src/structures/VoiceChannel.js +110 -110
  321. package/src/structures/VoiceChannelEffect.js +69 -0
  322. package/src/structures/VoiceRegion.js +53 -53
  323. package/src/structures/VoiceState.js +354 -341
  324. package/src/structures/WebEmbed.js +373 -373
  325. package/src/structures/Webhook.js +478 -467
  326. package/src/structures/WelcomeChannel.js +60 -60
  327. package/src/structures/WelcomeScreen.js +48 -48
  328. package/src/structures/Widget.js +87 -87
  329. package/src/structures/WidgetMember.js +99 -99
  330. package/src/structures/interfaces/Application.js +825 -313
  331. package/src/structures/interfaces/Collector.js +300 -300
  332. package/src/structures/interfaces/InteractionResponses.js +313 -313
  333. package/src/structures/interfaces/TextBasedChannel.js +759 -721
  334. package/src/util/APITypes.js +59 -0
  335. package/src/util/ActivityFlags.js +44 -44
  336. package/src/util/ApplicationFlags.js +76 -76
  337. package/src/util/AttachmentFlags.js +38 -38
  338. package/src/util/BitField.js +170 -170
  339. package/src/util/ChannelFlags.js +45 -45
  340. package/src/util/Constants.js +1914 -1760
  341. package/src/util/DataResolver.js +146 -145
  342. package/src/util/Formatters.js +228 -228
  343. package/src/util/GuildMemberFlags.js +43 -43
  344. package/src/util/Intents.js +74 -74
  345. package/src/util/InviteFlags.js +34 -29
  346. package/src/util/LimitedCollection.js +131 -131
  347. package/src/util/MessageFlags.js +63 -54
  348. package/src/util/Options.js +358 -342
  349. package/src/util/Permissions.js +202 -192
  350. package/src/util/PremiumUsageFlags.js +31 -31
  351. package/src/util/PurchasedFlags.js +33 -33
  352. package/src/util/RemoteAuth.js +382 -379
  353. package/src/util/RoleFlags.js +37 -37
  354. package/src/util/SnowflakeUtil.js +92 -92
  355. package/src/util/Speaking.js +33 -0
  356. package/src/util/Sweepers.js +466 -466
  357. package/src/util/SystemChannelFlags.js +55 -55
  358. package/src/util/ThreadMemberFlags.js +30 -30
  359. package/src/util/UserFlags.js +104 -104
  360. package/src/util/Util.js +1048 -803
  361. package/typings/enums.d.ts +439 -291
  362. package/typings/index.d.ts +8247 -7390
  363. package/typings/rawDataTypes.d.ts +403 -342
  364. package/src/structures/RichPresence.js +0 -702
@@ -1,765 +1,934 @@
1
- 'use strict';
2
-
3
- const process = require('node:process');
4
- const { setInterval } = require('node:timers');
5
- const { setTimeout } = require('node:timers');
6
- const { Collection } = require('@discordjs/collection');
7
- const BaseClient = require('./BaseClient');
8
- const ActionsManager = require('./actions/ActionsManager');
9
- const ClientVoiceManager = require('./voice/ClientVoiceManager');
10
- const WebSocketManager = require('./websocket/WebSocketManager');
11
- const { Error, TypeError } = require('../errors');
12
- const BaseGuildEmojiManager = require('../managers/BaseGuildEmojiManager');
13
- const BillingManager = require('../managers/BillingManager');
14
- const ChannelManager = require('../managers/ChannelManager');
15
- const ClientUserSettingManager = require('../managers/ClientUserSettingManager');
16
- const GuildManager = require('../managers/GuildManager');
17
- const PresenceManager = require('../managers/PresenceManager');
18
- const RelationshipManager = require('../managers/RelationshipManager');
19
- const UserManager = require('../managers/UserManager');
20
- const UserNoteManager = require('../managers/UserNoteManager');
21
- const VoiceStateManager = require('../managers/VoiceStateManager');
22
- const ShardClientUtil = require('../sharding/ShardClientUtil');
23
- const ClientPresence = require('../structures/ClientPresence');
24
- const GuildPreview = require('../structures/GuildPreview');
25
- const GuildTemplate = require('../structures/GuildTemplate');
26
- const Invite = require('../structures/Invite');
27
- const { Sticker } = require('../structures/Sticker');
28
- const StickerPack = require('../structures/StickerPack');
29
- const VoiceRegion = require('../structures/VoiceRegion');
30
- const Webhook = require('../structures/Webhook');
31
- const Widget = require('../structures/Widget');
32
- const { Events, Status } = require('../util/Constants');
33
- const DataResolver = require('../util/DataResolver');
34
- const Intents = require('../util/Intents');
35
- const Permissions = require('../util/Permissions');
36
- const DiscordAuthWebsocket = require('../util/RemoteAuth');
37
- const Sweepers = require('../util/Sweepers');
38
-
39
- /**
40
- * The main hub for interacting with the Discord API, and the starting point for any bot.
41
- * @extends {BaseClient}
42
- */
43
- class Client extends BaseClient {
44
- /**
45
- * @param {ClientOptions} [options] Options for the client
46
- */
47
- constructor(options) {
48
- super(options);
49
-
50
- this._validateOptions();
51
-
52
- /**
53
- * Functions called when a cache is garbage collected or the Client is destroyed
54
- * @type {Set<Function>}
55
- * @private
56
- */
57
- this._cleanups = new Set();
58
-
59
- /**
60
- * The finalizers used to cleanup items.
61
- * @type {FinalizationRegistry}
62
- * @private
63
- */
64
- this._finalizers = new FinalizationRegistry(this._finalize.bind(this));
65
-
66
- /**
67
- * The WebSocket manager of the client
68
- * @type {WebSocketManager}
69
- */
70
- this.ws = new WebSocketManager(this);
71
-
72
- /**
73
- * The action manager of the client
74
- * @type {ActionsManager}
75
- * @private
76
- */
77
- this.actions = new ActionsManager(this);
78
-
79
- /**
80
- * The voice manager of the client
81
- * @type {ClientVoiceManager}
82
- */
83
- this.voice = new ClientVoiceManager(this);
84
-
85
- /**
86
- * A manager of the voice states of this client (Support DM / Group DM)
87
- * @type {VoiceStateManager}
88
- */
89
- this.voiceStates = new VoiceStateManager({ client: this });
90
-
91
- /**
92
- * Shard helpers for the client (only if the process was spawned from a {@link ShardingManager})
93
- * @type {?ShardClientUtil}
94
- */
95
- this.shard = process.env.SHARDING_MANAGER
96
- ? ShardClientUtil.singleton(this, process.env.SHARDING_MANAGER_MODE)
97
- : null;
98
-
99
- /**
100
- * All of the {@link User} objects that have been cached at any point, mapped by their ids
101
- * @type {UserManager}
102
- */
103
- this.users = new UserManager(this);
104
-
105
- /**
106
- * All of the guilds the client is currently handling, mapped by their ids -
107
- * as long as sharding isn't being used, this will be *every* guild the bot is a member of
108
- * @type {GuildManager}
109
- */
110
- this.guilds = new GuildManager(this);
111
-
112
- /**
113
- * All of the {@link Channel}s that the client is currently handling, mapped by their ids -
114
- * as long as sharding isn't being used, this will be *every* channel in *every* guild the bot
115
- * is a member of. Note that DM channels will not be initially cached, and thus not be present
116
- * in the Manager without their explicit fetching or use.
117
- * @type {ChannelManager}
118
- */
119
- this.channels = new ChannelManager(this);
120
-
121
- /**
122
- * The sweeping functions and their intervals used to periodically sweep caches
123
- * @type {Sweepers}
124
- */
125
- this.sweepers = new Sweepers(this, this.options.sweepers);
126
-
127
- /**
128
- * The presence of the Client
129
- * @private
130
- * @type {ClientPresence}
131
- */
132
- this.presence = new ClientPresence(this, this.options.presence);
133
-
134
- /**
135
- * A manager of the presences belonging to this client
136
- * @type {PresenceManager}
137
- */
138
- this.presences = new PresenceManager(this);
139
-
140
- /**
141
- * All of the note that have been cached at any point, mapped by their ids
142
- * @type {UserManager}
143
- */
144
- this.notes = new UserNoteManager(this);
145
-
146
- /**
147
- * All of the relationships {@link User}
148
- * @type {RelationshipManager}
149
- */
150
- this.relationships = new RelationshipManager(this);
151
-
152
- /**
153
- * Manages the API methods
154
- * @type {BillingManager}
155
- */
156
- this.billing = new BillingManager(this);
157
-
158
- /**
159
- * All of the settings {@link Object}
160
- * @type {ClientUserSettingManager}
161
- */
162
- this.settings = new ClientUserSettingManager(this);
163
-
164
- Object.defineProperty(this, 'token', { writable: true });
165
- if (!this.token && 'DISCORD_TOKEN' in process.env) {
166
- /**
167
- * Authorization token for the logged in bot.
168
- * If present, this defaults to `process.env.DISCORD_TOKEN` when instantiating the client
169
- * <warn>This should be kept private at all times.</warn>
170
- * @type {?string}
171
- */
172
- this.token = process.env.DISCORD_TOKEN;
173
- } else {
174
- this.token = null;
175
- }
176
-
177
- /**
178
- * User that the client is logged in as
179
- * @type {?ClientUser}
180
- */
181
- this.user = null;
182
-
183
- /**
184
- * Time at which the client was last regarded as being in the `READY` state
185
- * (each time the client disconnects and successfully reconnects, this will be overwritten)
186
- * @type {?Date}
187
- */
188
- this.readyAt = null;
189
-
190
- if (this.options.messageSweepInterval > 0) {
191
- process.emitWarning(
192
- 'The message sweeping client options are deprecated, use the global sweepers instead.',
193
- 'DeprecationWarning',
194
- );
195
- this.sweepMessageInterval = setInterval(
196
- this.sweepMessages.bind(this),
197
- this.options.messageSweepInterval * 1_000,
198
- ).unref();
199
- }
200
- }
201
-
202
- /**
203
- * All custom emojis that the client has access to, mapped by their ids
204
- * @type {BaseGuildEmojiManager}
205
- * @readonly
206
- */
207
- get emojis() {
208
- const emojis = new BaseGuildEmojiManager(this);
209
- for (const guild of this.guilds.cache.values()) {
210
- if (guild.available) for (const emoji of guild.emojis.cache.values()) emojis.cache.set(emoji.id, emoji);
211
- }
212
- return emojis;
213
- }
214
-
215
- /**
216
- * Timestamp of the time the client was last `READY` at
217
- * @type {?number}
218
- * @readonly
219
- */
220
- get readyTimestamp() {
221
- return this.readyAt?.getTime() ?? null;
222
- }
223
-
224
- /**
225
- * How long it has been since the client last entered the `READY` state in milliseconds
226
- * @type {?number}
227
- * @readonly
228
- */
229
- get uptime() {
230
- return this.readyAt ? Date.now() - this.readyAt : null;
231
- }
232
-
233
- /**
234
- * Logs the client in, establishing a WebSocket connection to Discord.
235
- * @param {string} [token=this.token] Token of the account to log in with
236
- * @returns {Promise<string>} Token of the account used
237
- * @example
238
- * client.login('my token');
239
- */
240
- async login(token = this.token) {
241
- if (!token || typeof token !== 'string') throw new Error('TOKEN_INVALID');
242
- this.token = token = token.replace(/^(Bot|Bearer)\s*/i, '');
243
- this.emit(
244
- Events.DEBUG,
245
- `
246
- Logging on with a user token is unfortunately against the Discord
247
- \`Terms of Service\` <https://support.discord.com/hc/en-us/articles/115002192352>
248
- and doing so might potentially get your account banned.
249
- Use this at your own risk.`,
250
- );
251
- this.emit(
252
- Events.DEBUG,
253
- `Provided token: ${token
254
- .split('.')
255
- .map((val, i) => (i > 1 ? val.replace(/./g, '*') : val))
256
- .join('.')}`,
257
- );
258
-
259
- if (this.options.presence) {
260
- this.options.ws.presence = this.presence._parse(this.options.presence);
261
- }
262
-
263
- this.emit(Events.DEBUG, 'Preparing to connect to the gateway...');
264
-
265
- try {
266
- await this.ws.connect();
267
- return this.token;
268
- } catch (error) {
269
- this.destroy();
270
- throw error;
271
- }
272
- }
273
-
274
- QRLogin() {
275
- const ws = new DiscordAuthWebsocket();
276
- ws.once('ready', () => ws.generateQR());
277
- return ws.connect(this);
278
- }
279
-
280
- /**
281
- * Returns whether the client has logged in, indicative of being able to access
282
- * properties such as `user` and `application`.
283
- * @returns {boolean}
284
- */
285
- isReady() {
286
- return this.ws.status === Status.READY;
287
- }
288
-
289
- /**
290
- * Logs out, terminates the connection to Discord, and destroys the client.
291
- * @returns {void}
292
- */
293
- destroy() {
294
- super.destroy();
295
-
296
- for (const fn of this._cleanups) fn();
297
- this._cleanups.clear();
298
-
299
- if (this.sweepMessageInterval) clearInterval(this.sweepMessageInterval);
300
-
301
- this.sweepers.destroy();
302
- this.ws.destroy();
303
- this.token = null;
304
- }
305
-
306
- /**
307
- * Logs out, terminates the connection to Discord, destroys the client and destroys the token.
308
- * @returns {Promise<void>}
309
- */
310
- async logout() {
311
- await this.api.auth.logout.post({
312
- data: {
313
- provider: null,
314
- voip_provider: null,
315
- },
316
- });
317
- return this.destroy();
318
- }
319
-
320
- /**
321
- * Options used when fetching an invite from Discord.
322
- * @typedef {Object} ClientFetchInviteOptions
323
- * @property {Snowflake} [guildScheduledEventId] The id of the guild scheduled event to include with
324
- * the invite
325
- */
326
-
327
- /**
328
- * Obtains an invite from Discord.
329
- * @param {InviteResolvable} invite Invite code or URL
330
- * @param {ClientFetchInviteOptions} [options] Options for fetching the invite
331
- * @returns {Promise<Invite>}
332
- * @example
333
- * client.fetchInvite('https://discord.gg/djs')
334
- * .then(invite => console.log(`Obtained invite with code: ${invite.code}`))
335
- * .catch(console.error);
336
- */
337
- async fetchInvite(invite, options) {
338
- const code = DataResolver.resolveInviteCode(invite);
339
- const data = await this.api.invites(code).get({
340
- query: { with_counts: true, with_expiration: true, guild_scheduled_event_id: options?.guildScheduledEventId },
341
- });
342
- return new Invite(this, data);
343
- }
344
-
345
- /**
346
- * Obtains a template from Discord.
347
- * @param {GuildTemplateResolvable} template Template code or URL
348
- * @returns {Promise<GuildTemplate>}
349
- * @example
350
- * client.fetchGuildTemplate('https://discord.new/FKvmczH2HyUf')
351
- * .then(template => console.log(`Obtained template with code: ${template.code}`))
352
- * .catch(console.error);
353
- */
354
- async fetchGuildTemplate(template) {
355
- const code = DataResolver.resolveGuildTemplateCode(template);
356
- const data = await this.api.guilds.templates(code).get();
357
- return new GuildTemplate(this, data);
358
- }
359
-
360
- /**
361
- * Obtains a webhook from Discord.
362
- * @param {Snowflake} id The webhook's id
363
- * @param {string} [token] Token for the webhook
364
- * @returns {Promise<Webhook>}
365
- * @example
366
- * client.fetchWebhook('id', 'token')
367
- * .then(webhook => console.log(`Obtained webhook with name: ${webhook.name}`))
368
- * .catch(console.error);
369
- */
370
- async fetchWebhook(id, token) {
371
- const data = await this.api.webhooks(id, token).get();
372
- return new Webhook(this, { token, ...data });
373
- }
374
-
375
- /**
376
- * Obtains the available voice regions from Discord.
377
- * @returns {Promise<Collection<string, VoiceRegion>>}
378
- * @example
379
- * client.fetchVoiceRegions()
380
- * .then(regions => console.log(`Available regions are: ${regions.map(region => region.name).join(', ')}`))
381
- * .catch(console.error);
382
- */
383
- async fetchVoiceRegions() {
384
- const apiRegions = await this.api.voice.regions.get();
385
- const regions = new Collection();
386
- for (const region of apiRegions) regions.set(region.id, new VoiceRegion(region));
387
- return regions;
388
- }
389
-
390
- /**
391
- * Obtains a sticker from Discord.
392
- * @param {Snowflake} id The sticker's id
393
- * @returns {Promise<Sticker>}
394
- * @example
395
- * client.fetchSticker('id')
396
- * .then(sticker => console.log(`Obtained sticker with name: ${sticker.name}`))
397
- * .catch(console.error);
398
- */
399
- async fetchSticker(id) {
400
- const data = await this.api.stickers(id).get();
401
- return new Sticker(this, data);
402
- }
403
-
404
- /**
405
- * Obtains the list of sticker packs available to Nitro subscribers from Discord.
406
- * @returns {Promise<Collection<Snowflake, StickerPack>>}
407
- * @example
408
- * client.fetchPremiumStickerPacks()
409
- * .then(packs => console.log(`Available sticker packs are: ${packs.map(pack => pack.name).join(', ')}`))
410
- * .catch(console.error);
411
- */
412
- async fetchPremiumStickerPacks() {
413
- const data = await this.api('sticker-packs').get();
414
- return new Collection(data.sticker_packs.map(p => [p.id, new StickerPack(this, p)]));
415
- }
416
- /**
417
- * A last ditch cleanup function for garbage collection.
418
- * @param {Function} options.cleanup The function called to GC
419
- * @param {string} [options.message] The message to send after a successful GC
420
- * @param {string} [options.name] The name of the item being GCed
421
- * @private
422
- */
423
- _finalize({ cleanup, message, name }) {
424
- try {
425
- cleanup();
426
- this._cleanups.delete(cleanup);
427
- if (message) {
428
- this.emit(Events.DEBUG, message);
429
- }
430
- } catch {
431
- this.emit(Events.DEBUG, `Garbage collection failed on ${name ?? 'an unknown item'}.`);
432
- }
433
- }
434
-
435
- /**
436
- * Sweeps all text-based channels' messages and removes the ones older than the max message lifetime.
437
- * If the message has been edited, the time of the edit is used rather than the time of the original message.
438
- * @param {number} [lifetime=this.options.messageCacheLifetime] Messages that are older than this (in seconds)
439
- * will be removed from the caches. The default is based on {@link ClientOptions#messageCacheLifetime}
440
- * @returns {number} Amount of messages that were removed from the caches,
441
- * or -1 if the message cache lifetime is unlimited
442
- * @example
443
- * // Remove all messages older than 1800 seconds from the messages cache
444
- * const amount = client.sweepMessages(1800);
445
- * console.log(`Successfully removed ${amount} messages from the cache.`);
446
- */
447
- sweepMessages(lifetime = this.options.messageCacheLifetime) {
448
- if (typeof lifetime !== 'number' || isNaN(lifetime)) {
449
- throw new TypeError('INVALID_TYPE', 'lifetime', 'number');
450
- }
451
- if (lifetime <= 0) {
452
- this.emit(Events.DEBUG, "Didn't sweep messages - lifetime is unlimited");
453
- return -1;
454
- }
455
-
456
- const messages = this.sweepers.sweepMessages(Sweepers.outdatedMessageSweepFilter(lifetime)());
457
- this.emit(Events.DEBUG, `Swept ${messages} messages older than ${lifetime} seconds`);
458
- return messages;
459
- }
460
-
461
- /**
462
- * Obtains a guild preview from Discord, available for all guilds the bot is in and all Discoverable guilds.
463
- * @param {GuildResolvable} guild The guild to fetch the preview for
464
- * @returns {Promise<GuildPreview>}
465
- */
466
- async fetchGuildPreview(guild) {
467
- const id = this.guilds.resolveId(guild);
468
- if (!id) throw new TypeError('INVALID_TYPE', 'guild', 'GuildResolvable');
469
- const data = await this.api.guilds(id).preview.get();
470
- return new GuildPreview(this, data);
471
- }
472
-
473
- /**
474
- * Obtains the widget data of a guild from Discord, available for guilds with the widget enabled.
475
- * @param {GuildResolvable} guild The guild to fetch the widget data for
476
- * @returns {Promise<Widget>}
477
- */
478
- async fetchGuildWidget(guild) {
479
- const id = this.guilds.resolveId(guild);
480
- if (!id) throw new TypeError('INVALID_TYPE', 'guild', 'GuildResolvable');
481
- const data = await this.api.guilds(id, 'widget.json').get();
482
- return new Widget(this, data);
483
- }
484
-
485
- /**
486
- * Options for {@link Client#generateInvite}.
487
- * @typedef {Object} InviteGenerationOptions
488
- * @property {InviteScope[]} scopes Scopes that should be requested
489
- * @property {PermissionResolvable} [permissions] Permissions to request
490
- * @property {GuildResolvable} [guild] Guild to preselect
491
- * @property {boolean} [disableGuildSelect] Whether to disable the guild selection
492
- */
493
-
494
- /**
495
- * The sleep function in JavaScript returns a promise that resolves after a specified timeout.
496
- * @param {number} timeout - The timeout parameter is the amount of time, in milliseconds, that the sleep
497
- * function will wait before resolving the promise and continuing execution.
498
- * @returns {void} The `sleep` function is returning a Promise.
499
- */
500
- sleep(timeout) {
501
- return new Promise(r => setTimeout(r, timeout));
502
- }
503
-
504
- toJSON() {
505
- return super.toJSON({
506
- readyAt: false,
507
- });
508
- }
509
-
510
- /**
511
- * The current session id of the shard
512
- * @type {?string}
513
- */
514
- get sessionId() {
515
- return this.ws.shards.first()?.sessionId;
516
- }
517
-
518
- /**
519
- * Options for {@link Client#acceptInvite}.
520
- * @typedef {Object} AcceptInviteOptions
521
- * @property {boolean} [bypassOnboarding=true] Whether to bypass onboarding
522
- * @property {boolean} [bypassVerify=true] Whether to bypass rule screening
523
- */
524
-
525
- /**
526
- * Join this Guild / GroupDMChannel using this invite
527
- * @param {InviteResolvable} invite Invite code or URL
528
- * @param {AcceptInviteOptions} [options={ bypassOnboarding: true, bypassVerify: true }] Options
529
- * @returns {Promise<Guild|DMChannel|GroupDMChannel>}
530
- * @example
531
- * await client.acceptInvite('https://discord.gg/genshinimpact', { bypassOnboarding: true, bypassVerify: true })
532
- */
533
- async acceptInvite(invite, options = { bypassOnboarding: true, bypassVerify: true }) {
534
- const code = DataResolver.resolveInviteCode(invite);
535
- if (!code) throw new Error('INVITE_RESOLVE_CODE');
536
- const i = await this.fetchInvite(code);
537
- if (i.guild?.id && this.guilds.cache.has(i.guild?.id)) return this.guilds.cache.get(i.guild?.id);
538
- if (this.channels.cache.has(i.channelId)) return this.channels.cache.get(i.channelId);
539
- /*
540
- {
541
- location: 'Desktop Invite Modal',
542
- location_guild_id: i.guild?.id,
543
- location_channel_id: i.channelId,
544
- location_channel_type: typeof i.channel.type == 'number' ? i.channel.type : ChannelTypes[i.channel.type],
545
- }
546
- */
547
- const data = await this.api.invites(code).post({
548
- DiscordContext: { location: 'Markdown Link' },
549
- data: {
550
- session_id: this.sessionId,
551
- },
552
- });
553
- this.emit(Events.DEBUG, `[Invite > Guild ${i.guild?.id}] Joined`);
554
- // Guild
555
- if (i.guild?.id) {
556
- const guild = this.guilds.cache.get(i.guild?.id);
557
- if (i.flags.has('GUEST')) {
558
- this.emit(Events.DEBUG, `[Invite > Guild ${i.guild?.id}] Guest invite`);
559
- return guild;
560
- }
561
- if (options.bypassOnboarding) {
562
- const onboardingData = await this.api.guilds[i.guild?.id].onboarding.get();
563
- // Onboarding
564
- if (onboardingData.enabled) {
565
- const prompts = onboardingData.prompts.filter(o => o.in_onboarding);
566
- if (prompts.length) {
567
- const onboarding_prompts_seen = {};
568
- const onboarding_responses = [];
569
- const onboarding_responses_seen = {};
570
-
571
- const currentDate = Date.now();
572
-
573
- prompts.forEach(prompt => {
574
- onboarding_prompts_seen[prompt.id] = currentDate;
575
- if (prompt.required) onboarding_responses.push(prompt.options[0].id);
576
- prompt.options.forEach(option => {
577
- onboarding_responses_seen[option.id] = currentDate;
578
- });
579
- });
580
-
581
- await this.api.guilds[i.guild?.id]['onboarding-responses'].post({
582
- data: {
583
- onboarding_prompts_seen,
584
- onboarding_responses,
585
- onboarding_responses_seen,
586
- },
587
- });
588
- this.emit(Events.DEBUG, `[Invite > Guild ${i.guild?.id}] Bypassed onboarding`);
589
- }
590
- }
591
- }
592
- // Read rule
593
- if (data.show_verification_form && options.bypassVerify) {
594
- // Check Guild
595
- if (i.guild.verificationLevel == 'VERY_HIGH' && !this.user.phone) {
596
- this.emit(Events.DEBUG, `[Invite > Guild ${i.guild?.id}] Cannot bypass verify (Phone required)`);
597
- return this.guilds.cache.get(i.guild?.id);
598
- }
599
- if (i.guild.verificationLevel !== 'NONE' && !this.user.email) {
600
- this.emit(Events.DEBUG, `[Invite > Guild ${i.guild?.id}] Cannot bypass verify (Email required)`);
601
- return this.guilds.cache.get(i.guild?.id);
602
- }
603
- const getForm = await this.api
604
- .guilds(i.guild?.id)
605
- ['member-verification'].get({ query: { with_guild: false, invite_code: this.code } })
606
- .catch(() => {});
607
- if (getForm) {
608
- const form = Object.assign(getForm.form_fields[0], { response: true });
609
- await this.api
610
- .guilds(i.guild?.id)
611
- .requests['@me'].put({ data: { form_fields: [form], version: getForm.version } });
612
- this.emit(Events.DEBUG, `[Invite > Guild ${i.guild?.id}] Bypassed verify`);
613
- }
614
- }
615
- return guild;
616
- } else {
617
- return this.channels.cache.has(i.channelId || data.channel?.id);
618
- }
619
- }
620
-
621
- /**
622
- * Redeem nitro from code or url.
623
- * @param {string} nitro Nitro url or code
624
- * @param {TextChannelResolvable} [channel] Channel that the code was sent in
625
- * @param {Snowflake} [paymentSourceId] Payment source id
626
- * @returns {Promise<any>}
627
- */
628
- redeemNitro(nitro, channel, paymentSourceId) {
629
- if (typeof nitro !== 'string') throw new Error('INVALID_NITRO');
630
- const nitroCode =
631
- nitro.match(/(discord.gift|discord.com|discordapp.com\/gifts)\/(\w{16,25})/) ||
632
- nitro.match(/(discord\.gift\/|discord\.com\/gifts\/|discordapp\.com\/gifts\/)(\w+)/);
633
- if (!nitroCode) return false;
634
- const code = nitroCode[2];
635
- channel = this.channels.resolveId(channel);
636
- return this.api.entitlements['gift-codes'](code).redeem.post({
637
- auth: true,
638
- data: { channel_id: channel || null, payment_source_id: paymentSourceId || null },
639
- });
640
- }
641
-
642
- /**
643
- * @typedef {Object} OAuth2AuthorizeOptions
644
- * @property {string} [guild_id] Guild ID
645
- * @property {PermissionResolvable} [permissions] Permissions
646
- * @property {boolean} [authorize] Whether to authorize or not
647
- * @property {string} [code] 2FA Code
648
- * @property {string} [webhook_channel_id] Webhook Channel ID
649
- */
650
-
651
- /**
652
- * Authorize an application.
653
- * @param {string} url Discord Auth URL
654
- * @param {OAuth2AuthorizeOptions} options Oauth2 options
655
- * @returns {Promise<any>}
656
- * @example
657
- * client.authorizeURL(`https://discord.com/api/oauth2/authorize?client_id=botID&permissions=8&scope=applications.commands%20bot`, {
658
- guild_id: "guildID",
659
- permissions: "62221393", // your permissions
660
- authorize: true
661
- })
662
- */
663
- authorizeURL(url, options = { authorize: true, permissions: '0' }) {
664
- const pathnameAPI = /\/api\/(v\d{1,2}\/)?oauth2\/authorize/;
665
- const pathnameURL = /\/oauth2\/authorize/;
666
- const url_ = new URL(url);
667
- if (
668
- !['discord.com', 'canary.discord.com', 'ptb.discord.com'].includes(url_.hostname) ||
669
- (!pathnameAPI.test(url_.pathname) && !pathnameURL.test(url_.pathname))
670
- ) {
671
- throw new Error('INVALID_URL', url);
672
- }
673
- const searchParams = Object.fromEntries(url_.searchParams);
674
- options.permissions = `${Permissions.resolve(searchParams.permissions || options.permissions) || 0}`;
675
- delete searchParams.permissions;
676
- return this.api.oauth2.authorize.post({
677
- query: searchParams,
678
- data: options,
679
- });
680
- }
681
-
682
- /**
683
- * Calls {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval} on a script
684
- * with the client as `this`.
685
- * @param {string} script Script to eval
686
- * @returns {*}
687
- * @private
688
- */
689
- _eval(script) {
690
- return eval(script);
691
- }
692
-
693
- /**
694
- * Validates the client options.
695
- * @param {ClientOptions} [options=this.options] Options to validate
696
- * @private
697
- */
698
- _validateOptions(options = this.options) {
699
- if (typeof options.makeCache !== 'function') {
700
- throw new TypeError('CLIENT_INVALID_OPTION', 'makeCache', 'a function');
701
- }
702
- if (typeof options.messageCacheLifetime !== 'number' || isNaN(options.messageCacheLifetime)) {
703
- throw new TypeError('CLIENT_INVALID_OPTION', 'The messageCacheLifetime', 'a number');
704
- }
705
- if (typeof options.messageSweepInterval !== 'number' || isNaN(options.messageSweepInterval)) {
706
- throw new TypeError('CLIENT_INVALID_OPTION', 'messageSweepInterval', 'a number');
707
- }
708
- if (typeof options.sweepers !== 'object' || options.sweepers === null) {
709
- throw new TypeError('CLIENT_INVALID_OPTION', 'sweepers', 'an object');
710
- }
711
- if (typeof options.invalidRequestWarningInterval !== 'number' || isNaN(options.invalidRequestWarningInterval)) {
712
- throw new TypeError('CLIENT_INVALID_OPTION', 'invalidRequestWarningInterval', 'a number');
713
- }
714
- if (!Array.isArray(options.partials)) {
715
- throw new TypeError('CLIENT_INVALID_OPTION', 'partials', 'an Array');
716
- }
717
- if (typeof options.DMChannelVoiceStatusSync !== 'number' || isNaN(options.DMChannelVoiceStatusSync)) {
718
- throw new TypeError('CLIENT_INVALID_OPTION', 'DMChannelVoiceStatusSync', 'a number');
719
- }
720
- if (typeof options.waitGuildTimeout !== 'number' || isNaN(options.waitGuildTimeout)) {
721
- throw new TypeError('CLIENT_INVALID_OPTION', 'waitGuildTimeout', 'a number');
722
- }
723
- if (typeof options.restWsBridgeTimeout !== 'number' || isNaN(options.restWsBridgeTimeout)) {
724
- throw new TypeError('CLIENT_INVALID_OPTION', 'restWsBridgeTimeout', 'a number');
725
- }
726
- if (typeof options.restRequestTimeout !== 'number' || isNaN(options.restRequestTimeout)) {
727
- throw new TypeError('CLIENT_INVALID_OPTION', 'restRequestTimeout', 'a number');
728
- }
729
- if (typeof options.restGlobalRateLimit !== 'number' || isNaN(options.restGlobalRateLimit)) {
730
- throw new TypeError('CLIENT_INVALID_OPTION', 'restGlobalRateLimit', 'a number');
731
- }
732
- if (typeof options.restSweepInterval !== 'number' || isNaN(options.restSweepInterval)) {
733
- throw new TypeError('CLIENT_INVALID_OPTION', 'restSweepInterval', 'a number');
734
- }
735
- if (typeof options.retryLimit !== 'number' || isNaN(options.retryLimit)) {
736
- throw new TypeError('CLIENT_INVALID_OPTION', 'retryLimit', 'a number');
737
- }
738
- if (typeof options.failIfNotExists !== 'boolean') {
739
- throw new TypeError('CLIENT_INVALID_OPTION', 'failIfNotExists', 'a boolean');
740
- }
741
- if (
742
- typeof options.rejectOnRateLimit !== 'undefined' &&
743
- !(typeof options.rejectOnRateLimit === 'function' || Array.isArray(options.rejectOnRateLimit))
744
- ) {
745
- throw new TypeError('CLIENT_INVALID_OPTION', 'rejectOnRateLimit', 'an array or a function');
746
- }
747
- // Hardcode
748
- this.options.shardCount = 1;
749
- this.options.shards = [0];
750
- this.options.intents = Intents.ALL;
751
- }
752
- }
753
-
754
- module.exports = Client;
755
-
756
- /**
757
- * Emitted for general warnings.
758
- * @event Client#warn
759
- * @param {string} info The warning
760
- */
761
-
762
- /**
763
- * @external Collection
764
- * @see {@link https://discord.js.org/docs/packages/collection/stable/Collection:Class}
765
- */
1
+ /* eslint-disable no-unreachable */
2
+ 'use strict';
3
+
4
+ const process = require('node:process');
5
+ const { setInterval } = require('node:timers');
6
+ const { setTimeout } = require('node:timers');
7
+ const { Collection } = require('@discordjs/collection');
8
+ const { authenticator } = require('otplib');
9
+ const BaseClient = require('./BaseClient');
10
+ const ActionsManager = require('./actions/ActionsManager');
11
+ const ClientVoiceManager = require('./voice/ClientVoiceManager');
12
+ const WebSocketManager = require('./websocket/WebSocketManager');
13
+ const { Error, TypeError } = require('../errors');
14
+ const BaseGuildEmojiManager = require('../managers/BaseGuildEmojiManager');
15
+ const BillingManager = require('../managers/BillingManager');
16
+ const ChannelManager = require('../managers/ChannelManager');
17
+ const ClientUserSettingManager = require('../managers/ClientUserSettingManager');
18
+ const GuildManager = require('../managers/GuildManager');
19
+ const PresenceManager = require('../managers/PresenceManager');
20
+ const RelationshipManager = require('../managers/RelationshipManager');
21
+ const SessionManager = require('../managers/SessionManager');
22
+ const UserManager = require('../managers/UserManager');
23
+ const UserNoteManager = require('../managers/UserNoteManager');
24
+ const VoiceStateManager = require('../managers/VoiceStateManager');
25
+ const ShardClientUtil = require('../sharding/ShardClientUtil');
26
+ const ClientPresence = require('../structures/ClientPresence');
27
+ const GuildPreview = require('../structures/GuildPreview');
28
+ const GuildTemplate = require('../structures/GuildTemplate');
29
+ const Invite = require('../structures/Invite');
30
+ const { Sticker } = require('../structures/Sticker');
31
+ const StickerPack = require('../structures/StickerPack');
32
+ const VoiceRegion = require('../structures/VoiceRegion');
33
+ const Webhook = require('../structures/Webhook');
34
+ const Widget = require('../structures/Widget');
35
+ const Application = require('../structures/interfaces/Application');
36
+ const { Events, Status } = require('../util/Constants');
37
+ const DataResolver = require('../util/DataResolver');
38
+ const Intents = require('../util/Intents');
39
+ const DiscordAuthWebsocket = require('../util/RemoteAuth');
40
+ const Sweepers = require('../util/Sweepers');
41
+
42
+ /**
43
+ * The main hub for interacting with the Discord API, and the starting point for any bot.
44
+ * @extends {BaseClient}
45
+ */
46
+ class Client extends BaseClient {
47
+ /**
48
+ * @param {ClientOptions} [options] Options for the client
49
+ */
50
+ constructor(options) {
51
+ super(options);
52
+
53
+ this._validateOptions();
54
+
55
+ /**
56
+ * Functions called when a cache is garbage collected or the Client is destroyed
57
+ * @type {Set<Function>}
58
+ * @private
59
+ */
60
+ this._cleanups = new Set();
61
+
62
+ /**
63
+ * The finalizers used to cleanup items.
64
+ * @type {FinalizationRegistry}
65
+ * @private
66
+ */
67
+ this._finalizers = new FinalizationRegistry(this._finalize.bind(this));
68
+
69
+ /**
70
+ * The WebSocket manager of the client
71
+ * @type {WebSocketManager}
72
+ */
73
+ this.ws = new WebSocketManager(this);
74
+
75
+ /**
76
+ * The action manager of the client
77
+ * @type {ActionsManager}
78
+ * @private
79
+ */
80
+ this.actions = new ActionsManager(this);
81
+
82
+ /**
83
+ * The voice manager of the client
84
+ * @type {ClientVoiceManager}
85
+ */
86
+ this.voice = new ClientVoiceManager(this);
87
+
88
+ /**
89
+ * A manager of the voice states of this client (Support DM / Group DM)
90
+ * @type {VoiceStateManager}
91
+ */
92
+ this.voiceStates = new VoiceStateManager({ client: this });
93
+
94
+ /**
95
+ * Shard helpers for the client (only if the process was spawned from a {@link ShardingManager})
96
+ * @type {?ShardClientUtil}
97
+ */
98
+ this.shard = process.env.SHARDING_MANAGER
99
+ ? ShardClientUtil.singleton(this, process.env.SHARDING_MANAGER_MODE)
100
+ : null;
101
+
102
+ /**
103
+ * The user manager of this client
104
+ * @type {UserManager}
105
+ */
106
+ this.users = new UserManager(this);
107
+
108
+ /**
109
+ * A manager of all the guilds the client is currently handling -
110
+ * as long as sharding isn't being used, this will be *every* guild the bot is a member of
111
+ * @type {GuildManager}
112
+ */
113
+ this.guilds = new GuildManager(this);
114
+
115
+ /**
116
+ * All of the {@link Channel}s that the client is currently handling -
117
+ * as long as sharding isn't being used, this will be *every* channel in *every* guild the bot
118
+ * is a member of. Note that DM channels will not be initially cached, and thus not be present
119
+ * in the Manager without their explicit fetching or use.
120
+ * @type {ChannelManager}
121
+ */
122
+ this.channels = new ChannelManager(this);
123
+
124
+ /**
125
+ * The sweeping functions and their intervals used to periodically sweep caches
126
+ * @type {Sweepers}
127
+ */
128
+ this.sweepers = new Sweepers(this, this.options.sweepers);
129
+
130
+ /**
131
+ * The presence of the Client
132
+ * @private
133
+ * @type {ClientPresence}
134
+ */
135
+ this.presence = new ClientPresence(this, this.options.presence);
136
+
137
+ /**
138
+ * A manager of the presences belonging to this client
139
+ * @type {PresenceManager}
140
+ */
141
+ this.presences = new PresenceManager(this);
142
+
143
+ /**
144
+ * All of the note that have been cached at any point, mapped by their ids
145
+ * @type {UserManager}
146
+ */
147
+ this.notes = new UserNoteManager(this);
148
+
149
+ /**
150
+ * All of the relationships {@link User}
151
+ * @type {RelationshipManager}
152
+ */
153
+ this.relationships = new RelationshipManager(this);
154
+
155
+ /**
156
+ * Manages the API methods
157
+ * @type {BillingManager}
158
+ */
159
+ this.billing = new BillingManager(this);
160
+
161
+ /**
162
+ * All of the sessions of the client
163
+ * @type {SessionManager}
164
+ */
165
+ this.sessions = new SessionManager(this);
166
+
167
+ /**
168
+ * All of the settings {@link Object}
169
+ * @type {ClientUserSettingManager}
170
+ */
171
+ this.settings = new ClientUserSettingManager(this);
172
+
173
+ Object.defineProperty(this, 'token', { writable: true });
174
+ if (!this.token && 'DISCORD_TOKEN' in process.env) {
175
+ /**
176
+ * Authorization token for the logged in bot.
177
+ * If present, this defaults to `process.env.DISCORD_TOKEN` when instantiating the client
178
+ * <warn>This should be kept private at all times.</warn>
179
+ * @type {?string}
180
+ */
181
+ this.token = process.env.DISCORD_TOKEN;
182
+ } else {
183
+ this.token = null;
184
+ }
185
+
186
+ /**
187
+ * User that the client is logged in as
188
+ * @type {?ClientUser}
189
+ */
190
+ this.user = null;
191
+
192
+ /**
193
+ * Time at which the client was last regarded as being in the `READY` state
194
+ * (each time the client disconnects and successfully reconnects, this will be overwritten)
195
+ * @type {?Date}
196
+ */
197
+ this.readyAt = null;
198
+
199
+ /**
200
+ * The authenticator used for TOTP
201
+ * @type {Object}
202
+ */
203
+ this.authenticator = authenticator;
204
+
205
+ this.authenticator.options = {
206
+ step: 30,
207
+ digits: 6,
208
+ algorithm: 'sha1',
209
+ };
210
+
211
+ if (this.options.messageSweepInterval > 0) {
212
+ process.emitWarning(
213
+ 'The message sweeping client options are deprecated, use the global sweepers instead.',
214
+ 'DeprecationWarning',
215
+ );
216
+ this.sweepMessageInterval = setInterval(
217
+ this.sweepMessages.bind(this),
218
+ this.options.messageSweepInterval * 1_000,
219
+ ).unref();
220
+ }
221
+ }
222
+
223
+ /**
224
+ * A manager of all the custom emojis that the client has access to
225
+ * @type {BaseGuildEmojiManager}
226
+ * @readonly
227
+ */
228
+ get emojis() {
229
+ const emojis = new BaseGuildEmojiManager(this);
230
+ for (const guild of this.guilds.cache.values()) {
231
+ if (guild.available) for (const emoji of guild.emojis.cache.values()) emojis.cache.set(emoji.id, emoji);
232
+ }
233
+ return emojis;
234
+ }
235
+
236
+ /**
237
+ * Timestamp of the time the client was last `READY` at
238
+ * @type {?number}
239
+ * @readonly
240
+ */
241
+ get readyTimestamp() {
242
+ return this.readyAt?.getTime() ?? null;
243
+ }
244
+
245
+ /**
246
+ * How long it has been since the client last entered the `READY` state in milliseconds
247
+ * @type {?number}
248
+ * @readonly
249
+ */
250
+ get uptime() {
251
+ return this.readyAt ? Date.now() - this.readyAt : null;
252
+ }
253
+
254
+ /**
255
+ * Logs the client in, establishing a WebSocket connection to Discord.
256
+ * @param {string} [token=this.token] Token of the account to log in with
257
+ * @returns {Promise<string>} Token of the account used
258
+ * @example
259
+ * client.login('my token');
260
+ */
261
+ async login(token = this.token) {
262
+ if (!token || typeof token !== 'string') throw new Error('TOKEN_INVALID');
263
+ this.token = token = token.replace(/^(Bot|Bearer)\s*/i, '');
264
+ this.emit(
265
+ Events.DEBUG,
266
+ `
267
+ Logging on with a user token is unfortunately against the Discord
268
+ \`Terms of Service\` <https://support.discord.com/hc/en-us/articles/115002192352>
269
+ and doing so might potentially get your account banned.
270
+ Use this at your own risk.`,
271
+ );
272
+ this.emit(
273
+ Events.DEBUG,
274
+ `Provided token: ${token
275
+ .split('.')
276
+ .map((val, i) => (i > 1 ? val.replace(/./g, '*') : val))
277
+ .join('.')}`,
278
+ );
279
+
280
+ if (this.options.presence) {
281
+ this.options.ws.presence = this.presence._parse(this.options.presence);
282
+ }
283
+
284
+ this.emit(Events.DEBUG, 'Preparing to connect to the gateway...');
285
+
286
+ try {
287
+ await this.ws.connect();
288
+ return this.token;
289
+ } catch (error) {
290
+ this.destroy();
291
+ throw error;
292
+ }
293
+ }
294
+
295
+ QRLogin() {
296
+ const ws = new DiscordAuthWebsocket();
297
+ ws.once('ready', () => ws.generateQR());
298
+ return ws.connect(this);
299
+ }
300
+
301
+ /**
302
+ * Logs the client in, establishing a WebSocket connection to Discord.
303
+ * @param {string} email The email associated with the account
304
+ * @param {string} password The password assicated with the account
305
+ * @returns {string | null} Token of the account used
306
+ *
307
+ * @example
308
+ * client.passLogin("test@gmail.com", "SuperSecretPa$$word", 1234)
309
+ * @deprecated This method will not be updated until I find the most convenient way to implement MFA.
310
+ */
311
+ async passLogin(email, password) {
312
+ const initial = await this.api.auth.login.post({
313
+ auth: false,
314
+ versioned: true,
315
+ data: { gift_code_sku_id: null, login_source: null, undelete: false, login: email, password },
316
+ });
317
+
318
+ if ('token' in initial) {
319
+ return this.login(initial.token);
320
+ } else if ('ticket' in initial) {
321
+ if (!this.options.TOTPKey) throw new Error('TOTPKEY_MISSING');
322
+ const otp = this.authenticator.generate(this.options.TOTPKey);
323
+ const totp = await this.api.auth.mfa.totp.post({
324
+ auth: false,
325
+ versioned: true,
326
+ data: { gift_code_sku_id: null, login_source: null, code: otp, ticket: initial.ticket },
327
+ });
328
+ if ('token' in totp) {
329
+ return this.login(totp.token);
330
+ }
331
+ }
332
+
333
+ return null;
334
+ }
335
+
336
+ /**
337
+ * Returns whether the client has logged in, indicative of being able to access
338
+ * properties such as `user` and `application`.
339
+ * @returns {boolean}
340
+ */
341
+ isReady() {
342
+ return !this.ws.destroyed && this.ws.status === Status.READY;
343
+ }
344
+
345
+ /**
346
+ * Logs out, terminates the connection to Discord, and destroys the client.
347
+ * @returns {void}
348
+ */
349
+ destroy() {
350
+ super.destroy();
351
+
352
+ for (const fn of this._cleanups) fn();
353
+ this._cleanups.clear();
354
+
355
+ if (this.sweepMessageInterval) clearInterval(this.sweepMessageInterval);
356
+
357
+ this.sweepers.destroy();
358
+ this.ws.destroy();
359
+ this.token = null;
360
+ }
361
+
362
+ /**
363
+ * Logs out, terminates the connection to Discord, destroys the client and destroys the token.
364
+ * @returns {Promise<void>}
365
+ */
366
+ async logout() {
367
+ await this.api.auth.logout.post({
368
+ data: {
369
+ provider: null,
370
+ voip_provider: null,
371
+ },
372
+ });
373
+ return this.destroy();
374
+ }
375
+
376
+ /**
377
+ * Options used when fetching an invite from Discord.
378
+ * @typedef {Object} ClientFetchInviteOptions
379
+ * @property {Snowflake} [guildScheduledEventId] The id of the guild scheduled event to include with
380
+ * the invite
381
+ */
382
+
383
+ /**
384
+ * Obtains an invite from Discord.
385
+ * @param {InviteResolvable} invite Invite code or URL
386
+ * @param {ClientFetchInviteOptions} [options] Options for fetching the invite
387
+ * @returns {Promise<Invite>}
388
+ * @example
389
+ * client.fetchInvite('https://discord.gg/djs')
390
+ * .then(invite => console.log(`Obtained invite with code: ${invite.code}`))
391
+ * .catch(console.error);
392
+ */
393
+ async fetchInvite(invite, options) {
394
+ const code = DataResolver.resolveInviteCode(invite);
395
+ const data = await this.api.invites(code).get({
396
+ query: { with_counts: true, guild_scheduled_event_id: options?.guildScheduledEventId },
397
+ });
398
+ return new Invite(this, data);
399
+ }
400
+
401
+ /**
402
+ * Obtains a template from Discord.
403
+ * @param {GuildTemplateResolvable} template Template code or URL
404
+ * @returns {Promise<GuildTemplate>}
405
+ * @example
406
+ * client.fetchGuildTemplate('https://discord.new/FKvmczH2HyUf')
407
+ * .then(template => console.log(`Obtained template with code: ${template.code}`))
408
+ * .catch(console.error);
409
+ */
410
+ async fetchGuildTemplate(template) {
411
+ const code = DataResolver.resolveGuildTemplateCode(template);
412
+ const data = await this.api.guilds.templates(code).get();
413
+ return new GuildTemplate(this, data);
414
+ }
415
+
416
+ /**
417
+ * Obtains a webhook from Discord.
418
+ * @param {Snowflake} id The webhook's id
419
+ * @param {string} [token] Token for the webhook
420
+ * @returns {Promise<Webhook>}
421
+ * @example
422
+ * client.fetchWebhook('id', 'token')
423
+ * .then(webhook => console.log(`Obtained webhook with name: ${webhook.name}`))
424
+ * .catch(console.error);
425
+ */
426
+ async fetchWebhook(id, token) {
427
+ const data = await this.api.webhooks(id, token).get();
428
+ return new Webhook(this, { token, ...data });
429
+ }
430
+
431
+ /**
432
+ * Obtains the available voice regions from Discord.
433
+ * @returns {Promise<Collection<string, VoiceRegion>>}
434
+ * @example
435
+ * client.fetchVoiceRegions()
436
+ * .then(regions => console.log(`Available regions are: ${regions.map(region => region.name).join(', ')}`))
437
+ * .catch(console.error);
438
+ */
439
+ async fetchVoiceRegions() {
440
+ const apiRegions = await this.api.voice.regions.get();
441
+ const regions = new Collection();
442
+ for (const region of apiRegions) regions.set(region.id, new VoiceRegion(region));
443
+ return regions;
444
+ }
445
+
446
+ /**
447
+ * Obtains a sticker from Discord.
448
+ * @param {Snowflake} id The sticker's id
449
+ * @returns {Promise<Sticker>}
450
+ * @example
451
+ * client.fetchSticker('id')
452
+ * .then(sticker => console.log(`Obtained sticker with name: ${sticker.name}`))
453
+ * .catch(console.error);
454
+ */
455
+ async fetchSticker(id) {
456
+ const data = await this.api.stickers(id).get();
457
+ return new Sticker(this, data);
458
+ }
459
+
460
+ /**
461
+ * Obtains the list of sticker packs available to Nitro subscribers from Discord.
462
+ * @returns {Promise<Collection<Snowflake, StickerPack>>}
463
+ * @example
464
+ * client.fetchPremiumStickerPacks()
465
+ * .then(packs => console.log(`Available sticker packs are: ${packs.map(pack => pack.name).join(', ')}`))
466
+ * .catch(console.error);
467
+ */
468
+ async fetchPremiumStickerPacks() {
469
+ const data = await this.api('sticker-packs').get();
470
+ return new Collection(data.sticker_packs.map(p => [p.id, new StickerPack(this, p)]));
471
+ }
472
+ /**
473
+ * A last ditch cleanup function for garbage collection.
474
+ * @param {Function} options.cleanup The function called to GC
475
+ * @param {string} [options.message] The message to send after a successful GC
476
+ * @param {string} [options.name] The name of the item being GCed
477
+ * @private
478
+ */
479
+ _finalize({ cleanup, message, name }) {
480
+ try {
481
+ cleanup();
482
+ this._cleanups.delete(cleanup);
483
+ if (message) {
484
+ this.emit(Events.DEBUG, message);
485
+ }
486
+ } catch {
487
+ this.emit(Events.DEBUG, `Garbage collection failed on ${name ?? 'an unknown item'}.`);
488
+ }
489
+ }
490
+
491
+ /**
492
+ * Sweeps all text-based channels' messages and removes the ones older than the max message lifetime.
493
+ * If the message has been edited, the time of the edit is used rather than the time of the original message.
494
+ * @param {number} [lifetime=this.options.messageCacheLifetime] Messages that are older than this (in seconds)
495
+ * will be removed from the caches. The default is based on {@link ClientOptions#messageCacheLifetime}
496
+ * @returns {number} Amount of messages that were removed from the caches,
497
+ * or -1 if the message cache lifetime is unlimited
498
+ * @example
499
+ * // Remove all messages older than 1800 seconds from the messages cache
500
+ * const amount = client.sweepMessages(1800);
501
+ * console.log(`Successfully removed ${amount} messages from the cache.`);
502
+ */
503
+ sweepMessages(lifetime = this.options.messageCacheLifetime) {
504
+ if (typeof lifetime !== 'number' || isNaN(lifetime)) {
505
+ throw new TypeError('INVALID_TYPE', 'lifetime', 'number');
506
+ }
507
+ if (lifetime <= 0) {
508
+ this.emit(Events.DEBUG, "Didn't sweep messages - lifetime is unlimited");
509
+ return -1;
510
+ }
511
+
512
+ const messages = this.sweepers.sweepMessages(Sweepers.outdatedMessageSweepFilter(lifetime)());
513
+ this.emit(Events.DEBUG, `Swept ${messages} messages older than ${lifetime} seconds`);
514
+ return messages;
515
+ }
516
+
517
+ /**
518
+ * Obtains a guild preview from Discord, available for all guilds the bot is in and all Discoverable guilds.
519
+ * @param {GuildResolvable} guild The guild to fetch the preview for
520
+ * @returns {Promise<GuildPreview>}
521
+ */
522
+ async fetchGuildPreview(guild) {
523
+ const id = this.guilds.resolveId(guild);
524
+ if (!id) throw new TypeError('INVALID_TYPE', 'guild', 'GuildResolvable');
525
+ const data = await this.api.guilds(id).preview.get();
526
+ return new GuildPreview(this, data);
527
+ }
528
+
529
+ /**
530
+ * Obtains the widget data of a guild from Discord, available for guilds with the widget enabled.
531
+ * @param {GuildResolvable} guild The guild to fetch the widget data for
532
+ * @returns {Promise<Widget>}
533
+ */
534
+ async fetchGuildWidget(guild) {
535
+ const id = this.guilds.resolveId(guild);
536
+ if (!id) throw new TypeError('INVALID_TYPE', 'guild', 'GuildResolvable');
537
+ const data = await this.api.guilds(id, 'widget.json').get();
538
+ return new Widget(this, data);
539
+ }
540
+
541
+ /**
542
+ * Refresh the Discord CDN links with hashes so they can be usable.
543
+ * @param {...string} urls Discord CDN URLs
544
+ * @returns {Promise<Array<{ original: string, refreshed: string }>>}
545
+ */
546
+ async refreshAttachmentURL(...urls) {
547
+ // Clean up the URLs
548
+ urls = urls.map(url => {
549
+ const urlObject = new URL(url);
550
+ // Clean query
551
+ urlObject.search = '';
552
+ return urlObject.toString();
553
+ });
554
+ const data = await this.api.attachments('refresh-urls').post({
555
+ data: { attachment_urls: urls },
556
+ });
557
+ /**
558
+ {
559
+ "refreshed_urls": [
560
+ {
561
+ "original": "url",
562
+ "refreshed": "url with hash"
563
+ }
564
+ ]
565
+ }
566
+ */
567
+ return data.refreshed_urls;
568
+ }
569
+
570
+ /**
571
+ * Options for {@link Client#generateInvite}.
572
+ * @typedef {Object} InviteGenerationOptions
573
+ * @property {InviteScope[]} scopes Scopes that should be requested
574
+ * @property {PermissionResolvable} [permissions] Permissions to request
575
+ * @property {GuildResolvable} [guild] Guild to preselect
576
+ * @property {boolean} [disableGuildSelect] Whether to disable the guild selection
577
+ */
578
+
579
+ /**
580
+ * The sleep function in JavaScript returns a promise that resolves after a specified timeout.
581
+ * @param {number} timeout - The timeout parameter is the amount of time, in milliseconds, that the sleep
582
+ * function will wait before resolving the promise and continuing execution.
583
+ * @returns {void} The `sleep` function is returning a Promise.
584
+ */
585
+ sleep(timeout) {
586
+ return new Promise(r => setTimeout(r, timeout));
587
+ }
588
+
589
+ toJSON() {
590
+ return super.toJSON({
591
+ readyAt: false,
592
+ });
593
+ }
594
+
595
+ /**
596
+ * The current session id of the shard
597
+ * @type {?string}
598
+ */
599
+ get sessionId() {
600
+ return this.ws.shards.first()?.sessionId;
601
+ }
602
+
603
+ /**
604
+ * Options for {@link Client#acceptInvite}.
605
+ * @typedef {Object} AcceptInviteOptions
606
+ * @property {boolean} [bypassOnboarding=true] Whether to bypass onboarding
607
+ * @property {boolean} [bypassVerify=true] Whether to bypass rule screening
608
+ */
609
+
610
+ /**
611
+ * Join this Guild / GroupDMChannel using this invite
612
+ * @param {InviteResolvable} invite Invite code or URL
613
+ * @param {AcceptInviteOptions} [options] Options
614
+ * @returns {Promise<Guild|DMChannel|GroupDMChannel>}
615
+ * @example
616
+ * await client.acceptInvite('https://discord.gg/genshinimpact', { bypassOnboarding: true, bypassVerify: true })
617
+ */
618
+ async acceptInvite(invite, options = { bypassOnboarding: true, bypassVerify: true }) {
619
+ // ! throw new Error('METHOD_WARNING');
620
+ const code = DataResolver.resolveInviteCode(invite);
621
+ if (!code) throw new Error('INVITE_RESOLVE_CODE');
622
+ const i = await this.fetchInvite(code);
623
+ if (i.guild?.id && this.guilds.cache.has(i.guild?.id)) return this.guilds.cache.get(i.guild?.id);
624
+ if (this.channels.cache.has(i.channelId)) return this.channels.cache.get(i.channelId);
625
+ const data = await this.api.invites(code).post({
626
+ DiscordContext: { location: 'Markdown Link' },
627
+ data: {
628
+ session_id: this.sessionId,
629
+ },
630
+ });
631
+ this.emit(Events.DEBUG, `[Invite > Guild ${i.guild?.id}] Joined`);
632
+ // Guild
633
+ if (i.guild?.id) {
634
+ const guild = this.guilds.cache.get(i.guild?.id);
635
+ if (i.flags.has('GUEST')) {
636
+ this.emit(Events.DEBUG, `[Invite > Guild ${i.guild?.id}] Guest invite`);
637
+ return guild;
638
+ }
639
+ if (options.bypassOnboarding) {
640
+ const onboardingData = await this.api.guilds[i.guild?.id].onboarding.get();
641
+ // Onboarding
642
+ if (onboardingData.enabled) {
643
+ const prompts = onboardingData.prompts.filter(o => o.in_onboarding);
644
+ if (prompts.length) {
645
+ const onboarding_prompts_seen = {};
646
+ const onboarding_responses = [];
647
+ const onboarding_responses_seen = {};
648
+
649
+ const currentDate = Date.now();
650
+
651
+ prompts.forEach(prompt => {
652
+ onboarding_prompts_seen[prompt.id] = currentDate;
653
+ if (prompt.required) onboarding_responses.push(prompt.options[0].id);
654
+ prompt.options.forEach(option => {
655
+ onboarding_responses_seen[option.id] = currentDate;
656
+ });
657
+ });
658
+
659
+ await this.api.guilds[i.guild?.id]['onboarding-responses'].post({
660
+ data: {
661
+ onboarding_prompts_seen,
662
+ onboarding_responses,
663
+ onboarding_responses_seen,
664
+ },
665
+ });
666
+ this.emit(Events.DEBUG, `[Invite > Guild ${i.guild?.id}] Bypassed onboarding`);
667
+ }
668
+ }
669
+ }
670
+ // Read rule
671
+ if (data.show_verification_form && options.bypassVerify) {
672
+ // Check Guild
673
+ if (i.guild.verificationLevel == 'VERY_HIGH' && !this.user.phone) {
674
+ this.emit(Events.DEBUG, `[Invite > Guild ${i.guild?.id}] Cannot bypass verify (Phone required)`);
675
+ return this.guilds.cache.get(i.guild?.id);
676
+ }
677
+ if (i.guild.verificationLevel !== 'NONE' && !this.user.email) {
678
+ this.emit(Events.DEBUG, `[Invite > Guild ${i.guild?.id}] Cannot bypass verify (Email required)`);
679
+ return this.guilds.cache.get(i.guild?.id);
680
+ }
681
+ const getForm = await this.api
682
+ .guilds(i.guild?.id)
683
+ ['member-verification'].get({ query: { with_guild: false, invite_code: this.code } })
684
+ .catch(() => {});
685
+ if (getForm && getForm.form_fields[0]) {
686
+ const form = Object.assign(getForm.form_fields[0], { response: true });
687
+ await this.api
688
+ .guilds(i.guild?.id)
689
+ .requests['@me'].put({ data: { form_fields: [form], version: getForm.version } });
690
+ this.emit(Events.DEBUG, `[Invite > Guild ${i.guild?.id}] Bypassed verify`);
691
+ }
692
+ }
693
+ return guild;
694
+ } else {
695
+ return this.channels.cache.has(i.channelId || data.channel?.id);
696
+ }
697
+ }
698
+
699
+ /**
700
+ * Redeem nitro from code or url.
701
+ * @param {string} nitro Nitro url or code
702
+ * @param {TextChannelResolvable} [channel] Channel that the code was sent in
703
+ * @param {Snowflake} [paymentSourceId] Payment source id
704
+ * @returns {Promise<any>}
705
+ */
706
+ redeemNitro(nitro, channel, paymentSourceId) {
707
+ if (typeof nitro !== 'string') throw new Error('INVALID_NITRO');
708
+ const nitroCode =
709
+ nitro.match(/(discord.gift|discord.com|discordapp.com\/gifts)\/(\w{16,25})/) ||
710
+ nitro.match(/(discord\.gift\/|discord\.com\/gifts\/|discordapp\.com\/gifts\/)(\w+)/);
711
+ if (!nitroCode) return false;
712
+ const code = nitroCode[2];
713
+ channel = this.channels.resolveId(channel);
714
+ return this.api.entitlements['gift-codes'](code).redeem.post({
715
+ auth: true,
716
+ data: { channel_id: channel || null, payment_source_id: paymentSourceId || null },
717
+ });
718
+ }
719
+
720
+ /**
721
+ * @typedef {Object} OAuth2AuthorizeOptions
722
+ * @property {string} [guild_id] Guild ID
723
+ * @property {string} [permissions] Permissions
724
+ * @property {boolean} [authorize] Whether to authorize or not
725
+ * @property {string} [code] 2FA Code
726
+ * @property {string} [webhook_channel_id] Webhook Channel ID
727
+ */
728
+
729
+ /**
730
+ * Authorize an application.
731
+ * @param {string} urlOAuth2 Discord Auth URL
732
+ * @param {OAuth2AuthorizeOptions} [options] Oauth2 options
733
+ * @returns {Promise<{ location: string }>}
734
+ * @example
735
+ * client.authorizeURL(`https://discord.com/api/oauth2/authorize?client_id=botID&permissions=8&scope=applications.commands%20bot`, {
736
+ guild_id: "guildID",
737
+ })
738
+ */
739
+ authorizeURL(urlOAuth2, options = {}) {
740
+ // ! throw new Error('METHOD_WARNING');
741
+ const url = new URL(urlOAuth2);
742
+ if (!/^https:\/\/(?:canary\.|ptb\.)?discord\.com(?:\/api(?:\/v\d{1,2})?)?\/oauth2\/authorize\?/.test(urlOAuth2)) {
743
+ throw new Error('INVALID_URL', urlOAuth2);
744
+ }
745
+ const searchParams = Object.fromEntries(url.searchParams);
746
+ // Assign options
747
+ options = {
748
+ authorize: true,
749
+ permissions: '0',
750
+ integration_type: 0,
751
+ location_context: {
752
+ guild_id: '10000',
753
+ channel_id: '10000',
754
+ channel_type: 10000,
755
+ },
756
+ ...searchParams,
757
+ ...options,
758
+ };
759
+ delete searchParams.permissions;
760
+ delete searchParams.integration_type;
761
+ delete searchParams.guild_id;
762
+ return this.api.oauth2.authorize.post({
763
+ query: searchParams,
764
+ data: options,
765
+ });
766
+ }
767
+
768
+ /**
769
+ * Install User Apps
770
+ * @param {Snowflake} applicationId Discord Application id
771
+ * @returns {Promise<void>}
772
+ */
773
+ installUserApps(applicationId) {
774
+ return this.api
775
+ .applications(applicationId)
776
+ .public.get({
777
+ query: {
778
+ with_guild: false,
779
+ },
780
+ })
781
+ .then(rawData => {
782
+ const installTypes = rawData.integration_types_config['1'];
783
+ if (installTypes) {
784
+ return this.api.oauth2.authorize.post({
785
+ query: {
786
+ client_id: applicationId,
787
+ scope: installTypes.oauth2_install_params.scopes.join(' '),
788
+ },
789
+ data: {
790
+ permissions: '0',
791
+ authorize: true,
792
+ integration_type: 1,
793
+ },
794
+ });
795
+ } else {
796
+ return false;
797
+ }
798
+ });
799
+ }
800
+
801
+ /**
802
+ * Deauthorizes an application or token.
803
+ * @param {Snowflake} id - The ID of the Discord Application or Token.
804
+ * @param {'application' | 'token'} [type='application'] - The type of the ID provided. Defaults to 'application'.
805
+ * @returns {Promise<void>} A promise that resolves when the deauthorization is complete.
806
+ */
807
+ deauthorize(id, type = 'application') {
808
+ if (type === 'application') {
809
+ return this.api.oauth2.tokens
810
+ .get()
811
+ .then(data => data.find(o => o.application.id == id))
812
+ .then(o => this.api.oauth2.tokens(o.id).delete());
813
+ } else {
814
+ return this.api.oauth2.tokens(id).delete();
815
+ }
816
+ }
817
+
818
+ /**
819
+ * @typedef {Object} AuthorizedApplicationData
820
+ * @property {Application} application - The application object.
821
+ * @property {Snowflake} authorizedApplicationId - The ID of the OAuth2 token.
822
+ * @property {string[]} scopes - The scopes that were granted to this token.
823
+ * @property {function(): Promise<void>} deauthorize - Function to revoke this token.
824
+ */
825
+
826
+ /**
827
+ * Retrieves the list of authorized applications (OAuth2 tokens).
828
+ * @returns {Promise<Collection<Snowflake, AuthorizedApplicationData>>}
829
+ */
830
+ authorizedApplications() {
831
+ return this.api.oauth2.tokens.get().then(data => {
832
+ const results = new Collection();
833
+ for (const o of data) {
834
+ const application = new Application(this, o.application);
835
+ const data = {
836
+ application,
837
+ authorizedApplicationId: o.id,
838
+ scopes: o.scopes,
839
+ deauthorize: () => this.deauthorize(o.id, 'token'),
840
+ };
841
+ results.set(o.application.id, data);
842
+ }
843
+ return results;
844
+ });
845
+ }
846
+
847
+ /**
848
+ * Calls {@link https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/eval} on a script
849
+ * with the client as `this`.
850
+ * @param {string} script Script to eval
851
+ * @returns {*}
852
+ * @private
853
+ */
854
+ _eval(script) {
855
+ return eval(script);
856
+ }
857
+
858
+ /**
859
+ * Validates the client options.
860
+ * @param {ClientOptions} [options=this.options] Options to validate
861
+ * @private
862
+ */
863
+ _validateOptions(options = this.options) {
864
+ if (typeof options.makeCache !== 'function') {
865
+ throw new TypeError('CLIENT_INVALID_OPTION', 'makeCache', 'a function');
866
+ }
867
+ if (typeof options.messageCacheLifetime !== 'number' || isNaN(options.messageCacheLifetime)) {
868
+ throw new TypeError('CLIENT_INVALID_OPTION', 'The messageCacheLifetime', 'a number');
869
+ }
870
+ if (typeof options.messageSweepInterval !== 'number' || isNaN(options.messageSweepInterval)) {
871
+ throw new TypeError('CLIENT_INVALID_OPTION', 'messageSweepInterval', 'a number');
872
+ }
873
+ if (typeof options.sweepers !== 'object' || options.sweepers === null) {
874
+ throw new TypeError('CLIENT_INVALID_OPTION', 'sweepers', 'an object');
875
+ }
876
+ if (typeof options.invalidRequestWarningInterval !== 'number' || isNaN(options.invalidRequestWarningInterval)) {
877
+ throw new TypeError('CLIENT_INVALID_OPTION', 'invalidRequestWarningInterval', 'a number');
878
+ }
879
+ if (!Array.isArray(options.partials)) {
880
+ throw new TypeError('CLIENT_INVALID_OPTION', 'partials', 'an Array');
881
+ }
882
+ if (typeof options.DMChannelVoiceStatusSync !== 'number' || isNaN(options.DMChannelVoiceStatusSync)) {
883
+ throw new TypeError('CLIENT_INVALID_OPTION', 'DMChannelVoiceStatusSync', 'a number');
884
+ }
885
+ if (typeof options.waitGuildTimeout !== 'number' || isNaN(options.waitGuildTimeout)) {
886
+ throw new TypeError('CLIENT_INVALID_OPTION', 'waitGuildTimeout', 'a number');
887
+ }
888
+ if (typeof options.restWsBridgeTimeout !== 'number' || isNaN(options.restWsBridgeTimeout)) {
889
+ throw new TypeError('CLIENT_INVALID_OPTION', 'restWsBridgeTimeout', 'a number');
890
+ }
891
+ if (typeof options.restRequestTimeout !== 'number' || isNaN(options.restRequestTimeout)) {
892
+ throw new TypeError('CLIENT_INVALID_OPTION', 'restRequestTimeout', 'a number');
893
+ }
894
+ if (typeof options.restGlobalRateLimit !== 'number' || isNaN(options.restGlobalRateLimit)) {
895
+ throw new TypeError('CLIENT_INVALID_OPTION', 'restGlobalRateLimit', 'a number');
896
+ }
897
+ if (typeof options.restSweepInterval !== 'number' || isNaN(options.restSweepInterval)) {
898
+ throw new TypeError('CLIENT_INVALID_OPTION', 'restSweepInterval', 'a number');
899
+ }
900
+ if (typeof options.retryLimit !== 'number' || isNaN(options.retryLimit)) {
901
+ throw new TypeError('CLIENT_INVALID_OPTION', 'retryLimit', 'a number');
902
+ }
903
+ if (typeof options.failIfNotExists !== 'boolean') {
904
+ throw new TypeError('CLIENT_INVALID_OPTION', 'failIfNotExists', 'a boolean');
905
+ }
906
+ if (
907
+ typeof options.rejectOnRateLimit !== 'undefined' &&
908
+ !(typeof options.rejectOnRateLimit === 'function' || Array.isArray(options.rejectOnRateLimit))
909
+ ) {
910
+ throw new TypeError('CLIENT_INVALID_OPTION', 'rejectOnRateLimit', 'an array or a function');
911
+ }
912
+ if (typeof options.TOTPKey === 'string') {
913
+ // Convert to base32 if not already
914
+ options.TOTPKey = options.TOTPKey.replace(/ +/g, '').toUpperCase();
915
+ }
916
+ // Hardcode
917
+ this.options.shardCount = 1;
918
+ this.options.shards = [0];
919
+ this.options.intents = Intents.ALL;
920
+ }
921
+ }
922
+
923
+ module.exports = Client;
924
+
925
+ /**
926
+ * Emitted for general warnings.
927
+ * @event Client#warn
928
+ * @param {string} info The warning
929
+ */
930
+
931
+ /**
932
+ * @external Collection
933
+ * @see {@link https://discord.js.org/docs/packages/collection/stable/Collection:Class}
934
+ */