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

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

Related

I get this error: TypeError: Cannot read properties of undefined (reading 'members') whenever I execute command

const levels = require('discord-xp')
const { MessageEmbed } = require('discord.js')
const client = require('../../index')
module.exports = {
name: "edit",
description: "Edits a users level or xp",
usage: ".edit <user> [xp / level] [add / set / remove] <number>",
developersOnly: true,
run: async (message, args, client) => {
const usage = ".edit <user> [xp / level] [add / set / remove] <number>"
if (!args[0]) return message.channel.send(`> You need to state more arguments \`${usage}\``)
if (!mentionedMember) return message.channel.send(`> Mention a valid user / member.`);
if (!args[1]) return message.message.channel.send(`> You must state if you are editing the member's level or xp: \`${usage}\``)
const mentionedMember = message.mentions.members.first()
if (!['xp', 'level'].includes(args[1])) return message.channel.send(`> You did not specify if you are changing level or xp: \`${usage}\``)
if (args[1] === "xp") {
if (!['add', 'set', 'remove'].includes(args[2])) return message.channel.send(`You did not state if you're adding, setting, or removing`)
const value = Number(args[3]);
let levelUser = await Levels.fetch(mentionedMember.user.id, message.guild.id)
if (!levelUser) return message.channel.send('> That person isnt in the database yet.')
if (args[2] === 'add') {
if (!value) return message.channel.send('> That is not a valid number')
try {
await Levels.appendXp(mentionedMember.user.id, message.guild.id, value)
message.channel.send(`> Added \`${value}\` xp to ${mentionedMember}`)
} catch (err) {
console.log(err)
}
} else if (args[2] === 'remove') {
if (!value) return message.channel.send('> That is not a valid number')
try {
await Levels.subtractXp(mentionedMember.user.id, message.guild.id, value)
message.channel.send(`> Removed \`${value}\` xp to ${mentionedMember}`)
} catch (err) {
console.log(err)
}
} else if (args[2] === 'set') {
if (!value) return message.channel.send('> That is not a valid number')
try {
await Levels.setXp(mentionedMember.user.id, message.guild.id, value)
message.channel.send(`> Set ${mentionedMember}'s xp to \`${value}\``)
} catch (err) {
console.log(err)
}
}
} else if (args[1] === 'level') {
if (!['add', 'set', 'remove'].includes(args[2])) return message.channel.send(`You did not state if you're adding, setting, or removing`)
const value = Number(args[3]);
let levelUser = await Levels.fetch(mentionedMember.user.id, message.guild.id)
if (!levelUser) return message.channel.send('> That person isnt in the database yet.')
if (args[2] === 'add') {
if (!value) return message.channel.send('> That is not a valid number')
try {
await Levels.appendLevel(mentionedMember.user.id, message.guild.id, value)
message.channel.send(`> Added \`${value}\` level(s) to ${mentionedMember}`)
} catch (err) {
console.log(err)
}
} else if (args[2] === 'remove') {
if (!value) return message.channel.send('> That is not a valid number')
try {
await Levels.subtractLevel(mentionedMember.user.id, message.guild.id, value)
message.channel.send(`> Removed \`${value}\` level(s) to ${mentionedMember}`)
} catch (err) {
console.log(err)
}
} else if (args[2] === 'set') {
if (!value) return message.channel.send('> That is not a valid number')
try {
await Levels.setLevel(mentionedMember.user.id, message.guild.id, value)
message.channel.send(`> Set ${mentionedMember}'s level to \`${value}\``)
} catch (err) {
console.log(err)
}
}
}
}
}
This is supposed to be a level and xp edit command for my bots leveling system
i tested it on my self first but it didnt seem to work and i dont think theres any errors in my code. It send this super long error:
TypeError: Cannot read properties of undefined (reading 'members')
at Object.run (/home/runner/sung-jin-woo/commands/leveling/edit.js:13:46)
at Client.<anonymous> (/home/runner/sung-jin-woo/events/guild/messageCreate.js:124:18)
at Client.emit (node:events:402:35)
at MessageCreateAction.handle (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/actions/MessageCreate.js:25:14)
at Object.module.exports [as MESSAGE_CREATE] (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/websocket/WebSocketManager.js:350:31)
at WebSocketShard.onPacket (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/websocket/WebSocketShard.js:443:22)
at WebSocketShard.onMessage (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/websocket/WebSocketShard.js:300:10)
at WebSocket.onMessage (/home/runner/sung-jin-woo/node_modules/ws/lib/event-target.js:199:18)
at WebSocket.emit (node:events:390:28)
at Receiver.receiverOnMessage (/home/runner/sung-jin-woo/node_modules/ws/lib/websocket.js:1022:20)
at Receiver.emit (node:events:390:28)
at Receiver.dataMessage (/home/runner/sung-jin-woo/node_modules/ws/lib/receiver.js:522:14)
at Receiver.getData (/home/runner/sung-jin-woo/node_modules/ws/lib/receiver.js:440:17)
at Receiver.startLoop (/home/runner/sung-jin-woo/node_modules/ws/lib/receiver.js:148:22)
at Receiver._write (/home/runner/sung-jin-woo/node_modules/ws/lib/receiver.js:83:10) Promise {
<rejected> TypeError: Cannot read properties of undefined (reading 'members')
at Object.run (/home/runner/sung-jin-woo/commands/leveling/edit.js:13:46)
at Client.<anonymous> (/home/runner/sung-jin-woo/events/guild/messageCreate.js:124:18)
at Client.emit (node:events:402:35)
at MessageCreateAction.handle (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/actions/MessageCreate.js:25:14)
at Object.module.exports [as MESSAGE_CREATE] (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/websocket/WebSocketManager.js:350:31)
at WebSocketShard.onPacket (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/websocket/WebSocketShard.js:443:22)
at WebSocketShard.onMessage (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/websocket/WebSocketShard.js:300:10)
at WebSocket.onMessage (/home/runner/sung-jin-woo/node_modules/ws/lib/event-target.js:199:18)
at WebSocket.emit (node:events:390:28)
at Receiver.receiverOnMessage (/home/runner/sung-jin-woo/node_modules/ws/lib/websocket.js:1022:20)
at Receiver.emit (node:events:390:28)
at Receiver.dataMessage (/home/runner/sung-jin-woo/node_modules/ws/lib/receiver.js:522:14)
at Receiver.getData (/home/runner/sung-jin-woo/node_modules/ws/lib/receiver.js:440:17)
at Receiver.startLoop (/home/runner/sung-jin-woo/node_modules/ws/lib/receiver.js:148:22)
at Receiver._write (/home/runner/sung-jin-woo/node_modules/ws/lib/receiver.js:83:10)
}
so like can someone help me?
(if you need any more info about code say it in comment ill reply with the info there)
Whenever you see this error, check the line 'reading members'(in your case). That simply means you are doing a key access where keyname is 'members' and object inside which this key 'members' is present is undefined. For example X.members where X is undefined.So check in your code why this 'X'(imaginary name given for the sake of answer could be any name that you only know) is undefined or what could make that 'X' undefined. And after finding that you should put a check before doing the access i.e something like below to avoid these run time errors:
if(X) then X.members
OR
X?.members
Looking at your code the error is coming from here :
const mentionedMember = message.mentions.members.first()
Keep this line in correct place i.e all your access to mentionedMember should occur after this line and then change above line to :
const mentionedMember = message.mentions?.members.first() provided members has first() method. If you are not sure then you can do like this also const mentionedMember = message.?mentions?.members?.first()
There is one more way which is not cleaner but it's fine:
let mentionedMember;
if(message && message.mentions && message.mentions.members) {
mentionedMember = message.mentions.members.first()
}
In this line code:
if (!mentionedMember) return message.channel.send(`> Mention a valid user / member.`);
if (!args[1]) return message.message.channel.send(`> You must state if you are editing the member's level or xp: \`${usage}\``)
const mentionedMember = message.mentions.members.first()
Try to arrange this like:
const mentionedMember = message.mentions.members.first()
if (!mentionedMember) return message.channel.send(`> Mention a valid user / member.`);
if (!args[1]) return message.message.channel.send(`> You must state if you are editing the member's level or xp: \`${usage}\``)
In line:
if (!mentionedMember) return message.channel.send('> Mention a valid user / member.'); you already calling the mentionedMember which is its not readable.
Let me know if the error still there after you rearrange your code

