refactor(Bitfield): use discord-api-types enums instead (#7313)

Co-authored-by: Almeida <almeidx@pm.me>
This commit is contained in:
Suneet Tipirneni
2022-01-28 13:14:20 -05:00
committed by GitHub
parent 74f627c379
commit fbb1d0328b
64 changed files with 675 additions and 928 deletions

View File

@@ -90,12 +90,12 @@ body:
options:
- Not applicable (subpackage bug)
- No Partials
- USER
- CHANNEL
- GUILD_MEMBER
- MESSAGE
- REACTION
- GUILD_SCHEDULED_EVENT
- User
- Channel
- GuildMember
- Message
- Reaction
- GuildScheduledEvent
multiple: true
validations:
required: true
@@ -110,22 +110,22 @@ body:
options:
- Not applicable (subpackage bug)
- No Intents
- GUILDS
- GUILD_MEMBERS
- GUILD_BANS
- GUILD_EMOJIS_AND_STICKERS
- GUILD_INTEGRATIONS
- GUILD_WEBHOOKS
- GUILD_INVITES
- GUILD_VOICE_STATES
- GUILD_PRESENCES
- GUILD_MESSAGES
- GUILD_MESSAGE_REACTIONS
- GUILD_MESSAGE_TYPING
- DIRECT_MESSAGES
- DIRECT_MESSAGE_REACTIONS
- DIRECT_MESSAGE_TYPING
- GUILD_SCHEDULED_EVENTS
- Guilds
- GuildMembers
- GuildBans
- GuildEmojisAndStickers
- GuildIntegrations
- GuildWebhooks
- GuildInvites
- GuildVoiceStates
- GuildPresences
- GuildMessages
- GuildMessageReactions
- GuildMessageTyping
- DirectMessages
- DirectMessageMentions
- DirectMessageTyping
- GuildScheduledEvents
multiple: true
validations:
required: true

View File

@@ -81,8 +81,8 @@ const rest = new REST({ version: '9' }).setToken('token');
Afterwards we can create a quite simple example bot:
```js
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);

View File

@@ -81,8 +81,8 @@ const rest = new REST({ version: '9' }).setToken('token');
Afterwards we can create a quite simple example bot:
```js
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);

View File

@@ -24,9 +24,9 @@ const Webhook = require('../structures/Webhook');
const Widget = require('../structures/Widget');
const { Events, InviteScopes, Status } = require('../util/Constants');
const DataResolver = require('../util/DataResolver');
const Intents = require('../util/Intents');
const IntentsBitField = require('../util/IntentsBitField');
const Options = require('../util/Options');
const Permissions = require('../util/Permissions');
const PermissionsBitField = require('../util/PermissionsBitField');
const Sweepers = require('../util/Sweepers');
/**
@@ -404,9 +404,9 @@ class Client extends BaseClient {
* @example
* const link = client.generateInvite({
* permissions: [
* Permissions.FLAGS.SEND_MESSAGES,
* Permissions.FLAGS.MANAGE_GUILD,
* Permissions.FLAGS.MENTION_EVERYONE,
* PermissionFlagsBits.SendMessages,
* PermissionFlagsBits.ManageGuild,
* PermissionFlagsBits.MentionEveryone,
* ],
* scopes: ['bot'],
* });
@@ -437,7 +437,7 @@ class Client extends BaseClient {
query.set('scope', scopes.join(' '));
if (options.permissions) {
const permissions = Permissions.resolve(options.permissions);
const permissions = PermissionsBitField.resolve(options.permissions);
if (permissions) query.set('permissions', permissions);
}
@@ -480,7 +480,7 @@ class Client extends BaseClient {
if (typeof options.intents === 'undefined') {
throw new TypeError('CLIENT_MISSING_INTENTS');
} else {
options.intents = Intents.resolve(options.intents);
options.intents = IntentsBitField.resolve(options.intents);
}
if (typeof options.shardCount !== 'number' || isNaN(options.shardCount) || options.shardCount < 1) {
throw new TypeError('CLIENT_INVALID_OPTION', 'shardCount', 'a number greater than or equal to 1');

View File

@@ -1,6 +1,6 @@
'use strict';
const { PartialTypes } = require('../../util/Constants');
const Partials = require('../../util/Partials');
/*
@@ -43,7 +43,7 @@ class GenericAction {
},
this.client.channels,
id,
PartialTypes.CHANNEL,
Partials.Channel,
)
);
}
@@ -60,7 +60,7 @@ class GenericAction {
},
channel.messages,
id,
PartialTypes.MESSAGE,
Partials.Message,
cache,
)
);
@@ -76,17 +76,17 @@ class GenericAction {
},
message.reactions,
id,
PartialTypes.REACTION,
Partials.Reaction,
);
}
getMember(data, guild) {
return this.getPayload(data, guild.members, data.user.id, PartialTypes.GUILD_MEMBER);
return this.getPayload(data, guild.members, data.user.id, Partials.GuildMember);
}
getUser(data) {
const id = data.user_id;
return data.user ?? this.getPayload({ id }, this.client.users, id, PartialTypes.USER);
return data.user ?? this.getPayload({ id }, this.client.users, id, Partials.User);
}
getUserFromMember(data) {
@@ -107,7 +107,7 @@ class GenericAction {
{ id, guild_id: data.guild_id ?? guild.id },
guild.scheduledEvents,
id,
PartialTypes.GUILD_SCHEDULED_EVENT,
Partials.GuildScheduledEvent,
);
}
}

View File

@@ -2,7 +2,7 @@
const Action = require('./Action');
const { Events } = require('../../util/Constants');
const { PartialTypes } = require('../../util/Constants');
const Partials = require('../../util/Partials');
/*
{ user_id: 'id',
@@ -30,7 +30,7 @@ class MessageReactionAdd extends Action {
if (!message) return false;
// Verify reaction
const includePartial = this.client.options.partials.includes(PartialTypes.REACTION);
const includePartial = this.client.options.partials.includes(Partials.Reaction);
if (message.partial && !includePartial) return false;
const reaction = message.reactions._add({
emoji: data.emoji,

View File

@@ -2,9 +2,10 @@
const EventEmitter = require('node:events');
const { setTimeout, setInterval, clearTimeout, clearInterval } = require('node:timers');
const { GatewayIntentBits } = require('discord-api-types/v9');
const WebSocket = require('../../WebSocket');
const { Status, Events, ShardEvents, Opcodes, WSEvents } = require('../../util/Constants');
const Intents = require('../../util/Intents');
const IntentsBitField = require('../../util/IntentsBitField');
const STATUS_KEYS = Object.keys(Status);
const CONNECTION_STATE = Object.keys(WebSocket.WebSocket);
@@ -475,7 +476,7 @@ class WebSocketShard extends EventEmitter {
this.emit(ShardEvents.ALL_READY);
return;
}
const hasGuildsIntent = new Intents(this.manager.client.options.intents).has(Intents.FLAGS.GUILDS);
const hasGuildsIntent = new IntentsBitField(this.manager.client.options.intents).has(GatewayIntentBits.Guilds);
// Step 2. Create a timeout that will mark the shard as ready if there are still unavailable guilds
// * The timeout is 15 seconds by default
// * This can be optionally changed in the client options via the `waitGuildTimeout` option
@@ -610,7 +611,7 @@ class WebSocketShard extends EventEmitter {
// Clone the identify payload and assign the token and shard info
const d = {
...client.options.ws,
intents: Intents.resolve(client.options.intents),
intents: IntentsBitField.resolve(client.options.intents),
token: client.token,
shard: [this.id, Number(client.options.shardCount)],
};

View File

@@ -9,8 +9,8 @@ exports.ShardingManager = require('./sharding/ShardingManager');
exports.WebhookClient = require('./client/WebhookClient');
// Utilities
exports.ActivityFlags = require('./util/ActivityFlags');
exports.ApplicationFlags = require('./util/ApplicationFlags');
exports.ActivityFlagsBitField = require('./util/ActivityFlagsBitField');
exports.ApplicationFlagsBitField = require('./util/ApplicationFlagsBitField');
exports.BaseManager = require('./managers/BaseManager');
exports.BitField = require('./util/BitField');
exports.Collection = require('@discordjs/collection').Collection;
@@ -18,16 +18,17 @@ exports.Constants = require('./util/Constants');
exports.DataResolver = require('./util/DataResolver');
exports.EnumResolvers = require('./util/EnumResolvers');
exports.Formatters = require('./util/Formatters');
exports.Intents = require('./util/Intents');
exports.IntentsBitField = require('./util/IntentsBitField');
exports.LimitedCollection = require('./util/LimitedCollection');
exports.MessageFlags = require('./util/MessageFlags');
exports.MessageFlagsBitField = require('./util/MessageFlagsBitField');
exports.Options = require('./util/Options');
exports.Permissions = require('./util/Permissions');
exports.Partials = require('./util/Partials');
exports.PermissionsBitField = require('./util/PermissionsBitField');
exports.SnowflakeUtil = require('@sapphire/snowflake').DiscordSnowflake;
exports.Sweepers = require('./util/Sweepers');
exports.SystemChannelFlags = require('./util/SystemChannelFlags');
exports.ThreadMemberFlags = require('./util/ThreadMemberFlags');
exports.UserFlags = require('./util/UserFlags');
exports.SystemChannelFlagsBitField = require('./util/SystemChannelFlagsBitField');
exports.ThreadMemberFlagsBitField = require('./util/ThreadMemberFlagsBitField');
exports.UserFlagsBitField = require('./util/UserFlagsBitField');
exports.Util = require('./util/Util');
exports.version = require('../package.json').version;
@@ -158,21 +159,26 @@ exports.ApplicationCommandPermissionType = require('discord-api-types/v9').Appli
exports.ButtonStyle = require('discord-api-types/v9').ButtonStyle;
exports.ChannelType = require('discord-api-types/v9').ChannelType;
exports.ComponentType = require('discord-api-types/v9').ComponentType;
exports.GatewayIntentBits = require('discord-api-types/v9').GatewayIntentBits;
exports.GuildMFALevel = require('discord-api-types/v9').GuildMFALevel;
exports.GuildNSFWLevel = require('discord-api-types/v9').GuildNSFWLevel;
exports.GuildPremiumTier = require('discord-api-types/v9').GuildPremiumTier;
exports.GuildScheduledEventEntityType = require('discord-api-types/v9').GuildScheduledEventEntityType;
exports.GuildScheduledEventPrivacyLevel = require('discord-api-types/v9').GuildScheduledEventPrivacyLevel;
exports.GuildScheduledEventStatus = require('discord-api-types/v9').GuildScheduledEventStatus;
exports.GuildSystemChannelFlags = require('discord-api-types/v9').GuildSystemChannelFlags;
exports.GuildVerificationLevel = require('discord-api-types/v9').GuildVerificationLevel;
exports.InteractionType = require('discord-api-types/v9').InteractionType;
exports.InteractionResponseType = require('discord-api-types/v9').InteractionResponseType;
exports.InviteTargetType = require('discord-api-types/v9').InviteTargetType;
exports.MessageType = require('discord-api-types/v9').MessageType;
exports.MessageFlags = require('discord-api-types/v9').MessageFlags;
exports.PermissionFlagsBits = require('discord-api-types/v9').PermissionFlagsBits;
exports.RESTJSONErrorCodes = require('discord-api-types/v9').RESTJSONErrorCodes;
exports.StageInstancePrivacyLevel = require('discord-api-types/v9').StageInstancePrivacyLevel;
exports.StickerType = require('discord-api-types/v9').StickerType;
exports.StickerFormatType = require('discord-api-types/v9').StickerFormatType;
exports.UserFlags = require('discord-api-types/v9').UserFlags;
exports.WebhookType = require('discord-api-types/v9').WebhookType;
exports.ActionRow = require('@discordjs/builders').ActionRow;
exports.ButtonComponent = require('@discordjs/builders').ButtonComponent;

View File

@@ -117,7 +117,7 @@ class GuildChannelManager extends CachedManager {
* permissionOverwrites: [
* {
* id: message.author.id,
* deny: [Permissions.FLAGS.VIEW_CHANNEL],
* deny: [PermissionFlagsBits.ViewChannel],
* },
* ],
* })

View File

@@ -14,8 +14,8 @@ const OAuth2Guild = require('../structures/OAuth2Guild');
const { Role } = require('../structures/Role');
const { Events } = require('../util/Constants');
const DataResolver = require('../util/DataResolver');
const Permissions = require('../util/Permissions');
const SystemChannelFlags = require('../util/SystemChannelFlags');
const PermissionsBitField = require('../util/PermissionsBitField');
const SystemChannelFlagsBitField = require('../util/SystemChannelFlagsBitField');
const { resolveColor } = require('../util/Util');
let cacheWarningEmitted = false;
@@ -188,17 +188,17 @@ class GuildManager extends CachedManager {
if (!channel.permissionOverwrites) continue;
for (const overwrite of channel.permissionOverwrites) {
overwrite.allow &&= Permissions.resolve(overwrite.allow).toString();
overwrite.deny &&= Permissions.resolve(overwrite.deny).toString();
overwrite.allow &&= PermissionsBitField.resolve(overwrite.allow).toString();
overwrite.deny &&= PermissionsBitField.resolve(overwrite.deny).toString();
}
channel.permission_overwrites = channel.permissionOverwrites;
delete channel.permissionOverwrites;
}
for (const role of roles) {
role.color &&= resolveColor(role.color);
role.permissions &&= Permissions.resolve(role.permissions).toString();
role.permissions &&= PermissionsBitField.resolve(role.permissions).toString();
}
systemChannelFlags &&= SystemChannelFlags.resolve(systemChannelFlags);
systemChannelFlags &&= SystemChannelFlagsBitField.resolve(systemChannelFlags);
const data = await this.client.rest.post(Routes.guilds(), {
body: {

View File

@@ -58,7 +58,7 @@ class PermissionOverwriteManager extends CachedManager {
* message.channel.permissionOverwrites.set([
* {
* id: message.author.id,
* deny: [Permissions.FLAGS.VIEW_CHANNEL],
* deny: [PermissionsFlagsBit.ViewChannel],
* },
* ], 'Needed to change permissions');
*/

View File

