Cannot read the property 'roles' of undefined - discord.js

I'm making a bot and I have an error that I don't understand in this code : pas
const Discord = require("discord.js");
const client = new Discord.Client();
const token = "";
client.login(token)
client.on("message", async(message) => {
let staffRole = message.guild.roles.find("name", "Staff");
let staff = message.guild.member(message.author);
if (message.author.id === "424974772959444993" || message.member.roles.has(staffRole.id)) {
return;
}
var badWords = [
'asd',
'legionmods',
'verga',
'vrga',
'nmms',
'alv',
'electromods',
'remake'
];
var words = message.content.toLowerCase().trim().match(/\w+|\s+|[^\s\w]+/g);
var containsBadWord = words.some(word => {
return badWords.includes(word);
});
if (containsBadWord) {
message.delete();
message.author.send({embed: {
color: 3447003,
description: `Has dicho una palabra que no esta permitida en este servidor`
}
message.channel.send(`${prefix}tempmute ${message.author}`+" 5m palabra prohibida")
}
});
This is an error I get :
(node:4952) UnhandledPromiseRejectionWarning: TypeError: Cannot read property
'roles' of null
at Client.client.on (C:\Users\Francisco\Desktop\role\app.js:8:33)
Could someone help me please ? I am not good in debugging errors.

message.guild is probably returning null because the message was sent in a dm conversation, not a guild.
You can avoid this problem by writing:
if (message.channel.type !== 'text') return;
Also, a few GuildMemberRoleManager methods have changed a bit since discord.js v12+. You should replace:
let staffRole = message.guild.roles.find("name", "Staff");
With:
let staffRole = message.guild.roles.cache.find(role => role.name === "Staff");
And replace:
message.member.roles.has(staffRole.id)
With:
message.member.roles.cache.has(staffRole.id)

Related

discord.js v12 | TypeError: Cannot read property 'send' of undefined

Here is my entire code for my ban command. Good to note I am using Discord.JS Commando as well I have been struggling with this error but literally cannot figure out why I am getting it everything looks fine unless I have used a deprecated function. Would really appreciate someone to help me on this one I've been getting along quite well creating a rich featured bot before this happened.
const { Command } = require('discord.js-commando');
const { MessageEmbed } = require('discord.js');
const db = require('quick.db');
module.exports = class banCommand extends Command {
constructor(client) {
super(client, {
name: 'ban',
memberName: "ban",
group: 'moderation',
guildOnly: true,
userPermissions: ['BAN_MEMBERS'],
description: 'Bans the mentioned user from the server with additional modlog info.'
});
}
async run(message, args) {
if (!args[0]) return message.channel.send('**Please Provide A User To Ban!**')
let banMember = message.mentions.members.first() || message.guild.members.cache.get(args[0]) || message.guild.members.cache.find(r => r.user.username.toLowerCase() === args[0].toLocaleLowerCase()) || message.guild.members.cache.find(ro => ro.displayName.toLowerCase() === args[0].toLocaleLowerCase());
if (!banMember) return message.channel.send('**User Is Not In The Guild**');
if (banMember === message.member) return message.channel.send('**You Cannot Ban Yourself**')
var reason = args.slice(1).join(' ');
if (!banMember.bannable) return message.channel.send('**Cant Kick That User**')
banMember.send(`**Hello, You Have Been Banned From ${message.guild.name} for - ${reason || 'No Reason'}**`).then(() =>
message.guild.members.ban(banMember, { days: 7, reason: reason })).catch(() => null)
message.guild.members.ban(banMember, { days: 7, reason: reason })
if (reason) {
var sembed = new MessageEmbed()
.setColor('GREEN')
.setAuthor(message.guild.name, message.guild.iconURL())
.setDescription(`**${banMember.user.username}** has been banned for ${reason}`)
message.channel.send(sembed)
} else {
var sembed2 = new MessageEmbed()
.setColor('GREEN')
.setAuthor(message.guild.name, message.guild.iconURL())
.setDescription(`**${banMember.user.username}** has been banned`)
message.channel.send(sembed2)
}
let channel = db.fetch(`modlog_${message.guild.id}`)
if (channel == null) return;
if (!channel) return;
const embed = new MessageEmbed()
.setAuthor(`${message.guild.name} Modlogs`, message.guild.iconURL())
.setColor('#ff0000')
.setThumbnail(banMember.user.displayAvatarURL({ dynamic: true }))
.setFooter(message.guild.name, message.guild.iconURL())
.addField('**Moderation**', 'ban')
.addField('**Banned**', banMember.user.username)
.addField('**ID**', `${banMember.id}`)
.addField('**Banned By**', message.author.username)
.addField('**Reason**', `${reason || '**No Reason**'}`)
.addField('**Date**', message.createdAt.toLocaleString())
.setTimestamp();
var sChannel = message.guild.channels.cache.get(channel)
if (!sChannel) return;
sChannel.send(embed)
}
};
The reason you are getting the TypeError: args.slice(...).join is not a function error is because the slice method creates a new array of the sliced data, and so can not join(' ') since there is no space to join with. (i.e. it is not a string)
What you are looking for is args.slice(1).toString().replace(",", " ")
This removes the 2nd part of the args array object, then converts it to a string, then removes the commas in the string and replaces them with spaces.

Change avatar size Discord.js

I want to change the size of the profile photo when the photo is a gif, how can I do it?
I have tried user.displayAvatarURL ({size: 2048, dynamic: true}); but the bot crashes D:
the error is the following:: (node:15836) UnhandledPromiseRejectionWarning: TypeError: user.displayAvatarURL is not a function
module.exports = {
nombre: "avatar",
alias: ["foto"],
descripcion: "Este comando muestra la foto de perfil de un usuario",
run: (client, message, args) => {
const user = message.mentions.users.first() || message.author;
const avatarEmbed = new Discord.RichEmbed()
avatarEmbed.setColor(0x333333)
avatarEmbed.setAuthor(user.username)
avatarEmbed.setImage(user.displayAvatarURL);
message.channel.send(avatarEmbed);
}
}
I have found a way to fix the crash, I attach code :D
const user = message.mentions.users.first() || message.author;
if(user.displayAvatarURL.endsWith(".gif")){
const avatarEmbed = new Discord.RichEmbed()
avatarEmbed.setColor(0x333333)
avatarEmbed.setAuthor(user.username)
avatarEmbed.setImage(user.displayAvatarURL + "?size=1024");
message.channel.send(avatarEmbed);
} else {
const avatarEmbed = new Discord.RichEmbed()
avatarEmbed.setColor(0x333333)
avatarEmbed.setAuthor(user.username)
avatarEmbed.setImage(user.displayAvatarURL);
message.channel.send(avatarEmbed);
}

TypeError: Cannot read property 'roles' of undefined at Object.module.exports.run

I am trying to make a tempmute command which saves data to JSON then reads it every 3 seconds to see is the time experied. I made the mute command but I recive an error TypeError: Cannot read property 'roles' of undefined. I delete the if(!message.member.roles.has("675376537272582154")) return message.channel.send('Bu komutu kullanabilmek için「🔪」Mute Premission rolüne sahip olmasınız.') but this time it said TypeError: Cannot read property 'members' of undefined. Can someone help me?
Information
Discord.js Version: v11.6.1
Node.js Version: 12.0.0
Code
const { RichEmbed } = require('discord.js');
const fs = require('fs');
module.exports.run = async (message, args, bot) => {
if(!message.member.roles.has("675376537272582154")) return message.channel.send(`Bu komutu kullanabilmek için \`「🔪」Mute Premission\` rolüne sahip olmasınız.`);
let toMute = message.mentions.member.first() || message.guild.members.get(args[0])
if(!toMute) return message.channel.send(`:x: Susturulacak kullanıcıyı etiketlemelisin!`)
let timeMute = args[1]
if(!timeMute) return message.channel.send(':x: Susturma süresini dakika cinsinden yazmalısın!')
if(isNaN(args[1])) return message.channel.send(':x: Senin de bildiğin gibi süre sadece sayı olabilir!')
let reason = args.slice(2).join(" ")
if(!reason) return message.channel.send(':x: Susturma sebebini yazmalısın!')
if(toMute.id === message.author.id) return message.channel.send(`:x: Kendini susturamazsın bea!`)
if(toMute.roles.has('675376537272582154')) return message.channel.send(`:x: \`「🔪」Mute Premission\` rolüne sahip olan birini susturamazsın!`)
let role = message.guild.roles.find(x => x.name === '「🔇」Muted')
if(!role) return message.channel.send(':x: `「🔇」Muted` adlı rolü bulamıyorum!')
if(toMute.roles.has(role.id)) return message.channel.send(':x: Bu kullanıcı zaten susturulmuş!')
let modlog = message.guild.channels.find(c => c.name === '『🔰』punishment')
if(!modlog) return message.channel.send(':x: Mod-Log kanalını bulamıyorum!')
const embed = new RichEmbed()
.setTitle('Susturma')
//.setThumbnail(`${toMute.avatarURL}`)
.setDescription(`**Susturlan Kişi: \`${toMute.tag}\`** \n **ID Numarası: \`${toMute.id}\`**\n **Susturan Yetkili: \`${message.author.tag}\`**\n **Süre: \`${timeMute}\`** **Sebep: \`${reason}\`** `)
.setColor("#ff0000")
.setFooter('Kurallara Uymayanın Sonu')
.setTimestamp();
bot.mutes[toMute.id] = {
guild: message.guild.id,
time: Date.now() + parseInt(args[1]) * 10000
}
await toMute.addRole(role)
fs.writeFile("./mutes.json", JSON.stringify(bot.mutes, null, 4), err => {
if(err) throw err;
modlog.send(embed)
})
}
module.exports.conf = {
enabled: true,
guildOnly: true,
aliases: ['sustur'],
permLevel: 0
};
module.exports.help = {
name: 'mute',
description: 'Sustur gitsin',
usage: '!sustur #kullanıcı süre sebep'
}
member and guild are most likely undefined because your bot is receiving a DM message. Check if the message is from a guild before continuing with your code:
module.exports.run = async (message, args, bot) => {
if(!message.guild) return
// rest of code
}

Discord.js channelUpdate event, ignore certain channels

Hello Stackoverflow community. I'm quite curious, regarding the channelUpdate event in Discord.js, is it possible to ignore some channels but log the rest?
bot.on("channelUpdate", async (oldChannel, newChannel) => {
// Get stat channel IDs
let totalUsers = oldChannel.guild.channels.get('667335552558956554');
let onlineUsers = oldChannel.guild.channels.get('667335645894541331');
let totalBots = oldChannel.guild.channels.get('667337560179343374');
//Leave the stat channels alone, or too much logging will happen
//.parent.id === '667335310350352394';
if (totalUsers || onlineUsers || totalBots) return;
let oldCategory = oldChannel.parent;
let newCategory = newChannel.parent;
let guildsChannel = newChannel.guild;
if (!newCategory) newCategory = "None";
if (!guildsChannel || !guildsChannel.available) return;
let types = {
"text" : "Text channel",
"voice" : "Voice channel",
"null" : "None"
};
const logchannel = channel.guild.channels.find(channel => channel.name === "server-logs")
if (!logchannel) return;
if (!logchannel.permissionsFor(oldChannel.guild.me).has('VIEW_CHANNEL')) return;
if (!logchannel.permissionsFor(oldChannel.guild.me).has('SEND_MESSAGES')) return;
if (oldChannel.name !== newChannel.name) {
let channelNameUpdateEmbed = new Discord.RichEmbed()
.setColor("#ffc500")
.setDescription("Channel name updated.")
.addField("Old channel name", `\`${oldChannel.name}\``, true)
.addBlankField(true)
.addField("New channel name", `\`${newChannel.name}\``, true)
.addField("Channel type", `${types[newChannel.type]}`, true)
.addBlankField(true)
.addField("Channel category", `${newCategory}`, true)
.setFooter(`Channel ID: ${newChannel.id} 🔥`)
.setTimestamp()
logchannel.send(channelNameUpdateEmbed).catch()
}
});
Those marked as so called "Stat channels", is it possible to ignore those? Else log channels will get flooded every time a member goes online or offline
Thanks in advance!
Sure, you can create ingoreChannel arr and check if channel in ignore arr.
Like this:
bot.on('channelUpdate', async (oldChannel, newChannel) => {
const ignoreChannels = ['667335552558956554', '667335645894541331', '667337560179343374'];
// Get stat channel IDs
if (ignoreChannels.includes(oldChannel.id)) return;
//Leave the stat channels alone, or too much logging will happen
//.parent.id === '667335310350352394';
let oldCategory = oldChannel.parent;
let newCategory = newChannel.parent;
let guildsChannel = newChannel.guild;
if (!newCategory) newCategory = 'None';
if (!guildsChannel || !guildsChannel.available) return;
let types = {
text: 'Text channel',
voice: 'Voice channel',
null: 'None',
};
const logchannel = channel.guild.channels.find(channel => channel.name === 'server-logs');
if (!logchannel) return;
if (!logchannel.permissionsFor(oldChannel.guild.me).has('VIEW_CHANNEL')) return;
if (!logchannel.permissionsFor(oldChannel.guild.me).has('SEND_MESSAGES')) return;
if (oldChannel.name !== newChannel.name) {
let channelNameUpdateEmbed = new Discord.RichEmbed()
.setColor('#ffc500')
.setDescription('Channel name updated.')
.addField('Old channel name', `\`${oldChannel.name}\``, true)
.addBlankField(true)
.addField('New channel name', `\`${newChannel.name}\``, true)
.addField('Channel type', `${types[newChannel.type]}`, true)
.addBlankField(true)
.addField('Channel category', `${newCategory}`, true)
.setFooter(`Channel ID: ${newChannel.id} 🔥`)
.setTimestamp();
logchannel.send(channelNameUpdateEmbed).catch();
}
});

Discord.js - Give role a all channel

Hello I would like to create an order (! Giverole) so that it gives the roles (mute) to all the channels of the server or to be made the order.
client.on('message', message => {
if(message.content.startsWith(prefix + "giverole")) {
var mute_role = message.guild.roles.find(r => r.name == 'mute', {READ_MESSAGES: true, SEND_MESSAGES: false})
if (!mute_role) return message.channel.send(`**${message.author.username}**, role not found`)
message.guild.channels.overwritePermissions(channel => channel.addRole(mute_role));
var lock_embed = new Discord.RichEmbed()
.setColor("#ffad33")
.setDescription(":lock: **Salon bloqué pour les gens mute**")
message.channel.send(lock_embed)
thank you in advance
At the fist - try always get role with role ID, its more safely.
If I understand your question correctly and you need a certain role on all channels to establish certain rights. So you can use this code.
client.on('message', message => {
if(message.content.startsWith(prefix + "giverole")) {
let muteRole = message.guild.roles.get('ROLEID')
if (!muteRole) return message.channel.send(`**${message.author.username}**, role not found`)
message.guild.channels.map(channel => {
if(channel.type === 'text') {
channel.overwritePermissions(muteRole, {
VIEW_CHANNEL: true,
SEND_MESSAGES: false
})
.then(console.log)
.catch(console.log);
}
})
let lock_embed = new Discord.RichEmbed()
.setColor("#ffad33")
.setDescription(":lock: **Salon bloqué pour les gens mute**")
message.channel.send(lock_embed)
}
})
```

Resources