feat(VoiceState): add methods for fetching voice state

#10442 backport
This commit is contained in:
Elysia
2024-09-17 19:25:19 +07:00
parent 8dfa37fbd9
commit 5a0910a4f9
3 changed files with 33 additions and 0 deletions

View File

@@ -32,6 +32,28 @@ class VoiceStateManager extends CachedManager {
if (cache) this.cache.set(data.user_id, entry); if (cache) this.cache.set(data.user_id, entry);
return entry; return entry;
} }
/**
* Obtains a user's voice state from discord or from the cache if it's already available.
* @param {GuildMemberResolvable|'@me'} member The member whose voice state is to be fetched
* @param {BaseFetchOptions} [options] Additional options for this fetch
* @returns {Promise<VoiceState>}
* @example
* // Fetch a member's voice state
* guild.voiceStates.fetch("66564597481480192")
* .then(console.log)
* .catch(console.error);
*/
async fetch(member, { cache = true, force = false } = {}) {
if (!this.guild?.id) throw new Error('Guild is not defined');
const id = member === '@me' ? member : this.guild.members.resolveId(member);
if (!force) {
const existing = this.cache.get(id === '@me' ? this.client.user.id : id);
if (existing) return existing;
}
const data = await this.client.api.guilds(this.guild.id)['voice-states'][id].get();
return this._add(data, cache);
}
} }
module.exports = VoiceStateManager; module.exports = VoiceStateManager;

View File

@@ -328,6 +328,15 @@ class VoiceState extends Base {
}); });
} }
/**
* Fetches this voice state.
* @param {boolean} [force=true] Whether to skip the cache check and request the API
* @returns {Promise<VoiceState>}
*/
fetch(force = true) {
return this.guild?.voiceStates?.fetch(this.id, { force });
}
toJSON() { toJSON() {
return super.toJSON({ return super.toJSON({
id: true, id: true,

2
typings/index.d.ts vendored
View File

@@ -3559,6 +3559,7 @@ export class VoiceState extends Base {
public setStatus(status?: string): Promise<void>; public setStatus(status?: string): Promise<void>;
public getPreview(): Promise<string>; public getPreview(): Promise<string>;
public postPreview(base64Image: string): Promise<void>; public postPreview(base64Image: string): Promise<void>;
public fetch(force?: boolean): Promise<VoiceState>;
} }
export class Webhook extends WebhookMixin() { export class Webhook extends WebhookMixin() {
@@ -4579,6 +4580,7 @@ export class UserManager extends CachedManager<Snowflake, User, UserResolvable>
export class VoiceStateManager extends CachedManager<Snowflake, VoiceState, typeof VoiceState> { export class VoiceStateManager extends CachedManager<Snowflake, VoiceState, typeof VoiceState> {
private constructor(guild: Guild, iterable?: Iterable<RawVoiceStateData>); private constructor(guild: Guild, iterable?: Iterable<RawVoiceStateData>);
public guild: Guild; public guild: Guild;
public fetch(member: GuildMemberResolvable | '@me', options?: BaseFetchOptions): Promise<VoiceState>;
} }
//#endregion //#endregion