discord.js bot joining vc and playing audio - javascript

I want to detect when a specific user joins a voice channel so that the bot joins that same voice channel and starts playing audio.
My code doesn't work: the bot doesn't join the channel. How can I fix this?
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")
}
}
});

Related

discord.js error "channel is not defined"

So im making a mute command which creates a mute role and gives it to the mentioned user, and currently i am getting an error: channel is not defined,
I do not know how to fix this error and i need help with this
module.exports = class MuteCommand extends BaseCommand {
constructor() {
super('mute', 'moderation', []);
}
async run(client, message, args) {
if (!message.member.hasPermission("MUTE_MEMBERS")) return message.channel.send("You do not have Permission to use this command.");
if (!message.guild.me.hasPermission('MANAGE_ROLES')) return message.channel.send("I do not have Permission to mute members.");
let reason = args.slice(1).join(' ');
let roleName = 'Muted';
let muteRole = message.guild.roles.cache.find(x => x.name === roleName);
if (typeof muteRole === undefined) {
guild.roles.create({ data: { name: 'Muted', permissions: ['SEND_MESSAGES', 'ADD_REACTIONS'] } });
} else {
}
muteRole = message.guild.roles.cache.find(x => x.name === roleName);
channel.updateOverwrite(channel.guild.roles.muteRole, { SEND_MESSAGES: false });
const mentionedMember = message.mentions.member.first() || message.guild.members.cache.get(args[0]);
const muteEmbed = new Discord.MessageEmbed()
.setTitle('You have been Muted in '+message.guild.name)
.setDescription('Reason for Mute: '+reason)
.setColor('#6DCE75')
.setTimestamp()
.setFooter(client.user.tag, client.user.displayAvatarURL())
.setImage(message.mentionedMember.displayAvatarURL());
if (!args[0]) return message.channel.send('You must mention a user to mute.');
if (!mentionedMember) return message.channel.send('The user mentioned is not in the server.');
if (mentionedMember.user.id == message.author.id) return message.channel.send('You cannot mute yourself.');
if (mentionedMember.user.id == client.user.id) return message.channel.send('You cannot mute me smh.');
if (!reason) reason = 'No reason given.';
if (mentionedMember.roles.cache.has(muteRole.id)) return message.channel.send('This user has already been muted.');
if (message.member.roles.highest.position <= mentionedMember.roles.highest.position) return message.chanel.send('You cannot mute someone whos role is higher and/or the same as yours');
await mentionedMember.send(muteEmbed).catch(err => console.log(err));
await mentionedMember.roles.add(muteRole.id).catch(err => console.log(err).then(message.channel.send('There was an issue while muting the mentioned Member')));
}
}
I beileive that there could be even more errors than i think in this code as I am fairly new to coding.
You have used "channel" without declaring it. Hence, it is undefined.
check your line "channel.updateOverwrite(channel.guild.roles.muteRole, { SEND_MESSAGES: false });"
const { Client, Intents } = require('discord.js')
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', msg => {
if (msg.content === 'ping') {
msg.channel.send('pong');
});
});
Please refer the below links
Discord.JS documentation: https://github.com/discordjs/discord.js
Stack-overflow answer: Discord.js sending a message to a specific channel

add roles command not working (discord.js)

