I am new to JS (and DiscordJS) - I was hoping to figure out why this is crashing my bot.
The intention is to produce a 5% chance to reply to all users who have the specified role ID.
The bot turns on correctly, but as soon as anything is detected or changed in the server, it crashes with: TypeError: Cannot read properties of undefined (reading 'cache')
Any pointers or tips are greatly appreciated!
client.on("messageCreate", (message) => {
let args = message.content.trim().split(" ");
if (message.author.roles.cache.has("641904594041045002")) {
if (message.author.bot) return;
if (message.author.id === "95784650613456896") return;
const responses = [
"Reply1",
"Reply2",
"Reply3",
"Reply4",
];
const reply = responses[Math.floor(Math.random() * responses.length)];
if (Math.random() < 0.05) {
//0.50 = 50% chance
message.reply(`${reply}`);
}
}
});
EDIT:
Changing if (message.author.roles.cache.has("641904594041045002")) {
to
if (message.member.roles.cache.has("641904594041045002")) {
fixes the problem, until a user joins a voice channel - which causes the bot to crash again, with the same TypeError.
EDIT2:
client.on("messageCreate", async (message) => { //now async
let args = message.content.trim().split(" ");
const member = await message.guild.members.fetch(message.author.id) //fetch author ID
if(message.member.roles.cache.some(r=>["bois"].includes(r.name)) ); {
if (message.author.bot) return;
if (message.author.id === "95784650613456896") return;
const responses = [
"Reply1",
"Reply2",
"Reply3",
"Reply4",
];
const reply = responses[Math.floor(Math.random() * responses.length)];
if (Math.random() < 0.99) {
//0.50 = 50% chance
message.reply(`${reply}`);
}
}
});
This produces a different crash (when a user joins/leaves a voice call): DiscordAPIError[10013]: Unknown User
CodePudding user response:
Instead of message.author
, which returns a User object that doesn't have the roles
property, you should use message.member
which returns a GuildMember object instead:
if (message.member.roles.cache.has("641904594041045002")) {
You might need to fetch the member like so:
const member = await message.guild.members.fetch(message.author)
if (member.roles.cache.has("641904594041045002")) {