Discord.js ReferenceError: channel is not defined - javascript

I'm using the discordjs bot guide and copied their help command from the GitHub. However the code gives an error. I've tried almost every solution I could find for the ReferenceError I'm getting. What am I doing wrong?
My code:
const { prefix } = require('../../config.json');
module.exports = {
name: 'help',
description: 'List all of my commands or info about a specific command.',
aliases: ['commands'],
usage: '[command name]',
cooldown: 5,
execute(message, args) {
const data = [];
const { commands } = message.client;
if (!args.length) {
data.push('Here\'s a list of all my commands:');
data.push(commands.map(command => command.name).join(', '));
data.push(`\nYou can send \`${prefix}help [command name]\` to get info on a specific command!`);
return message.author.send(data, { split: true })
.then(() => {
if (message.channel.type === 'dm') return;
message.reply('I\'ve sent you a DM with all my commands!');
})
.catch(error => {
console.error(`Could not send help DM to ${message.author.tag}.\n`, error);
message.reply('it seems like I can\'t DM you!');
});
}
const name = args[0].toLowerCase();
const command = commands.get(name) || commands.find(c => c.aliases && c.aliases.includes(name));
if (!command) {
return message.reply('that\'s not a valid command!');
}
data.push(`**Name:** ${command.name}`);
if (command.aliases) data.push(`**Aliases:** ${command.aliases.join(', ')}`);
if (command.description) data.push(`**Description:** ${command.description}`);
if (command.usage) data.push(`**Usage:** ${prefix}${command.name} ${command.usage}`);
data.push(`**Cooldown:** ${command.cooldown || 3} second(s)`);
message.channel.send(data, { split: true });
},
};
The error:
ReferenceError: channel is not defined
at Object.execute (C:\Users\user\JS Bot\commands\utility\help.js:64:5)
at Client.<anonymous> (C:\Users\user\JS Bot\index.js:78:11)
at Client.emit (events.js:315:20)
at MessageCreateAction.handle (C:\Users\user\JS Bot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\user\JS Bot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (C:\Users\user\JS Bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
at WebSocketShard.onPacket (C:\Users\user\JS Bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
at WebSocketShard.onMessage (C:\Users\user\JS Bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
at WebSocket.onMessage (C:\Users\user\JS Bot\node_modules\ws\lib\event-target.js:132:16)
at WebSocket.emit (events.js:315:20)

Related

How can I fix this ReferenceError when using .setSelfDeaf()?

I'm trying to use .setSelfDeaf() in my code but I couldn't figure it out. Every way I tried ended up crashing the bot when executed.
Could someone help me to use it? I want is the bot the deafen itself every time it joins a voice channel.
Edit: added the error I am getting and the updated code upon request.
The error I am getting:
2021-03-04T06:25:06.238627+00:00 app[worker.1]: /app/code.js:53
2021-03-04T06:25:06.238628+00:00 app[worker.1]: connection.voice.setSelfDeaf(true);
2021-03-04T06:25:06.238629+00:00 app[worker.1]: ^
2021-03-04T06:25:06.238629+00:00 app[worker.1]:
2021-03-04T06:25:06.238629+00:00 app[worker.1]: ReferenceError: connection is not defined
2021-03-04T06:25:06.238630+00:00 app[worker.1]: at Client.<anonymous> (/app/code.js:53:5)
2021-03-04T06:25:06.238630+00:00 app[worker.1]: at Client.emit (events.js:327:22)
2021-03-04T06:25:06.238631+00:00 app[worker.1]: at VoiceStateUpdate.handle (/app/node_modules/discord.js/src/client/actions/VoiceStateUpdate.js:40:14)
2021-03-04T06:25:06.238632+00:00 app[worker.1]: at Object.module.exports [as VOICE_STATE_UPDATE] (/app/node_modules/discord.js/src/client/websocket/handlers/VOICE_STATE_UPDATE.js:4:35)
2021-03-04T06:25:06.238632+00:00 app[worker.1]: at WebSocketManager.handlePacket (/app/node_modules/discord.js/src/client/websocket/WebSocketManager.js:384:31)
2021-03-04T06:25:06.238633+00:00 app[worker.1]: at WebSocketShard.onPacket (/app/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
2021-03-04T06:25:06.238633+00:00 app[worker.1]: at WebSocketShard.onMessage (/app/node_modules/discord.js/src/client/websocket/WebSocketShard.js:301:10)
2021-03-04T06:25:06.238634+00:00 app[worker.1]: at WebSocket.onMessage (/app/node_modules/ws/lib/event-target.js:132:16)
2021-03-04T06:25:06.238634+00:00 app[worker.1]: at WebSocket.emit (events.js:315:20)
2021-03-04T06:25:06.238634+00:00 app[worker.1]: at Receiver.receiverOnMessage (/app/node_modules/ws/lib/websocket.js:825:20)
2021-03-04T06:25:06.279643+00:00 heroku[worker.1]: Process exited with status 1
2021-03-04T06:25:06.340294+00:00 heroku[worker.1]: State changed from up to crashed
The updated code:
const Discord = require('discord.js'),
DisTube = require('distube'),
client = new Discord.Client(),
config = {
prefix: "em!",
token: process.env.TOKEN || "[insert discord bot token]"
};
const distube = new DisTube(client, { searchSongs: true, emitNewSongOnly: true });
client.on('ready', () => {
console.log(`e-Music is up and running`);
client.user.setActivity(`em!play`)
});
client.on("message", async (message) => {
if (message.author.bot) return;
if (!message.content.startsWith(config.prefix)) return;
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift();
if (command == "play")
distube.play(message, args.join(" "));
if (["repeat", "loop"].includes(command))
distube.setRepeatMode(message, parseInt(args[0]));
if (command == "stop") {
distube.stop(message);
message.channel.send("Stopped the music!");
}
if (command == "skip")
distube.skip(message);
if (command == "queue") {
let queue = distube.getQueue(message);
message.channel.send('Current queue:\n' + queue.songs.map((song, id) =>
`**${id + 1}**. ${song.name} - \`${song.formattedDuration}\``
).slice(0, 10).join("\n"));
}
if ([`3d`, `bassboost`, `echo`, `karaoke`, `nightcore`, `vaporwave`].includes(command)) {
let filter = distube.setFilter(message, command);
message.channel.send("Current queue filter: " + (filter || "Off"));
}
});
client.on("voiceStateUpdate", (oldVoiceState, newVoiceState) => {
if (newVoiceState.id == client.user.id) {
connection.voice.setSelfDeaf(true);
};
});
const status = (queue) => `Volume: \`${queue.volume}%\` | Filter: \`${queue.filter || "Off"}\` | Loop: \`${queue.repeatMode ? queue.repeatMode == 2 ? "All Queue" : "This Song" : "Off"}\` | Autoplay: \`${queue.autoplay ? "On" : "Off"}\``;
distube
.on("playSong", (message, queue, song) => message.channel.send(
`Playing \`${song.name}\` - \`${song.formattedDuration}\`\nRequested by: ${song.user}\n${status(queue)}`
))
.on("addSong", (message, queue, song) => message.channel.send(
`Added ${song.name} - \`${song.formattedDuration}\` to the queue by ${song.user}`
))
.on("playList", (message, queue, playlist, song) => message.channel.send(
`Play \`${playlist.name}\` playlist (${playlist.songs.length} songs).\nRequested by: ${song.user}\nNow playing \`${song.name}\` - \`${song.formattedDuration}\`\n${status(queue)}`
))
.on("addList", (message, queue, playlist) => message.channel.send(
`Added \`${playlist.name}\` playlist (${playlist.songs.length} songs) to queue\n${status(queue)}`
))
.on("searchResult", (message, result) => {
let i = 0;
message.channel.send(`**Choose an option from below**\n${result.map(song => `**${++i}**. ${song.name} - \`${song.formattedDuration}\``).join("\n")}\n*Enter anything else or wait 60 seconds to cancel*`);
})
.on("searchCancel", (message) => message.channel.send(`Searching canceled`))
.on("error", (message, e) => {
console.error(e)
message.channel.send("An error encountered: " + e);
});
client.login(config.token);
If you read the error ReferenceError: connection is not defined, it tells you what is wrong. connection in the following code is not a variable:
client.on("voiceStateUpdate", (oldVoiceState, newVoiceState) => {
if (newVoiceState.id == client.user.id) {
connection.voice.setSelfDeaf(true);
};
});
There is a connection property on newVoiceState though, although that isn't what you want in this scenario. You would want to use the .setSelfDeaf method from VoiceState:
client.on("voiceStateUpdate", (oldVoiceState, newVoiceState) => {
if (newVoiceState.id == client.user.id) {
newVoiceState.setSelfDeaf(true);
};
});

How to remove a role when getting another(discord.js)

All that I got was just this one (there, when writing (! +), He fulfills the role, but even then she is a non-worker, please help)
bot.on('message', msg => {
if (msg.content === prefix + '+') {
member.roles.remove(801095844044341279).catch(console.error);
}
});
knocks out this error
C:\Users\user\Desktop\bot\index.js:40
member.roles.remove(801095844044341279).catch(console.error);
^
ReferenceError: member is not defined
at Client.<anonymous> (C:\Users\user\Desktop\bot\index.js:40:5)
at Client.emit (events.js:327:22)
at MessageCreateAction.handle (C:\Users\user\Desktop\bot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\user\Desktop\bot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (C:\Users\user\Desktop\bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
at WebSocketShard.onPacket (C:\Users\user\Desktop\bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
at WebSocketShard.onMessage (C:\Users\user\Desktop\bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
at WebSocket.onMessage (C:\Users\user\Desktop\bot\node_modules\ws\lib\event-target.js:132:16)
at WebSocket.emit (events.js:315:20)
at Receiver.receiverOnMessage (C:\Users\user\Desktop\bot\node_modules\ws\lib\websocket.js:825:20)
You need to use the Message object to get the member from it.
Like this:
bot.on('message', msg => {
if (msg.content === prefix + '+') {
msg.member.roles.remove('801095844044341279').catch(() => {
console.error("failed to remove role");
});
}
});
I also fixed your console.error as it was invalid syntax, if it fails to remove the role it will error to the console properly now.

(Discord.js) TypeError: Cannot read property 'add' of undefined

So here's the code:
const mutedRole = message.guild.roles.cache.find(role => role.name === "Muted");
if (!mutedUser) return message.channel.send()
if (!message.author) return;
if (!mutedRole) {
message.guild.roles.create({
data: {
name: 'Muted',
color: '#6C877C',
permissions: ["CREATE_INSTANT_INVITE", "VIEW_CHANNEL"],
},
})
.catch(console.error);
}
mutedUser.roles.add(mutedRole).catch(console.error);
When I run the bot, I get the error:
2020-08-14T05:22:08.731213+00:00 app[Worker.1]: TypeError: Cannot read property 'add' of undefined
2020-08-14T05:22:08.731236+00:00 app[Worker.1]: at Object.execute (/app/commands/mute.js:69:29)
2020-08-14T05:22:08.731236+00:00 app[Worker.1]: at Client.<anonymous> (/app/bread.js:111:14)
2020-08-14T05:22:08.731238+00:00 app[Worker.1]: at Client.emit (events.js:315:20)
2020-08-14T05:22:08.731239+00:00 app[Worker.1]: at MessageCreateAction.handle (/app/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
2020-08-14T05:22:08.731241+00:00 app[Worker.1]: at Object.module.exports [as MESSAGE_CREATE] (/app/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
2020-08-14T05:22:08.731242+00:00 app[Worker.1]: at WebSocketManager.handlePacket (/app/node_modules/discord.js/src/client/websocket/WebSocketManager.js:386:31)
2020-08-14T05:22:08.731242+00:00 app[Worker.1]: at WebSocketShard.onPacket (/app/node_modules/discord.js/src/client/websocket/WebSocketShard.js:436:22)
2020-08-14T05:22:08.731242+00:00 app[Worker.1]: at WebSocketShard.onMessage (/app/node_modules/discord.js/src/client/websocket/WebSocketShard.js:293:10)
2020-08-14T05:22:08.731243+00:00 app[Worker.1]: at WebSocket.onMessage (/app/node_modules/ws/lib/event-target.js:125:16)
2020-08-14T05:22:08.731244+00:00 app[Worker.1]: at WebSocket.emit (events.js:315:20)
As seen on the code, I add the part where the bot would make a role as when the role is unavailable. But still, it thinks as that the role never exist.
Before this was copied, I aslo wrote the code like this:
if (!mutedRole) {
guild.roles.create({
data: {
name: 'Muted',
color: '#6C877C',
permissions: ["CREATE_INSTANT_INVITE", "VIEW_CHANNEL"],
},
})
.catch(console.error);
}
And the result is still the same. I also put the bot's role on the most top list of all roles on my test server. Can anyone find out why?
I'm currently using discord.js v12 and stable version of node.
Note: full code here: https://github.com/centralomd/breadbot/blob/master/commands/mute.js
The error comes from line 14:
const mutedUser = message.mentions.users.first() || message.guild.members.get(args[0])
If there are no mentions in the message.mentions.users Collection, you are trying to get a GuildMember using message.guild.members.get().
Discord JS v12 introduces the concept of managers, you will no longer be able to directly use Collection methods such as Collection.get() on data structures like Client.users and Guild.members.
You'll have to change it with:
const mutedUser = message.mentions.users.first() || message.guild.members.cache.get(args[0])
if (!mutedUser) return message.channel.send("Invalid user.");
Note: message.mentions.users will get users in other guilds as well. I recommend you to use message.mentions.members.

How to fix RichEmbed Discord.js

I know the question exists but even though I looked into the other question and i used 'sendEmbed' instead of 'send' but nothing seems to work, if anyone can help with this error I'll be grateful :)
this is my code:
const Discord = require('discord.js');
const bot = new Discord.Client();
const token = "Removed For Security";
const PREFIX = "!";
bot.on('ready', () => {
console.log("Bot is online");
})
bot.on('message', (msg) => {
let args = msg.content.substring(PREFIX.length).split(" ");
switch (args[0]) {
case 'ping':
msg.channel.send("pong!")
break;
case 'clear':
if (!args[1])
return msg.reply('Error please define second argument');
msg.channel.bulkDelete(args[1]);
break;
case 'embed': {
const embed = new Discord.RichEmbed()
.addField('Player Name', msg.author.username)
msg.channel.send(embed)
break;
}
}
})
bot.login(token);
and this is the error:
C:\Users\isam\Desktop\discord bot\index.js:24
const embed = new Discord.RichEmbed()
^
TypeError: Discord.RichEmbed is not a constructor
at Client.bot.on (C:\Users\isam\Desktop\discord bot\index.js:24:27)
at Client.emit (events.js:193:13)
at MessageCreateAction.handle (C:\Users\isam\Desktop\discord bot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\isam\Desktop\discord bot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (C:\Users\isam\Desktop\discord bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:386:31)
at WebSocketShard.onPacket (C:\Users\isam\Desktop\discord bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:436:22)
at WebSocketShard.onMessage (C:\Users\isam\Desktop\discord bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:293:10)
at WebSocket.onMessage (C:\Users\isam\Desktop\discord bot\node_modules\ws\lib\event-target.js:125:16)
at WebSocket.emit (events.js:193:13)
at Receiver.receiverOnMessage (C:\Users\isam\Desktop\discord bot\node_modules\ws\lib\websocket.js:800:20)
As you can see the error is in RichEmbed constructor, also my Discord.js version is '12.2.0', Any ideas?
Discord.RichEmbed got removed in v12.
just use Discord.MessageEmbed instead.
it's essentially the same. just a new name.
new docs: https://discord.js.org/#/docs/main/v12/class/MessageEmbed
Discord.RichEmbed got removed in V12
try this :
const embed = new Discord.MessageEmbed()
//l'embed
msg.channel.send(embed)

Discord.js Bot crashing while used command

my problem is when i write command! Tempmute (user) (time) and in field (time) i'll write for example 10 s / m / h / d it works great but when i wrote other letter in this field bot just crash.
Can any one tell me how to fix it? Thanks in advance!
Code:
if (command === `${prefix}tempmute`) {
let tomute = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[0]));
if(!tomute) return message.reply("Nie moge znaleźć określonego użytkownika");
if(tomute.hasPermission("ADMINISTRATOR")) return message.reply("Ta osoba ma zbyt wysoką rangę lub nie masz permisji!");
let muterole = message.guild.roles.find(r => r.name === "muted");
if(!muterole){
try {
muterole = message.guild.createRole({
name: "muted",
color: "#0000000",
permissions: []
})
message.guild.channels.forEach(async (channel, id) => {
channel.overwritePermissions(muterole,{
SEND_MESSAGES: false,
ADD_REACTIONS: false
});
});
} catch(e) {
console.log(e.stack);
}
}
let mutetime = args[1];
if(!mutetime) return message.reply("Wprowadź czas na jaki ma byc zmutowana osoba")
tomute.addRole(muterole.id);
message.reply(`<#${tomute.id}> został zmutowany na ${ms(ms(mutetime))}`);
setTimeout(function(){
tomute.id.removeRole(muterole.id);
message.channel.send(`<#${tomute.id}> został odmutowany!`);
}, ms(mutetime));
}
}
);
Error in console:
C:\Users\pr0mo\OneDrive\Pulpit\Discord Rust Bot\node_modules\ms\index.js:34
throw new Error(
^
Error: val is not a non-empty string or a valid number. val=undefined
at module.exports (C:\Users\pr0mo\OneDrive\Pulpit\Discord Rust Bot\node_modules\ms\index.js:34:9)
at Client.<anonymous> (C:\Users\pr0mo\OneDrive\Pulpit\Discord Rust Bot\bot.js:241:58)
at Client.emit (events.js:210:5)
at MessageCreateHandler.handle (C:\Users\pr0mo\OneDrive\Pulpit\Discord Rust Bot\node_modules\discord.js\src\client\websocket\packets\handlers\MessageCreate.js:9:34)
at WebSocketPacketManager.handle (C:\Users\pr0mo\OneDrive\Pulpit\Discord Rust Bot\node_modules\discord.js\src\client\websocket\packets\WebSocketPacketManager.js:105:65)
at WebSocketConnection.onPacket (C:\Users\pr0mo\OneDrive\Pulpit\Discord Rust Bot\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:333:35)
at WebSocketConnection.onMessage (C:\Users\pr0mo\OneDrive\Pulpit\Discord Rust Bot\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:296:17)
at WebSocket.onMessage (C:\Users\pr0mo\OneDrive\Pulpit\Discord Rust Bot\node_modules\ws\lib\event-target.js:120:16)
at WebSocket.emit (events.js:210:5)
at Receiver.receiverOnMessage (C:\Users\pr0mo\OneDrive\Pulpit\Discord Rust Bot\node_modules\ws\lib\websocket.js:789:20)
Add your code to the try catch statement it won't crash anymore, but if you want to check if the argument corresponds to what you want, you can make an regexp
try catch:
try
{
}catch(error)
{
console.log(error)
}
Regex:
var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
mutetime);
if(!match)return;

Categories

Resources