I am Coding my own discord bot for my server, I have a issue that the bot says no role doesn't exit even if I mentions the role. Here is the code:
const Discord = require('discord.js')
const client = new Discord.Client()
client.on("message", message => {
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase()
if (command === "add") {
if (!message.member.hasPermission("MANAGE_ROLES"))
return message.channel.send("Insufficient permissions")
const member = message.mentions.members.first()
if (!member)
return message.channel.send("No user mentioned")
const add = args.slice(1).join(" ")
if (!add)
return message.channel.send("No role said")
const roleAdd = message.guild.roles.find(role => role.name === add);
if (!roleAdd)
return message.channel.send("Role does not exist")
if (member.roles.has(roleAdd.id)){
return message.channel.send("User already has role")
}
if (member) {
member.addRole(roleAdd).catch((error) =>{
message.channel.send("I cant add...")
}).then((member) => {
message.channel.send(`:thumbsup: ${roleAdd} added to ${member.displayName}`)
})
}
}
})
client.login(config.token)
What did I made a mistake? Thanks.
First make sure you are using discord.js v12. Type npm i discord.js#latest in your terminal. Here you can see all changes in discord.js v12.
If you are using discord.js v12 now, this code should work for you:
if (!message.member.hasPermission("MANAGE_ROLES"))
return message.channel.send("Insufficient permissions")
const member = message.mentions.members.first()
if (!member)
return message.channel.send("No user mentioned")
const add = args.slice(1).join(" ");
if (!add)
return message.channel.send("No role said")
const roleAdd = message.guild.roles.cache.find(role => role.name === add);
if (!roleAdd)
return message.channel.send("Role does not exist")
if (member.roles.cache.has(roleAdd.id)) {
return message.channel.send("User already has role")
}
if (member) {
member.roles.add(roleAdd).catch((error) => {
message.channel.send("I cant add...")
}).then((member) => {
message.channel.send(`:thumbsup: ${roleAdd} added to ${member.displayName}`)
})
}
Mention the role you want to add won't work because here
const roleAdd = message.guild.roles.cache.find(role => role.name === add);
you just find the role by its name. To fix that you can change that line into:
const roleAdd = message.guild.roles.cache.find(role => role.name === add) || message.mentions.roles.first();
This will allow a user to mention the role as well.

How to make bot autorole when someone join voice channel?

How can I make my bot give a role when a user joins a specific voice channel ?
const team1role = message.guild.roles.find((role) => role.name === "Team 1");
const team1members = team1role.members;
const chan1 = message.guild.channels.find((channel) => channel.name === "Team 1")
team1members.forEach((member) => {
member.setVoiceChannel(chan1);
});
You'll want to go inside your main file (the same one as where you put your client.login(TOKEN) function) and create a new event :
client.on('voiceStateUpdate', (oldState, newState) => {
if (!newState.channel || !newState.member) return; // Triggered if the user left a channel
const testChannel = newState.guild.channels.cache.find(c => c.name === 'Team 1');
if (newState.channelID === testChannel.id) { // Triggered when the user joined the channel we tested for
const role = newState.guild.roles.cache.find(r => r.name === 'Team 1');
if (!newState.member.roles.cache.has(role)) newState.member.roles.add(role); // Add the role to the user if they don't already have it
}
});

Discord.js : How do i make my bot play an audio when someones enter any channel

I found someone's trying the same but mine appers this " TypeError: oldPresence.guild.channels.get is not a function"
bot.on('voiceStateUpdate', (oldPresence, newPresence) => {
let newUserChannel = newPresence.voiceChannel
let oldUserChannel = oldPresence.voiceChannel
let textChannel = oldPresence.guild.channels.get('TEXTCHANNEL ID')
connection.join()
.then()
if(oldUserChannel === undefined && newUserChannel !== undefined) {
if (newMember.id === 'MEMBER ID')
{
newUserChannel.join()
.then(connection => {
console.log("Joined voice channel!");
const dispatcher = connection.playFile("E:\UniConverter\Downloaded\Trio.mp3");
dispatcher.on("end", end => {newUserChannel.leave()});
})
.catch(console.error);
}
else
textChannel.send("Hello")
}
}
);
bot.login (token);
In the latest version of Discord.js (v12) the correct function is:
oldPresence.guild.channels.cache.get('ID');

Checking the channel name

const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', (oldMessage, newMessage, role, args, guild) => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', message => {
if (message.content === '.') {
if (message.guild.channel === 'dot-wars') {
message.guild.members.forEach(member => {
var role = message.guild.roles.find(role => role.name === 'Dot Master!');
member.removeRole(role);
})
}
var role = message.guild.roles.find(role => role.name === 'Dot Master!');
message.member.addRole(role);
}
});
okay so what i want to do is when someone sends a '.' the bot will remove the 'Dot Master!' role from everyone in the server and then add the 'Dot Master!' role to the person that sent it, but only if it is in the 'dot-wars' channel.
A text channel has a name property for reading its name. However, make sure you're checking the channel the message was sent in, not the guild (Message#channel).
if (message.channel.name === 'dot-wars') {
...
}

Categories