@@ -7,7 +7,7 @@ const CachedManager = require('./CachedManager');
const { TypeError } = require('../errors');
const { Role } = require('../structures/Role');
const DataResolver = require('../util/DataResolver');
const Permissions = require('../util/Permissions');
const PermissionsBitField = require('../util/PermissionsBitField');
const { resolveColor } = require('../util/Util');
let cacheWarningEmitted = false;
@@ -137,7 +137,7 @@ class RoleManager extends CachedManager {
async create(options = {}) {
let { name, color, hoist, permissions, position, mentionable, reason, icon, unicodeEmoji } = options;
color &&= resolveColor(color);
if (typeof permissions !== 'undefined') permissions = new Permissions(permissions);
if (typeof permissions !== 'undefined') permissions = new PermissionsBitField(permissions);
if (icon) {
const guildEmojiURL = this.guild.emojis.resolve(icon)?.url;
icon = guildEmojiURL ? await DataResolver.resolveImage(guildEmojiURL) : await DataResolver.resolveImage(icon);
@@ -195,7 +195,7 @@ class RoleManager extends CachedManager {
name: data.name,
color: typeof data.color === 'undefined' ? undefined : resolveColor(data.color),
hoist: data.hoist,
permissions: typeof data.permissions === 'undefined' ? undefined : new Permissions(data.permissions),
permissions: typeof data.permissions === 'undefined' ? undefined : new PermissionsBitField(data.permissions),
mentionable: data.mentionable,
icon,
unicode_emoji: data.unicodeEmoji,

View File

@@ -95,7 +95,7 @@ class UserManager extends CachedManager {
* Fetches a user's flags.
* @param {UserResolvable} user The UserResolvable to identify
* @param {BaseFetchOptions} [options] Additional options for this fetch
* @returns {Promise<UserFlags>}
* @returns {Promise<UserFlagsBitField>}
*/
async fetchFlags(user, options) {
return (await this.fetch(user, options)).flags;

View File

@@ -1,8 +1,8 @@
'use strict';
const { Collection } = require('@discordjs/collection');
const { PermissionFlagsBits } = require('discord-api-types/v9');
const GuildChannel = require('./GuildChannel');
const Permissions = require('../util/Permissions');
/**
* Represents a voice-based guild channel on Discord.
@@ -72,11 +72,11 @@ class BaseGuildVoiceChannel extends GuildChannel {
if (!permissions) return false;
// This flag allows joining even if timed out
if (permissions.has(Permissions.FLAGS.ADMINISTRATOR, false)) return true;
if (permissions.has(PermissionFlagsBits.Administrator, false)) return true;
return (
this.guild.me.communicationDisabledUntilTimestamp < Date.now() &&
permissions.has(Permissions.FLAGS.CONNECT, false)
permissions.has(PermissionFlagsBits.Connect, false)
);
}

View File

@@ -4,7 +4,7 @@ const { Routes } = require('discord-api-types/v9');
const Team = require('./Team');
const Application = require('./interfaces/Application');
const ApplicationCommandManager = require('../managers/ApplicationCommandManager');
const ApplicationFlags = require('../util/ApplicationFlags');
const ApplicationFlagsBitField = require('../util/ApplicationFlagsBitField');
/**
* Represents a Client OAuth2 Application.
@@ -27,9 +27,9 @@ class ClientApplication extends Application {
if ('flags' in data) {
/**
* The flags this application has
* @type {ApplicationFlags}
* @type {ApplicationFlagsBitField}
*/
this.flags = new ApplicationFlags(data.flags).freeze();
this.flags = new ApplicationFlagsBitField(data.flags).freeze();
}
if ('cover_image' in data) {

View File

@@ -22,9 +22,10 @@ const PresenceManager = require('../managers/PresenceManager');
const RoleManager = require('../managers/RoleManager');
const StageInstanceManager = require('../managers/StageInstanceManager');
const VoiceStateManager = require('../managers/VoiceStateManager');
const { PartialTypes, Status } = require('../util/Constants');
const { Status } = require('../util/Constants');
const DataResolver = require('../util/DataResolver');
const SystemChannelFlags = require('../util/SystemChannelFlags');
const Partials = require('../util/Partials');
const SystemChannelFlagsBitField = require('../util/SystemChannelFlagsBitField');
const Util = require('../util/Util');
/**
@@ -295,9 +296,9 @@ class Guild extends AnonymousGuild {
if ('system_channel_flags' in data) {
/**
* The value set for the guild's system channel flags
* @type {Readonly<SystemChannelFlags>}
* @type {Readonly<SystemChannelFlagsBitField>}
*/
this.systemChannelFlags = new SystemChannelFlags(data.system_channel_flags).freeze();
this.systemChannelFlags = new SystemChannelFlagsBitField(data.system_channel_flags).freeze();
}
if ('max_members' in data) {
@@ -543,7 +544,7 @@ class Guild extends AnonymousGuild {
get me() {
return (
this.members.resolve(this.client.user.id) ??
(this.client.options.partials.includes(PartialTypes.GUILD_MEMBER)
(this.client.options.partials.includes(Partials.GuildMember)
? this.members._add({ user: { id: this.client.user.id } }, true)
: null)
);
@@ -845,7 +846,7 @@ class Guild extends AnonymousGuild {
_data.default_message_notifications = data.defaultMessageNotifications;
}
if (typeof data.systemChannelFlags !== 'undefined') {
_data.system_channel_flags = SystemChannelFlags.resolve(data.systemChannelFlags);
_data.system_channel_flags = SystemChannelFlagsBitField.resolve(data.systemChannelFlags);
}
if (typeof data.rulesChannel !== 'undefined') {
_data.rules_channel_id = this.client.channels.resolveId(data.rulesChannel);

View File

@@ -9,7 +9,7 @@ const Invite = require('./Invite');
const { StageInstance } = require('./StageInstance');
const { Sticker } = require('./Sticker');
const Webhook = require('./Webhook');
const { PartialTypes } = require('../util/Constants');
const Partials = require('../util/Partials');
const Util = require('../util/Util');
/**
@@ -274,7 +274,7 @@ class GuildAuditLogsEntry {
* @type {?User}
*/
this.executor = data.user_id
? guild.client.options.partials.includes(PartialTypes.USER)
? guild.client.options.partials.includes(Partials.User)
? guild.client.users._add({ id: data.user_id })
: guild.client.users.cache.get(data.user_id)
: null;
@@ -384,7 +384,7 @@ class GuildAuditLogsEntry {
this.target.id = data.target_id;
// MEMBER_DISCONNECT and similar types do not provide a target_id.
} else if (targetType === Targets.USER && data.target_id) {
this.target = guild.client.options.partials.includes(PartialTypes.USER)
this.target = guild.client.options.partials.includes(Partials.User)
? guild.client.users._add({ id: data.target_id })
: guild.client.users.cache.get(data.target_id);
} else if (targetType === Targets.GUILD) {

View File

@@ -1,12 +1,12 @@
'use strict';
const { ChannelType, Routes } = require('discord-api-types/v9');
const { ChannelType, Routes, PermissionFlagsBits } = require('discord-api-types/v9');
const { Channel } = require('./Channel');
const PermissionOverwrites = require('./PermissionOverwrites');
const { Error } = require('../errors');
const PermissionOverwriteManager = require('../managers/PermissionOverwriteManager');
const { VoiceBasedChannelTypes } = require('../util/Constants');
const Permissions = require('../util/Permissions');
const PermissionsBitField = require('../util/PermissionsBitField');
const Util = require('../util/Util');
/**
@@ -122,11 +122,11 @@ class GuildChannel extends Channel {
// Handle empty overwrite
if (
(!channelVal &&
parentVal.deny.bitfield === Permissions.defaultBit &&
parentVal.allow.bitfield === Permissions.defaultBit) ||
parentVal.deny.bitfield === PermissionsBitField.defaultBit &&
parentVal.allow.bitfield === PermissionsBitField.defaultBit) ||
(!parentVal &&
channelVal.deny.bitfield === Permissions.defaultBit &&
channelVal.allow.bitfield === Permissions.defaultBit)
channelVal.deny.bitfield === PermissionsBitField.defaultBit &&
channelVal.allow.bitfield === PermissionsBitField.defaultBit)
) {
return true;
}
@@ -155,7 +155,7 @@ class GuildChannel extends Channel {
* Gets the overall set of permissions for a member or role in this channel, taking into account channel overwrites.
* @param {GuildMemberResolvable|RoleResolvable} memberOrRole The member or role to obtain the overall permissions for
* @param {boolean} [checkAdmin=true] Whether having `ADMINISTRATOR` will return all permissions
* @returns {?Readonly<Permissions>}
* @returns {?Readonly<PermissionsBitField>}
*/
permissionsFor(memberOrRole, checkAdmin = true) {
const member = this.guild.members.resolve(memberOrRole);
@@ -194,28 +194,30 @@ class GuildChannel extends Channel {
* Gets the overall set of permissions for a member in this channel, taking into account channel overwrites.
* @param {GuildMember} member The member to obtain the overall permissions for
* @param {boolean} checkAdmin=true Whether having `ADMINISTRATOR` will return all permissions
* @returns {Readonly<Permissions>}
* @returns {Readonly<PermissionsBitField>}
* @private
*/
memberPermissions(member, checkAdmin) {
if (checkAdmin && member.id === this.guild.ownerId) return new Permissions(Permissions.ALL).freeze();
if (checkAdmin && member.id === this.guild.ownerId) {
return new PermissionsBitField(PermissionsBitField.All).freeze();
}
const roles = member.roles.cache;
const permissions = new Permissions(roles.map(role => role.permissions));
const permissions = new PermissionsBitField(roles.map(role => role.permissions));
if (checkAdmin && permissions.has(Permissions.FLAGS.ADMINISTRATOR)) {
return new Permissions(Permissions.ALL).freeze();
if (checkAdmin && permissions.has(PermissionFlagsBits.Administrator)) {
return new PermissionsBitField(PermissionsBitField.All).freeze();
}
const overwrites = this.overwritesFor(member, true, roles);
return permissions
.remove(overwrites.everyone?.deny ?? Permissions.defaultBit)
.add(overwrites.everyone?.allow ?? Permissions.defaultBit)
.remove(overwrites.roles.length > 0 ? overwrites.roles.map(role => role.deny) : Permissions.defaultBit)
.add(overwrites.roles.length > 0 ? overwrites.roles.map(role => role.allow) : Permissions.defaultBit)
.remove(overwrites.member?.deny ?? Permissions.defaultBit)
.add(overwrites.member?.allow ?? Permissions.defaultBit)
.remove(overwrites.everyone?.deny ?? PermissionsBitField.defaultBit)
.add(overwrites.everyone?.allow ?? PermissionsBitField.defaultBit)
.remove(overwrites.roles.length > 0 ? overwrites.roles.map(role => role.deny) : PermissionsBitField.defaultBit)
.add(overwrites.roles.length > 0 ? overwrites.roles.map(role => role.allow) : PermissionsBitField.defaultBit)
.remove(overwrites.member?.deny ?? PermissionsBitField.defaultBit)
.add(overwrites.member?.allow ?? PermissionsBitField.defaultBit)
.freeze();
}
@@ -223,22 +225,22 @@ class GuildChannel extends Channel {
* Gets the overall set of permissions for a role in this channel, taking into account channel overwrites.
* @param {Role} role The role to obtain the overall permissions for
* @param {boolean} checkAdmin Whether having `ADMINISTRATOR` will return all permissions
* @returns {Readonly<Permissions>}
* @returns {Readonly<PermissionsBitField>}
* @private
*/
rolePermissions(role, checkAdmin) {
if (checkAdmin && role.permissions.has(Permissions.FLAGS.ADMINISTRATOR)) {
return new Permissions(Permissions.ALL).freeze();
if (checkAdmin && role.permissions.has(PermissionFlagsBits.Administrator)) {
return new PermissionsBitField(PermissionsBitField.All).freeze();
}
const everyoneOverwrites = this.permissionOverwrites.cache.get(this.guild.id);
const roleOverwrites = this.permissionOverwrites.cache.get(role.id);
return role.permissions
.remove(everyoneOverwrites?.deny ?? Permissions.defaultBit)
.add(everyoneOverwrites?.allow ?? Permissions.defaultBit)
.remove(roleOverwrites?.deny ?? Permissions.defaultBit)
.add(roleOverwrites?.allow ?? Permissions.defaultBit)
.remove(everyoneOverwrites?.deny ?? PermissionsBitField.defaultBit)
.add(everyoneOverwrites?.allow ?? PermissionsBitField.defaultBit)
.remove(roleOverwrites?.deny ?? PermissionsBitField.defaultBit)
.add(roleOverwrites?.allow ?? PermissionsBitField.defaultBit)
.freeze();
}
@@ -260,7 +262,7 @@ class GuildChannel extends Channel {
* @readonly
*/
get members() {
return this.guild.members.cache.filter(m => this.permissionsFor(m).has(Permissions.FLAGS.VIEW_CHANNEL, false));
return this.guild.members.cache.filter(m => this.permissionsFor(m).has(PermissionFlagsBits.ViewChannel, false));
}
/**
@@ -503,12 +505,12 @@ class GuildChannel extends Channel {
if (!permissions) return false;
// This flag allows managing even if timed out
if (permissions.has(Permissions.FLAGS.ADMINISTRATOR, false)) return true;
if (permissions.has(PermissionFlagsBits.Administrator, false)) return true;
if (this.guild.me.communicationDisabledUntilTimestamp > Date.now()) return false;
const bitfield = VoiceBasedChannelTypes.includes(this.type)
? Permissions.FLAGS.MANAGE_CHANNELS | Permissions.FLAGS.CONNECT
: Permissions.FLAGS.VIEW_CHANNEL | Permissions.FLAGS.MANAGE_CHANNELS;
? PermissionFlagsBits.ManageChannels | PermissionFlagsBits.Connect
: PermissionFlagsBits.ViewChannel | PermissionFlagsBits.ManageChannels;
return permissions.has(bitfield, false);
}
@@ -521,7 +523,7 @@ class GuildChannel extends Channel {
if (this.client.user.id === this.guild.ownerId) return true;
const permissions = this.permissionsFor(this.client.user);
if (!permissions) return false;
return permissions.has(Permissions.FLAGS.VIEW_CHANNEL, false);
return permissions.has(PermissionFlagsBits.ViewChannel, false);
}
/**

View File

@@ -1,10 +1,9 @@
'use strict';
const { Routes } = require('discord-api-types/v9');
const { Routes, PermissionFlagsBits } = require('discord-api-types/v9');
const BaseGuildEmoji = require('./BaseGuildEmoji');
const { Error } = require('../errors');
const GuildEmojiRoleManager = require('../managers/GuildEmojiRoleManager');
const Permissions = require('../util/Permissions');
/**
* Represents a custom emoji.
@@ -57,7 +56,7 @@ class GuildEmoji extends BaseGuildEmoji {
*/
get deletable() {
if (!this.guild.me) throw new Error('GUILD_UNCACHED_ME');
return !this.managed && this.guild.me.permissions.has(Permissions.FLAGS.MANAGE_EMOJIS_AND_STICKERS);
return !this.managed && this.guild.me.permissions.has(PermissionFlagsBits.ManageEmojisAndStickers);
}
/**
@@ -78,7 +77,7 @@ class GuildEmoji extends BaseGuildEmoji {
throw new Error('EMOJI_MANAGED');
} else {
if (!this.guild.me) throw new Error('GUILD_UNCACHED_ME');
if (!this.guild.me.permissions.has(Permissions.FLAGS.MANAGE_EMOJIS_AND_STICKERS)) {
if (!this.guild.me.permissions.has(PermissionFlagsBits.ManageEmojisAndStickers)) {
throw new Error('MISSING_MANAGE_EMOJIS_AND_STICKERS_PERMISSION', this.guild);
}
}

View File

@@ -1,11 +1,12 @@
'use strict';
const { PermissionFlagsBits } = require('discord-api-types/v9');
const Base = require('./Base');
const VoiceState = require('./VoiceState');
const TextBasedChannel = require('./interfaces/TextBasedChannel');
const { Error } = require('../errors');
const GuildMemberRoleManager = require('../managers/GuildMemberRoleManager');
const Permissions = require('../util/Permissions');
const PermissionsBitField = require('../util/PermissionsBitField');
/**
* Represents a member of a guild on Discord.
@@ -214,12 +215,12 @@ class GuildMember extends Base {
/**
* The overall set of permissions for this member, taking only roles and owner status into account
* @type {Readonly<Permissions>}
* @type {Readonly<PermissionsBitField>}
* @readonly
*/
get permissions() {
if (this.user.id === this.guild.ownerId) return new Permissions(Permissions.ALL).freeze();
return new Permissions(this.roles.cache.map(role => role.permissions)).freeze();
if (this.user.id === this.guild.ownerId) return new PermissionsBitField(PermissionsBitField.All).freeze();
return new PermissionsBitField(this.roles.cache.map(role => role.permissions)).freeze();
}
/**
@@ -243,7 +244,7 @@ class GuildMember extends Base {
*/
get kickable() {
if (!this.guild.me) throw new Error('GUILD_UNCACHED_ME');
return this.manageable && this.guild.me.permissions.has(Permissions.FLAGS.KICK_MEMBERS);
return this.manageable && this.guild.me.permissions.has(PermissionFlagsBits.KickMembers);
}
/**
@@ -253,7 +254,7 @@ class GuildMember extends Base {
*/
get bannable() {
if (!this.guild.me) throw new Error('GUILD_UNCACHED_ME');
return this.manageable && this.guild.me.permissions.has(Permissions.FLAGS.BAN_MEMBERS);
return this.manageable && this.guild.me.permissions.has(PermissionFlagsBits.BanMembers);
}
/**
@@ -262,7 +263,7 @@ class GuildMember extends Base {
* @readonly
*/
get moderatable() {
return this.manageable && (this.guild.me?.permissions.has(Permissions.FLAGS.MODERATE_MEMBERS) ?? false);
return this.manageable && (this.guild.me?.permissions.has(PermissionFlagsBits.ModerateMembers) ?? false);
}
/**
@@ -277,7 +278,7 @@ class GuildMember extends Base {
* Returns `channel.permissionsFor(guildMember)`. Returns permissions for a member in a guild channel,
* taking into account roles and permission overwrites.
* @param {GuildChannelResolvable} channel The guild channel to use as context
* @returns {Readonly<Permissions>}
* @returns {Readonly<PermissionsBitField>}
*/
permissionsIn(channel) {
channel = this.guild.channels.resolve(channel);

View File

@@ -3,7 +3,7 @@
const { DiscordSnowflake } = require('@sapphire/snowflake');
const { InteractionType, ApplicationCommandType, ComponentType } = require('discord-api-types/v9');
const Base = require('./Base');
const Permissions = require('../util/Permissions');
const PermissionsBitField = require('../util/PermissionsBitField');
/**
* Represents an interaction.
@@ -71,9 +71,11 @@ class Interaction extends Base {
/**
* The permissions of the member, if one exists, in the channel this interaction was executed in
* @type {?Readonly<Permissions>}
* @type {?Readonly<PermissionsBitField>}
*/
this.memberPermissions = data.member?.permissions ? new Permissions(data.member.permissions).freeze() : null;
this.memberPermissions = data.member?.permissions
? new PermissionsBitField(data.member.permissions).freeze()
: null;
/**
* The locale of the user who invoked this interaction

View File

@@ -1,12 +1,11 @@
'use strict';
const { RouteBases, Routes } = require('discord-api-types/v9');
const { RouteBases, Routes, PermissionFlagsBits } = require('discord-api-types/v9');
const Base = require('./Base');
const { GuildScheduledEvent } = require('./GuildScheduledEvent');
const IntegrationApplication = require('./IntegrationApplication');
const InviteStageInstance = require('./InviteStageInstance');
const { Error } = require('../errors');
const Permissions = require('../util/Permissions');
/**
* Represents an invitation to a guild channel.
@@ -226,8 +225,8 @@ class Invite extends Base {
if (!guild || !this.client.guilds.cache.has(guild.id)) return false;
if (!guild.me) throw new Error('GUILD_UNCACHED_ME');
return Boolean(
this.channel?.permissionsFor(this.client.user).has(Permissions.FLAGS.MANAGE_CHANNELS, false) ||
guild.me.permissions.has(Permissions.FLAGS.MANAGE_GUILD),
this.channel?.permissionsFor(this.client.user).has(PermissionFlagsBits.ManageChannels, false) ||
guild.me.permissions.has(PermissionFlagsBits.ManageGuild),
);
}

View File

@@ -3,7 +3,13 @@
const { createComponent, Embed } = require('@discordjs/builders');
const { Collection } = require('@discordjs/collection');
const { DiscordSnowflake } = require('@sapphire/snowflake');
const { InteractionType, ChannelType, MessageType } = require('discord-api-types/v9');
const {
InteractionType,
ChannelType,
MessageType,
MessageFlags,
PermissionFlagsBits,
} = require('discord-api-types/v9');
const Base = require('./Base');
const ClientApplication = require('./ClientApplication');
const InteractionCollector = require('./InteractionCollector');
@@ -15,8 +21,8 @@ const { Sticker } = require('./Sticker');
const { Error } = require('../errors');
const ReactionManager = require('../managers/ReactionManager');
const { NonSystemMessageTypes } = require('../util/Constants');
const MessageFlags = require('../util/MessageFlags');
const Permissions = require('../util/Permissions');
const MessageFlagsBitField = require('../util/MessageFlagsBitField');
const PermissionsBitField = require('../util/PermissionsBitField');
const Util = require('../util/Util');
/**
@@ -277,17 +283,17 @@ class Message extends Base {
if ('flags' in data) {
/**
* Flags that are applied to the message
* @type {Readonly<MessageFlags>}
* @type {Readonly<MessageFlagsBitField>}
*/
this.flags = new MessageFlags(data.flags).freeze();
this.flags = new MessageFlagsBitField(data.flags).freeze();
} else {
this.flags = new MessageFlags(this.flags).freeze();
this.flags = new MessageFlagsBitField(this.flags).freeze();
}
/**
* Reference data sent in a message that contains ids identifying the referenced message.
* This can be present in the following types of message:
* * Crossposted messages (IS_CROSSPOST {@link MessageFlags.FLAGS message flag})
* * Crossposted messages (`MessageFlags.Crossposted`)
* * {@link MessageType.ChannelFollowAdd}
* * {@link MessageType.ChannelPinnedMessage}
* * {@link MessageType.Reply}
@@ -403,7 +409,7 @@ class Message extends Base {
* @readonly
*/
get hasThread() {
return this.flags.has(MessageFlags.FLAGS.HAS_THREAD);
return this.flags.has(MessageFlags.HasThread);
}
/**
@@ -571,11 +577,11 @@ class Message extends Base {
const permissions = this.channel?.permissionsFor(this.client.user);
if (!permissions) return false;
// This flag allows deleting even if timed out
if (permissions.has(Permissions.FLAGS.ADMINISTRATOR, false)) return true;
if (permissions.has(PermissionFlagsBits.Administrator, false)) return true;
return Boolean(
this.author.id === this.client.user.id ||
(permissions.has(Permissions.FLAGS.MANAGE_MESSAGES, false) &&
(permissions.has(PermissionFlagsBits.ManageMessages, false) &&
this.guild.me.communicationDisabledUntilTimestamp < Date.now()),
);
}
@@ -591,7 +597,7 @@ class Message extends Base {
!this.system &&
(!this.guild ||
(channel?.viewable &&
channel?.permissionsFor(this.client.user)?.has(Permissions.FLAGS.MANAGE_MESSAGES, false))),
channel?.permissionsFor(this.client.user)?.has(PermissionFlagsBits.ManageMessages, false))),
);
}
@@ -615,12 +621,12 @@ class Message extends Base {
*/
get crosspostable() {
const bitfield =
Permissions.FLAGS.SEND_MESSAGES |
(this.author.id === this.client.user.id ? Permissions.defaultBit : Permissions.FLAGS.MANAGE_MESSAGES);
PermissionFlagsBits.SendMessages |
(this.author.id === this.client.user.id ? PermissionsBitField.defaultBit : PermissionFlagsBits.ManageMessages);
const { channel } = this;
return Boolean(
channel?.type === ChannelType.GuildNews &&
!this.flags.has(MessageFlags.FLAGS.CROSSPOSTED) &&
!this.flags.has(MessageFlags.Crossposted) &&
this.type === MessageType.Default &&
channel.viewable &&
channel.permissionsFor(this.client.user)?.has(bitfield, false),
@@ -633,7 +639,8 @@ class Message extends Base {
* @property {?string} [content] Content to be edited
* @property {Embed[]|APIEmbed[]} [embeds] Embeds to be added/edited
* @property {MessageMentionOptions} [allowedMentions] Which mentions should be parsed from the message content
* @property {MessageFlags} [flags] Which flags to set for the message. Only `SUPPRESS_EMBEDS` can be edited.
* @property {MessageFlags} [flags] Which flags to set for the message.
* Only `MessageFlags.SuppressEmbeds` can be edited.
* @property {MessageAttachment[]} [attachments] An array of attachments to keep,
* all attachments will be kept if omitted
* @property {FileOptions[]|BufferResolvable[]|MessageAttachment[]} [files] Files to add to the message
@@ -844,12 +851,12 @@ class Message extends Base {
* @returns {Promise<Message>}
*/
suppressEmbeds(suppress = true) {
const flags = new MessageFlags(this.flags.bitfield);
const flags = new MessageFlagsBitField(this.flags.bitfield);
if (suppress) {
flags.add(MessageFlags.FLAGS.SUPPRESS_EMBEDS);
flags.add(MessageFlags.SuppressEmbeds);
} else {
flags.remove(MessageFlags.FLAGS.SUPPRESS_EMBEDS);
flags.remove(MessageFlags.SuppressEmbeds);
}
return this.edit({ flags });

View File

@@ -5,6 +5,7 @@ const { createComponent, Embed } = require('@discordjs/builders');
const { MessageFlags } = require('discord-api-types/v9');
const { RangeError } = require('../errors');
const DataResolver = require('../util/DataResolver');
const MessageFlagsBitField = require('../util/MessageFlagsBitField');
const Util = require('../util/Util');
/**
@@ -141,8 +142,11 @@ class MessagePayload {
let flags;
if (typeof this.options.flags !== 'undefined' || this.isMessage || this.isMessageManager) {
// eslint-disable-next-line eqeqeq
flags = this.options.flags != null ? new MessageFlags(this.options.flags).bitfield : this.target.flags?.bitfield;
flags =
// eslint-disable-next-line eqeqeq
this.options.flags != null
? new MessageFlagsBitField(this.options.flags).bitfield
: this.target.flags?.bitfield;
}
if (isInteraction && this.options.ephemeral) {

View File

@@ -1,7 +1,7 @@
'use strict';
const BaseGuild = require('./BaseGuild');
const Permissions = require('../util/Permissions');
const PermissionsBitField = require('../util/PermissionsBitField');
/**
* A partial guild received when using {@link GuildManager#fetch} to fetch multiple guilds.
@@ -19,9 +19,9 @@ class OAuth2Guild extends BaseGuild {
/**
* The permissions that the client user has in this guild
* @type {Readonly<Permissions>}
* @type {Readonly<PermissionsBitField>}
*/
this.permissions = new Permissions(BigInt(data.permissions)).freeze();
this.permissions = new PermissionsBitField(BigInt(data.permissions)).freeze();
}
}

View File

@@ -4,7 +4,7 @@ const { OverwriteType } = require('discord-api-types/v9');
const Base = require('./Base');
const { Role } = require('./Role');
const { TypeError } = require('../errors');
const Permissions = require('../util/Permissions');
const PermissionsBitField = require('../util/PermissionsBitField');
/**
* Represents a permission overwrite for a role or member in a guild channel.
@@ -43,17 +43,17 @@ class PermissionOverwrites extends Base {
if ('deny' in data) {
/**
* The permissions that are denied for the user or role.
* @type {Readonly<Permissions>}
* @type {Readonly<PermissionsBitField>}
*/
this.deny = new Permissions(BigInt(data.deny)).freeze();
this.deny = new PermissionsBitField(BigInt(data.deny)).freeze();
}
if ('allow' in data) {
/**
* The permissions that are allowed for the user or role.
* @type {Readonly<Permissions>}
* @type {Readonly<PermissionsBitField>}
*/
this.allow = new Permissions(BigInt(data.allow)).freeze();
this.allow = new PermissionsBitField(BigInt(data.allow)).freeze();
}
}
@@ -98,9 +98,9 @@ class PermissionOverwrites extends Base {
* An object mapping permission flags to `true` (enabled), `null` (unset) or `false` (disabled).
* ```js
* {
* 'SEND_MESSAGES': true,
* 'EMBED_LINKS': null,
* 'ATTACH_FILES': false,
* 'SendMessages': true,
* 'EmbedLinks': null,
* 'AttachFiles': false,
* }
* ```
* @typedef {Object} PermissionOverwriteOptions
@@ -108,8 +108,8 @@ class PermissionOverwrites extends Base {
/**
* @typedef {Object} ResolvedOverwriteOptions
* @property {Permissions} allow The allowed permissions
* @property {Permissions} deny The denied permissions
* @property {PermissionsBitField} allow The allowed permissions
* @property {PermissionsBitField} deny The denied permissions
*/
/**
@@ -119,8 +119,8 @@ class PermissionOverwrites extends Base {
* @returns {ResolvedOverwriteOptions}
*/
static resolveOverwriteOptions(options, { allow, deny } = {}) {
allow = new Permissions(allow);
deny = new Permissions(deny);
allow = new PermissionsBitField(allow);
deny = new PermissionsBitField(deny);
for (const [perm, value] of Object.entries(options)) {
if (value === true) {
@@ -175,8 +175,8 @@ class PermissionOverwrites extends Base {
return {
id: overwrite.id,
type: overwrite.type,
allow: Permissions.resolve(overwrite.allow ?? Permissions.defaultBit).toString(),
deny: Permissions.resolve(overwrite.deny ?? Permissions.defaultBit).toString(),
allow: PermissionsBitField.resolve(overwrite.allow ?? PermissionsBitField.defaultBit).toString(),
deny: PermissionsBitField.resolve(overwrite.deny ?? PermissionsBitField.defaultBit).toString(),
};
}
@@ -187,8 +187,8 @@ class PermissionOverwrites extends Base {
return {
id: userOrRole.id,
type,
allow: Permissions.resolve(overwrite.allow ?? Permissions.defaultBit).toString(),
deny: Permissions.resolve(overwrite.deny ?? Permissions.defaultBit).toString(),
allow: PermissionsBitField.resolve(overwrite.allow ?? PermissionsBitField.defaultBit).toString(),
deny: PermissionsBitField.resolve(overwrite.deny ?? PermissionsBitField.defaultBit).toString(),
};
}
}

View File

@@ -2,7 +2,7 @@
const Base = require('./Base');
const { Emoji } = require('./Emoji');
const ActivityFlags = require('../util/ActivityFlags');
const ActivityFlagsBitField = require('../util/ActivityFlagsBitField');
const Util = require('../util/Util');
/**
@@ -244,9 +244,9 @@ class Activity {
/**
* Flags that describe the activity
* @type {Readonly<ActivityFlags>}
* @type {Readonly<ActivityFlagsBitField>}
*/
this.flags = new ActivityFlags(data.flags).freeze();
this.flags = new ActivityFlagsBitField(data.flags).freeze();
/**
* Emoji for a custom activity

View File

@@ -1,10 +1,10 @@
'use strict';
const { DiscordSnowflake } = require('@sapphire/snowflake');
const { Routes } = require('discord-api-types/v9');
const { Routes, PermissionFlagsBits } = require('discord-api-types/v9');
const Base = require('./Base');
const { Error } = require('../errors');
const Permissions = require('../util/Permissions');
const PermissionsBitField = require('../util/PermissionsBitField');
const Util = require('../util/Util');
/**
@@ -77,9 +77,9 @@ class Role extends Base {
if ('permissions' in data) {
/**
* The permissions of the role
* @type {Readonly<Permissions>}
* @type {Readonly<PermissionsBitField>}
*/
this.permissions = new Permissions(BigInt(data.permissions)).freeze();
this.permissions = new PermissionsBitField(BigInt(data.permissions)).freeze();
}
if ('managed' in data) {
@@ -167,7 +167,7 @@ class Role extends Base {
get editable() {
if (this.managed) return false;
const clientMember = this.guild.members.resolve(this.client.user);
if (!clientMember.permissions.has(Permissions.FLAGS.MANAGE_ROLES)) return false;
if (!clientMember.permissions.has(PermissionFlagsBits.ManageRoles)) return false;
return clientMember.roles.highest.comparePositionTo(this) > 0;
}
@@ -226,7 +226,7 @@ class Role extends Base {
* taking into account permission overwrites.
* @param {GuildChannel|Snowflake} channel The guild channel to use as context
* @param {boolean} [checkAdmin=true] Whether having `ADMINISTRATOR` will return all permissions
* @returns {Readonly<Permissions>}
* @returns {Readonly<PermissionsBitField>}
*/
permissionsIn(channel, checkAdmin = true) {
channel = this.guild.channels.resolve(channel);
@@ -286,7 +286,7 @@ class Role extends Base {
* @returns {Promise<Role>}
* @example
* // Set the permissions of the role
* role.setPermissions([Permissions.FLAGS.KICK_MEMBERS, Permissions.FLAGS.BAN_MEMBERS])
* role.setPermissions([PermissionFlagsBits.KickMembers, PermissionFlagsBits.BanMembers])
* .then(updated => console.log(`Updated permissions to ${updated.permissions.bitfield}`))
* .catch(console.error);
* @example

View File

@@ -1,12 +1,11 @@
'use strict';
const { ChannelType, Routes } = require('discord-api-types/v9');
const { ChannelType, PermissionFlagsBits, Routes } = require('discord-api-types/v9');
const { Channel } = require('./Channel');
const TextBasedChannel = require('./interfaces/TextBasedChannel');
const { RangeError } = require('../errors');
const MessageManager = require('../managers/MessageManager');
const ThreadMemberManager = require('../managers/ThreadMemberManager');
const Permissions = require('../util/Permissions');
/**
* Represents a thread channel on Discord.
@@ -254,7 +253,7 @@ class ThreadChannel extends Channel {
* account.
* @param {GuildMemberResolvable|RoleResolvable} memberOrRole The member or role to obtain the overall permissions for
* @param {boolean} [checkAdmin=true] Whether having `ADMINISTRATOR` will return all permissions
* @returns {?Readonly<Permissions>}
* @returns {?Readonly<PermissionsBitField>}
*/
permissionsFor(memberOrRole, checkAdmin) {
return this.parent?.permissionsFor(memberOrRole, checkAdmin) ?? null;
@@ -457,8 +456,8 @@ class ThreadChannel extends Channel {
!this.joined &&
this.permissionsFor(this.client.user)?.has(
this.type === ChannelType.GuildPrivateThread
? Permissions.FLAGS.MANAGE_THREADS
: Permissions.FLAGS.VIEW_CHANNEL,
? PermissionFlagsBits.ManageThreads
: PermissionFlagsBits.ViewChannel,
false,
)
);
@@ -473,11 +472,11 @@ class ThreadChannel extends Channel {
const permissions = this.permissionsFor(this.client.user);
if (!permissions) return false;
// This flag allows managing even if timed out
if (permissions.has(Permissions.FLAGS.ADMINISTRATOR, false)) return true;
if (permissions.has(PermissionFlagsBits.Administrator, false)) return true;
return (
this.guild.me.communicationDisabledUntilTimestamp < Date.now() &&
permissions.has(Permissions.FLAGS.MANAGE_THREADS, false)
permissions.has(PermissionFlagsBits.ManageThreads, false)
);
}
@@ -490,7 +489,7 @@ class ThreadChannel extends Channel {
if (this.client.user.id === this.guild.ownerId) return true;
const permissions = this.permissionsFor(this.client.user);
if (!permissions) return false;
return permissions.has(Permissions.FLAGS.VIEW_CHANNEL, false);
return permissions.has(PermissionFlagsBits.ViewChannel, false);
}
/**
@@ -502,12 +501,12 @@ class ThreadChannel extends Channel {
const permissions = this.permissionsFor(this.client.user);
if (!permissions) return false;
// This flag allows sending even if timed out
if (permissions.has(Permissions.FLAGS.ADMINISTRATOR, false)) return true;
if (permissions.has(PermissionFlagsBits.Administrator, false)) return true;
return (
!(this.archived && this.locked && !this.manageable) &&
(this.type !== ChannelType.GuildPrivateThread || this.joined || this.manageable) &&
permissions.has(Permissions.FLAGS.SEND_MESSAGES_IN_THREADS, false) &&
permissions.has(PermissionFlagsBits.SendMessagesInThreads, false) &&
this.guild.me.communicationDisabledUntilTimestamp < Date.now()
);
}

View File

@@ -1,7 +1,7 @@
'use strict';
const Base = require('./Base');
const ThreadMemberFlags = require('../util/ThreadMemberFlags');
const ThreadMemberFlagsBitField = require('../util/ThreadMemberFlagsBitField');
/**
* Represents a Member for a Thread.
@@ -38,9 +38,9 @@ class ThreadMember extends Base {
if ('flags' in data) {
/**
* The flags for this thread member
* @type {ThreadMemberFlags}
* @type {ThreadMemberFlagsBitField}
*/
this.flags = new ThreadMemberFlags(data.flags).freeze();
this.flags = new ThreadMemberFlagsBitField(data.flags).freeze();
}
}

View File

@@ -3,7 +3,7 @@
const { DiscordSnowflake } = require('@sapphire/snowflake');
const Base = require('./Base');
const TextBasedChannel = require('./interfaces/TextBasedChannel');
const UserFlags = require('../util/UserFlags');
const UserFlagsBitField = require('../util/UserFlagsBitField');
/**
* Represents a user on Discord.
@@ -105,9 +105,9 @@ class User extends Base {
if ('public_flags' in data) {
/**
* The flags for this user
* @type {?UserFlags}
* @type {?UserFlagsBitField}
*/
this.flags = new UserFlags(data.public_flags);
this.flags = new UserFlagsBitField(data.public_flags);
}
}
@@ -263,7 +263,7 @@ class User extends Base {
/**
* Fetches this user's flags.
* @param {boolean} [force=false] Whether to skip the cache check and request the API
* @returns {Promise<UserFlags>}
* @returns {Promise<UserFlagsBitField>}
*/
fetchFlags(force = false) {
return this.client.users.fetchFlags(this.id, { force });

View File

@@ -1,7 +1,7 @@
'use strict';
const { PermissionFlagsBits } = require('discord-api-types/v9');
const BaseGuildVoiceChannel = require('./BaseGuildVoiceChannel');
const Permissions = require('../util/Permissions');
/**
* Represents a guild voice channel on Discord.
@@ -15,7 +15,7 @@ class VoiceChannel extends BaseGuildVoiceChannel {
*/
get joinable() {
if (!super.joinable) return false;
if (this.full && !this.permissionsFor(this.client.user).has(Permissions.FLAGS.MOVE_MEMBERS, false)) return false;
if (this.full && !this.permissionsFor(this.client.user).has(PermissionFlagsBits.MoveMembers, false)) return false;
return true;
}
@@ -28,10 +28,11 @@ class VoiceChannel extends BaseGuildVoiceChannel {
const permissions = this.permissionsFor(this.client.user);
if (!permissions) return false;
// This flag allows speaking even if timed out
if (permissions.has(Permissions.FLAGS.ADMINISTRATOR, false)) return true;
if (permissions.has(PermissionFlagsBits.Administrator, false)) return true;
return (
this.guild.me.communicationDisabledUntilTimestamp < Date.now() && permissions.has(Permissions.FLAGS.SPEAK, false)
this.guild.me.communicationDisabledUntilTimestamp < Date.now() &&
permissions.has(PermissionFlagsBits.Speak, false)
);
}

View File

@@ -1,8 +1,7 @@
'use strict';
const { InteractionResponseType, Routes } = require('discord-api-types/v9');
const { InteractionResponseType, MessageFlags, Routes } = require('discord-api-types/v9');
const { Error } = require('../../errors');
const MessageFlags = require('../../util/MessageFlags');
const MessagePayload = require('../MessagePayload');
/**
@@ -29,7 +28,7 @@ class InteractionResponses {
* @property {boolean} [ephemeral] Whether the reply should be ephemeral
* @property {boolean} [fetchReply] Whether to fetch the reply
* @property {MessageFlags} [flags] Which flags to set for the message.
* Only `SUPPRESS_EMBEDS` and `EPHEMERAL` can be set.
* Only `MessageFlags.SuppressEmbeds` and `MessageFlags.Ephemeral` can be set.
*/
/**
@@ -60,7 +59,7 @@ class InteractionResponses {
body: {
type: InteractionResponseType.DeferredChannelMessageWithSource,
data: {
flags: options.ephemeral ? MessageFlags.FLAGS.EPHEMERAL : undefined,
flags: options.ephemeral ? MessageFlags.Ephemeral : undefined,
},
},
auth: false,

View File

@@ -72,7 +72,7 @@ class TextBasedChannel {
* @typedef {BaseMessageOptions} MessageOptions
* @property {ReplyOptions} [reply] The options for replying to a message
* @property {StickerResolvable[]} [stickers=[]] Stickers to send in the message
* @property {MessageFlags} [flags] Which flags to set for the message. Only `SUPPRESS_EMBEDS` can be set.
* @property {MessageFlags} [flags] Which flags to set for the message. Only `MessageFlags.SuppressEmbeds` can be set.
*/
/**

View File

@@ -1,44 +0,0 @@
'use strict';
const BitField = require('./BitField');
/**
* Data structure that makes it easy to interact with an {@link Activity#flags} bitfield.
* @extends {BitField}
*/
class ActivityFlags extends BitField {}
/**
* @name ActivityFlags
* @kind constructor
* @memberof ActivityFlags
* @param {BitFieldResolvable} [bits=0] Bit(s) to read from
*/
/**
* Numeric activity flags. All available properties:
* * `INSTANCE`
* * `JOIN`
* * `SPECTATE`
* * `JOIN_REQUEST`
* * `SYNC`
* * `PLAY`
* * `PARTY_PRIVACY_FRIENDS`
* * `PARTY_PRIVACY_VOICE_CHANNEL`
* * `EMBEDDED`
* @type {Object}
* @see {@link https://discord.com/developers/docs/topics/gateway#activity-object-activity-flags}
*/
ActivityFlags.FLAGS = {
INSTANCE: 1 << 0,
JOIN: 1 << 1,
SPECTATE: 1 << 2,
JOIN_REQUEST: 1 << 3,
SYNC: 1 << 4,
PLAY: 1 << 5,
PARTY_PRIVACY_FRIENDS: 1 << 6,
PARTY_PRIVACY_VOICE_CHANNEL: 1 << 7,
EMBEDDED: 1 << 8,
};
module.exports = ActivityFlags;

View File

@@ -0,0 +1,25 @@
'use strict';
const { ActivityFlags } = require('discord-api-types/v9');
const BitField = require('./BitField');
/**
* Data structure that makes it easy to interact with an {@link Activity#flags} bitfield.
* @extends {BitField}
*/
class ActivityFlagsBitField extends BitField {}
/**
* @name ActivityFlagsBitField
* @kind constructor
* @memberof ActivityFlagsBitField
* @param {BitFieldResolvable} [bits=0] Bit(s) to read from
*/
/**
* Numeric activity flags.
* @type {ActivityFlags}
*/
ActivityFlagsBitField.Flags = ActivityFlags;
module.exports = ActivityFlagsBitField;

View File

@@ -1,48 +0,0 @@
'use strict';
const BitField = require('./BitField');
/**
* Data structure that makes it easy to interact with a {@link ClientApplication#flags} bitfield.
* @extends {BitField}
*/
class ApplicationFlags extends BitField {}
/**
* @name ApplicationFlags
* @kind constructor
* @memberof ApplicationFlags
* @param {BitFieldResolvable} [bits=0] Bit(s) to read from
*/
/**
* Bitfield of the packed bits
* @type {number}
* @name ApplicationFlags#bitfield
*/
/**
* Numeric application flags. All available properties:
* * `GATEWAY_PRESENCE`
* * `GATEWAY_PRESENCE_LIMITED`
* * `GATEWAY_GUILD_MEMBERS`
* * `GATEWAY_GUILD_MEMBERS_LIMITED`
* * `VERIFICATION_PENDING_GUILD_LIMIT`
* * `EMBEDDED`
* * `GATEWAY_MESSAGE_CONTENT`
* * `GATEWAY_MESSAGE_CONTENT_LIMITED`
* @type {Object}
* @see {@link https://discord.com/developers/docs/resources/application#application-object-application-flags}
*/
ApplicationFlags.FLAGS = {
GATEWAY_PRESENCE: 1 << 12,
GATEWAY_PRESENCE_LIMITED: 1 << 13,
GATEWAY_GUILD_MEMBERS: 1 << 14,
GATEWAY_GUILD_MEMBERS_LIMITED: 1 << 15,
VERIFICATION_PENDING_GUILD_LIMIT: 1 << 16,
EMBEDDED: 1 << 17,
GATEWAY_MESSAGE_CONTENT: 1 << 18,
GATEWAY_MESSAGE_CONTENT_LIMITED: 1 << 19,
};
module.exports = ApplicationFlags;

View File

@@ -0,0 +1,31 @@
'use strict';
const { ApplicationFlags } = require('discord-api-types/v9');
const BitField = require('./BitField');
/**
* Data structure that makes it easy to interact with a {@link ClientApplication#flags} bitfield.
* @extends {BitField}
*/
class ApplicationFlagsBitField extends BitField {}
/**
* @name ApplicationFlagsBitField
* @kind constructor
* @memberof ApplicationFlagsBitField
* @param {BitFieldResolvable} [bits=0] Bit(s) to read from
*/
/**
* Bitfield of the packed bits
* @type {number}
* @name ApplicationFlagsBitField#bitfield
*/
/**
* Numeric application flags. All available properties:
* @type {ApplicationFlags}
*/
ApplicationFlagsBitField.Flags = ApplicationFlags;
module.exports = ApplicationFlagsBitField;

View File

@@ -101,7 +101,7 @@ class BitField {
*/
serialize(...hasParams) {
const serialized = {};
for (const [flag, bit] of Object.entries(this.constructor.FLAGS)) serialized[flag] = this.has(bit, ...hasParams);
for (const [flag, bit] of Object.entries(this.constructor.Flags)) serialized[flag] = this.has(bit, ...hasParams);
return serialized;
}
@@ -111,7 +111,7 @@ class BitField {
* @returns {string[]}
*/
toArray(...hasParams) {
return Object.keys(this.constructor.FLAGS).filter(bit => this.has(bit, ...hasParams));
return Object.keys(this.constructor.Flags).filter(bit => this.has(bit, ...hasParams));
}
toJSON() {
@@ -128,7 +128,7 @@ class BitField {
/**
* Data that can be resolved to give a bitfield. This can be:
* * A bit number (this can be a number literal or a value taken from {@link BitField.FLAGS})
* * A bit number (this can be a number literal or a value taken from {@link BitField.Flags})
* * A string bit number
* * An instance of BitField
* * An Array of BitFieldResolvable
@@ -146,7 +146,7 @@ class BitField {
if (bit instanceof BitField) return bit.bitfield;
if (Array.isArray(bit)) return bit.map(p => this.resolve(p)).reduce((prev, p) => prev | p, defaultBit);
if (typeof bit === 'string') {
if (typeof this.FLAGS[bit] !== 'undefined') return this.FLAGS[bit];
if (typeof this.Flags[bit] !== 'undefined') return this.Flags[bit];
if (!isNaN(bit)) return typeof defaultBit === 'bigint' ? BigInt(bit) : Number(bit);
}
throw new RangeError('BITFIELD_INVALID', bit);
@@ -159,7 +159,7 @@ class BitField {
* @type {Object}
* @abstract
*/
BitField.FLAGS = {};
BitField.Flags = {};
/**
* @type {number|bigint}

View File

@@ -135,20 +135,6 @@ exports.ShardEvents = {
ALL_READY: 'allReady',
};
/**
* The type of Structure allowed to be a partial:
* * USER
* * CHANNEL (only affects DMChannels)
* * GUILD_MEMBER
* * MESSAGE
* * REACTION
* * GUILD_SCHEDULED_EVENT
* <warn>Partials require you to put checks in place when handling data. See the "Partial Structures" topic on the
* [guide](https://discordjs.guide/popular-topics/partials.html) for more information.</warn>
* @typedef {string} PartialType
*/
exports.PartialTypes = keyMirror(['USER', 'CHANNEL', 'GUILD_MEMBER', 'MESSAGE', 'REACTION', 'GUILD_SCHEDULED_EVENT']);
/**
* The type of a WebSocket message event, e.g. `MESSAGE_CREATE`. Here are the available events:
* * READY

View File

@@ -1,66 +0,0 @@
'use strict';
const BitField = require('./BitField');
/**
* Data structure that makes it easy to calculate intents.
* @extends {BitField}
*/
class Intents extends BitField {}
/**
* @name Intents
* @kind constructor
* @memberof Intents
* @param {IntentsResolvable} [bits=0] Bit(s) to read from
*/
/**
* Data that can be resolved to give a permission number. This can be:
* * A string (see {@link Intents.FLAGS})
* * An intents flag
* * An instance of Intents
* * An array of IntentsResolvable
* @typedef {string|number|Intents|IntentsResolvable[]} IntentsResolvable
*/
/**
* Numeric WebSocket intents. All available properties:
* * `GUILDS`
* * `GUILD_MEMBERS`
* * `GUILD_BANS`
* * `GUILD_EMOJIS_AND_STICKERS`
* * `GUILD_INTEGRATIONS`
* * `GUILD_WEBHOOKS`
* * `GUILD_INVITES`
* * `GUILD_VOICE_STATES`
* * `GUILD_PRESENCES`
* * `GUILD_MESSAGES`
* * `GUILD_MESSAGE_REACTIONS`
* * `GUILD_MESSAGE_TYPING`
* * `DIRECT_MESSAGES`
* * `DIRECT_MESSAGE_REACTIONS`
* * `DIRECT_MESSAGE_TYPING`
* * `GUILD_SCHEDULED_EVENTS`
* @type {Object}
* @see {@link https://discord.com/developers/docs/topics/gateway#list-of-intents}
*/
Intents.FLAGS = {
GUILDS: 1 << 0,
GUILD_MEMBERS: 1 << 1,
GUILD_BANS: 1 << 2,
GUILD_EMOJIS_AND_STICKERS: 1 << 3,
GUILD_INTEGRATIONS: 1 << 4,
GUILD_WEBHOOKS: 1 << 5,
GUILD_INVITES: 1 << 6,
GUILD_VOICE_STATES: 1 << 7,
GUILD_PRESENCES: 1 << 8,
GUILD_MESSAGES: 1 << 9,
GUILD_MESSAGE_REACTIONS: 1 << 10,
GUILD_MESSAGE_TYPING: 1 << 11,
DIRECT_MESSAGES: 1 << 12,
DIRECT_MESSAGE_REACTIONS: 1 << 13,
DIRECT_MESSAGE_TYPING: 1 << 14,
GUILD_SCHEDULED_EVENTS: 1 << 16,
};
module.exports = Intents;

View File

@@ -0,0 +1,33 @@
'use strict';
const { GatewayIntentBits } = require('discord-api-types/v9');
const BitField = require('./BitField');
/**
* Data structure that makes it easy to calculate intents.
* @extends {BitField}
*/
class IntentsBitField extends BitField {}
/**
* @name IntentsBitField
* @kind constructor
* @memberof IntentsBitField
* @param {IntentsResolvable} [bits=0] Bit(s) to read from
*/
/**
* Data that can be resolved to give a permission number. This can be:
* * A string (see {@link IntentsBitField.Flags})
* * An intents flag
* * An instance of {@link IntentsBitField}
* * An array of IntentsResolvable
* @typedef {string|number|IntentsBitField|IntentsResolvable[]} IntentsResolvable
*/
/**
* Numeric WebSocket intents
* @type {GatewayIntentBits}
*/
IntentsBitField.Flags = GatewayIntentBits;
module.exports = IntentsBitField;

View File

@@ -1,48 +0,0 @@
'use strict';
const BitField = require('./BitField');
/**
* Data structure that makes it easy to interact with a {@link Message#flags} bitfield.
* @extends {BitField}
*/
class MessageFlags extends BitField {}
/**
* @name MessageFlags
* @kind constructor
* @memberof MessageFlags
* @param {BitFieldResolvable} [bits=0] Bit(s) to read from
*/
/**
* Bitfield of the packed bits
* @type {number}
* @name MessageFlags#bitfield
*/
/**
* Numeric message flags. All available properties:
* * `CROSSPOSTED`
* * `IS_CROSSPOST`
* * `SUPPRESS_EMBEDS`
* * `SOURCE_MESSAGE_DELETED`
* * `URGENT`
* * `HAS_THREAD`
* * `EPHEMERAL`
* * `LOADING`
* @type {Object}
* @see {@link https://discord.com/developers/docs/resources/channel#message-object-message-flags}
*/
MessageFlags.FLAGS = {
CROSSPOSTED: 1 << 0,
IS_CROSSPOST: 1 << 1,
SUPPRESS_EMBEDS: 1 << 2,
SOURCE_MESSAGE_DELETED: 1 << 3,
URGENT: 1 << 4,
HAS_THREAD: 1 << 5,
EPHEMERAL: 1 << 6,
LOADING: 1 << 7,
};
module.exports = MessageFlags;

View File

@@ -0,0 +1,31 @@
'use strict';
const { MessageFlags } = require('discord-api-types/v9');
const BitField = require('./BitField');
/**
* Data structure that makes it easy to interact with a {@link Message#flags} bitfield.
* @extends {BitField}
*/
class MessageFlagsBitField extends BitField {}
/**
* @name MessageFlagsBitField
* @kind constructor
* @memberof MessageFlagsBitField
* @param {BitFieldResolvable} [bits=0] Bit(s) to read from
*/
/**
* Bitfield of the packed bits
* @type {number}
* @name MessageFlagsBitField#bitfield
*/
/**
* Numeric message flags.
* @type {MessageFlags}
*/
MessageFlagsBitField.Flags = MessageFlags;
module.exports = MessageFlagsBitField;

View File

@@ -23,7 +23,7 @@ const { DefaultRestOptions } = require('@discordjs/rest');
* <warn>Overriding the cache used in `GuildManager`, `ChannelManager`, `GuildChannelManager`, `RoleManager`,
* and `PermissionOverwriteManager` is unsupported and **will** break functionality</warn>
* @property {MessageMentionOptions} [allowedMentions] Default value for {@link MessageOptions#allowedMentions}
* @property {PartialType[]} [partials] Structures allowed to be partial. This means events can be emitted even when
* @property {Partials[]} [partials] Structures allowed to be partial. This means events can be emitted even when
* they're missing all the data for a particular structure. See the "Partial Structures" topic on the
* [guide](https://discordjs.guide/popular-topics/partials.html) for some
* important usage information, as partials require you to put checks in place when handling data.

View File

@@ -0,0 +1,13 @@
'use strict';
function createEnum(keys) {
const obj = {};
for (const [index, key] of keys.entries()) {
if (key === null) continue;
obj[key] = index;
obj[index] = key;
}
return obj;
}
module.exports = createEnum(['User', 'Channel', 'GuildMember', 'Message', 'Reaction', 'GuildScheduledEvent']);

View File

@@ -1,177 +0,0 @@
'use strict';
const BitField = require('./BitField');
/**
* Data structure that makes it easy to interact with a permission bitfield. All {@link GuildMember}s have a set of
* permissions in their guild, and each channel in the guild may also have {@link PermissionOverwrites} for the member
* that override their default permissions.
* @extends {BitField}
*/
class Permissions extends BitField {
/**
* Bitfield of the packed bits
* @type {bigint}
* @name Permissions#bitfield
*/
/**
* Data that can be resolved to give a permission number. This can be:
* * A string (see {@link Permissions.FLAGS})
* * A permission number
* * An instance of Permissions
* * An Array of PermissionResolvable
* @typedef {string|bigint|Permissions|PermissionResolvable[]} PermissionResolvable
*/
/**
* Gets all given bits that are missing from the bitfield.
* @param {BitFieldResolvable} bits Bit(s) to check for
* @param {boolean} [checkAdmin=true] Whether to allow the administrator permission to override
* @returns {string[]}
*/
missing(bits, checkAdmin = true) {
return checkAdmin && this.has(this.constructor.FLAGS.ADMINISTRATOR) ? [] : super.missing(bits);
}
/**
* Checks whether the bitfield has a permission, or any of multiple permissions.
* @param {PermissionResolvable} permission Permission(s) to check for
* @param {boolean} [checkAdmin=true] Whether to allow the administrator permission to override
* @returns {boolean}
*/
any(permission, checkAdmin = true) {
return (checkAdmin && super.has(this.constructor.FLAGS.ADMINISTRATOR)) || super.any(permission);
}
/**
* Checks whether the bitfield has a permission, or multiple permissions.
* @param {PermissionResolvable} permission Permission(s) to check for
* @param {boolean} [checkAdmin=true] Whether to allow the administrator permission to override
* @returns {boolean}
*/
has(permission, checkAdmin = true) {
return (checkAdmin && super.has(this.constructor.FLAGS.ADMINISTRATOR)) || super.has(permission);
}
/**
* Gets an {@link Array} of bitfield names based on the permissions available.
* @returns {string[]}
*/
toArray() {
return super.toArray(false);
}
}
/**
* Numeric permission flags. All available properties:
* * `CREATE_INSTANT_INVITE` (create invitations to the guild)
* * `KICK_MEMBERS`
* * `BAN_MEMBERS`
* * `ADMINISTRATOR` (implicitly has *all* permissions, and bypasses all channel overwrites)
* * `MANAGE_CHANNELS` (edit and reorder channels)
* * `MANAGE_GUILD` (edit the guild information, region, etc.)
* * `ADD_REACTIONS` (add new reactions to messages)
* * `VIEW_AUDIT_LOG`
* * `PRIORITY_SPEAKER`
* * `STREAM`
* * `VIEW_CHANNEL`
* * `SEND_MESSAGES`
* * `SEND_TTS_MESSAGES`
* * `MANAGE_MESSAGES` (delete messages and reactions)
* * `EMBED_LINKS` (links posted will have a preview embedded)
* * `ATTACH_FILES`
* * `READ_MESSAGE_HISTORY` (view messages that were posted prior to opening Discord)
* * `MENTION_EVERYONE`
* * `USE_EXTERNAL_EMOJIS` (use emojis from different guilds)
* * `VIEW_GUILD_INSIGHTS`
* * `CONNECT` (connect to a voice channel)
* * `SPEAK` (speak in a voice channel)
* * `MUTE_MEMBERS` (mute members across all voice channels)
* * `DEAFEN_MEMBERS` (deafen members across all voice channels)
* * `MOVE_MEMBERS` (move members between voice channels)
* * `USE_VAD` (use voice activity detection)
* * `CHANGE_NICKNAME`
* * `MANAGE_NICKNAMES` (change other members' nicknames)
* * `MANAGE_ROLES`
* * `MANAGE_WEBHOOKS`
* * `MANAGE_EMOJIS_AND_STICKERS`
* * `USE_APPLICATION_COMMANDS`
* * `REQUEST_TO_SPEAK`
* * `MANAGE_EVENTS`
* * `MANAGE_THREADS`
* * `CREATE_PUBLIC_THREADS`
* * `CREATE_PRIVATE_THREADS`
* * `USE_EXTERNAL_STICKERS` (use stickers from different guilds)
* * `SEND_MESSAGES_IN_THREADS`
* * `START_EMBEDDED_ACTIVITIES`
* * `MODERATE_MEMBERS`
* @type {Object<string, bigint>}
* @see {@link https://discord.com/developers/docs/topics/permissions#permissions-bitwise-permission-flags}
*/
Permissions.FLAGS = {
CREATE_INSTANT_INVITE: 1n << 0n,
KICK_MEMBERS: 1n << 1n,
BAN_MEMBERS: 1n << 2n,
ADMINISTRATOR: 1n << 3n,
MANAGE_CHANNELS: 1n << 4n,
MANAGE_GUILD: 1n << 5n,
ADD_REACTIONS: 1n << 6n,
VIEW_AUDIT_LOG: 1n << 7n,
PRIORITY_SPEAKER: 1n << 8n,
STREAM: 1n << 9n,
VIEW_CHANNEL: 1n << 10n,
SEND_MESSAGES: 1n << 11n,
SEND_TTS_MESSAGES: 1n << 12n,
MANAGE_MESSAGES: 1n << 13n,
EMBED_LINKS: 1n << 14n,
ATTACH_FILES: 1n << 15n,
READ_MESSAGE_HISTORY: 1n << 16n,
MENTION_EVERYONE: 1n << 17n,
USE_EXTERNAL_EMOJIS: 1n << 18n,
VIEW_GUILD_INSIGHTS: 1n << 19n,
CONNECT: 1n << 20n,
SPEAK: 1n << 21n,
MUTE_MEMBERS: 1n << 22n,
DEAFEN_MEMBERS: 1n << 23n,
MOVE_MEMBERS: 1n << 24n,
USE_VAD: 1n << 25n,
CHANGE_NICKNAME: 1n << 26n,
MANAGE_NICKNAMES: 1n << 27n,
MANAGE_ROLES: 1n << 28n,
MANAGE_WEBHOOKS: 1n << 29n,
MANAGE_EMOJIS_AND_STICKERS: 1n << 30n,
USE_APPLICATION_COMMANDS: 1n << 31n,
REQUEST_TO_SPEAK: 1n << 32n,
MANAGE_EVENTS: 1n << 33n,
MANAGE_THREADS: 1n << 34n,
CREATE_PUBLIC_THREADS: 1n << 35n,
CREATE_PRIVATE_THREADS: 1n << 36n,
USE_EXTERNAL_STICKERS: 1n << 37n,
SEND_MESSAGES_IN_THREADS: 1n << 38n,
START_EMBEDDED_ACTIVITIES: 1n << 39n,
MODERATE_MEMBERS: 1n << 40n,
};
/**
* Bitfield representing every permission combined
* @type {bigint}
*/
Permissions.ALL = Object.values(Permissions.FLAGS).reduce((all, p) => all | p, 0n);
/**
* Bitfield representing the default permissions for users
* @type {bigint}
*/
Permissions.DEFAULT = BigInt(104324673);
/**
* Bitfield representing the permissions required for moderators of stage channels
* @type {bigint}
*/
Permissions.STAGE_MODERATOR =
Permissions.FLAGS.MANAGE_CHANNELS | Permissions.FLAGS.MUTE_MEMBERS | Permissions.FLAGS.MOVE_MEMBERS;
Permissions.defaultBit = BigInt(0);
module.exports = Permissions;

View File

@@ -0,0 +1,95 @@
'use strict';
const { PermissionFlagsBits } = require('discord-api-types/v9');
const BitField = require('./BitField');
/**
* Data structure that makes it easy to interact with a permission bitfield. All {@link GuildMember}s have a set of
* permissions in their guild, and each channel in the guild may also have {@link PermissionOverwrites} for the member
* that override their default permissions.
* @extends {BitField}
*/
class PermissionsBitField extends BitField {
/**
* Bitfield of the packed bits
* @type {bigint}
* @name Permissions#bitfield
*/
/**
* Data that can be resolved to give a permission number. This can be:
* * A string (see {@link PermissionsBitField.Flags})
* * A permission number
* * An instance of {@link PermissionsBitField}
* * An Array of PermissionResolvable
* @typedef {string|bigint|PermissionsBitField|PermissionResolvable[]} PermissionResolvable
*/
/**
* Gets all given bits that are missing from the bitfield.
* @param {BitFieldResolvable} bits Bit(s) to check for
* @param {boolean} [checkAdmin=true] Whether to allow the administrator permission to override
* @returns {string[]}
*/
missing(bits, checkAdmin = true) {
return checkAdmin && this.has(PermissionFlagsBits.Administrator) ? [] : super.missing(bits);
}
/**
* Checks whether the bitfield has a permission, or any of multiple permissions.
* @param {PermissionResolvable} permission Permission(s) to check for
* @param {boolean} [checkAdmin=true] Whether to allow the administrator permission to override
* @returns {boolean}
*/
any(permission, checkAdmin = true) {
return (checkAdmin && super.has(PermissionFlagsBits.Administrator)) || super.any(permission);
}
/**
* Checks whether the bitfield has a permission, or multiple permissions.
* @param {PermissionResolvable} permission Permission(s) to check for
* @param {boolean} [checkAdmin=true] Whether to allow the administrator permission to override
* @returns {boolean}
*/
has(permission, checkAdmin = true) {
return (checkAdmin && super.has(PermissionFlagsBits.Administrator)) || super.has(permission);
}
/**
* Gets an {@link Array} of bitfield names based on the permissions available.
* @returns {string[]}
*/
toArray() {
return super.toArray(false);
}
}
/**
* Numeric permission flags.
* @type {PermissionFlagsBits}
* @see {@link https://discord.com/developers/docs/topics/permissions#permissions-bitwise-permission-flags}
*/
PermissionsBitField.Flags = PermissionFlagsBits;
/**
* Bitfield representing every permission combined
* @type {bigint}
*/
PermissionsBitField.All = Object.values(PermissionFlagsBits).reduce((all, p) => all | p, 0n);
/**
* Bitfield representing the default permissions for users
* @type {bigint}
*/
PermissionsBitField.Default = BigInt(104324673);
/**
* Bitfield representing the permissions required for moderators of stage channels
* @type {bigint}
*/
PermissionsBitField.StageModerator =
PermissionFlagsBits.ManageChannels | PermissionFlagsBits.MuteMembers | PermissionFlagsBits.MoveMembers;
PermissionsBitField.defaultBit = BigInt(0);
module.exports = PermissionsBitField;

View File

@@ -1,51 +0,0 @@
'use strict';
const BitField = require('./BitField');
/**
* Data structure that makes it easy to interact with a {@link Guild#systemChannelFlags} bitfield.
* <info>Note that all event message types are enabled by default,
* and by setting their corresponding flags you are disabling them</info>
* @extends {BitField}
*/
class SystemChannelFlags extends BitField {}
/**
* @name SystemChannelFlags
* @kind constructor
* @memberof SystemChannelFlags
* @param {SystemChannelFlagsResolvable} [bits=0] Bit(s) to read from
*/
/**
* Bitfield of the packed bits
* @type {number}
* @name SystemChannelFlags#bitfield
*/
/**
* Data that can be resolved to give a system channel flag bitfield. This can be:
* * A string (see {@link SystemChannelFlags.FLAGS})
* * A system channel flag
* * An instance of SystemChannelFlags
* * An Array of SystemChannelFlagsResolvable
* @typedef {string|number|SystemChannelFlags|SystemChannelFlagsResolvable[]} SystemChannelFlagsResolvable
*/
/**
* Numeric system channel flags. All available properties:
* * `SUPPRESS_JOIN_NOTIFICATIONS` (Suppress member join notifications)
* * `SUPPRESS_PREMIUM_SUBSCRIPTIONS` (Suppress server boost notifications)
* * `SUPPRESS_GUILD_REMINDER_NOTIFICATIONS` (Suppress server setup tips)
* * `SUPPRESS_JOIN_NOTIFICATION_REPLIES` (Hide member join sticker reply buttons)
* @type {Object}
* @see {@link https://discord.com/developers/docs/resources/guild#guild-object-system-channel-flags}
*/
SystemChannelFlags.FLAGS = {
SUPPRESS_JOIN_NOTIFICATIONS: 1 << 0,
SUPPRESS_PREMIUM_SUBSCRIPTIONS: 1 << 1,
SUPPRESS_GUILD_REMINDER_NOTIFICATIONS: 1 << 2,
SUPPRESS_JOIN_NOTIFICATION_REPLIES: 1 << 3,
};
module.exports = SystemChannelFlags;

View File

@@ -0,0 +1,42 @@
'use strict';
const { GuildSystemChannelFlags } = require('discord-api-types/v9');
const BitField = require('./BitField');
/**
* Data structure that makes it easy to interact with a {@link Guild#systemChannelFlags} bitfield.
* <info>Note that all event message types are enabled by default,
* and by setting their corresponding flags you are disabling them</info>
* @extends {BitField}
*/
class SystemChannelFlagsBitField extends BitField {}
/**
* @name SystemChannelFlagsBitField
* @kind constructor
* @memberof SystemChannelFlagsBitField
* @param {SystemChannelFlagsResolvable} [bits=0] Bit(s) to read from
*/
/**
* Bitfield of the packed bits
* @type {number}
* @name SystemChannelFlagsBitField#bitfield
*/
/**
* Data that can be resolved to give a system channel flag bitfield. This can be:
* * A string (see {@link SystemChannelFlagsBitField.Flags})
* * A system channel flag
* * An instance of SystemChannelFlagsBitField
* * An Array of SystemChannelFlagsResolvable
* @typedef {string|number|SystemChannelFlagsBitField|SystemChannelFlagsResolvable[]} SystemChannelFlagsResolvable
*/
/**
* Numeric system channel flags.
* @type {GuildSystemChannelFlags}
*/
SystemChannelFlagsBitField.Flags = GuildSystemChannelFlags;
module.exports = SystemChannelFlagsBitField;

View File

@@ -6,25 +6,25 @@ const BitField = require('./BitField');
* Data structure that makes it easy to interact with a {@link ThreadMember#flags} bitfield.
* @extends {BitField}
*/
class ThreadMemberFlags extends BitField {}
class ThreadMemberFlagsBitField extends BitField {}
/**
* @name ThreadMemberFlags
* @name ThreadMemberFlagsBitField
* @kind constructor
* @memberof ThreadMemberFlags
* @memberof ThreadMemberFlagsBitField
* @param {BitFieldResolvable} [bits=0] Bit(s) to read from
*/
/**
* Bitfield of the packed bits
* @type {number}
* @name ThreadMemberFlags#bitfield
* @name ThreadMemberFlagsBitField#bitfield
*/
/**
* Numeric thread member flags. There are currently no bitflags relevant to bots for this.
* @type {Object<string, number>}
*/
ThreadMemberFlags.FLAGS = {};
ThreadMemberFlagsBitField.Flags = {};
module.exports = ThreadMemberFlags;
module.exports = ThreadMemberFlagsBitField;

View File

@@ -1,59 +0,0 @@
'use strict';
const BitField = require('./BitField');
/**
* Data structure that makes it easy to interact with a {@link User#flags} bitfield.
* @extends {BitField}
*/
class UserFlags extends BitField {}
/**
* @name UserFlags
* @kind constructor
* @memberof UserFlags
* @param {BitFieldResolvable} [bits=0] Bit(s) to read from
*/
/**
* Bitfield of the packed bits
* @type {number}
* @name UserFlags#bitfield
*/
/**
* Numeric user flags. All available properties:
* * `STAFF`
* * `PARTNER`
* * `HYPESQUAD`
* * `BUG_HUNTER_LEVEL_1`
* * `HYPESQUAD_ONLINE_HOUSE_1`
* * `HYPESQUAD_ONLINE_HOUSE_2`
* * `HYPESQUAD_ONLINE_HOUSE_3`
* * `PREMIUM_EARLY_SUPPORTER`
* * `TEAM_PSEUDO_USER`
* * `BUG_HUNTER_LEVEL_2`
* * `VERIFIED_BOT`
* * `VERIFIED_DEVELOPER`
* * `CERTIFIED_MODERATOR`
* * `BOT_HTTP_INTERACTIONS`
* @type {Object}
* @see {@link https://discord.com/developers/docs/resources/user#user-object-user-flags}
*/
UserFlags.FLAGS = {
STAFF: 1 << 0,
PARTNER: 1 << 1,
HYPESQUAD: 1 << 2,
BUG_HUNTER_LEVEL_1: 1 << 3,
HYPESQUAD_ONLINE_HOUSE_1: 1 << 6,
HYPESQUAD_ONLINE_HOUSE_2: 1 << 7,
HYPESQUAD_ONLINE_HOUSE_3: 1 << 8,
PREMIUM_EARLY_SUPPORTER: 1 << 9,
TEAM_PSEUDO_USER: 1 << 10,
BUG_HUNTER_LEVEL_2: 1 << 14,
VERIFIED_BOT: 1 << 16,
VERIFIED_DEVELOPER: 1 << 17,
CERTIFIED_MODERATOR: 1 << 18,
BOT_HTTP_INTERACTIONS: 1 << 19,
};
module.exports = UserFlags;

View File

@@ -0,0 +1,31 @@
'use strict';
const { UserFlags } = require('discord-api-types/v9');
const BitField = require('./BitField');
/**
* Data structure that makes it easy to interact with a {@link User#flags} bitfield.
* @extends {BitField}
*/
class UserFlagsBitField extends BitField {}
/**
* @name UserFlagsBitField
* @kind constructor
* @memberof UserFlagsBitField
* @param {BitFieldResolvable} [bits=0] Bit(s) to read from
*/
/**
* Bitfield of the packed bits
* @type {number}
* @name UserFlagsBitField#bitfield
*/
/**
* Numeric user flags.
* @type {UserFlags}
*/
UserFlagsBitField.Flags = UserFlags;
module.exports = UserFlagsBitField;

View File

@@ -1,11 +1,11 @@
'use strict';
const assert = require('node:assert');
const { ChannelType } = require('discord-api-types/v9');
const { ChannelType, GatewayIntentBits } = require('discord-api-types/v9');
const { token } = require('./auth');
const { Client, Intents } = require('../src');
const { Client } = require('../src');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages] });
client.on('ready', async () => {
try {

View File

@@ -5,17 +5,17 @@
const request = require('superagent');
const ytdl = require('ytdl-core');
const { token, song } = require('./auth.js');
const { Client, Intents } = require('../src');
const { ChannelType } = require('discord-api-types/v9');
const { Client } = require('../src');
const { ChannelType, GatewayIntentBits } = require('discord-api-types/v9');
console.time('magic');
const client = new Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_MESSAGE_REACTIONS,
Intents.FLAGS.GUILD_MEMBERS,
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.GuildMembers,
],
});

View File

@@ -1,10 +1,11 @@
'use strict';
const { GatewayIntentBits } = require('discord-api-types/v9');
const { token, guildId, channelId, messageId } = require('./auth.js');
const { Client, Intents, ReactionCollector } = require('../src');
const { Client, ReactionCollector } = require('../src');
const client = new Client({
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MESSAGE_REACTIONS],
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildMessageReactions],
});
client.on('ready', async () => {

View File

@@ -1,15 +1,16 @@
'use strict';
const fetch = require('node-fetch');
const fs = require('node:fs');
const path = require('node:path');
const process = require('node:process');
const { setTimeout: sleep } = require('node:timers/promises');
const util = require('node:util');
const { GatewayIntentBits } = require('discord-api-types/v9');
const fetch = require('node-fetch');
const { owner, token } = require('./auth.js');
const { Client, Intents, MessageAttachment, Embed } = require('../src');
const { Client, MessageAttachment, Embed } = require('../src');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages] });
const buffer = l => fetch(l).then(res => res.buffer());
const read = util.promisify(fs.readFile);

View File

@@ -2,11 +2,12 @@
const process = require('node:process');
const { setTimeout } = require('node:timers');
const { GatewayIntentBits } = require('discord-api-types/v9');
const { token } = require('./auth.json');
const { Client, Intents } = require('../src');
const { Client } = require('../src');
const client = new Client({
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES],
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages],
shards: process.argv[2],
shardCount: process.argv[3],
});

View File

@@ -1,9 +1,9 @@
'use strict';
const { token } = require('./auth');
const { Client } = require('../src');
const { Client, GatewayIntentBits } = require('../src');
const client = new Client({ intents: ['GUILDS', 'GUILD_MESSAGES'] });
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages] });
client
.on('ready', () => console.log('ready'))
.on('messageCreate', async message => {

View File

@@ -1,14 +1,15 @@
'use strict';
const process = require('node:process');
const { GatewayIntentBits } = require('discord-api-types/v9');
const { token, prefix, owner } = require('./auth.js');
const { Client, Intents } = require('../src');
const { Client } = require('../src');
// eslint-disable-next-line no-console
const log = (...args) => console.log(process.uptime().toFixed(3), ...args);
const client = new Client({
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES],
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages],
shardCount: 2,
});

View File

@@ -1,15 +1,16 @@
'use strict';
const process = require('node:process');
const { GatewayIntentBits } = require('discord-api-types/v9');
const { token, prefix, owner } = require('./auth.js');
const { Client, Options, Intents, Formatters } = require('../src');
const { Client, Options, Formatters } = require('../src');
// eslint-disable-next-line no-console
const log = (...args) => console.log(process.uptime().toFixed(3), ...args);
const client = new Client({
// 😏
intents: Object.values(Intents.FLAGS).reduce((acc, p) => acc | p, 0),
intents: Object.values(GatewayIntentBits).reduce((acc, p) => acc | p, 0),
makeCache: Options.cacheWithLimits({
MessageManager: 10,
PresenceManager: 10,

View File

@@ -1,14 +1,15 @@
'use strict';
const fetch = require('node-fetch');
const fs = require('node:fs');
const path = require('node:path');
const { setTimeout: sleep } = require('node:timers/promises');
const util = require('node:util');
const { GatewayIntentBits } = require('discord-api-types/v9');
const fetch = require('node-fetch');
const { owner, token, webhookChannel, webhookToken } = require('./auth.js');
const { Client, Intents, MessageAttachment, Embed, WebhookClient } = require('../src');
const { Client, MessageAttachment, Embed, WebhookClient } = require('../src');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages] });
const buffer = l => fetch(l).then(res => res.buffer());
const read = util.promisify(fs.readFile);

View File

@@ -79,6 +79,14 @@ import {
GuildScheduledEventPrivacyLevel,
GuildScheduledEventStatus,
IntegrationExpireBehavior,
ApplicationFlags,
PermissionFlagsBits,
ThreadMemberFlags,
UserFlags,
MessageFlags,
GuildSystemChannelFlags,
GatewayIntentBits,
ActivityFlags,
} from 'discord-api-types/v9';
import { ChildProcess } from 'node:child_process';
import { EventEmitter } from 'node:events';
@@ -155,7 +163,7 @@ export class Activity {
public createdTimestamp: number;
public details: string | null;
public emoji: Emoji | null;
public flags: Readonly<ActivityFlags>;
public flags: Readonly<ActivityFlagsBitField>;
public id: string;
public name: string;
public party: {
@@ -175,8 +183,10 @@ export class Activity {
public equals(activity: Activity): boolean;
}
export class ActivityFlags extends BitField<ActivityFlagsString> {
public static FLAGS: Record<ActivityFlagsString, number>;
export type ActivityFlagsString = keyof typeof ActivityFlags;
export class ActivityFlagsBitField extends BitField<ActivityFlagsString> {
public static flags: ActivityFlags;
public static resolve(bit?: BitFieldResolvable<ActivityFlagsString, number>): number;
}
@@ -255,8 +265,8 @@ export class ApplicationCommand<PermissionsFetchType = {}> extends Base {
export type ApplicationResolvable = Application | Activity | Snowflake;
export class ApplicationFlags extends BitField<ApplicationFlagsString> {
public static FLAGS: Record<ApplicationFlagsString, number>;
export class ApplicationFlagsBitField extends BitField<ApplicationFlagsString> {
public static flags: ApplicationFlags;
public static resolve(bit?: BitFieldResolvable<ApplicationFlagsString, number>): number;
}
@@ -401,6 +411,8 @@ export class BaseGuildVoiceChannel extends GuildChannel {
public fetchInvites(cache?: boolean): Promise<Collection<string, Invite>>;
}
export type EnumLike<E, V> = Record<keyof E, V>;
export class BitField<S extends string, N extends number | bigint = number> {
public constructor(bits?: BitFieldResolvable<S, N>);
public bitfield: N;
@@ -416,7 +428,7 @@ export class BitField<S extends string, N extends number | bigint = number> {
public toJSON(): N extends number ? number : string;
public valueOf(): N;
public [Symbol.iterator](): IterableIterator<S>;
public static FLAGS: Record<string, number | bigint>;
public static Flags: EnumLike<unknown, number | bigint>;
public static resolve(bit?: BitFieldResolvable<string, number | bigint>): number | bigint;
}
@@ -563,7 +575,7 @@ export class ClientApplication extends Application {
public botRequireCodeGrant: boolean | null;
public commands: ApplicationCommandManager;
public cover: string | null;
public flags: Readonly<ApplicationFlags>;
public flags: Readonly<ApplicationFlagsBitField>;
public owner: User | Team | null;
public readonly partial: boolean;
public rpcOrigins: string[];
@@ -902,7 +914,7 @@ export class Guild extends AnonymousGuild {
public stageInstances: StageInstanceManager;
public stickers: GuildStickerManager;
public readonly systemChannel: TextChannel | null;
public systemChannelFlags: Readonly<SystemChannelFlags>;
public systemChannelFlags: Readonly<SystemChannelFlagsBitField>;
public systemChannelId: Snowflake | null;
public vanityURLUses: number | null;
public readonly voiceAdapterCreator: InternalDiscordGatewayAdapterCreator;
@@ -1015,8 +1027,8 @@ export class GuildBan extends Base {
export abstract class GuildChannel extends Channel {
public constructor(guild: Guild, data?: RawGuildChannelData, client?: Client, immediatePatch?: boolean);
private memberPermissions(member: GuildMember, checkAdmin: boolean): Readonly<Permissions>;
private rolePermissions(role: Role, checkAdmin: boolean): Readonly<Permissions>;
private memberPermissions(member: GuildMember, checkAdmin: boolean): Readonly<PermissionsBitField>;
private rolePermissions(role: Role, checkAdmin: boolean): Readonly<PermissionsBitField>;
public readonly createdAt: Date;
public readonly createdTimestamp: number;
public readonly calculatedPosition: number;
@@ -1039,11 +1051,11 @@ export abstract class GuildChannel extends Channel {
public edit(data: ChannelData, reason?: string): Promise<this>;
public equals(channel: GuildChannel): boolean;
public lockPermissions(): Promise<this>;
public permissionsFor(memberOrRole: GuildMember | Role, checkAdmin?: boolean): Readonly<Permissions>;
public permissionsFor(memberOrRole: GuildMember | Role, checkAdmin?: boolean): Readonly<PermissionsBitField>;
public permissionsFor(
memberOrRole: GuildMemberResolvable | RoleResolvable,
checkAdmin?: boolean,
): Readonly<Permissions> | null;
): Readonly<PermissionsBitField> | null;
public setName(name: string, reason?: string): Promise<this>;
public setParent(channel: CategoryChannelResolvable | null, options?: SetParentOptions): Promise<this>;
public setPosition(position: number, options?: SetChannelPositionOptions): Promise<this>;
@@ -1085,7 +1097,7 @@ export class GuildMember extends PartialTextBasedChannel(Base) {
public readonly moderatable: boolean;
public nickname: string | null;
public readonly partial: false;
public readonly permissions: Readonly<Permissions>;
public readonly permissions: Readonly<PermissionsBitField>;
public readonly premiumSince: Date | null;
public premiumSinceTimestamp: number | null;
public readonly presence: Presence | null;
@@ -1106,7 +1118,7 @@ export class GuildMember extends PartialTextBasedChannel(Base) {
readonly communicationDisabledUntil: Date;
};
public kick(reason?: string): Promise<GuildMember>;
public permissionsIn(channel: GuildChannelResolvable): Readonly<Permissions>;
public permissionsIn(channel: GuildChannelResolvable): Readonly<PermissionsBitField>;
public setNickname(nickname: string | null, reason?: string): Promise<GuildMember>;
public toJSON(): unknown;
public toString(): MemberMention;
@@ -1251,9 +1263,11 @@ export class IntegrationApplication extends Application {
public verifyKey: string | null;
}
export class Intents extends BitField<IntentsString> {
public static FLAGS: Record<IntentsString, number>;
public static resolve(bit?: BitFieldResolvable<IntentsString, number>): number;
export type GatewayIntentsString = keyof typeof GatewayIntentBits;
export class IntentsBitField extends BitField<GatewayIntentsString> {
public static flags: GatewayIntentBits;
public static resolve(bit?: BitFieldResolvable<GatewayIntentsString, number>): number;
}
export type CacheType = 'cached' | 'raw' | undefined;
@@ -1295,7 +1309,7 @@ export class Interaction<Cached extends CacheType = CacheType> extends Base {
public type: InteractionType;
public user: User;
public version: number;
public memberPermissions: CacheTypeReducer<Cached, Readonly<Permissions>>;
public memberPermissions: CacheTypeReducer<Cached, Readonly<PermissionsBitField>>;
public locale: string;
public guildLocale: CacheTypeReducer<Cached, string, string, string>;
public inGuild(): this is Interaction<'raw' | 'cached'>;
@@ -1473,7 +1487,7 @@ export class Message<Cached extends boolean = boolean> extends Base {
public type: MessageType;
public readonly url: string;
public webhookId: Snowflake | null;
public flags: Readonly<MessageFlags>;
public flags: Readonly<MessageFlagsBitField>;
public reference: MessageReference | null;
public awaitMessageComponent<T extends ComponentType = ComponentType.ActionRow>(
options?: AwaitMessageCollectorOptionsParams<T, Cached>,
@@ -1582,8 +1596,10 @@ export class MessageContextMenuCommandInteraction<
public inRawGuild(): this is MessageContextMenuCommandInteraction<'raw'>;
}
export class MessageFlags extends BitField<MessageFlagsString> {
public static FLAGS: Record<MessageFlagsString, number>;
export type MessageFlagsString = keyof typeof MessageFlags;
export class MessageFlagsBitField extends BitField<MessageFlagsString> {
public static flags: MessageFlags;
public static resolve(bit?: BitFieldResolvable<MessageFlagsString, number>): number;
}
@@ -1666,7 +1682,7 @@ export class NewsChannel extends BaseGuildTextChannel {
export class OAuth2Guild extends BaseGuild {
private constructor(client: Client, data: RawOAuth2GuildData);
public owner: boolean;
public permissions: Readonly<Permissions>;
public permissions: Readonly<PermissionsBitField>;
}
export class PartialGroupDMChannel extends Channel {
@@ -1679,9 +1695,9 @@ export class PartialGroupDMChannel extends Channel {
export class PermissionOverwrites extends Base {
private constructor(client: Client, data: RawPermissionOverwriteData, channel: NonThreadGuildBasedChannel);
public allow: Readonly<Permissions>;
public allow: Readonly<PermissionsBitField>;
public readonly channel: NonThreadGuildBasedChannel;
public deny: Readonly<Permissions>;
public deny: Readonly<PermissionsBitField>;
public id: Snowflake;
public type: OverwriteType;
public edit(options: PermissionOverwriteOptions, reason?: string): Promise<PermissionOverwrites>;
@@ -1694,17 +1710,19 @@ export class PermissionOverwrites extends Base {
public static resolve(overwrite: OverwriteResolvable, guild: Guild): APIOverwrite;
}
export class Permissions extends BitField<PermissionString, bigint> {
export type PermissionsString = keyof typeof PermissionFlagsBits;
export class PermissionsBitField extends BitField<PermissionsString, bigint> {
public any(permission: PermissionResolvable, checkAdmin?: boolean): boolean;
public has(permission: PermissionResolvable, checkAdmin?: boolean): boolean;
public missing(bits: BitFieldResolvable<PermissionString, bigint>, checkAdmin?: boolean): PermissionString[];
public serialize(checkAdmin?: boolean): Record<PermissionString, boolean>;
public toArray(): PermissionString[];
public missing(bits: BitFieldResolvable<PermissionsString, bigint>, checkAdmin?: boolean): PermissionsString[];
public serialize(checkAdmin?: boolean): Record<PermissionsString, boolean>;
public toArray(): PermissionsString[];
public static ALL: bigint;
public static DEFAULT: bigint;
public static STAGE_MODERATOR: bigint;
public static FLAGS: PermissionFlags;
public static All: bigint;
public static Default: bigint;
public static StageModerator: bigint;
public static flags: typeof PermissionFlagsBits;
public static resolve(permission?: PermissionResolvable): bigint;
}
@@ -1780,7 +1798,7 @@ export class Role extends Base {
public readonly members: Collection<Snowflake, GuildMember>;
public mentionable: boolean;
public name: string;
public permissions: Readonly<Permissions>;
public permissions: Readonly<PermissionsBitField>;
public readonly position: number;
public rawPosition: number;
public tags: RoleTagData | null;
@@ -1791,7 +1809,10 @@ export class Role extends Base {
public edit(data: RoleData, reason?: string): Promise<Role>;
public equals(role: Role): boolean;
public iconURL(options?: ImageURLOptions): string | null;
public permissionsIn(channel: NonThreadGuildBasedChannel | Snowflake, checkAdmin?: boolean): Readonly<Permissions>;
public permissionsIn(
channel: NonThreadGuildBasedChannel | Snowflake,
checkAdmin?: boolean,
): Readonly<PermissionsBitField>;
public setColor(color: ColorResolvable, reason?: string): Promise<Role>;
public setHoist(hoist?: boolean, reason?: string): Promise<Role>;
public setMentionable(mentionable?: boolean, reason?: string): Promise<Role>;
@@ -2084,8 +2105,10 @@ export class Sweepers {
): GlobalSweepFilter<SweeperDefinitions['messages'][0], SweeperDefinitions['messages'][1]>;
}
export class SystemChannelFlags extends BitField<SystemChannelFlagsString> {
public static FLAGS: Record<SystemChannelFlagsString, number>;
export type SystemChannelFlagsString = keyof typeof GuildSystemChannelFlags;
export class SystemChannelFlagsBitField extends BitField<SystemChannelFlagsString> {
public static flags: GuildSystemChannelFlags;
public static resolve(bit?: BitFieldResolvable<SystemChannelFlagsString, number>): number;
}
@@ -2164,11 +2187,11 @@ export class ThreadChannel extends TextBasedChannelMixin(Channel) {
public edit(data: ThreadEditData, reason?: string): Promise<ThreadChannel>;
public join(): Promise<ThreadChannel>;
public leave(): Promise<ThreadChannel>;
public permissionsFor(memberOrRole: GuildMember | Role, checkAdmin?: boolean): Readonly<Permissions>;
public permissionsFor(memberOrRole: GuildMember | Role, checkAdmin?: boolean): Readonly<PermissionsBitField>;
public permissionsFor(
memberOrRole: GuildMemberResolvable | RoleResolvable,
checkAdmin?: boolean,
): Readonly<Permissions> | null;
): Readonly<PermissionsBitField> | null;
public fetchOwner(options?: BaseFetchOptions): Promise<ThreadMember | null>;
public fetchStarterMessage(options?: BaseFetchOptions): Promise<Message>;
public setArchived(archived?: boolean, reason?: string): Promise<ThreadChannel>;
@@ -2184,7 +2207,7 @@ export class ThreadChannel extends TextBasedChannelMixin(Channel) {
export class ThreadMember extends Base {
private constructor(thread: ThreadChannel, data?: RawThreadMemberData);
public flags: ThreadMemberFlags;
public flags: ThreadMemberFlagsBitField;
public readonly guildMember: GuildMember | null;
public id: Snowflake;
public readonly joinedAt: Date | null;
@@ -2195,8 +2218,10 @@ export class ThreadMember extends Base {
public remove(reason?: string): Promise<ThreadMember>;
}
export class ThreadMemberFlags extends BitField<ThreadMemberFlagsString> {
public static FLAGS: Record<ThreadMemberFlagsString, number>;
export type ThreadMemberFlagsString = keyof typeof ThreadMemberFlags;
export class ThreadMemberFlagsBitField extends BitField<ThreadMemberFlagsString> {
public static flags: ThreadMemberFlags;
public static resolve(bit?: BitFieldResolvable<ThreadMemberFlagsString, number>): number;
}
@@ -2227,7 +2252,7 @@ export class User extends PartialTextBasedChannel(Base) {
public discriminator: string;
public readonly defaultAvatarURL: string;
public readonly dmChannel: DMChannel | null;
public flags: Readonly<UserFlags> | null;
public flags: Readonly<UserFlagsBitField> | null;
public readonly hexAccentColor: HexColorString | null | undefined;
public id: Snowflake;
public readonly partial: false;
@@ -2241,7 +2266,7 @@ export class User extends PartialTextBasedChannel(Base) {
public displayAvatarURL(options?: ImageURLOptions): string;
public equals(user: User): boolean;
public fetch(force?: boolean): Promise<User>;
public fetchFlags(force?: boolean): Promise<UserFlags>;
public fetchFlags(force?: boolean): Promise<UserFlagsBitField>;
public toString(): UserMention;
}
@@ -2255,8 +2280,10 @@ export class UserContextMenuCommandInteraction<
public inRawGuild(): this is UserContextMenuCommandInteraction<'raw'>;
}
export class UserFlags extends BitField<UserFlagsString> {
public static FLAGS: Record<UserFlagsString, number>;
export type UserFlagsString = keyof typeof UserFlags;
export class UserFlagsBitField extends BitField<UserFlagsString> {
public static flags: UserFlags;
public static resolve(bit?: BitFieldResolvable<UserFlagsString, number>): number;
}
@@ -2582,9 +2609,6 @@ export const Constants: {
};
Events: ConstantsEvents;
ShardEvents: ConstantsShardEvents;
PartialTypes: {
[K in PartialTypes]: K;
};
WSEvents: {
[K in WSEventType]: K;
};
@@ -3016,7 +3040,7 @@ export class UserManager extends CachedManager<Snowflake, User, UserResolvable>
public createDM(user: UserResolvable, options?: BaseFetchOptions): Promise<DMChannel>;
public deleteDM(user: UserResolvable): Promise<DMChannel>;
public fetch(user: UserResolvable, options?: BaseFetchOptions): Promise<User>;
public fetchFlags(user: UserResolvable, options?: BaseFetchOptions): Promise<UserFlags>;
public fetchFlags(user: UserResolvable, options?: BaseFetchOptions): Promise<UserFlagsBitField>;
public send(user: UserResolvable, options: string | MessagePayload | MessageOptions): Promise<Message>;
}
@@ -3091,17 +3115,6 @@ export interface WebhookFields extends PartialWebhookFields {
//#region Typedefs
export type ActivityFlagsString =
| 'INSTANCE'
| 'JOIN'
| 'SPECTATE'
| 'JOIN_REQUEST'
| 'SYNC'
| 'PLAY'
| 'PARTY_PRIVACY_FRIENDS'
| 'PARTY_PRIVACY_VOICE_CHANNEL'
| 'EMBEDDED';
export type ActivitiesOptions = Omit<ActivityOptions, 'shardId'>;
export interface ActivityOptions {
@@ -3294,15 +3307,7 @@ export interface ApplicationCommandPermissions extends ApplicationCommandPermiss
export type ApplicationCommandResolvable = ApplicationCommand | Snowflake;
export type ApplicationFlagsString =
| 'GATEWAY_PRESENCE'
| 'GATEWAY_PRESENCE_LIMITED'
| 'GATEWAY_GUILD_MEMBERS'
| 'GATEWAY_GUILD_MEMBERS_LIMITED'
| 'VERIFICATION_PENDING_GUILD_LIMIT'
| 'EMBEDDED'
| 'GATEWAY_MESSAGE_CONTENT'
| 'GATEWAY_MESSAGE_CONTENT_LIMITED';
export type ApplicationFlagsString = keyof typeof ApplicationFlags;
export interface AuditLogChange {
key: APIAuditLogChange['key'];
@@ -3548,10 +3553,10 @@ export interface ClientOptions {
shardCount?: number;
makeCache?: CacheFactory;
allowedMentions?: MessageMentionOptions;
partials?: PartialTypes[];
partials?: Partials[];
failIfNotExists?: boolean;
presence?: PresenceData;
intents: BitFieldResolvable<IntentsString, number>;
intents: BitFieldResolvable<GatewayIntentsString, number>;
waitGuildTimeout?: number;
sweepers?: SweeperOptions;
ws?: WebSocketOptions;
@@ -4450,31 +4455,13 @@ export type InteractionDeferUpdateOptions = Omit<InteractionDeferReplyOptions, '
export interface InteractionReplyOptions extends Omit<WebhookMessageOptions, 'username' | 'avatarURL' | 'flags'> {
ephemeral?: boolean;
fetchReply?: boolean;
flags?: BitFieldResolvable<'SUPPRESS_EMBEDS' | 'EPHEMERAL', number>;
flags?: BitFieldResolvable<Extract<MessageFlagsString, 'SuppressEmbeds' | 'Ephemeral'>, number>;
}
export interface InteractionUpdateOptions extends MessageEditOptions {
fetchReply?: boolean;
}
export type IntentsString =
| 'GUILDS'
| 'GUILD_MEMBERS'
| 'GUILD_BANS'
| 'GUILD_EMOJIS_AND_STICKERS'
| 'GUILD_INTEGRATIONS'
| 'GUILD_WEBHOOKS'
| 'GUILD_INVITES'
| 'GUILD_VOICE_STATES'
| 'GUILD_PRESENCES'
| 'GUILD_MESSAGES'
| 'GUILD_MESSAGE_REACTIONS'
| 'GUILD_MESSAGE_TYPING'
| 'DIRECT_MESSAGES'
| 'DIRECT_MESSAGE_REACTIONS'
| 'DIRECT_MESSAGE_TYPING'
| 'GUILD_SCHEDULED_EVENTS';
export interface InviteGenerationOptions {
permissions?: PermissionResolvable;
guild?: GuildResolvable;
@@ -4603,16 +4590,6 @@ export interface MessageEvent {
target: WebSocket;
}
export type MessageFlagsString =
| 'CROSSPOSTED'
| 'IS_CROSSPOST'
| 'SUPPRESS_EMBEDS'
| 'SOURCE_MESSAGE_DELETED'
| 'URGENT'
| 'HAS_THREAD'
| 'EPHEMERAL'
| 'LOADING';
export interface MessageInteraction {
id: Snowflake;
type: InteractionType;
@@ -4649,7 +4626,7 @@ export interface MessageOptions {
reply?: ReplyOptions;
stickers?: StickerResolvable[];
attachments?: MessageAttachment[];
flags?: BitFieldResolvable<'SUPPRESS_EMBEDS', number>;
flags?: BitFieldResolvable<Extract<MessageFlagsString, 'SuppressEmbeds'>, number>;
}
export type MessageReactionResolvable =
@@ -4725,57 +4702,14 @@ export interface OverwriteData {
export type OverwriteResolvable = PermissionOverwrites | OverwriteData;
export type PermissionFlags = Record<PermissionString, bigint>;
export type PermissionFlags = Record<keyof typeof PermissionFlagsBits, bigint>;
export type PermissionOverwriteOptions = Partial<Record<PermissionString, boolean | null>>;
export type PermissionOverwriteOptions = Partial<Record<keyof typeof PermissionFlagsBits, boolean | null>>;
export type PermissionResolvable = BitFieldResolvable<PermissionString, bigint>;
export type PermissionResolvable = BitFieldResolvable<keyof typeof PermissionFlagsBits, bigint>;
export type PermissionOverwriteResolvable = UserResolvable | RoleResolvable | PermissionOverwrites;
export type PermissionString =
| 'CREATE_INSTANT_INVITE'
| 'KICK_MEMBERS'
| 'BAN_MEMBERS'
| 'ADMINISTRATOR'
| 'MANAGE_CHANNELS'
| 'MANAGE_GUILD'
| 'ADD_REACTIONS'
| 'VIEW_AUDIT_LOG'
| 'PRIORITY_SPEAKER'
| 'STREAM'
| 'VIEW_CHANNEL'
| 'SEND_MESSAGES'
| 'SEND_TTS_MESSAGES'
| 'MANAGE_MESSAGES'
| 'EMBED_LINKS'
| 'ATTACH_FILES'
| 'READ_MESSAGE_HISTORY'
| 'MENTION_EVERYONE'
| 'USE_EXTERNAL_EMOJIS'
| 'VIEW_GUILD_INSIGHTS'
| 'CONNECT'
| 'SPEAK'
| 'MUTE_MEMBERS'
| 'DEAFEN_MEMBERS'
| 'MOVE_MEMBERS'
| 'USE_VAD'
| 'CHANGE_NICKNAME'
| 'MANAGE_NICKNAMES'
| 'MANAGE_ROLES'
| 'MANAGE_WEBHOOKS'
| 'MANAGE_EMOJIS_AND_STICKERS'
| 'USE_APPLICATION_COMMANDS'
| 'REQUEST_TO_SPEAK'
| 'MANAGE_THREADS'
| 'CREATE_PUBLIC_THREADS'
| 'CREATE_PRIVATE_THREADS'
| 'USE_EXTERNAL_STICKERS'
| 'SEND_MESSAGES_IN_THREADS'
| 'START_EMBEDDED_ACTIVITIES'
| 'MODERATE_MEMBERS'
| 'MANAGE_EVENTS';
export type RecursiveArray<T> = ReadonlyArray<T | RecursiveArray<T>>;
export type RecursiveReadonlyArray<T> = ReadonlyArray<T | RecursiveReadonlyArray<T>>;
@@ -4852,7 +4786,14 @@ export interface PartialRoleData extends RoleData {
id?: Snowflake | number;
}
export type PartialTypes = 'USER' | 'CHANNEL' | 'GUILD_MEMBER' | 'MESSAGE' | 'REACTION' | 'GUILD_SCHEDULED_EVENT';
export enum Partials {
User,
Channel,
GuildMember,
Message,
Reaction,
GuildScheduledEvent,
}
export interface PartialUser extends Partialize<User, 'username' | 'tag' | 'discriminator'> {}
@@ -4876,8 +4817,8 @@ export interface ReplyMessageOptions extends Omit<MessageOptions, 'reply'> {
}
export interface ResolvedOverwriteOptions {
allow: Permissions;
deny: Permissions;
allow: PermissionsBitField;
deny: PermissionsBitField;
}
export interface RoleData {
@@ -4955,12 +4896,6 @@ export type Status = number;
export type StickerResolvable = Sticker | Snowflake;
export type SystemChannelFlagsString =
| 'SUPPRESS_JOIN_NOTIFICATIONS'
| 'SUPPRESS_PREMIUM_SUBSCRIPTIONS'
| 'SUPPRESS_GUILD_REMINDER_NOTIFICATIONS'
| 'SUPPRESS_JOIN_NOTIFICATION_REPLIES';
export type SystemChannelFlagsResolvable = BitFieldResolvable<SystemChannelFlagsString, number>;
export type SystemMessageType = Exclude<
@@ -5068,26 +5003,8 @@ export interface ThreadEditData {
invitable?: boolean;
}
export type ThreadMemberFlagsString = '';
export type ThreadMemberResolvable = ThreadMember | UserResolvable;
export type UserFlagsString =
| 'STAFF'
| 'PARTNER'
| 'HYPESQUAD'
| 'BUG_HUNTER_LEVEL_1'
| 'HYPESQUAD_ONLINE_HOUSE_1'
| 'HYPESQUAD_ONLINE_HOUSE_2'
| 'HYPESQUAD_ONLINE_HOUSE_3'
| 'PREMIUM_EARLY_SUPPORTER'
| 'TEAM_PSEUDO_USER'
| 'BUG_HUNTER_LEVEL_2'
| 'VERIFIED_BOT'
| 'VERIFIED_DEVELOPER'
| 'CERTIFIED_MODERATOR'
| 'BOT_HTTP_INTERACTIONS';
export type UserMention = `<@${Snowflake}>`;
export type UserResolvable = User | Snowflake | Message | GuildMember | ThreadMember;
@@ -5264,6 +5181,7 @@ export type InternalDiscordGatewayAdapterCreator = (
// External
export {
ActivityType,
ActivityFlags,
ApplicationCommandType,
ApplicationCommandOptionType,
ApplicationCommandPermissionType,
@@ -5273,6 +5191,7 @@ export {
GuildMFALevel,
GuildNSFWLevel,
GuildPremiumTier,
GatewayIntentBits,
GuildScheduledEventEntityType,
GuildScheduledEventPrivacyLevel,
GuildScheduledEventStatus,
@@ -5281,10 +5200,15 @@ export {
InteractionResponseType,
InviteTargetType,
MessageType,
MessageFlags,
PermissionFlagsBits,
RESTJSONErrorCodes,
StageInstancePrivacyLevel,
StickerType,
StickerFormatType,
GuildSystemChannelFlags,
ThreadMemberFlags,
UserFlags,
WebhookType,
} from 'discord-api-types/v9';
export {

View File

@@ -14,6 +14,8 @@ import {
ApplicationCommandPermissionType,
ChannelType,
InteractionType,
GatewayIntentBits,
PermissionFlagsBits,
} from 'discord-api-types/v9';
import { AuditLogEvent } from 'discord-api-types/v9';
import {
@@ -47,7 +49,7 @@ import {
GuildEmojiManager,
GuildMember,
GuildResolvable,
Intents,
IntentsBitField,
Interaction,
InteractionCollector,
Message,
@@ -59,7 +61,7 @@ import {
Options,
PartialTextBasedChannelFields,
PartialUser,
Permissions,
PermissionsBitField,
ReactionCollector,
Role,
RoleManager,
@@ -105,7 +107,7 @@ declare const serialize: <T>(value: T) => Serialized<T>;
declare const notPropertyOf: <T, P extends PropertyKey>(value: T, property: P & Exclude<P, keyof T>) => void;
const client: Client = new Client({
intents: Intents.FLAGS.GUILDS,
intents: GatewayIntentBits.Guilds,
makeCache: Options.cacheWithLimits({
MessageManager: 200,
// @ts-expect-error
@@ -719,7 +721,7 @@ client.on('interactionCreate', async interaction => {
const button = new ButtonComponent();
const actionRow = new ActionRow({ type: ComponentType.ActionRow, components: [button] });
const actionRow = new ActionRow<ActionRowComponent>({ type: ComponentType.ActionRow, components: [button] });
await interaction.reply({ content: 'Hi!', components: [actionRow] });
@@ -772,8 +774,8 @@ expectType<{}>(
]),
),
);
expectType<string>(serialize(new Permissions(Permissions.FLAGS.ATTACH_FILES)));
expectType<number>(serialize(new Intents(Intents.FLAGS.GUILDS)));
expectType<string>(serialize(new PermissionsBitField(PermissionFlagsBits.AttachFiles)));
expectType<number>(serialize(new IntentsBitField(GatewayIntentBits.Guilds)));
expectAssignable<unknown>(
serialize(
new Collection([