diff --git a/src/client/Client.js b/src/client/Client.js index a28beb2e8082..5b68e45afcd6 100644 --- a/src/client/Client.js +++ b/src/client/Client.js @@ -236,7 +236,7 @@ class Client extends BaseClient { ); if (this.options.presence) { - this.options.ws.presence = await this.presence._parse(this.options.presence); + this.options.ws.presence = this.presence._parse(this.options.presence); } this.emit(Events.DEBUG, 'Preparing to connect to the gateway...'); @@ -284,12 +284,10 @@ class Client extends BaseClient { * .then(invite => console.log(`Obtained invite with code: ${invite.code}`)) * .catch(console.error); */ - fetchInvite(invite) { + async fetchInvite(invite) { const code = DataResolver.resolveInviteCode(invite); - return this.api - .invites(code) - .get({ query: { with_counts: true, with_expiration: true } }) - .then(data => new Invite(this, data)); + const data = await this.api.invites(code).get({ query: { with_counts: true, with_expiration: true } }); + return new Invite(this, data); } /** @@ -301,12 +299,10 @@ class Client extends BaseClient { * .then(template => console.log(`Obtained template with code: ${template.code}`)) * .catch(console.error); */ - fetchGuildTemplate(template) { + async fetchGuildTemplate(template) { const code = DataResolver.resolveGuildTemplateCode(template); - return this.api.guilds - .templates(code) - .get() - .then(data => new GuildTemplate(this, data)); + const data = await this.api.guilds.templates(code).get(); + return new GuildTemplate(this, data); } /** @@ -319,11 +315,9 @@ class Client extends BaseClient { * .then(webhook => console.log(`Obtained webhook with name: ${webhook.name}`)) * .catch(console.error); */ - fetchWebhook(id, token) { - return this.api - .webhooks(id, token) - .get() - .then(data => new Webhook(this, { token, ...data })); + async fetchWebhook(id, token) { + const data = await this.api.webhooks(id, token).get(); + return new Webhook(this, { token, ...data }); } /** @@ -334,12 +328,11 @@ class Client extends BaseClient { * .then(regions => console.log(`Available regions are: ${regions.map(region => region.name).join(', ')}`)) * .catch(console.error); */ - fetchVoiceRegions() { - return this.api.voice.regions.get().then(res => { - const regions = new Collection(); - for (const region of res) regions.set(region.id, new VoiceRegion(region)); - return regions; - }); + async fetchVoiceRegions() { + const apiRegions = await this.api.voice.regions.get(); + const regions = new Collection(); + for (const region of apiRegions) regions.set(region.id, new VoiceRegion(region)); + return regions; } /** @@ -433,13 +426,11 @@ class Client extends BaseClient { * @param {GuildResolvable} guild The guild to fetch the preview for * @returns {Promise} */ - fetchGuildPreview(guild) { + async fetchGuildPreview(guild) { const id = this.guilds.resolveId(guild); if (!id) throw new TypeError('INVALID_TYPE', 'guild', 'GuildResolvable'); - return this.api - .guilds(id) - .preview.get() - .then(data => new GuildPreview(this, data)); + const data = await this.api.guilds(id).preview.get(); + return new GuildPreview(this, data); } /** diff --git a/src/managers/GuildEmojiManager.js b/src/managers/GuildEmojiManager.js index 6be10c7237d1..6c1c689db58c 100644 --- a/src/managers/GuildEmojiManager.js +++ b/src/managers/GuildEmojiManager.js @@ -65,10 +65,8 @@ class GuildEmojiManager extends BaseGuildEmojiManager { } } - return this.client.api - .guilds(this.guild.id) - .emojis.post({ data, reason }) - .then(emoji => this.client.actions.GuildEmojiCreate.handle(this.guild, emoji).emoji); + const emoji = await this.client.api.guilds(this.guild.id).emojis.post({ data, reason }); + return this.client.actions.GuildEmojiCreate.handle(this.guild, emoji).emoji; } /** diff --git a/src/managers/GuildManager.js b/src/managers/GuildManager.js index 7d8535da7702..c4a7c9c3abf6 100644 --- a/src/managers/GuildManager.js +++ b/src/managers/GuildManager.js @@ -195,45 +195,42 @@ class GuildManager extends CachedManager { } if (systemChannelFlags) systemChannelFlags = SystemChannelFlags.resolve(systemChannelFlags); - return new Promise((resolve, reject) => - this.client.api.guilds - .post({ - data: { - name, - icon, - verification_level: verificationLevel, - default_message_notifications: defaultMessageNotifications, - explicit_content_filter: explicitContentFilter, - roles, - channels, - afk_channel_id: afkChannelId, - afk_timeout: afkTimeout, - system_channel_id: systemChannelId, - system_channel_flags: systemChannelFlags, - }, - }) - .then(data => { - if (this.client.guilds.cache.has(data.id)) return resolve(this.client.guilds.cache.get(data.id)); + const data = await this.client.api.guilds.post({ + data: { + name, + icon, + verification_level: verificationLevel, + default_message_notifications: defaultMessageNotifications, + explicit_content_filter: explicitContentFilter, + roles, + channels, + afk_channel_id: afkChannelId, + afk_timeout: afkTimeout, + system_channel_id: systemChannelId, + system_channel_flags: systemChannelFlags, + }, + }); - const handleGuild = guild => { - if (guild.id === data.id) { - clearTimeout(timeout); - this.client.removeListener(Events.GUILD_CREATE, handleGuild); - this.client.decrementMaxListeners(); - resolve(guild); - } - }; - this.client.incrementMaxListeners(); - this.client.on(Events.GUILD_CREATE, handleGuild); + if (this.client.guilds.cache.has(data.id)) return this.client.guilds.cache.get(data.id); - const timeout = setTimeout(() => { - this.client.removeListener(Events.GUILD_CREATE, handleGuild); - this.client.decrementMaxListeners(); - resolve(this.client.guilds._add(data)); - }, 10000).unref(); - return undefined; - }, reject), - ); + return new Promise(resolve => { + const handleGuild = guild => { + if (guild.id === data.id) { + clearTimeout(timeout); + this.client.removeListener(Events.GUILD_CREATE, handleGuild); + this.client.decrementMaxListeners(); + resolve(guild); + } + }; + this.client.incrementMaxListeners(); + this.client.on(Events.GUILD_CREATE, handleGuild); + + const timeout = setTimeout(() => { + this.client.removeListener(Events.GUILD_CREATE, handleGuild); + this.client.decrementMaxListeners(); + resolve(this.client.guilds._add(data)); + }, 10000).unref(); + }); } /** diff --git a/src/managers/GuildMemberManager.js b/src/managers/GuildMemberManager.js index defced96937d..d5c7292e97c7 100644 --- a/src/managers/GuildMemberManager.js +++ b/src/managers/GuildMemberManager.js @@ -277,8 +277,8 @@ class GuildMemberManager extends CachedManager { * .then(pruned => console.log(`I just pruned ${pruned} people!`)) * .catch(console.error); */ - prune({ days = 7, dry = false, count: compute_prune_count = true, roles = [], reason } = {}) { - if (typeof days !== 'number') return Promise.reject(new TypeError('PRUNE_DAYS_TYPE')); + async prune({ days = 7, dry = false, count: compute_prune_count = true, roles = [], reason } = {}) { + if (typeof days !== 'number') throw new TypeError('PRUNE_DAYS_TYPE'); const query = { days }; const resolvedRoles = []; @@ -286,7 +286,7 @@ class GuildMemberManager extends CachedManager { for (const role of roles) { const resolvedRole = this.guild.roles.resolveId(role); if (!resolvedRole) { - return Promise.reject(new TypeError('INVALID_ELEMENT', 'Array', 'options.roles', role)); + throw new TypeError('INVALID_ELEMENT', 'Array', 'options.roles', role); } resolvedRoles.push(resolvedRole); } @@ -297,16 +297,11 @@ class GuildMemberManager extends CachedManager { const endpoint = this.client.api.guilds(this.guild.id).prune; - if (dry) { - return endpoint.get({ query, reason }).then(data => data.pruned); - } + const { pruned } = await (dry + ? endpoint.get({ query, reason }) + : endpoint.post({ data: { ...query, compute_prune_count }, reason })); - return endpoint - .post({ - data: { ...query, compute_prune_count }, - reason, - }) - .then(data => data.pruned); + return pruned; } /** @@ -366,17 +361,14 @@ class GuildMemberManager extends CachedManager { return this.guild.bans.remove(user, reason); } - _fetchSingle({ user, cache, force = false }) { + async _fetchSingle({ user, cache, force = false }) { if (!force) { const existing = this.cache.get(user); - if (existing && !existing.partial) return Promise.resolve(existing); + if (existing && !existing.partial) return existing; } - return this.client.api - .guilds(this.guild.id) - .members(user) - .get() - .then(data => this._add(data, cache)); + const data = await this.client.api.guilds(this.guild.id).members(user).get(); + return this._add(data, cache); } _fetchMany({ diff --git a/src/managers/GuildStickerManager.js b/src/managers/GuildStickerManager.js index b8c15517dd30..bffb0b397a1d 100644 --- a/src/managers/GuildStickerManager.js +++ b/src/managers/GuildStickerManager.js @@ -57,10 +57,10 @@ class GuildStickerManager extends CachedManager { const data = { name, tags, description: description ?? '' }; - return this.client.api + const sticker = await this.client.api .guilds(this.guild.id) - .stickers.post({ data, files: [file], reason, dontUsePayloadJSON: true }) - .then(sticker => this.client.actions.GuildStickerCreate.handle(this.guild, sticker).sticker); + .stickers.post({ data, files: [file], reason, dontUsePayloadJSON: true }); + return this.client.actions.GuildStickerCreate.handle(this.guild, sticker).sticker; } /** diff --git a/src/managers/MessageManager.js b/src/managers/MessageManager.js index 4f61ab1516dc..7ac9dcad29fb 100644 --- a/src/managers/MessageManager.js +++ b/src/managers/MessageManager.js @@ -80,12 +80,11 @@ class MessageManager extends CachedManager { * .then(messages => console.log(`Received ${messages.size} messages`)) * .catch(console.error); */ - fetchPinned(cache = true) { - return this.client.api.channels[this.channel.id].pins.get().then(data => { - const messages = new Collection(); - for (const message of data) messages.set(message.id, this._add(message, cache)); - return messages; - }); + async fetchPinned(cache = true) { + const data = await this.client.api.channels[this.channel.id].pins.get(); + const messages = new Collection(); + for (const message of data) messages.set(message.id, this._add(message, cache)); + return messages; } /** diff --git a/src/managers/PermissionOverwriteManager.js b/src/managers/PermissionOverwriteManager.js index 4bd4337195b6..cadb4890b21f 100644 --- a/src/managers/PermissionOverwriteManager.js +++ b/src/managers/PermissionOverwriteManager.js @@ -54,7 +54,9 @@ class PermissionOverwriteManager extends CachedManager { */ set(overwrites, reason) { if (!Array.isArray(overwrites) && !(overwrites instanceof Collection)) { - throw new TypeError('INVALID_TYPE', 'overwrites', 'Array or Collection of Permission Overwrites', true); + return Promise.reject( + new TypeError('INVALID_TYPE', 'overwrites', 'Array or Collection of Permission Overwrites', true), + ); } return this.channel.edit({ permissionOverwrites: overwrites, reason }); } @@ -81,7 +83,7 @@ class PermissionOverwriteManager extends CachedManager { let { type, reason } = overwriteOptions; if (typeof type !== 'number') { userOrRole = this.channel.guild.roles.resolve(userOrRole) ?? this.client.users.resolve(userOrRole); - if (!userOrRole) return Promise.reject(new TypeError('INVALID_TYPE', 'parameter', 'User nor a Role')); + if (!userOrRole) throw new TypeError('INVALID_TYPE', 'parameter', 'User nor a Role'); type = userOrRole instanceof Role ? OverwriteTypes.role : OverwriteTypes.member; } diff --git a/src/managers/ReactionManager.js b/src/managers/ReactionManager.js index 771e05416400..57e7c0022487 100644 --- a/src/managers/ReactionManager.js +++ b/src/managers/ReactionManager.js @@ -57,12 +57,9 @@ class ReactionManager extends CachedManager { * Removes all reactions from a message. * @returns {Promise} */ - removeAll() { - return this.client.api - .channels(this.message.channel.id) - .messages(this.message.id) - .reactions.delete() - .then(() => this.message); + async removeAll() { + await this.client.api.channels(this.message.channel.id).messages(this.message.id).reactions.delete(); + return this.message; } } diff --git a/src/managers/ReactionUserManager.js b/src/managers/ReactionUserManager.js index 625aff2a5b42..5fc2147021e8 100644 --- a/src/managers/ReactionUserManager.js +++ b/src/managers/ReactionUserManager.js @@ -57,15 +57,14 @@ class ReactionUserManager extends CachedManager { * @param {UserResolvable} [user=this.client.user] The user to remove the reaction of * @returns {Promise} */ - remove(user = this.client.user) { + async remove(user = this.client.user) { const userId = this.client.users.resolveId(user); - if (!userId) return Promise.reject(new Error('REACTION_RESOLVE_USER')); + if (!userId) throw new Error('REACTION_RESOLVE_USER'); const message = this.reaction.message; - return this.client.api.channels[message.channel.id].messages[message.id].reactions[this.reaction.emoji.identifier][ + await this.client.api.channels[message.channel.id].messages[message.id].reactions[this.reaction.emoji.identifier][ userId === this.client.user.id ? '@me' : userId - ] - .delete() - .then(() => this.reaction); + ].delete(); + return this.reaction; } } diff --git a/src/managers/RoleManager.js b/src/managers/RoleManager.js index 65b675278853..211f96f30c9d 100644 --- a/src/managers/RoleManager.js +++ b/src/managers/RoleManager.js @@ -118,31 +118,27 @@ class RoleManager extends CachedManager { * .then(console.log) * .catch(console.error); */ - create(options = {}) { + async create(options = {}) { let { name, color, hoist, permissions, position, mentionable, reason } = options; if (color) color = resolveColor(color); if (typeof permissions !== 'undefined') permissions = new Permissions(permissions); - return this.client.api - .guilds(this.guild.id) - .roles.post({ - data: { - name, - color, - hoist, - permissions, - mentionable, - }, - reason, - }) - .then(r => { - const { role } = this.client.actions.GuildRoleCreate.handle({ - guild_id: this.guild.id, - role: r, - }); - if (position) return role.setPosition(position, reason); - return role; - }); + const data = await this.client.api.guilds(this.guild.id).roles.post({ + data: { + name, + color, + hoist, + permissions, + mentionable, + }, + reason, + }); + const { role } = this.client.actions.GuildRoleCreate.handle({ + guild_id: this.guild.id, + role: data, + }); + if (position) return role.setPosition(position, reason); + return role; } /** diff --git a/src/managers/ThreadMemberManager.js b/src/managers/ThreadMemberManager.js index a8b6498286f6..deff230d7974 100644 --- a/src/managers/ThreadMemberManager.js +++ b/src/managers/ThreadMemberManager.js @@ -74,13 +74,11 @@ class ThreadMemberManager extends CachedManager { * @param {string} [reason] The reason for adding this member * @returns {Promise} */ - add(member, reason) { + async add(member, reason) { const id = member === '@me' ? member : this.client.users.resolveId(member); - if (!id) return Promise.reject(new TypeError('INVALID_TYPE', 'member', 'UserResolvable')); - return this.client.api - .channels(this.thread.id, 'thread-members', id) - .put({ reason }) - .then(() => id); + if (!id) throw new TypeError('INVALID_TYPE', 'member', 'UserResolvable'); + await this.client.api.channels(this.thread.id, 'thread-members', id).put({ reason }); + return id; } /** @@ -89,11 +87,9 @@ class ThreadMemberManager extends CachedManager { * @param {string} [reason] The reason for removing this member from the thread * @returns {Promise} */ - remove(id, reason) { - return this.client.api - .channels(this.thread.id, 'thread-members', id) - .delete({ reason }) - .then(() => id); + async remove(id, reason) { + await this.client.api.channels(this.thread.id, 'thread-members', id).delete({ reason }); + return id; } /** diff --git a/src/sharding/Shard.js b/src/sharding/Shard.js index e732686ef643..334331c66027 100644 --- a/src/sharding/Shard.js +++ b/src/sharding/Shard.js @@ -106,7 +106,7 @@ class Shard extends EventEmitter { * before resolving (`-1` or `Infinity` for no wait) * @returns {Promise} */ - async spawn(timeout = 30000) { + spawn(timeout = 30000) { if (this.process) throw new Error('SHARDING_PROCESS_EXISTS', this.id); if (this.worker) throw new Error('SHARDING_WORKER_EXISTS', this.id); @@ -137,7 +137,7 @@ class Shard extends EventEmitter { this.emit('spawn', child); if (timeout === -1 || timeout === Infinity) return child; - await new Promise((resolve, reject) => { + return new Promise((resolve, reject) => { const cleanup = () => { clearTimeout(spawnTimeoutTimer); this.off('ready', onReady); @@ -147,7 +147,7 @@ class Shard extends EventEmitter { const onReady = () => { cleanup(); - resolve(); + resolve(child); }; const onDisconnect = () => { @@ -170,7 +170,6 @@ class Shard extends EventEmitter { this.once('disconnect', onDisconnect); this.once('death', onDeath); }); - return child; } /** diff --git a/src/structures/Guild.js b/src/structures/Guild.js index 2ceefb279972..7b33352f7cc5 100644 --- a/src/structures/Guild.js +++ b/src/structures/Guild.js @@ -556,13 +556,9 @@ class Guild extends AnonymousGuild { * Resolves with a collection mapping templates by their codes. * @returns {Promise>} */ - fetchTemplates() { - return this.client.api - .guilds(this.id) - .templates.get() - .then(templates => - templates.reduce((col, data) => col.set(data.code, new GuildTemplate(this.client, data)), new Collection()), - ); + async fetchTemplates() { + const templates = await this.client.api.guilds(this.id).templates.get(); + return templates.reduce((col, data) => col.set(data.code, new GuildTemplate(this.client, data)), new Collection()); } /** @@ -580,22 +576,18 @@ class Guild extends AnonymousGuild { * @param {string} [description] The description for the template * @returns {Promise} */ - createTemplate(name, description) { - return this.client.api - .guilds(this.id) - .templates.post({ data: { name, description } }) - .then(data => new GuildTemplate(this.client, data)); + async createTemplate(name, description) { + const data = await this.client.api.guilds(this.id).templates.post({ data: { name, description } }); + return new GuildTemplate(this.client, data); } /** * Obtains a guild preview for this guild from Discord. * @returns {Promise} */ - fetchPreview() { - return this.client.api - .guilds(this.id) - .preview.get() - .then(data => new GuildPreview(this.client, data)); + async fetchPreview() { + const data = await this.client.api.guilds(this.id).preview.get(); + return new GuildPreview(this.client, data); } /** @@ -637,15 +629,11 @@ class Guild extends AnonymousGuild { * .then(webhooks => console.log(`Fetched ${webhooks.size} webhooks`)) * .catch(console.error); */ - fetchWebhooks() { - return this.client.api - .guilds(this.id) - .webhooks.get() - .then(data => { - const hooks = new Collection(); - for (const hook of data) hooks.set(hook.id, new Webhook(this.client, hook)); - return hooks; - }); + async fetchWebhooks() { + const apiHooks = await this.client.api.guilds(this.id).webhooks.get(); + const hooks = new Collection(); + for (const hook of apiHooks) hooks.set(hook.id, new Webhook(this.client, hook)); + return hooks; } /** @@ -713,21 +701,19 @@ class Guild extends AnonymousGuild { * .then(audit => console.log(audit.entries.first())) * .catch(console.error); */ - fetchAuditLogs(options = {}) { + async fetchAuditLogs(options = {}) { if (options.before && options.before instanceof GuildAuditLogs.Entry) options.before = options.before.id; if (typeof options.type === 'string') options.type = GuildAuditLogs.Actions[options.type]; - return this.client.api - .guilds(this.id) - ['audit-logs'].get({ - query: { - before: options.before, - limit: options.limit, - user_id: this.client.users.resolveId(options.user), - action_type: options.type, - }, - }) - .then(data => GuildAuditLogs.build(this, data)); + const data = await this.client.api.guilds(this.id)['audit-logs'].get({ + query: { + before: options.before, + limit: options.limit, + user_id: this.client.users.resolveId(options.user), + action_type: options.type, + }, + }); + return GuildAuditLogs.build(this, data); } /** @@ -781,7 +767,7 @@ class Guild extends AnonymousGuild { * .then(updated => console.log(`New guild name ${updated}`)) * .catch(console.error); */ - edit(data, reason) { + async edit(data, reason) { const _data = {}; if (data.name) _data.name = data.name; if (typeof data.verificationLevel !== 'undefined') { @@ -830,10 +816,8 @@ class Guild extends AnonymousGuild { _data.description = data.description; } if (data.preferredLocale) _data.preferred_locale = data.preferredLocale; - return this.client.api - .guilds(this.id) - .patch({ data: _data, reason }) - .then(newData => this.client.actions.GuildUpdate.handle(newData).updated); + const newData = await this.client.api.guilds(this.id).patch({ data: _data, reason }); + return this.client.actions.GuildUpdate.handle(newData).updated; } /** @@ -1158,7 +1142,7 @@ class Guild extends AnonymousGuild { * .then(guild => console.log(`Updated channel positions for ${guild}`)) * .catch(console.error); */ - setChannelPositions(channelPositions) { + async setChannelPositions(channelPositions) { const updatedChannels = channelPositions.map(r => ({ id: this.client.channels.resolveId(r.channel), position: r.position, @@ -1166,16 +1150,11 @@ class Guild extends AnonymousGuild { parent_id: typeof r.parent !== 'undefined' ? this.channels.resolveId(r.parent) : undefined, })); - return this.client.api - .guilds(this.id) - .channels.patch({ data: updatedChannels }) - .then( - () => - this.client.actions.GuildChannelsPositionUpdate.handle({ - guild_id: this.id, - channels: updatedChannels, - }).guild, - ); + await this.client.api.guilds(this.id).channels.patch({ data: updatedChannels }); + return this.client.actions.GuildChannelsPositionUpdate.handle({ + guild_id: this.id, + channels: updatedChannels, + }).guild; } /** @@ -1194,7 +1173,7 @@ class Guild extends AnonymousGuild { * .then(guild => console.log(`Role positions updated for ${guild}`)) * .catch(console.error); */ - setRolePositions(rolePositions) { + async setRolePositions(rolePositions) { // Make sure rolePositions are prepared for API rolePositions = rolePositions.map(o => ({ id: this.roles.resolveId(o.role), @@ -1202,18 +1181,13 @@ class Guild extends AnonymousGuild { })); // Call the API to update role positions - return this.client.api - .guilds(this.id) - .roles.patch({ - data: rolePositions, - }) - .then( - () => - this.client.actions.GuildRolesPositionUpdate.handle({ - guild_id: this.id, - roles: rolePositions, - }).guild, - ); + await this.client.api.guilds(this.id).roles.patch({ + data: rolePositions, + }); + return this.client.actions.GuildRolesPositionUpdate.handle({ + guild_id: this.id, + roles: rolePositions, + }).guild; } /** @@ -1222,17 +1196,15 @@ class Guild extends AnonymousGuild { * @param {string} [reason] Reason for changing the guild's widget settings * @returns {Promise} */ - setWidgetSettings(settings, reason) { - return this.client.api - .guilds(this.id) - .widget.patch({ - data: { - enabled: settings.enabled, - channel_id: this.channels.resolveId(settings.channel), - }, - reason, - }) - .then(() => this); + async setWidgetSettings(settings, reason) { + await this.client.api.guilds(this.id).widget.patch({ + data: { + enabled: settings.enabled, + channel_id: this.channels.resolveId(settings.channel), + }, + reason, + }); + return this; } /** @@ -1244,13 +1216,10 @@ class Guild extends AnonymousGuild { * .then(g => console.log(`Left the guild ${g}`)) * .catch(console.error); */ - leave() { - if (this.ownerId === this.client.user.id) return Promise.reject(new Error('GUILD_OWNED')); - return this.client.api - .users('@me') - .guilds(this.id) - .delete() - .then(() => this.client.actions.GuildDelete.handle({ id: this.id }).guild); + async leave() { + if (this.ownerId === this.client.user.id) throw new Error('GUILD_OWNED'); + await this.client.api.users('@me').guilds(this.id).delete(); + return this.client.actions.GuildDelete.handle({ id: this.id }).guild; } /** @@ -1262,11 +1231,9 @@ class Guild extends AnonymousGuild { * .then(g => console.log(`Deleted the guild ${g}`)) * .catch(console.error); */ - delete() { - return this.client.api - .guilds(this.id) - .delete() - .then(() => this.client.actions.GuildDelete.handle({ id: this.id }).guild); + async delete() { + await this.client.api.guilds(this.id).delete(); + return this.client.actions.GuildDelete.handle({ id: this.id }).guild; } /** diff --git a/src/structures/GuildAuditLogs.js b/src/structures/GuildAuditLogs.js index f4f097f873e4..c600c2931fdd 100644 --- a/src/structures/GuildAuditLogs.js +++ b/src/structures/GuildAuditLogs.js @@ -198,9 +198,10 @@ class GuildAuditLogs { * Handles possible promises for entry targets. * @returns {Promise} */ - static build(...args) { + static async build(...args) { const logs = new GuildAuditLogs(...args); - return Promise.all(logs.entries.map(e => e.target)).then(() => logs); + await Promise.all(logs.entries.map(e => e.target)); + return logs; } /** @@ -500,19 +501,17 @@ class GuildAuditLogsEntry { ), ); } else if (targetType === Targets.INVITE) { - this.target = guild.members.fetch(guild.client.user.id).then(me => { + this.target = guild.members.fetch(guild.client.user.id).then(async me => { if (me.permissions.has(Permissions.FLAGS.MANAGE_GUILD)) { let change = this.changes.find(c => c.key === 'code'); change = change.new ?? change.old; - return guild.invites.fetch().then(invites => { - this.target = invites.find(i => i.code === change) ?? null; - }); + const invites = await guild.invites.fetch(); + this.target = invites.find(i => i.code === change) ?? null; } else { this.target = this.changes.reduce((o, c) => { o[c.key] = c.new ?? c.old; return o; }, {}); - return this.target; } }); } else if (targetType === Targets.MESSAGE) { diff --git a/src/structures/GuildChannel.js b/src/structures/GuildChannel.js index 002d372e5a0e..39f7009d7d2b 100644 --- a/src/structures/GuildChannel.js +++ b/src/structures/GuildChannel.js @@ -296,18 +296,17 @@ class GuildChannel extends Channel { if (data.parent) data.parent = this.client.channels.resolveId(data.parent); if (typeof data.position !== 'undefined') { - await Util.setPosition( + const updatedChannels = await Util.setPosition( this, data.position, false, this.guild._sortedChannels(this), this.client.api.guilds(this.guild.id).channels, reason, - ).then(updatedChannels => { - this.client.actions.GuildChannelsPositionUpdate.handle({ - guild_id: this.guild.id, - channels: updatedChannels, - }); + ); + this.client.actions.GuildChannelsPositionUpdate.handle({ + guild_id: this.guild.id, + channels: updatedChannels, }); } @@ -389,8 +388,7 @@ class GuildChannel extends Channel { setParent(channel, { lockPermissions = true, reason } = {}) { return this.edit( { - // eslint-disable-next-line no-prototype-builtins - parent: channel ?? null, + parentId: channel?.id ?? channel ?? null, lockPermissions, }, reason, @@ -430,21 +428,20 @@ class GuildChannel extends Channel { * .then(newChannel => console.log(`Channel's new position is ${newChannel.position}`)) * .catch(console.error); */ - setPosition(position, { relative, reason } = {}) { - return Util.setPosition( + async setPosition(position, { relative, reason } = {}) { + const updatedChannels = await Util.setPosition( this, position, relative, this.guild._sortedChannels(this), this.client.api.guilds(this.guild.id).channels, reason, - ).then(updatedChannels => { - this.client.actions.GuildChannelsPositionUpdate.handle({ - guild_id: this.guild.id, - channels: updatedChannels, - }); - return this; + ); + this.client.actions.GuildChannelsPositionUpdate.handle({ + guild_id: this.guild.id, + channels: updatedChannels, }); + return this; } /** @@ -600,11 +597,9 @@ class GuildChannel extends Channel { * .then(console.log) * .catch(console.error); */ - delete(reason) { - return this.client.api - .channels(this.id) - .delete({ reason }) - .then(() => this); + async delete(reason) { + await this.client.api.channels(this.id).delete({ reason }); + return this; } } diff --git a/src/structures/GuildEmoji.js b/src/structures/GuildEmoji.js index 00dd215b30ce..a60ffcd09760 100644 --- a/src/structures/GuildEmoji.js +++ b/src/structures/GuildEmoji.js @@ -107,9 +107,9 @@ class GuildEmoji extends BaseGuildEmoji { * .then(e => console.log(`Edited emoji ${e}`)) * .catch(console.error); */ - edit(data, reason) { + async edit(data, reason) { const roles = data.roles?.map(r => r.id ?? r); - return this.client.api + const newData = await this.client.api .guilds(this.guild.id) .emojis(this.id) .patch({ @@ -118,12 +118,10 @@ class GuildEmoji extends BaseGuildEmoji { roles, }, reason, - }) - .then(newData => { - const clone = this._clone(); - clone._patch(newData); - return clone; }); + const clone = this._clone(); + clone._patch(newData); + return clone; } /** @@ -141,12 +139,9 @@ class GuildEmoji extends BaseGuildEmoji { * @param {string} [reason] Reason for deleting the emoji * @returns {Promise} */ - delete(reason) { - return this.client.api - .guilds(this.guild.id) - .emojis(this.id) - .delete({ reason }) - .then(() => this); + async delete(reason) { + await this.client.api.guilds(this.guild.id).emojis(this.id).delete({ reason }); + return this; } /** diff --git a/src/structures/GuildPreview.js b/src/structures/GuildPreview.js index 09a206176922..239476fe4896 100644 --- a/src/structures/GuildPreview.js +++ b/src/structures/GuildPreview.js @@ -140,14 +140,10 @@ class GuildPreview extends Base { * Fetches this guild. * @returns {Promise} */ - fetch() { - return this.client.api - .guilds(this.id) - .preview.get() - .then(data => { - this._patch(data); - return this; - }); + async fetch() { + const data = await this.client.api.guilds(this.id).preview.get(); + this._patch(data); + return this; } /** diff --git a/src/structures/GuildTemplate.js b/src/structures/GuildTemplate.js index 09e94c4a4fd1..5a09607e4a92 100644 --- a/src/structures/GuildTemplate.js +++ b/src/structures/GuildTemplate.js @@ -109,11 +109,10 @@ class GuildTemplate extends Base { icon: await DataResolver.resolveImage(icon), }, }); - // eslint-disable-next-line consistent-return - return new Promise(resolve => { - const createdGuild = client.guilds.cache.get(data.id); - if (createdGuild) return resolve(createdGuild); + if (client.guilds.cache.has(data.id)) return client.guilds.cache.get(data.id); + + return new Promise(resolve => { const resolveGuild = guild => { client.off(Events.GUILD_CREATE, handleGuild); client.decrementMaxListeners(); @@ -146,36 +145,27 @@ class GuildTemplate extends Base { * @param {EditGuildTemplateOptions} [options] Options for editing the template * @returns {Promise} */ - edit({ name, description } = {}) { - return this.client.api - .guilds(this.guildId) - .templates(this.code) - .patch({ data: { name, description } }) - .then(data => this._patch(data)); + async edit({ name, description } = {}) { + const data = await this.client.api.guilds(this.guildId).templates(this.code).patch({ data: { name, description } }); + return this._patch(data); } /** * Deletes this template. * @returns {Promise} */ - delete() { - return this.client.api - .guilds(this.guildId) - .templates(this.code) - .delete() - .then(() => this); + async delete() { + await this.client.api.guilds(this.guildId).templates(this.code).delete(); + return this; } /** * Syncs this template to the current state of the guild. * @returns {Promise} */ - sync() { - return this.client.api - .guilds(this.guildId) - .templates(this.code) - .put() - .then(data => this._patch(data)); + async sync() { + const data = await this.client.api.guilds(this.guildId).templates(this.code).put(); + return this._patch(data); } /** diff --git a/src/structures/Integration.js b/src/structures/Integration.js index 644882eade17..814846ec0536 100644 --- a/src/structures/Integration.js +++ b/src/structures/Integration.js @@ -126,12 +126,9 @@ class Integration extends Base { * @returns {Promise} * @param {string} [reason] Reason for deleting this integration */ - delete(reason) { - return this.client.api - .guilds(this.guild.id) - .integrations(this.id) - .delete({ reason }) - .then(() => this); + async delete(reason) { + await this.client.api.guilds(this.guild.id).integrations(this.id).delete({ reason }); + return this; } toJSON() { diff --git a/src/structures/Invite.js b/src/structures/Invite.js index 95bad22b21eb..04868284e3a8 100644 --- a/src/structures/Invite.js +++ b/src/structures/Invite.js @@ -189,8 +189,9 @@ class Invite extends Base { * @param {string} [reason] Reason for deleting this invite * @returns {Promise} */ - delete(reason) { - return this.client.api.invites[this.code].delete({ reason }).then(() => this); + async delete(reason) { + await this.client.api.invites[this.code].delete({ reason }); + return this; } /** diff --git a/src/structures/Message.js b/src/structures/Message.js index 536b628de8ef..b00da726f2aa 100644 --- a/src/structures/Message.js +++ b/src/structures/Message.js @@ -637,8 +637,9 @@ class Message extends Base { * .then(console.log) * .catch(console.error) */ - pin() { - return this.channel.messages.pin(this.id).then(() => this); + async pin() { + await this.channel.messages.pin(this.id); + return this; } /** @@ -650,8 +651,9 @@ class Message extends Base { * .then(console.log) * .catch(console.error) */ - unpin() { - return this.channel.messages.unpin(this.id).then(() => this); + async unpin() { + await this.channel.messages.unpin(this.id); + return this; } /** diff --git a/src/structures/Role.js b/src/structures/Role.js index 897ad48ced19..4d290243d98f 100644 --- a/src/structures/Role.js +++ b/src/structures/Role.js @@ -310,21 +310,20 @@ class Role extends Base { * .then(updated => console.log(`Role position: ${updated.position}`)) * .catch(console.error); */ - setPosition(position, { relative, reason } = {}) { - return Util.setPosition( + async setPosition(position, { relative, reason } = {}) { + const updatedRoles = await Util.setPosition( this, position, relative, this.guild._sortedRoles(), this.client.api.guilds(this.guild.id).roles, reason, - ).then(updatedRoles => { - this.client.actions.GuildRolesPositionUpdate.handle({ - guild_id: this.guild.id, - roles: updatedRoles, - }); - return this; + ); + this.client.actions.GuildRolesPositionUpdate.handle({ + guild_id: this.guild.id, + roles: updatedRoles, }); + return this; } /** @@ -337,11 +336,10 @@ class Role extends Base { * .then(deleted => console.log(`Deleted role ${deleted.name}`)) * .catch(console.error); */ - delete(reason) { - return this.client.api.guilds[this.guild.id].roles[this.id].delete({ reason }).then(() => { - this.client.actions.GuildRoleDelete.handle({ guild_id: this.guild.id, role_id: this.id }); - return this; - }); + async delete(reason) { + await this.client.api.guilds[this.guild.id].roles[this.id].delete({ reason }); + this.client.actions.GuildRoleDelete.handle({ guild_id: this.guild.id, role_id: this.id }); + return this; } /** diff --git a/src/structures/TextChannel.js b/src/structures/TextChannel.js index f88060b24fb4..7b0a2df88587 100644 --- a/src/structures/TextChannel.js +++ b/src/structures/TextChannel.js @@ -143,12 +143,11 @@ class TextChannel extends GuildChannel { * .then(hooks => console.log(`This channel has ${hooks.size} hooks`)) * .catch(console.error); */ - fetchWebhooks() { - return this.client.api.channels[this.id].webhooks.get().then(data => { - const hooks = new Collection(); - for (const hook of data) hooks.set(hook.id, new Webhook(this.client, hook)); - return hooks; - }); + async fetchWebhooks() { + const data = await this.client.api.channels[this.id].webhooks.get(); + const hooks = new Collection(); + for (const hook of data) hooks.set(hook.id, new Webhook(this.client, hook)); + return hooks; } /** @@ -176,15 +175,14 @@ class TextChannel extends GuildChannel { if (typeof avatar === 'string' && !avatar.startsWith('data:')) { avatar = await DataResolver.resolveImage(avatar); } - return this.client.api.channels[this.id].webhooks - .post({ - data: { - name, - avatar, - }, - reason, - }) - .then(data => new Webhook(this.client, data)); + const data = await this.client.api.channels[this.id].webhooks.post({ + data: { + name, + avatar, + }, + reason, + }); + return new Webhook(this.client, data); } // These are here only for documentation purposes - they are implemented by TextBasedChannel diff --git a/src/structures/ThreadChannel.js b/src/structures/ThreadChannel.js index ac91157f5c9e..f31af56b9af0 100644 --- a/src/structures/ThreadChannel.js +++ b/src/structures/ThreadChannel.js @@ -212,16 +212,18 @@ class ThreadChannel extends Channel { * Makes the client user join the thread. * @returns {Promise} */ - join() { - return this.members.add('@me').then(() => this); + async join() { + await this.members.add('@me'); + return this; } /** * Makes the client user leave the thread. * @returns {Promise} */ - leave() { - return this.members.remove('@me').then(() => this); + async leave() { + await this.members.remove('@me'); + return this; } /** @@ -444,11 +446,9 @@ class ThreadChannel extends Channel { * .then(deletedThread => console.log(deletedThread)) * .catch(console.error); */ - delete(reason) { - return this.client.api - .channels(this.id) - .delete({ reason }) - .then(() => this); + async delete(reason) { + await this.client.api.channels(this.id).delete({ reason }); + return this; } // These are here only for documentation purposes - they are implemented by TextBasedChannel diff --git a/src/structures/ThreadMember.js b/src/structures/ThreadMember.js index 526334455a44..147f603f76c6 100644 --- a/src/structures/ThreadMember.js +++ b/src/structures/ThreadMember.js @@ -87,8 +87,9 @@ class ThreadMember extends Base { * @param {string} [reason] Reason for removing the member * @returns {ThreadMember} */ - remove(reason) { - return this.thread.members.remove(this.id, reason).then(() => this); + async remove(reason) { + await this.thread.members.remove(this.id, reason); + return this; } } diff --git a/src/structures/Webhook.js b/src/structures/Webhook.js index 61960bcdb996..5fe1d78f0942 100644 --- a/src/structures/Webhook.js +++ b/src/structures/Webhook.js @@ -166,15 +166,13 @@ class Webhook { } const { data, files } = await messagePayload.resolveFiles(); - return this.client.api - .webhooks(this.id, this.token) - .post({ - data, - files, - query: { thread_id: messagePayload.options.threadId, wait: true }, - auth: false, - }) - .then(d => this.client.channels?.cache.get(d.channel_id)?.messages._add(d, false) ?? d); + const d = await this.client.api.webhooks(this.id, this.token).post({ + data, + files, + query: { thread_id: messagePayload.options.threadId, wait: true }, + auth: false, + }); + return this.client.channels?.cache.get(d.channel_id)?.messages._add(d, false) ?? d; } /** @@ -195,17 +193,15 @@ class Webhook { * }).catch(console.error); * @see {@link https://api.slack.com/messaging/webhooks} */ - sendSlackMessage(body) { + async sendSlackMessage(body) { if (!this.token) throw new Error('WEBHOOK_TOKEN_UNAVAILABLE'); - return this.client.api - .webhooks(this.id, this.token) - .slack.post({ - query: { wait: true }, - auth: false, - data: body, - }) - .then(data => data.toString() === 'ok'); + const data = await this.client.api.webhooks(this.id, this.token).slack.post({ + query: { wait: true }, + auth: false, + data: body, + }); + return data.toString() === 'ok'; } /** diff --git a/src/structures/interfaces/Application.js b/src/structures/interfaces/Application.js index 4518d63a31a4..2dad85da9b0d 100644 --- a/src/structures/interfaces/Application.js +++ b/src/structures/interfaces/Application.js @@ -92,17 +92,13 @@ class Application extends Base { * Gets the application's rich presence assets. * @returns {Promise>} */ - fetchAssets() { - return this.client.api.oauth2 - .applications(this.id) - .assets.get() - .then(assets => - assets.map(a => ({ - id: a.id, - name: a.name, - type: AssetTypes[a.type - 1], - })), - ); + async fetchAssets() { + const assets = await this.client.api.oauth2.applications(this.id).assets.get(); + return assets.map(a => ({ + id: a.id, + name: a.name, + type: AssetTypes[a.type - 1], + })); } /** diff --git a/src/structures/interfaces/TextBasedChannel.js b/src/structures/interfaces/TextBasedChannel.js index de4d2bc24f73..dee00b89f494 100644 --- a/src/structures/interfaces/TextBasedChannel.js +++ b/src/structures/interfaces/TextBasedChannel.js @@ -155,7 +155,8 @@ class TextBasedChannel { const GuildMember = require('../GuildMember'); if (this instanceof User || this instanceof GuildMember) { - return this.createDM().then(dm => dm.send(options)); + const dm = await this.createDM(); + return dm.send(options); } let messagePayload; diff --git a/src/util/Util.js b/src/util/Util.js index 44fc59f49829..4f7561f08b70 100644 --- a/src/util/Util.js +++ b/src/util/Util.js @@ -267,19 +267,19 @@ class Util extends null { * @param {FetchRecommendedShardsOptions} [options] Options for fetching the recommended shard count * @returns {Promise} The recommended number of shards */ - static fetchRecommendedShards(token, { guildsPerShard = 1000, multipleOf = 1 } = {}) { + static async fetchRecommendedShards(token, { guildsPerShard = 1000, multipleOf = 1 } = {}) { if (!token) throw new DiscordError('TOKEN_MISSING'); const defaults = Options.createDefault(); - return fetch(`${defaults.http.api}/v${defaults.http.version}${Endpoints.botGateway}`, { + const response = await fetch(`${defaults.http.api}/v${defaults.http.version}${Endpoints.botGateway}`, { method: 'GET', headers: { Authorization: `Bot ${token.replace(/^Bot\s*/i, '')}` }, - }) - .then(res => { - if (res.ok) return res.json(); - if (res.status === 401) throw new DiscordError('TOKEN_INVALID'); - throw res; - }) - .then(data => Math.ceil((data.shards * (1000 / guildsPerShard)) / multipleOf) * multipleOf); + }); + if (!response.ok) { + if (response.status === 401) throw new DiscordError('TOKEN_INVALID'); + throw response; + } + const { shards } = await response.json(); + return Math.ceil((shards * (1000 / guildsPerShard)) / multipleOf) * multipleOf; } /** @@ -500,11 +500,12 @@ class Util extends null { * @returns {Promise} Updated item list, with `id` and `position` properties * @private */ - static setPosition(item, position, relative, sorted, route, reason) { + static async setPosition(item, position, relative, sorted, route, reason) { let updatedItems = [...sorted.values()]; Util.moveElementInArray(updatedItems, item, position, relative); updatedItems = updatedItems.map((r, i) => ({ id: r.id, position: i })); - return route.patch({ data: updatedItems, reason }).then(() => updatedItems); + await route.patch({ data: updatedItems, reason }); + return updatedItems; } /**