2021-06-11 16:50:43 +05:00
|
|
|
import { VoiceChannel, StageChannel, Collection, Snowflake } from "discord.js";
|
2021-06-11 14:06:51 +05:00
|
|
|
import { entersState, joinVoiceChannel, VoiceConnection, VoiceConnectionStatus } from "@discordjs/voice";
|
|
|
|
import { VoiceSubscription } from "./VoiceSubscription";
|
|
|
|
|
|
|
|
class VoiceUtils {
|
2021-06-11 16:50:43 +05:00
|
|
|
public cache = new Collection<Snowflake, VoiceSubscription>();
|
2021-06-11 14:06:51 +05:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Joins a voice channel
|
|
|
|
* @param {StageChannel|VoiceChannel} channel The voice channel
|
|
|
|
* @param {({deaf?: boolean;maxTime?: number;})} [options] Join options
|
|
|
|
* @returns {Promise<VoiceSubscription>}
|
|
|
|
*/
|
2021-06-11 16:50:43 +05:00
|
|
|
public async connect(
|
2021-06-11 14:06:51 +05:00
|
|
|
channel: VoiceChannel | StageChannel,
|
|
|
|
options?: {
|
2021-06-11 14:17:42 +05:00
|
|
|
deaf?: boolean;
|
|
|
|
maxTime?: number;
|
|
|
|
}
|
|
|
|
): Promise<VoiceSubscription> {
|
2021-06-11 14:06:51 +05:00
|
|
|
let conn = joinVoiceChannel({
|
|
|
|
guildId: channel.guild.id,
|
|
|
|
channelId: channel.id,
|
|
|
|
adapterCreator: channel.guild.voiceAdapterCreator,
|
|
|
|
selfDeaf: Boolean(options?.deaf)
|
|
|
|
});
|
|
|
|
|
|
|
|
try {
|
|
|
|
conn = await entersState(conn, VoiceConnectionStatus.Ready, options?.maxTime ?? 20000);
|
2021-06-11 16:50:43 +05:00
|
|
|
const sub = new VoiceSubscription(conn);
|
|
|
|
this.cache.set(channel.guild.id, sub);
|
|
|
|
return sub;
|
2021-06-11 14:17:42 +05:00
|
|
|
} catch (err) {
|
2021-06-11 14:06:51 +05:00
|
|
|
conn.destroy();
|
|
|
|
throw err;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Disconnects voice connection
|
|
|
|
* @param {VoiceConnection} connection The voice connection
|
|
|
|
*/
|
2021-06-11 16:50:43 +05:00
|
|
|
public disconnect(connection: VoiceConnection | VoiceSubscription) {
|
2021-06-11 14:28:21 +05:00
|
|
|
if (connection instanceof VoiceSubscription) return connection.voiceConnection.destroy();
|
2021-06-11 14:45:27 +05:00
|
|
|
return connection.destroy();
|
2021-06-11 14:06:51 +05:00
|
|
|
}
|
2021-06-11 16:50:43 +05:00
|
|
|
|
|
|
|
public getConnection(guild: Snowflake) {
|
|
|
|
return this.cache.get(guild);
|
|
|
|
}
|
2021-06-11 14:06:51 +05:00
|
|
|
}
|
|
|
|
|
2021-06-11 14:17:42 +05:00
|
|
|
export { VoiceUtils };
|