rockcord 4.0.0-dev.4

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