Creating channel and setChannel troubles - discord.js

I'm having trouble creating a discord bot, what it should do is detect whenever someone jkoins a specific voice Chat, and if a user does, the bot would have to create a new channel with, as the name, the nickname of the user who joined, then move that user to the new created channel and set that channel to private so no one can join.
Currently my problems are:
-I can't set the name of the new channel as the nickname of the user
-I can't move the user to that channel
-And I think the rest may work
Here is the part of my code:
client.on('voiceStateUpdate', (oldMember, newMember) => {
if(newMember.channelID != '693086073244483614') return;
const nick = newMember.nickname;
newMember.guild.channels.create('test', { type: 'voice' })
.then(() => {
newMember.setChannel('test');
console.log(`Hello from ${newMember.channel}!`);
const nChannel = newMember.channel;
nChannel.setParent('690292158636360032');
nChannel.overwritePermissions([
{
parent: '#690292158636360032',
id: '532236212967047169',
deny: ['CONNECT'],
},
]);
});
});
Any help would be appriciated, I'm new to both discord bots and javascript, so thanks a lot!

The Client#voiceStateUpdate event does not return a member, it returns a VoiceState. https://discord.js.org/#/docs/main/stable/class/Client?scrollTo=e-voiceStateUpdate
From the VoiceState, you can get a member with <VoiceState>.member.
So to fix your error, replace const nick = newMember.nickname to const nick = newMember.member.nickname.

client.on('voiceStateUpdate', (oldMember, newMember) => {
var oldUserChannel = oldMember.voiceChannel;
var newUserChannel = newMember.voiceChannel;
if(oldUserChannel === undefined && newUserChannel !== undefined) { //User joined the channel.
if(newMember.voiceChannel.id != '693086073244483614') return; //Check if the user join the right voice channel.
let nick = newMember.nickname;
if(nick == null){
nick = newMember.user.username; //If the member doesn't have a nickname.
}
newMember.guild.createChannel(nick, { type: 'voice' })
.then((nChannel) => {
console.log(`Hello from ${nChannel}!`);
nChannel.setParent('690292158636360032'); //Your category ID
nChannel.overwritePermissions(nChannel.guild.defaultRole.id, {
VIEW_CHANNEL: false
});
newMember.setVoiceChannel(nChannel)
});
} else if(newUserChannel === undefined){ //User left the channel.
if(oldMember.voiceChannel.parent == null) return;
if(oldMember.voiceChannel.parent.id != '690292158636360032') return; //Check if the voice channel is under the specified category.
if(oldMember.voiceChannel.members.first() == null){ //There is no more users in this channel.
oldMember.voiceChannel.delete(); //Delete the channel.
}
}
});
Here is the final result, fully working. I also add a system to automatically remove the channel if there is nobody in.
I have added some annotations, tell me if you have any questions.

Related

How to ban user on pinging someone?

I'm trying to make a discord bot on, when pinging the owner, auto bans the author that pinged the player. The issue is, it bans the player for saying anything, how would I make it that it'd only ban if they pinged the owner?
Here's the code.
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = '<#329005206526361610>'
client.once('ready', () => {
console.log("Wary's Defender Bot is up");
});
function getUserFromMention(mention) {
if (!mention) return;
if (mention.startsWith('!')) {
mention = mention.slice(1);
}
if (mention.startsWith('<#329005206526361610') && mention.endsWith('>')) return {
// mention = mention.slice(2, -1),
return: client.users.cache.get(mention)
}
}
client.on('message', _message => {
// if(!_message.content.users.has('#warycoolio')) return;
const user = getUserFromMention(_message.content);
if(user) return;
console.log('found target')
var member = _message.author
var rMember = _message.guild.member(_message.author)
// ban7, 'lol.'
rMember.ban({ days: 7, reason: 'They deserved it'}); {
// Successmessage
console.log('target dead.')
}
});
You can do this by checking _message.mentions.users with .has() and passing in the guild owner's id.
Use .has() instead of checking message content, this will automatically check the Message#mentions collection.
Dynamically get the guild owner's id using Guild#ownerID.
client.on('message', _message => {
if (_message.mentions.users.has(_message.guild.ownerID)) {
_message.author.ban({ days: 7, reason: 'They deserved it'});
}
});
You could just do a quick check to see if the mentions include a mention to the owner of the server, and then ban the user.
client.on("message", _message => {
if (_message.mentions.users.first().id === "owner id") {
message.author.ban()
}
})

Discord.JS bot not responding to several commmands

