discord-sb.js 1.0.0

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