Discord.js not sending messages (no errors) - discord.js

I've just started using discord.js to make a bot to my discord server. I'm trying to make the bot to send a message but it just doesn't do it. I don't even get any errors.
Here's a clip of the code that doesn't work:
bot.on('voiceStateUpdate', (oldMember, newMember) => {
let newUserChannel = newMember.voiceChannel
let oldUserChannel = oldMember.voiceChannel
if(oldUserChannel === undefined && newUserChannel !== undefined) {
// User Joins a voice channel
console.log("Join");
if(newMember = manu) {
console.log("kyllä")
bot.on('message', msg => {
msg.channel.send("Manu, oletko käynyt parturissa? \n Kirjoita vastauksesi numero. \n 1. Olen \n 2. En");
})
bot.on('message', msg => {
if(msg.content === "2") {
msg.channel.send("Ja parturin kautta takasin");
}
else if(msg.content === "1") {
msg.channel.send("Hyvvö");
}
else {
msg.channel.send("Puhu suomea");
}
})
}
}
else if(newUserChannel === undefined){
// User leaves a voice channel
console.log("Leave");
}
})
If you can understand the language in the text sections please notice this bot is just for fun :D.
What am I doing wrong?

You wrote if(newMember = manu) {. You need to use === or == to compare two values. Use = only to assign a value to a variable.

I think the problem is: You put a bot.on in a bot.on. What you can do is put the second bot.on with messages underneath the other bot.on, and it should fix your problem.

Related

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

Read message sent after command start

I am trying to make a sort of trivia bot but the problem is that I can't get it working. I have it so that when you type "-quiz" it sends a embed with a random question. Now you might say that I need to make a separate JSON file and put the questions and answers there, the problem is, is that I need variables in those strings and when I tried it, it wouldn't work because the order or something like that. I tried to fix that but it seems like a bad solution anyway. I set it up so it looks for a message after the initial commands, problem is that it reads it's own embed and I honestly don't know how to make it skip bot messages
client.on('message', message =>{
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if(command === 'quiz'){
var TypeID = (Math.floor(Math.random() * 11))
var toLog = (Math.floor(Math.random() * 2))
{ //there is something here that is used for the variables above but it is super long
}
var question = [`Question one`, `Question two`]
var answers = [[Answer1_1, Answer1_2],[Answer1_1]]
if(toLog === 0){
const quizEmbed1 = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle('quiz')
.setDescription(`${question[0]}`)
message.channel.send(quizEmbed1)
if(!message.content || message.author.bot) return;
if(message.content === [answers[0], answers[1], answers[2], answers[3], answers[4], answers[5]]){
message.channel.send('Good Job! That is right!')
}else{
message.channel.send('Oops! that is wrong.')
}
}else if(toLog == 1){
const quizEmbed2 = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle('quiz')
.setDescription(`${question[1]}`)
message.channel.send(quizEmbed2)
if(!message.content || message.author.bot) return;
if(message.content === [answers[6]]){
message.channel.send('Good Job! That is right!')
}else{
message.channel.send('Oops! That is wrong.')
}
}
}
});
if something it wrong it is most likely because I changed it to make it smaller, I am fairly newer to coding in JavaScript
Try using a MessageCollector. There is a good guide on the discord.js guide
Or using awaitMessages. Again there is a guide on the discord.js guide
Here is the example using awaitMessages
const filter = response => {
return item.answers.some(answer => answer.toLowerCase() === response.content.toLowerCase());
};
message.channel.send(item.question).then(() => {
message.channel.awaitMessages(filter, { max: 1, time: 30000, errors: ['time'] })
.then(collected => {
message.channel.send(`${collected.first().author} got the correct answer!`);
})
.catch(collected => {
message.channel.send('Looks like nobody got the answer this time.');
});
});

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`)
}
})

Creating channel and setChannel troubles

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.

Edit message in a specific channel in a specific guild | Discord.js

Hello
(I'm French so sorry for my bad English)
I want my bot to edit a message in a specific channel, I tried lots of codes but none of them worked.
let channels = Bot.guilds.find(g => g.id == "guild id").channels.filter(c => c.id == "another guild id").array();
channels.forEach(channel => {
channel.fetchMessage("message id").edit("Message Edited");
);
I also tried with for etc... channel is defined, but it can't fetch any message...
I don't even know if I can do that...
Thanks for helping me !
You can use the get() and find() methods to do so as shown below.
// Note: This code must be inside of an async function.
const guild = bot.guilds.get('guildIDhere');
if (!guild) return console.log('Unable to find guild.');
const channel = guild.channels.find(c => c.id === 'channelIDhere' && c.type === 'text');
if (!channel) return console.log('Unable to find channel.');
try {
const message = await channel.fetchMessage('messageIDhere');
if (!message) return console.log('Unable to find message.');
await message.edit('Test.');
console.log('Done.');
} catch(err) {
console.error(err);
}

Resources