Skip to content

Commit

Permalink
Merge branch 'main' into refactor/typeof-undefined
Browse files Browse the repository at this point in the history
  • Loading branch information
almeidx committed Mar 12, 2023
2 parents 98d467a + 955e8fe commit 6cb9de7
Show file tree
Hide file tree
Showing 20 changed files with 106 additions and 111 deletions.
2 changes: 1 addition & 1 deletion packages/builders/src/messages/embed/Embed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ export class EmbedBuilder {
*
* @remarks
* This method behaves similarly
* to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice | Array.prototype.splice}.
* to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice | Array.prototype.splice}.
* The maximum amount of fields that can be added is 25.
*
* It's useful for modifying and adjusting order of the already-existing fields of an embed.
Expand Down
4 changes: 2 additions & 2 deletions packages/core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ pnpm add @discordjs/core
```ts
import { REST } from '@discordjs/rest';
import { WebSocketManager } from '@discordjs/ws';
import { GatewayIntentBits, InteractionType, MessageFlags, Client } from '@discordjs/core';
import { GatewayDispatchEvents, GatewayIntentBits, InteractionType, MessageFlags, Client } from '@discordjs/core';

// Create REST and WebSocket managers directly
const rest = new REST({ version: '10' }).setToken(token);
Expand All @@ -51,7 +51,7 @@ const client = new Client({ rest, ws });
// Listen for interactions
// Each event contains an `api` prop along with the event data that allows you to interface with the Discord REST API
client.on(GatewayDispatchEvents.InteractionCreate, async ({ data: interaction, api }) => {
if (!(interaction.type === InteractionType.ApplicationCommand) || interaction.data.name !== 'ping') {
if (interaction.type !== InteractionType.ApplicationCommand || interaction.data.name !== 'ping') {
return;
}

Expand Down
17 changes: 17 additions & 0 deletions packages/core/src/api/guild.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import type { RawFile } from '@discordjs/rest';
import { makeURLSearchParams, type REST } from '@discordjs/rest';
import type {
RESTPatchAPIGuildVoiceStateCurrentMemberJSONBody,
RESTPatchAPIGuildVoiceStateCurrentMemberResult,
} from 'discord-api-types/v10';
import {
Routes,
type GuildMFALevel,
Expand Down Expand Up @@ -976,4 +980,17 @@ export class GuildsAPI {
public async getWebhooks(id: Snowflake) {
return this.rest.get(Routes.guildWebhooks(id)) as Promise<RESTGetAPIGuildWebhooksResult>;
}

/**
* Sets the voice state for the current user
*
* @see {@link https://discord.com/developers/docs/resources/guild#modify-current-user-voice-state}
* @param guildId - The id of the guild
* @param options - The options to use when setting the voice state
*/
public async setVoiceState(guildId: Snowflake, options: RESTPatchAPIGuildVoiceStateCurrentMemberJSONBody = {}) {
return this.rest.patch(Routes.guildVoiceState(guildId, '@me'), {
body: options,
}) as Promise<RESTPatchAPIGuildVoiceStateCurrentMemberResult>;
}
}
6 changes: 6 additions & 0 deletions packages/core/src/api/interactions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ export class InteractionsAPI {
) {
await this.rest.post(Routes.interactionCallback(interactionId, interactionToken), {
files,
auth: false,
body: {
type: InteractionResponseType.ChannelMessageWithSource,
data,
Expand All @@ -44,6 +45,7 @@ export class InteractionsAPI {
*/
public async defer(interactionId: Snowflake, interactionToken: string) {
await this.rest.post(Routes.interactionCallback(interactionId, interactionToken), {
auth: false,
body: {
type: InteractionResponseType.DeferredChannelMessageWithSource,
},
Expand All @@ -59,6 +61,7 @@ export class InteractionsAPI {
*/
public async deferMessageUpdate(interactionId: Snowflake, interactionToken: string) {
await this.rest.post(Routes.interactionCallback(interactionId, interactionToken), {
auth: false,
body: {
type: InteractionResponseType.DeferredMessageUpdate,
},
Expand Down Expand Up @@ -143,6 +146,7 @@ export class InteractionsAPI {
) {
await this.rest.post(Routes.interactionCallback(interactionId, interactionToken), {
files,
auth: false,
body: {
type: InteractionResponseType.UpdateMessage,
data,
Expand All @@ -164,6 +168,7 @@ export class InteractionsAPI {
data: APICommandAutocompleteInteractionResponseCallbackData,
) {
await this.rest.post(Routes.interactionCallback(interactionId, interactionToken), {
auth: false,
body: {
type: InteractionResponseType.ApplicationCommandAutocompleteResult,
data,
Expand All @@ -185,6 +190,7 @@ export class InteractionsAPI {
data: APIModalInteractionResponseCallbackData,
) {
await this.rest.post(Routes.interactionCallback(interactionId, interactionToken), {
auth: false,
body: {
type: InteractionResponseType.Modal,
data,
Expand Down
15 changes: 0 additions & 15 deletions packages/core/src/api/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@ import {
type RESTPatchAPICurrentUserResult,
type RESTPatchAPIGuildMemberJSONBody,
type RESTPatchAPIGuildMemberResult,
type RESTPatchAPIGuildVoiceStateCurrentMemberJSONBody,
type RESTPatchAPIGuildVoiceStateCurrentMemberResult,
type RESTPostAPICurrentUserCreateDMChannelResult,
type RESTPutAPICurrentUserApplicationRoleConnectionJSONBody,
type RESTPutAPICurrentUserApplicationRoleConnectionResult,
Expand Down Expand Up @@ -99,19 +97,6 @@ export class UsersAPI {
}) as Promise<RESTPatchAPIGuildMemberResult>;
}

/**
* Sets the voice state for the current user
*
* @see {@link https://discord.com/developers/docs/resources/guild#modify-current-user-voice-state}
* @param guildId - The id of the guild
* @param options - The options to use when setting the voice state
*/
public async setVoiceState(guildId: Snowflake, options: RESTPatchAPIGuildVoiceStateCurrentMemberJSONBody = {}) {
return this.rest.patch(Routes.guildVoiceState(guildId, '@me'), {
body: options,
}) as Promise<RESTPatchAPIGuildVoiceStateCurrentMemberResult>;
}

/**
* Opens a new DM channel with a user
*
Expand Down
26 changes: 14 additions & 12 deletions packages/core/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import { AsyncEventEmitter } from '@vladfrangu/async_event_emitter';
import {
GatewayDispatchEvents,
GatewayOpcodes,
type GatewayVoiceStateUpdateData,
type APIGuildMember,
type GatewayAutoModerationActionExecutionDispatchData,
type GatewayAutoModerationRuleCreateDispatchData,
Expand All @@ -17,6 +16,7 @@ import {
type GatewayChannelDeleteDispatchData,
type GatewayChannelPinsUpdateDispatchData,
type GatewayChannelUpdateDispatchData,
type GatewayGuildAuditLogEntryCreateDispatchData,
type GatewayGuildBanAddDispatchData,
type GatewayGuildBanRemoveDispatchData,
type GatewayGuildCreateDispatchData,
Expand All @@ -25,8 +25,8 @@ import {
type GatewayGuildIntegrationsUpdateDispatchData,
type GatewayGuildMemberAddDispatchData,
type GatewayGuildMemberRemoveDispatchData,
type GatewayGuildMembersChunkDispatchData,
type GatewayGuildMemberUpdateDispatchData,
type GatewayGuildMembersChunkDispatchData,
type GatewayGuildRoleCreateDispatchData,
type GatewayGuildRoleDeleteDispatchData,
type GatewayGuildRoleUpdateDispatchData,
Expand All @@ -51,6 +51,7 @@ import {
type GatewayMessageReactionRemoveDispatchData,
type GatewayMessageReactionRemoveEmojiDispatchData,
type GatewayMessageUpdateDispatchData,
type GatewayPresenceUpdateData,
type GatewayPresenceUpdateDispatchData,
type GatewayReadyDispatchData,
type GatewayRequestGuildMembersData,
Expand All @@ -60,15 +61,15 @@ import {
type GatewayThreadCreateDispatchData,
type GatewayThreadDeleteDispatchData,
type GatewayThreadListSyncDispatchData,
type GatewayThreadMembersUpdateDispatchData,
type GatewayThreadMemberUpdateDispatchData,
type GatewayThreadMembersUpdateDispatchData,
type GatewayThreadUpdateDispatchData,
type GatewayTypingStartDispatchData,
type GatewayUserUpdateDispatchData,
type GatewayVoiceServerUpdateDispatchData,
type GatewayVoiceStateUpdateData,
type GatewayVoiceStateUpdateDispatchData,
type GatewayWebhooksUpdateDispatchData,
type GatewayPresenceUpdateData,
} from 'discord-api-types/v10';
import { API } from './api/index.js';

Expand All @@ -88,10 +89,17 @@ export interface WithIntrinsicProps<T> extends IntrinsicProps {
}

export interface MappedEvents {
[GatewayDispatchEvents.AutoModerationActionExecution]: [
WithIntrinsicProps<GatewayAutoModerationActionExecutionDispatchData>,
];
[GatewayDispatchEvents.AutoModerationRuleCreate]: [WithIntrinsicProps<GatewayAutoModerationRuleCreateDispatchData>];
[GatewayDispatchEvents.AutoModerationRuleDelete]: [WithIntrinsicProps<GatewayAutoModerationRuleDeleteDispatchData>];
[GatewayDispatchEvents.AutoModerationRuleUpdate]: [WithIntrinsicProps<GatewayAutoModerationRuleUpdateDispatchData>];
[GatewayDispatchEvents.ChannelCreate]: [WithIntrinsicProps<GatewayChannelCreateDispatchData>];
[GatewayDispatchEvents.ChannelDelete]: [WithIntrinsicProps<GatewayChannelDeleteDispatchData>];
[GatewayDispatchEvents.ChannelPinsUpdate]: [WithIntrinsicProps<GatewayChannelPinsUpdateDispatchData>];
[GatewayDispatchEvents.ChannelUpdate]: [WithIntrinsicProps<GatewayChannelUpdateDispatchData>];
[GatewayDispatchEvents.GuildAuditLogEntryCreate]: [WithIntrinsicProps<GatewayGuildAuditLogEntryCreateDispatchData>];
[GatewayDispatchEvents.GuildBanAdd]: [WithIntrinsicProps<GatewayGuildBanAddDispatchData>];
[GatewayDispatchEvents.GuildBanRemove]: [WithIntrinsicProps<GatewayGuildBanRemoveDispatchData>];
[GatewayDispatchEvents.GuildCreate]: [WithIntrinsicProps<GatewayGuildCreateDispatchData>];
Expand Down Expand Up @@ -134,6 +142,7 @@ export interface MappedEvents {
[GatewayDispatchEvents.MessageUpdate]: [WithIntrinsicProps<GatewayMessageUpdateDispatchData>];
[GatewayDispatchEvents.PresenceUpdate]: [WithIntrinsicProps<GatewayPresenceUpdateDispatchData>];
[GatewayDispatchEvents.Ready]: [WithIntrinsicProps<GatewayReadyDispatchData>];
[GatewayDispatchEvents.Resumed]: [WithIntrinsicProps<never>];
[GatewayDispatchEvents.StageInstanceCreate]: [WithIntrinsicProps<GatewayStageInstanceCreateDispatchData>];
[GatewayDispatchEvents.StageInstanceDelete]: [WithIntrinsicProps<GatewayStageInstanceDeleteDispatchData>];
[GatewayDispatchEvents.StageInstanceUpdate]: [WithIntrinsicProps<GatewayStageInstanceUpdateDispatchData>];
Expand All @@ -143,18 +152,11 @@ export interface MappedEvents {
[GatewayDispatchEvents.ThreadMemberUpdate]: [WithIntrinsicProps<GatewayThreadMemberUpdateDispatchData>];
[GatewayDispatchEvents.ThreadMembersUpdate]: [WithIntrinsicProps<GatewayThreadMembersUpdateDispatchData>];
[GatewayDispatchEvents.ThreadUpdate]: [WithIntrinsicProps<GatewayThreadUpdateDispatchData>];
[GatewayDispatchEvents.TypingStart]: [WithIntrinsicProps<GatewayTypingStartDispatchData>];
[GatewayDispatchEvents.UserUpdate]: [WithIntrinsicProps<GatewayUserUpdateDispatchData>];
[GatewayDispatchEvents.VoiceServerUpdate]: [WithIntrinsicProps<GatewayVoiceServerUpdateDispatchData>];
[GatewayDispatchEvents.VoiceStateUpdate]: [WithIntrinsicProps<GatewayVoiceStateUpdateDispatchData>];
[GatewayDispatchEvents.WebhooksUpdate]: [WithIntrinsicProps<GatewayWebhooksUpdateDispatchData>];
[GatewayDispatchEvents.Resumed]: [WithIntrinsicProps<never>];
[GatewayDispatchEvents.TypingStart]: [WithIntrinsicProps<GatewayTypingStartDispatchData>];
[GatewayDispatchEvents.AutoModerationActionExecution]: [
WithIntrinsicProps<GatewayAutoModerationActionExecutionDispatchData>,
];
[GatewayDispatchEvents.AutoModerationRuleCreate]: [WithIntrinsicProps<GatewayAutoModerationRuleCreateDispatchData>];
[GatewayDispatchEvents.AutoModerationRuleDelete]: [WithIntrinsicProps<GatewayAutoModerationRuleDeleteDispatchData>];
[GatewayDispatchEvents.AutoModerationRuleUpdate]: [WithIntrinsicProps<GatewayAutoModerationRuleUpdateDispatchData>];
}

export type ManagerShardEventsMap = {
Expand Down
6 changes: 3 additions & 3 deletions packages/discord.js/src/client/actions/Action.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ class GenericAction {
getChannel(data) {
const id = data.channel_id ?? data.id;
return (
data.channel ??
data[this.client.actions.injectedChannel] ??
this.getPayload(
{
id,
Expand All @@ -51,7 +51,7 @@ class GenericAction {
getMessage(data, channel, cache) {
const id = data.message_id ?? data.id;
return (
data.message ??
data[this.client.actions.injectedMessage] ??
this.getPayload(
{
id,
Expand Down Expand Up @@ -86,7 +86,7 @@ class GenericAction {

getUser(data) {
const id = data.user_id;
return data.user ?? this.getPayload({ id }, this.client.users, id, Partials.User);
return data[this.client.actions.injectedUser] ?? this.getPayload({ id }, this.client.users, id, Partials.User);
}

getUserFromMember(data) {
Expand Down
7 changes: 7 additions & 0 deletions packages/discord.js/src/client/actions/ActionsManager.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
'use strict';

class ActionsManager {
// These symbols represent fully built data that we inject at times when calling actions manually. Action#getUser,
// for example, will return the injected data (which is assumed to be a built structure) instead of trying to make it
// from provided data
injectedUser = Symbol('djs.actions.injectedUser');
injectedChannel = Symbol('djs.actions.injectedChannel');
injectedMessage = Symbol('djs.actions.injectedMessage');

constructor(client) {
this.client = client;

Expand Down
1 change: 1 addition & 0 deletions packages/discord.js/src/managers/MessageManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ class MessageManager extends CachedManager {

/**
* Options used to fetch multiple messages.
* <info>The `before`, `after`, and `around` parameters are mutually exclusive.</info>
* @typedef {Object} FetchMessagesOptions
* @property {number} [limit] The maximum number of messages to return
* @property {Snowflake} [before] Consider only messages before this id
Expand Down
2 changes: 1 addition & 1 deletion packages/discord.js/src/managers/ThreadManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ class ThreadManager extends CachedManager {
let id;
const query = makeURLSearchParams({ limit });
if (before !== undefined) {
if (before instanceof ThreadChannel || /^\d{16,19}$/.test(String(before))) {
if (before instanceof ThreadChannel || /^\d{17,19}$/.test(String(before))) {
id = this.resolveId(before);
timestamp = this.resolve(before)?.archivedAt?.toISOString();
const toUse = type === 'private' && !fetchAll ? id : timestamp;
Expand Down
6 changes: 3 additions & 3 deletions packages/discord.js/src/structures/Message.js
Original file line number Diff line number Diff line change
Expand Up @@ -787,9 +787,9 @@ class Message extends Base {

return this.client.actions.MessageReactionAdd.handle(
{
user: this.client.user,
channel: this.channel,
message: this,
[this.client.actions.injectedUser]: this.client.user,
[this.client.actions.injectedChannel]: this.channel,
[this.client.actions.injectedMessage]: this,
emoji: resolvePartialEmoji(emoji),
},
true,
Expand Down
15 changes: 15 additions & 0 deletions packages/discord.js/src/structures/interfaces/Collector.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,20 @@ class Collector extends EventEmitter {

if (options.time) this._timeout = setTimeout(() => this.stop('time'), options.time).unref();
if (options.idle) this._idletimeout = setTimeout(() => this.stop('idle'), options.idle).unref();

/**
* The timestamp at which this collector last collected an item
* @type {?number}
*/
this.lastCollectedTimestamp = null;
}

/**
* The Date at which this collector last collected an item
* @type {?Date}
*/
get lastCollectedAt() {
return this.lastCollectedTimestamp && new Date(this.lastCollectedTimestamp);
}

/**
Expand All @@ -118,6 +132,7 @@ class Collector extends EventEmitter {
*/
this.emit('collect', ...args);

this.lastCollectedTimestamp = Date.now();
if (this._idletimeout) {
clearTimeout(this._idletimeout);
this._idletimeout = setTimeout(() => this.stop('idle'), this.options.idle).unref();
Expand Down
2 changes: 2 additions & 0 deletions packages/discord.js/typings/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1060,6 +1060,8 @@ export abstract class Collector<K, V, F extends unknown[] = []> extends EventEmi

public readonly client: Client;
public collected: Collection<K, V>;
public lastCollectedTimestamp: number | null;
public get lastCollectedAt(): Date | null;
public ended: boolean;
public get endReason(): string | null;
public filter: CollectorFilter<[V, ...F]>;
Expand Down
2 changes: 1 addition & 1 deletion packages/proxy-container/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ COPY --from=builder /usr/proxy/out/yarn.lock ./yarn.lock
RUN yarn install

COPY --from=builder /usr/proxy/out/full/ .
COPY tsup.config.js tsup.config.js
COPY tsup.config.ts tsup.config.ts
COPY turbo.json turbo.json
COPY tsconfig.json tsconfig.json
RUN yarn dlx turbo run build --filter=@discordjs/proxy-container...
Expand Down
6 changes: 3 additions & 3 deletions packages/rest/src/lib/RequestManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -499,14 +499,14 @@ export class RequestManager extends EventEmitter {
* @internal
*/
private static generateRouteData(endpoint: RouteLike, method: RequestMethod): RouteData {
const majorIdMatch = /^\/(?:channels|guilds|webhooks)\/(\d{16,19})/.exec(endpoint);
const majorIdMatch = /^\/(?:channels|guilds|webhooks)\/(\d{17,19})/.exec(endpoint);

// Get the major id for this route - global otherwise
const majorId = majorIdMatch?.[1] ?? 'global';

const baseRoute = endpoint
// Strip out all ids
.replaceAll(/\d{16,19}/g, ':id')
.replaceAll(/\d{17,19}/g, ':id')
// Strip out reaction as they fall under the same bucket
.replace(/\/reactions\/(.*)/, '/reactions/:reaction');

Expand All @@ -515,7 +515,7 @@ export class RequestManager extends EventEmitter {
// Hard-Code Old Message Deletion Exception (2 week+ old messages are a different bucket)
// https://github.com/discord/discord-api-docs/issues/1295
if (method === RequestMethod.Delete && baseRoute === '/channels/:id/messages/:id') {
const id = /\d{16,19}$/.exec(endpoint)![0]!;
const id = /\d{17,19}$/.exec(endpoint)![0]!;
const timestamp = DiscordSnowflake.timestampFrom(id);
if (Date.now() - timestamp > 1_000 * 60 * 60 * 24 * 14) {
exceptions += '/Delete Old Message';
Expand Down
14 changes: 14 additions & 0 deletions packages/voice/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,20 @@

All notable changes to this project will be documented in this file.

# [@discordjs/voice@0.15.0](https://github.com/discordjs/discord.js/compare/@discordjs/voice@0.14.0...@discordjs/voice@0.15.0) - (2023-03-12)

## Bug Fixes

- **Voice:** Send keep alives without awaiting a response (#9202) ([c6d98fa](https://github.com/discordjs/discord.js/commit/c6d98fa0c55a482cd4a81abd6f08290c29839b1b))

## Documentation

- Fix version export (#9049) ([8b70f49](https://github.com/discordjs/discord.js/commit/8b70f497a1207e30edebdecd12b926c981c13d28))

## Features

- **website:** Add support for source file links (#9048) ([f6506e9](https://github.com/discordjs/discord.js/commit/f6506e99c496683ee0ab67db0726b105b929af38))

# [@discordjs/voice@0.14.0](https://github.com/discordjs/discord.js/compare/@discordjs/voice@0.13.0...@discordjs/voice@0.14.0) - (2022-11-28)

## Bug Fixes
Expand Down

0 comments on commit 6cb9de7

Please sign in to comment.