简体   繁体   中英

discord.js “member is undefined”

I'm attempting to filter out bot accounts that advertise on my server by banning usernames that join with the "discord.gg" username.

However it keeps returning error "member is undefined"

const Discord = require('discord.js');

const client = new Discord.Client();

const prefix = '-';

client.once('ready', () => {
    console.log('online');
})

client.on("message", async message => {
  if (member.user.username.includes("discord.gg")) {
    member.ban({days:7,reason:"Advertising."})
      .then(() => console.log(`Banned ${member.displayName}, ${m}`))
      .catch(console.error);
}
});
client.login(process.env.token);

You will need to use this

if (member.user.username.includes("discord.gg")) {
    member.ban({days:7,reason:"Advertising."})
      .then(() => console.log(`Banned ${member.displayName}`))
      .catch(console.error);
}

in a scope where member is defined.

One way to do this would be to listen to the guildMemberAdd event instead of the message For example:

client.on("guildMemberAdd", async (member) => {
  if (member.user.username.includes("discord.gg")) {
    member.ban({days:7,reason:"Advertising."})
      .then(() => console.log(`Banned ${member.displayName}`))
      .catch(console.error);
  }
});

This would ban any member whose username includes discord.gg as soon as they join the server.

Otherwise you could just modify your current code like:

client.on("message", async message => {
  if (message.member.user.username.includes("discord.gg")) {
    message.member.ban({days:7,reason:"Advertising."})
      .then(() => console.log(`Banned ${member.displayName}`))
      .catch(console.error);
  }
});

But this would error if a user sends the bot a direct message ( message.member is undefined if there is no guild)

To counteract that you could also check if the message was sent in a guild with

if (message.guild) {
  /* rest of the code */
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM