I have this code to add/remove the streaming role when a user types ?stream <user>
It works fine when this happens the whole command is entered, but when only ?stream
if (!member.roles.cache.some(role => role.name === 'streaming')) {
^
TypeError: Cannot read property 'roles' of undefined
and i have no idea why?
this is the code:
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(' ');
const command = args.shift().toLowerCase();
const member = message.mentions.members.first();
if (command === 'stream') {
if(message.member.permissions.has("MANAGE_ROLES")){
if (!member.roles.cache.some(role => role.name === 'streaming')) {
member.roles.add('744292301874135122')
message.channel.send('`Added streaming role.`')
} else
member.roles.remove('744292301874135122') && message.channel.send('`Removed streaming role.`')
} else message.channel.send('`You dont have permission.`')
}
});
Discord.js can't get the member you defined in this method:
const member = message.mentions.members.first();
Because there is no mention when you just type ?stream. So discord.js can't get the roles of the member because the member is not defined.
Related
I was making an alias system for my discord bot, and I wanted to say: "if the user entered the wrong command name or alias then return: invalid command/alias", but I'm getting an error:
C:\Users\Pooyan\Desktop\PDM Bot Main\events\guild\message.js:16
if(!cmd || client.commands.find(a => !a.aliases && !a.aliases.includes(cmd))) return message.channel.send('Invalid command');
^
TypeError: Cannot read properties of undefined (reading 'includes')
at C:\Users\Pooyan\Desktop\PDM Bot Main\events\guild\message.js:16:83
My code:
module.exports = async (message, client, Discord) => {
const prefix = process.env.PREFIX;
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const cmd = args.shift().toLowerCase();
const command = client.commands.get(cmd) ||
client.commands.find(a => a.aliases && a.aliases.includes(cmd));
if(!cmd || client.commands.find(a => !a.aliases && !a.aliases.includes(cmd))) return message.channel.send('Invalid command');
}
I'm using discord.js v13 and Node.js v16.14.2
I found the solution myself,
All I needed to do was:
if(!command) return message.channel.send('Invalid Command/alias');
after those two lines,
It means if command name was not correct, or if the alias was not correct, return "Invalid Command/alias"
Remove the first ! in your find method, it will fix the error
I'm currently trying to implement speech recognition into a discord bot, but I keep running into errors. I'm also new to Discord.JS and programming as a whole.
I copied some of the following code from an event file that interprets normal messages instead of speech, and it works fine there.
The following line throws an "UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'startsWith' of undefined": if (!msg.content.startsWith(prefix) || msg.author.bot) return;
My entire file:
const fs = require('fs');
module.exports = {
name: "join",
description: "Joins the VC that user is in",
async execute(client, message, args, Discord) {
const voiceChannel = message.member.voice.channel;
const connection = await voiceChannel.join();
if (!voiceChannel) return message.channel.send('Join a VC retard');
const permissions = voiceChannel.permissionsFor(message.client.user);
if (!permissions.has('CONNECT')) return message.channel.send("You don't have the correct permissions");
if (!permissions.has('SPEAK')) return message.channel.send("You don't have the correct permissions");
connection.client.on('speech', msg => {
console.log(msg.content);
const prefix = 'yo bot ' || 'Aries ' || 'Ares ' || 'yobot ';
if (!msg.content.startsWith(prefix) || msg.author.bot) return;
const args = msg.content.slice(prefix.length).split(/ +/);
const cmd = args.shift().toLowerCase();
const command = client.commands.get(cmd);
if (command) command.execute(client, msg, args, Discord);
})
}
}
If message content is not a string then you cannot use that function.
You need to check if message content exists first:
if (!msg.content
|| !msg.content.startsWith(prefix)
|| msg.author.bot
) {...}
You need to make sure that the message content is defined, before reading it's startsWith property. You can do this with optional chaining.
if (!msg?.content?.startsWith(prefix) || msg.author.bot) return;
msg?.content?.startWith(prefix) will return undefined if either:
msg does not have a content propery
content does not have a startWith property
This is my discord reject code:
client.on('message', msg => {
if (msg.channel instanceof Discord.DMChannel && msg.author.id !== "828093594098204702") {
const Reject = new Discord.MessageEmbed()
.setColor("#FF0000")
.setTitle('Error')
.setDescription('This command can only be used in the server.')
msg.author.send(Reject);
}
})
This is the error I'm getting:
const member = msg.guild.members.cache.get(msg.author.id);
^
TypeError: Cannot read property 'members' of null
at Client.<anonymous>
How can I fix this?
(v13)
I know, that you are using messages, but if you will you'll change your mind and will start using slash commands, use if (!interaction.guild) return;, this will disable slash commands in DMS. Also you can add interaction.followUp to return a message.
client.on("message", message => {
if(message.author.bot
|| message.channel.type === "dm") return;
// your code here
}
this is what I use to filter out bots and dms.
I am having trouble with getting the right information from message.mentions.roles.first() and message.mentions.members.first()
This is my command handler in Index.js
bot.on('message', async (message, guild, helpList, roles) => {
if (!message.content.startsWith(prefix) || message.author.bot || !message.member.hasPermission('MANAGE_ROLES')) return;
const args = message.content.slice(prefix.length).split(' ') ;
const command = args.shift().toLowerCase();
const aRole = message.mentions.roles.first();
const Role = aRole.id
const name = args.join(' ');
const User = message.mentions.members.first();
if (!Role && command !== 'create' && command !== 'give' && command !== 'take' && command !== 'help' && command !== 'list') {return message.channel.send('Sorry, that role was not found.')}
if (!User && (command == 'give' || command == 'take') ) {return message.reply ("That name doesnt match a user.");}
try{
bot.commands.get(command).execute(message, Role, name, User, guild, helpList);
} catch(e){
console.log(e)
}
});
bot.commands.get(command).execute(message, Role, name, User, guild, helpList);
} catch(e){
console.log(e)
}
});
Here is my take.js, a command to remove a role from the specified member.
module.exports = {
name: 'take',
description: '',
execute(message, Role, User, roles){
try{
User.roles.remove(Role);
return message.channel.send (`${Role} has been removed from ${User}'s list of rolls.`);
}catch(e){
console.log(e);
console.log(Role)
console.log(User)
}}}
This is the error I get.
TypeError: Cannot read property 'remove' of undefined
at Object.execute (/mnt/c/Users/bgera/OneDrive/Desktop/BOTT/RoleBot/commands/take.js:6:16)
at Client.<anonymous> (/mnt/c/Users/bgera/OneDrive/Desktop/BOTT/RoleBot/index.js:34:33)
at Client.emit (events.js:310:20)
at MessageCreateAction.handle (/mnt/c/Users/bgera/OneDrive/Desktop/BOTT/RoleBot/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (/mnt/c/Users/bgera/OneDrive/Desktop/BOTT/RoleBot/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (/mnt/c/Users/bgera/OneDrive/Desktop/BOTT/RoleBot/node_modules/discord.js/src/client/websocket/WebSocketManager.js:386:31)
at WebSocketShard.onPacket (/mnt/c/Users/bgera/OneDrive/Desktop/BOTT/RoleBot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:437:22)
at WebSocketShard.onMessage (/mnt/c/Users/bgera/OneDrive/Desktop/BOTT/RoleBot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:294:10)
at WebSocket.onMessage (/mnt/c/Users/bgera/OneDrive/Desktop/BOTT/RoleBot/node_modules/ws/lib/event-target.js:125:16)
at WebSocket.emit (events.js:310:20)
711442214043254854
<#&711442214043254854> <#!271438275619586062>
Why is Role not working? Any help is greatly appreciated.
Actually in your code when you call execute function here
bot.commands.get(command).execute(message, Role, name, User, guild, helpList);
The execute function in take.js will wait for these parameters :
[parameter] => [variable type received]
message => Message
Role => String (id of the Role mentionned)
User => String (not GuildMember as intended)
guild => undefined
helpList => undefined
In fact, in the order you give parameters to the execute function, you are giving the variable name and not User. So instead of User being a GuildMember it's a String and of course String.roles is undefined, that's why the error says cannot read property 'remove' of undefined.
To fix your error you should modify
bot.commands.get(command).execute(message, Role, name, User, guild, helpList);
to
bot.commands.get(command).execute(message, Role, User, name, guild, helpList);
(Look closely, I inverted name parameter with User parameter)
But wait, it's not finished
Another issue in your code is that you are declaring too much parameters.
bot.on("message", callback(Message)) will only call callback() with one parameter (see docs here).
guild, helpList, roles are always undefined as parameters here.
So you should remove unnecessary parameters like that :
bot.on("message", (message) => {
...
}
And same for execute function call, remove unused parameters :
bot.commands.get(command).execute(message, Role, User);
I think that's it. I hope I've been understandable :D
I keep getting this error
TypeError: Cannot read property 'size' of undefined
at Client.client.on.message
(/home/colter/Code/groundskeeper/index.js:38:30)
at emitOne (events.js:116:13)
at Client.emit (events.js:211:7)
at MessageCreateHandler.handle
I have checked for errors and compared it to the sample code. It all looks right to me.
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();
// Here is my syntax for adding commands. So far simple ones, but commands non the less!
if (command === 'ping') {
message.channel.send('Pong');
}
else if (command === 'beep') {
message.channel.send('Boop');
}
else if (command === 'server') {
message.channel.send(`Server name: ${message.guild.name}\nTotal members: ${message.guild.memberCount}`);
}
else if (command === 'user-info') {
message.channel.send(`Your username: ${message.author.username}\nYour ID: ${message.author.id}`);
}
else if (command === 'args-info') {
if (!args.length) {
return message.channel.send(`Your didnt provide any arguments, ${message.author}!`);
}
else if (args[0] === 'foo') {
return message.channel.send('bar');
}
message.channel.send(`first argument: ${args[0]}`);
}
else if (command === 'kick') {
if (!message.mentions.user.size) {
return message.reply('you need to tag a user in order to kick them');
}
const taggedUser = message.mentions.users.first();
message.channel.send(`You wanted to kick: ${taggedUser}`);
}
});
client.login(token);
the expected output should be you need to tag a user in order to kick them from my bot when I use the ?kick command.
On your code:
message.mentions.user.size
Is trying to read the property size of user, that is inside mentions, that is inside message.
If message, mentions and user don't exist, there's no size property to be read, you cannot read a property of something that does not exist.
You can check beforehand if it exists:
if(message.mentions.user) {
if (!message.mentions.user.size) {
return message.reply('you need to tag a user in order to kick them');
}
}
On line 38, you have what appears to be a simple typographical error.
user (singular) is not a valid property of MessageMentions. The correct property is users (plural), which you use correctly a few lines later.
Perhaps you could use this, if you only need to kick one person at a time.
if(!message.guild) return; // Only runs if in a server
const member = message.mentions.members.first(); // This gets the first guild member, not user.
if (member && message.member.hasPermission('KICK_MEMBERS')) { // Only tries to kick them if they exist and have permission
try {
member.kick(args.slice(1).join(' '); // Gives reason, if any and kicks them.
} catch (err) {
console.error(err);
}
} else {
message.channel.send(`You tried to kick: ${args[0]}`);
}
You should use this for kick command!
client.on("message", (message) => {
// the cmd >> if (message.content.startsWith("{prefix}kick")) {
//permission set to kick members only >> if (!message.member.hasPermission(["KICK_MEMBERS"])) return message.channel.send // not enough perms message >("this bot Found An Error! Error: You Do Not Have Kick Members Permission!")
// >> this is used to define #mentions const member = message.mentions.members.first()
if (!member) {
return message
.reply
// A User didnt mention someone so thy get this error>> (`the bot Found An Error! Error: A User Was Not Mentioned!`)
();
}
// if the bots role doesnt have their role above the user>> if (!member.kickable) {
return message.reply(
`bot Found An Error! Error: Permission Is Not Above The User, Try Again When This Is Fixed!`
);
return (
member
// >> sucess kick message .kick()
.then(() => message.reply(`bot Kicked ${member.user.tag} Sucessfully!`))
);
// error bot message >> .catch(error => message.reply('Error! Please Try Again!`))
});