59 lines
2.4 KiB
JavaScript
59 lines
2.4 KiB
JavaScript
// Debug
|
|
import ModuleDebugBuilder from "../utilities/moduleDebugBuilder.js";
|
|
const log = new ModuleDebugBuilder("bot", "join");
|
|
// Modules
|
|
import { joinVoiceChannel, VoiceConnectionStatus } from "@discordjs/voice";
|
|
import {replyToInteraction} from "../utilities/messageHandler.js";
|
|
import {createAudioInstance} from "../controllers/audioController.js";
|
|
import OpusEncoderPkg from "@discordjs/opus";
|
|
|
|
// Declare the encoder (module is incompatible modern import method)
|
|
const { OpusEncoder } = OpusEncoderPkg;
|
|
const encoder = new OpusEncoder(48000, 2);
|
|
|
|
/**
|
|
* Join the specified voice channel
|
|
*
|
|
* @param interaction Message interaction from discord
|
|
* @param {string||any} guildID The specified Guild ID if this function is run from the client instead of from an interaction in Discord
|
|
* @param {string||any} channelID The channel ID to join
|
|
* @param guild The guild object to be used to create a voice adapter
|
|
* @param {function} callback The callback that will be needed if this function is run with a Guild ID instead of an interaction
|
|
*/
|
|
export default async function join({interaction= undefined, guildID= undefined, channelID = undefined, guildObj = undefined, callback = undefined}){
|
|
if (interaction){
|
|
const voiceChannel = interaction.options.getChannel('voicechannel');
|
|
channelID = voiceChannel.id;
|
|
guildID = interaction.guildId;
|
|
guildObj = interaction.guild;
|
|
if (interaction) replyToInteraction(interaction, `Ok, Joining ${voiceChannel.name}`);
|
|
}
|
|
log.DEBUG("Channel ID: ", channelID)
|
|
log.DEBUG("Guild ID: ", guildID)
|
|
|
|
const voiceConnection = joinVoiceChannel({
|
|
channelId: channelID,
|
|
guildId: guildID,
|
|
adapterCreator: guildObj.voiceAdapterCreator,
|
|
selfMute: false,
|
|
selfDeaf: false,
|
|
});
|
|
|
|
const audioInstance = await createAudioInstance();
|
|
|
|
audioInstance.on('data', buffer => {
|
|
buffer = Buffer.from(buffer);
|
|
const encoded = encoder.encode(buffer);
|
|
// TODO Add a function here to check the volume of either buffer and only play audio to discord when there is audio to be played
|
|
voiceConnection.playOpusPacket(encoded);
|
|
})
|
|
|
|
// Exit the audio handler when the bot disconnects
|
|
voiceConnection.on(VoiceConnectionStatus.Destroyed, () => {
|
|
audioInstance.quit();
|
|
})
|
|
|
|
audioInstance.start();
|
|
|
|
if (guildID && callback) callback();
|
|
} |