My bot is not responding to any commands except for the .purge command.
Here is my code.
const { Client, MessageEmbed } = require('discord.js');
const client = new Client();
const { prefix, token } = require('./config.json');
client.on('ready', () => {
client.user.setStatus('invisible');
console.log('Bot ready!');
client.user.setActivity('Bot is in WIP Do not expect stuff to work', {
type: 'STREAMING',
url: "https://www.twitch.tv/jonkps4"
});
console.log('Changed status!');
});
client.on('message', message => {
if (message.content.startsWith(".") || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (message === 'apply') {
message.reply("The Small Developers Application form link is:")
message.reply("https://forms.gle/nb6QwNySjC63wSMUA")
}
if (message === 'kick') {
const user = message.mentions.users.first();
// If we have a user mentioned
if (user) {
// Now we get the member from the user
const member = message.guild.member(user);
// If the member is in the guild
if (member) {
member
.kick('Optional reason that will display in the audit logs')
.then(() => {
// We let the message author know we were able to kick the person
message.reply(`Successfully kicked ${user.tag}`);
})
.catch(err => {
message.reply('I was unable to kick the member \n Maybe due to I having missing permissions or My role is not the higher than the role the person to kick has');
// Log the error
console.error(err);
});
} else {
// The mentioned user isn't in this guild
message.reply("That user isn't in this guild!");
}
// Otherwise, if no user was mentioned
} else {
message.reply("You didn't mention the user to kick!");
}
}
if (command === 'purge') {
const amount = parseInt(args[0]) + 1;
if (isNaN(amount)) {
return message.reply('Not a valid number');
} else if (amount > 100) {
return message.reply('Too many messages to clear. \n In order to clear the whole channel or clear more please either ```1. Right click on the channel and click Clone Channel``` or ```2. Execute this command again but more times and a number less than 100.```');
} else if (amount <= 1) {
return message.reply('Amount of messages to clear **MUST** not be less than 1 or more than 100.')
}
message.channel.bulkDelete(amount, true).catch(err => {
console.error(err);
message.channel.send('**There was an error trying to prune messages in this channel!**');
});
}
});
client.login(token);
I need a specific command to work which is the .apply command
and i would like to know why my embeds do not work.
I tried this embed example It didn't work.
const embed = new MessageEmbed()
// Set the title of the field
.setTitle('A slick little embed')
// Set the color of the embed
.setColor(0xff0000)
// Set the main content of the embed
.setDescription('Hello, this is a slick embed!');
.setThumbnail('https://tr.rbxcdn.com/23e104f6348dd71d597c3246990b9d84/420/420/Decal/Png')
// Send the embed to the same channel as the message
message.channel.send(embed);
What did I do wrong? I am quite new to Discord.JS Any help would be needed.
You used the message parameter instead of command. Instead of message === 'xxx' put command === 'xxx'. Simple mistake, I think that was what you meant anyways. Of course the purge command worked because you put command === 'purge' there

Sending a message to specific channel when user joins voice channel doesnt work

Already looked for every issue on stackoverflow and nothing works.
I want my bot to send a message, if someone joins a specific voice channel.
client.on('voiceStateUpdate', (oldMember, newMember) => {
// Here I'm storing the IDs of their voice channels, if available
const oldChannel = oldMember.voiceChannel ? oldMember.voiceChannel.id : null;
const newChannel = newMember.voiceChannel ? newMember.voiceChannel.id : null;
if (oldChannel == newChannel) return; // If there has been no change, exit
// Here I'm getting the client's channel (client.voiceChannel does not exist)
const clientMember = oldMember.guild.member(client.user),
clientChannel = clientMember ? clientMember.voiceChannel.id : null;
// Here I'm getting the channel, just replace VVV this VVV with the channel's ID
const textChannel = oldMember.guild.channels.get('765520462439645191');
if (!textChannel) throw new Error("That channel does not exist.");
// Here I don't need to check if they're the same, since it would've exit before
if (newChannel == clientChannel) {
// console.log("A user joined.");
textChannel.send(`${newMember} has joined the voice channel.`);
} else if (oldChannel == clientChannel) {
// console.log("A user left.");
textChannel.send(`${newMember} has left the voice channel.`);
}
Doesnt work. No error but it doesnt work. Please help ty
I think this should work:
client.on('voiceStateUpdate', (oldMember, newMember) => {
const newUserChannel = newMember.voice.channelID
const oldUserChannel = oldMember.voice.channelID
const textChannel = message.guild.channels.cache.get('TEXT CHANNEL ID')
if(newUserChannel === 'VOICE CHANNEL ID') {
textChannel.send(`${newMember.user.username} (${newMember.id}) has joined the channel`)
} else if (oldUserChannel === 'VOICE CHANNEL ID' && newUserChannel !== 'VOICE CHANNEL ID') {
textChannel.send(`${newMember.user.username} (${newMember.id}) has left the channel`)
}
})

how to: update a users permissions to send mesages in a text channel after joining voice

Im attempting to make a bot updatre permissions for a member to gain access to a text channel after joining a voice channel. I had found a previous solution however I had no luck with it.
const pairs = require('./channelPairs.json');
client.on('voiceStateUpdate', (oldMember, newMember) => {
let oldID;
let newID;
if (oldMember.voiceChannel) oldID = oldMember.voiceChannel.id;
if (newMember.voiceChannel) newID = newMember.voiceChannel.id;
for (let i = 0; i < pairs.length; i++) {
const textChannel = newMember.guild.channels.cache.get(pairs[i].text);
if (!textChannel) {
console.log('Invalid text channel ID in json.');
continue;
}
const vcID = pairs[i].voice;
if (oldID !== vcID && newID === vcID) { // Joined the voice channel.
textChannel.overwritePermissions(newMember, {
VIEW_CHANNEL: true,
SEND_MESSAGES: true
}).catch(console.error);
} else if (oldID === vcID && newID !== vcID) { // Left the voice channel.
textChannel.overwritePermissions(newMember, {
VIEW_CHANNEL: null,
SEND_MESSAGES: null
}).catch(console.error);
}
}
});
Any help would be appreciated, I am not getting any errors however the text channel isnt updating permissions for the users.

How to check if members having a particular role are present in a particular voice channel in discord.js

I'm trying to find if any member having a particular role id is present in a particular voice channel. If even 1 member having the particular role id is present in that particular voice channel, then only those members can use the commands of music bot.
From my research, I have came to know that voiceStateUpdate may help but the problem is I don't know how to use it in my codes(cause I am new to JavaScript). Here is the link to the documentation:
https://discord.js.org/#/docs/main/stable/class/Client?scrollTo=e-voiceStateUpdate .
Here is a part of my code:
client.on('voiceStateUpdate', (oldMember, newMember) => {
});
client.on('message', async message => {
if (message.author.bot) return
if (!message.content.startsWith(prefix)) return
let messageArray = message.content.split(" ");
let cmd = messageArray[0];
const args = message.content.substring(prefix.length).split(' ');
const searchString = args.slice(1).join(' ')
const url = args[1] ? args[1].replace(/<(._)>/g, '$1') : ''
const serverQueue = queue.get(message.guild.id)
if() { //the conditional statement I am trying to put here but I don't know how to do it properly
if (message.content.startsWith(`${prefix}play`)) {
const voiceChannel = message.member.voice.channel
if (!voiceChannel) return message.channel.send("You need to be in a voice channel to play music")
.......
So the main thing is that I don't know what to write their exactly in the if statement that would make my code work properly.
client.on("message", async message => {
// Checking if the message author is a bot.
if (message.author.bot) return false;
// Checking if the message was sent in a DM channel.
if (!message.guild) return false;
// The role that can use the command.
const Role = message.guild.roles.cache.get("RoleID");
// The voice channel in which the command can be used.
const VoiceChannel = message.guild.channels.cache.get("VoiceChannelID");
if (message.content.toLowerCase() == "test") {
// Checking if the GuildMember is in a VoiceChannel.
if (!message.member.voice.channel) return message.reply("You need to be in a voice channel.");
// Checking if the GuildMember is in the required VoiceChannel.
if (message.member.voice.channelID !== VoiceChannel.id) return message.reply("You are in the wrong VoiceChannel.");
// Checking if the GuildMember has the required Role.
if (!message.member.roles.cache.has(Role.id)) return message.reply("You are not allowed to execute this command.");
// Execute your command.
return message.reply("Command executed");
};
});
So from what I can understand, you want the command to only execute when a user with the role 'Example Role' is in the channel 'Example Channel'
For this you will need the role id and the channel id.
client.on("message", async message => {
if (message.author.bot) return;
if (!(message.guild)) return;
var roleID = 'RoleID';
var vc = message.guild.channels.cache.get("VoiceChannelID");
if (message.content.toLowerCase() == "test") {
canUse = false;
vc.members.forEach((member) => {
if (member.roles.has(roleID)) {
canUse = True;
}
})
if (!(canUse)) { // nobody in the voice channel has the role specified.
return;
}
console.log("A member of the voice channel has the role specified")
}
});

Resources