If bot is in the channel, ignore the join command - javascript

I'm making a discord bot and I came across a problem, if I type $join into chat, I want the bot to join the voice channel I'm in and play a sound. That is working but when the bot is already in the voice channel and I type $join again, it just plays the sound again and I want it to play the sound only once when it connects to the channel. I tried to solve it with some if, else and return functions but it didn't work, thanks for help.
This is my code working like I described.
message.delete({
timeout: 5000
})
const voiceChannel = message.member.voice.channel
if (voiceChannel) {
const connection = await voiceChannel.join()
const dispatcher = connection.play("./sounds/xxx.mp3")
dispatcher.setVolume(0.5)
} else {
message.reply("you need to be in a voice channel!").then(message => {
message.delete({
timeout: 5000
})
})
}

You need to check whether the channel of your voice connection is the same you're about to join: if so, you don't need to do anything (you're already in the channel), otherwise you join, make the sound etc...
You can do this with VoiceConnection.channel
Here's how I would do it:
const voiceChannel = message.member.voice.channel
if (voiceChannel) {
// Check if any of the ALREADY EXISTING connections are in that channel, if not connect
if (!client.voice.connections.some(conn => conn.channel.id == voiceChannel.id)) {
const connection = await voiceChannel.join()
const dispatcher = connection.play("./sounds/xxx.mp3")
dispatcher.setVolume(0.5)
} // else: you're already in the channel
} else {
let m = await message.reply("You need to be in a voice channel!")
m.delete({ timeout: 5000 })
}

Related

Send a TTS message to a text channel when a person joins a specific voice channel

I'm trying to create my first bot with TypeScript for discord. I'm trying to achieve a bot that sends a message to a text channel when a person joins a specific voice channel.
My code:
const { Client, Intents } = require('discord.js');
const client = new Client({
token: 'thetokenisfilled:D',
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_VOICE_STATES,
],
});
client.on('voiceStateUpdate', async (oldState, newState) => {
console.log ("funciona");
const DISCORDIOS_ID = '500010831535276032';
const DISCORDIOSTXT_ID = '505856553623224334';
// if there is no newState channel, the user has just left a channel
const USER_LEFT = !newState.channel;
// if there is no oldState channel, the user has just joined a channel
const USER_JOINED = !oldState.channel;
// if there are oldState and newState channels, but the IDs are different,
// user has just switched voice channels
const USER_SWITCHED = newState.channel?.id !== oldState.channel?.id;
// if a user has just left a channel, stop executing the code
if (USER_LEFT)
return;
if (
// if a user has just joined or switched to a voice channel
(USER_JOINED || USER_SWITCHED) &&
// and the new voice channel is the same as the support channel
newState.channel.id === DISCORDIOS_ID
) {
try {
let logChannel = await client.channels.fetch(DISCORDIOSTXT_ID);
logChannel.send(`joined the support channel`);
//logChannel.send(`${newState.member.displayName} joined the support channel`, { tts: true });
} catch (err) {
console.error('❌ Error finding the log channel, check the error below');
console.error(err);
return;
}
}
});
For some reason the bot runs but it's not doing nothing in the channels. It's not sending the simple message or the TTS message.

Play Audio when Joining a Voice Channel DiscordJS v13

I've been trying all night to get a simple task working, but yet I am not able to figure out how.
Basically what I achieved is that the Bot joins a Voice Channel when somebody joins, play an Audio file and that's it. What I want to achieve is that it joins when somebody joins, play the Audio file and then leave and as when somebody leaves the voice chat. It's supposed to join the voice chat, play a different audio file and then leave again.
All in all seems easy, but I've been banging my head against it with no results. If possible I would also like to have the code be tidy there aswell.
Here is the code (using discord.js v13):
client.on('voiceStateUpdate', (oldState, newState) => {
if (oldState.channelId === null) {
console.log("Joined")
//playAudio(newState.channelId, './files/bruh.mp3')
const connection = joinVoiceChannel({
channelId: newState.channelId,
guildId: newState.guild.id,
adapterCreator: newState.guild.voiceAdapterCreator,
})
console.log(newState.guild.voiceAdapterCreator)
const player = createAudioPlayer();
connection.subscribe(player)
const resource = createAudioResource('./files/riff.mp3')
player.play(resource)
} else if (newState.channelId === null) {
console.log("Left")
}
});
Edith: With when somebody joins. I mean when somebody joins Voice Chat.
After a Good Nights sleep I was able to figure it out, for anyone corious, here is the code!
var isReady = true
function playAudio(chID, guID, adpID, audioFile) {
isReady = false
const connection = joinVoiceChannel({
channelId: chID,
guildId: guID,
adapterCreator: adpID,
})
const player = createAudioPlayer();
connection.subscribe(player)
const resource = createAudioResource(audioFile)
player.play(resource)
player.on(AudioPlayerStatus.Idle, () => {
connection.destroy()
});
isReady = true
}