Discord.js ReferenceError: channel is not defined

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)

i have an error titled: "TypeError: Cannot read property 'execute' of undefined" and cannot fix it

I am trying to make a discord bot use an advanced command handler and it isn't working.
Error Message:
at Client.<anonymous> (C:\Users\bryce\OneDrive\Desktop\bot\main.js:76:39)
at Client.emit (events.js:315:20)
at MessageCreateAction.handle (C:\Users\bryce\OneDrive\Desktop\bot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\bryce\OneDrive\Desktop\bot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (C:\Users\bryce\OneDrive\Desktop\bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
at WebSocketShard.onPacket (C:\Users\bryce\OneDrive\Desktop\bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
at WebSocketShard.onMessage (C:\Users\bryce\OneDrive\Desktop\bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
at WebSocket.onMessage (C:\Users\bryce\OneDrive\Desktop\bot\node_modules\ws\lib\event-target.js:132:16)
at WebSocket.emit (events.js:315:20)
main.js
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = '='
const fs = require('fs');
// create the collection
client.commands = new Discord.Collection();
// get an array of every file in the commands folder
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
// iterate a function through every file
for (file of commandFiles) {
const command = require(`./commands/${file}`);
console.log(file)
// map the command to the collection with the key as the command name,
// and the value as the whole exported object
client.commands.set(command.name, command);
};
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 === 'twitch'){
message.channel.send('https://www.twitch.tv/gamergirlspeed');
}else if (command == 'youtube'){
message.channel.send('https://www.youtube.com/channel/UCHN61ta8sZ-EkJ6JvlGRkng');
}else if (command == 'tiktok'){
message.channel.send('https://www.tiktok.com/#gamergirlspeed?lang=en ')
}else if (command == 'help'){
message.channel.send('**| =twitch**\n**| =youtube**\n**| =tiktok**\n**| =epic**\n**| =mods**\n**| =version**\n**| =author**\n**| =purge (broken)**\n**| =twitter**\n**| =switch**\n**| =rule1**\n**| =rule2**\n**| =rule3**\n**| =rule4**\n**| =rule5**\n**| =rule6**\n**| =rule7**\n**| =rule8**\n**| =rule9**\n**| =botcommands**')
}else if (command == 'epic'){
message.channel.send("Speed's Epic account is: Speed_Ster06")
}else if (command == 'mods'){
message.channel.send("Speed_Ster06's current mods are: FyreFoxe, RAPHBOSS")
}else if (command == 'version'){
message.channel.send("FyreFoxe's SpeedForce Bot is in version 1.7")
}else if (command == 'author'){
message.channel.send('SpeedForce Is Created by Bravmi#6740')
}else if (command == 'twitter'){
message.channel.send('https://twitter.com/GamerGirlSpeed1 ')
}else if (command == 'playstation'){
message.command.send("Speed's Playstation Account is: Speed_Ster06")
}else if (command == 'switch'){
message.channel.send("Speed's Switch Account is: SpeedSter6")
}else if (command === 'purge'){
client.commands.get('purge').execute(message,args);
}else if (command == 'rule1'){
message.channel.send('Do not spam')
}else if (command == 'rule2'){
message.channel.send("Don't be mean to others, It's just not nice.")
}else if (command == 'rule3'){
message.channel.send("No NSFW, It's just, we don't do that here.")
}else if (command == 'rule4'){
message.channel.send("No raiding, I think it's pretty clear what the punishment would be if you did.")
}else if (command == 'rule5'){
message.channel.send(" Don't boycott the discord/minecraft server.")
}else if (command == 'rule6'){
message.channel.send("Don't beg for roles.")
}else if (command == 'rule7'){
message.channel.send("Don’t advertise unless in the correct channel.")
}else if (command == 'rule8'){
message.channel.send("Don't put clips in the clips channel that aren't from my stream.")
}else if (command == 'rule9'){
message.channel.send("Rules are based upon logic or common sense. Don't do things that seem bad, only because it's 'Not a rule'.")
}else if (command == 'botcommands'){
message.channel.send('Bot Commands:\n----------------------------------------------------------------------------------------------------------------\n**1.** “!rank” shows you your rank level\n**2.** “!levels” shows you a leader board of all the other people’s levels\n**3.** “!help” helps find out information about commands\n**4.** “!links” shows the links to my YouTube and Twitch channels\n**5.** “!d bump” help show the discord server to other people\n**6.** “=help” Shows you all the cmds you can do with our custom SpeedForce Bot made by FyreFoxe\n----------------------------------------------------------------------------------------------------------------')
}else if (command === 'warn'){
client.commands.get('warn.js').execute(message, args);
}
//else if (command === 'kick'){
//client.commands.get('kick').execute(message, args)
//}else if (command === 'ban'){
//client.commands.get('ban').execute(message, args)
//}
});
//Copyright LightSide Development, 2021
client.once('ready', () => {
console.log('Online!')
setInterval(() => {
targetGuild = client.guilds.cache.get('782068409646448640')
if(targetGuild) {
client.user.setActivity({ name: targetGuild.memberCount + ' SpeedSters!', type: 'WATCHING' }, { name: 'with commands!', type: 'PLAYING' }, { name: 'You...', type: 'WATCHING' })
.then(console.log)
.catch(console.error);
}
}, 1000 * 60 * 1);
});
client.login('expunged')
warn.js
const Discord = reqire("discord.js");
const fs = require("fs");
const ms = require("ms");
let warns = JSON.parse(fs.readFileSync("./warnings.json", "utf8"));
module.exports.run = async (bot, message, args) => {
//=warn #name <reason>
if(!message.member.hasPermission("MANAGE_MEMBERS")) return message.reply("You don't have permission!");
let wUser = message.guild.member(message.mentions.users.first()) || message.guild.members.get(args[0])
if(!wUser) return message.reply("The user specified does not exist!")
if(wUser.hasPermission("MANAGE_MESSAGES")) return message.reply("You cannot warn them!");
let reason = args.join(" ").slice(22);
if(!warns[wUser.id]) warns[wUser.id] = {
warns: 0
};
warns[wUser.id].warns++;
fs.writeFile("./warnings.json", JSON.stringify(warns), (error) => {
if (err) console.log(error);
});
let warnEmbed = new Discord.RichEmbed()
.setDescription("Warns")
.setAuthor(message.author.username)
.setColor("#fc6400")
.addField("Warned User", `<#${wUser.tag}>`)
.addField("Warned in", message.channel)
.addField("Number of Warnings", warns[wUser.id].warns)
.addField("Reason", reason)
let warnchannel = message.guild.channels.find(`name`, "warnings");
if(!warnchannel) return message.reply("The Logging channel has been deleted or renamed, contact Bravmi#6740");
warnchannel.send(warnEmbed);
if(warns[wUser.id].warns == 5){
message.guild.member(wUser).ban(reason);
warnchannel.send(`${wUser.tag} has been banned for ${reason}`)
}
}
module.exports.help = {
name: "warn"
}
the error occurs when i use the warn command, it crashes the bot and gives me the error message and i don't know what to do.
i have tried looking at it with some friends and they don't know what to do either, is there any way to fix it?
The error "Cannot read property 'execute' of undefined" means exactly what it says.
In your case, you are trying to call the function "execute" on an object that does not exist.
The error is even giving you the line number that it is occurring "(C:\Users\bryce\OneDrive\Desktop\bot\main.js:76:39)".
Without line numbers in the code you posted above, I can't be sure, but it looks to me like the offending code is.
client.commands.get('warn.js').execute(message, args);
Which means client.commands.get('warn.js') is not returning an object. ie. calling the function client.commands.get('warn.js') is returning undefined.
I dare say, you may want to try client.commands.get('warn').execute(message, args)
When you add your files to the collection at the start of your file you use client.commands.set(command.name, command);. This sets the key in the collection to the name of the command.
However, in your command file you use the following code module.exports.help = { name: "warn" } and there is no definition of what should be module.exports.name.
I would suggest changing the module.exports.help to module.exports and then remove the .js from all lines where you have client.commands.get('...')

TypeError: value.split is not a function

I'm creating a discord.js bot v12 and I get this error on line 2 when I use the purge command in discord and I'm assuming value.split is not a function and wondering if I should be doing something else since I'm using v12 of discord.js:
Uncaught Promise Error:
TypeError: args.split is not a function or its return value is not iterable
at Object.module.exports.run (c:\Users\Kazzu\Desktop\src\commands\prune.js:2:34)
at module.exports (c:\Users\Kazzu\Desktop\src\events\message.js:33:9)
at Client.emit (events.js:323:22)
at MessageCreateAction.handle (c:\Users\Kazzu\Desktop\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (c:\Users\Kazzu\Desktop\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (c:\Users\Kazzu\Desktop\node_modules\discord.js\src\client\websocket\WebSocketManager.js:386:31)
at WebSocketShard.onPacket (c:\Users\Kazzu\Desktop\node_modules\discord.js\src\client\websocket\WebSocketShard.js:436:22)
at WebSocketShard.onMessage (c:\Users\Kazzu\Desktop\node_modules\discord.js\src\client\websocket\WebSocketShard.js:293:10)
at WebSocket.onMessage (c:\Users\Kazzu\Desktop\node_modules\ws\lib\event-target.js:120:16)
at WebSocket.emit (events.js:311:20)
This is my code:
module.exports.run = async (client, message, args) => {
let [ userId, limit ] = args.split(/\s+/);
if(!userId && !limit) {
let deletedMessages = await message.channel.bulkDelete();
message.channel.send(`${deletedMessages.size} messages were deleted.`);
}
if(!userId || !limit) return message.channel.send('Please provide the correct arguments.');
let r = new RegExp(/^\d+$/);
if(!r.test(userId)) return message.channel.send('Please provide a valid user id.');
if(isNaN(limit)) return message.channel.send('Please provide a numeric value for limit');
if(limit > 100) return message.channel.send('Limit must be less than or equal to 100.');
try {
let fetchedMessages = await message.channel.messages.fetch({ limit });
let filteredMessages = fetchedMessages.filter(message => message.author.id === userId);
let deletedMessages = await message.channel.bulkDelete(filteredMessages);
message.channel.send(`${deletedMessages.size} messages were deleted.`);
}
catch(err) {
console.log(err);
}
}
module.exports.help = {
name: "purge",
description: "Deletes a number of messages from a user in a channel."
}
module.exports.requirements = {
userPerms: [],
clientPerms: [],
ownerOnly: false
}
It seems that args is not type of string. When you call .split() for something other than a string, JavaScript runtime cannot find the .split() method for that type. So, make sure you are passing a string to your function or try something like that:
if (typeof string === args) {
var str = args.toString();
}
Turns out I needed to replace value.split to value.slice

When checking invites is the following

If I create a new express invitation to the server when the bot is turned on, an error occurs. In other cases, it works
const invites = {};
const wait = require('util').promisify(setTimeout);
client.on('ready', () => {
wait(1000);
g.fetchInvites().then(guildInvites => {
invites[g.id] = guildInvites;
});
});
});
client.on('guildMemberAdd', member => {
member.guild.fetchInvites().then(guildInvites => {
const ei = invites[member.guild.id];
invites[member.guild.id] = guildInvites;
const invite = guildInvites.find(i => ei.get(i.code).uses < i.uses);
const inviter = client.users.get(invite.inviter.id);
const logChannel = member.guild.channels.find(channel => channel.name === "join-logs");
logChannel.send(`${member.user.tag} joined using invite code ${invite.code} from ${inviter.tag}. Invite was used ${invite.uses} times since its creation.`);
});
});
Errors:
2019-07-07T09:49:20.363359+00:00 app[worker.1]: Unhandled Rejection:
2019-07-07T09:49:20.363377+00:00 app[worker.1]: TypeError: Cannot read property 'uses' of undefined
2019-07-07T09:49:20.363378+00:00 app[worker.1]: at guildInvites.find.i (./bot.js:398:57)
2019-07-07T09:49:20.363380+00:00 app[worker.1]: at Map.find (./node_modules/discord.js/src/util/Collection.js:160:13)
2019-07-07T09:49:20.363381+00:00 app[worker.1]: at member.guild.fetchInvites.then.guildInvites (./bot.js:398:33)
2019-07-07T09:49:20.363382+00:00 app[worker.1]: at process._tickCallback (internal/process/next_tick.js:68:7)
398 deadline
const invite = guildInvites.find(i => ei.get(i.code).uses < i.uses);
The invite used is new, and isn't yet in the cache. However, ei.get(i.code).uses assumes it is, and tries to use a property of it when it doesn't exist.
This revised predicate function will return the invite that isn't cached, or the invite that increased in uses.
const invite = guildInvites.find(i => !ei.get(i.code) || ei.get(i.code).uses < i.uses);

Categories

Resources