Channel members are not getting updated

I'm using discord.js v13.
I want to disconnect all members from a voice channel. Using interaction.guild.channels.fetch(), I'm able to get voice channels and the members' information.
But when I switch the voice channel, the data is still wrong because it's not updating.
This is my code:
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const { commandName } = interaction;
switch (commandName) {
case 'channels':
const channelInput = interaction.options.getString('channelname');
const channelExist = (await interaction.guild.channels.fetch()).find(channel => {
return channel.name == channelInput && channel.isVoice()
})
if (!channelExist) {
await interaction.reply('no voice channel');
break;
}
console.log(channelExist.members)
console.log('===========')
break;
}
});
How can I fix this problem?
To receive updates from voice channels on who is joining and leaving which channels you need to supply you client with the GUILD_VOICE_STATES intent. That will allow your data to update.

Discordjs join voice channel and says a something then leave voice channel

I want my bot to join the voice channel where the commanding person is located and say something then leave, I tried to do this but I failed. The bot joins the sound channel but does not say anything. How can I do that?
Codes:
client.on('message', async message => {
if (!message.guild) return;
if (message.content.toLowerCase() === prefix + "bruh" ) {
if (message.member.voice.channel) {
const connection = await message.member.voice.channel.join();
} else {
message.reply('First of all you have to join an audio channel !');
const ytdl = require('ytdl-core');
connection.play(ytdl('https://www.youtube.com/watch?v=2ZIpFytCSVc', { filter: 'audioonly' }));
}
}
});
Your bot is not playing that YouTube video because you did not tell it to since you put the play() method in the else statement, not the if statement where it belongs.
Also, when importing a package, it is important you do so at the top of your file, not within the code, this is bad practice.
const ytdl = require('ytdl-core');
client.on('message', async message => {
if (!message.guild) return;
if (message.content.toLowerCase() === prefix + "bruh") {
if (message.member.voice.channel) {
const connection = await message.member.voice.channel.join();
connection.play(ytdl('https://www.youtube.com/watch?v=2ZIpFytCSVc', { filter: 'audioonly' }));
} else {
message.reply('First of all you have to join an audio channel !');
}
}
});

Discord Bot that Plays an Audio File When Someone Joins

I would like the bot to join a voice channel when someone joins and then play a sound file.
So far, I've gotten the bot to join the voice channel but it just doesn't play the sound and no errors show so I don't really know what is going wrong.
const Discord = require('discord.js');
const bot = new Discord.Client();
bot.login('BOT TOKEN');
bot.on('voiceStateUpdate', (oldMember, newMember) => {
let newUserChannel = newMember.voiceChannel
let oldUserChannel = oldMember.voiceChannel
let textChannel = oldMember.guild.channels.get('TEXTCHANNEL ID')
if(oldUserChannel === undefined && newUserChannel !== undefined) {
if (newMember.id === 'MEMEBER ID') //Member 1
{
newUserChannel.join()
.then(connection => {
console.log("Joined voice channel!");
const dispatcher = connection.playFile("C:\Users\NAME\Documents\Welcome_Bot\music\bossman.mp3");
dispatcher.on("end", end => {newUserChannel.leave()});
})
.catch(console.error);
}
else if (newMember.id === 'MEMEBER ID') //Member 2
{
textChannel.send('Hello Member 2')
}
else if (newMember.id === 'MEMEBER ID') //Member 3
{
textChannel.send('Hello Member 3')
}
else //Random
{
textChannel.send("Hello")
}
}
});
I believe your issue is that the bot isn't actually joining the channel before you call the dispatcher. The bot needs to be told to enter the channel before you call the dispatcher. Havn't worked on audio in a while but I believe that connection.join() right above your dispatcher would work. You may need to .then() to ensure it dosn't initilize the dispatcher before the bot joins the channel.

Categories

Resources