我在尝试使discord.js机器人上出错:

时间:2020-08-28 06:04:52

标签: javascript visual-studio discord.js

错误: TypeError:无法读取null的属性“ id” 在Object.execute(/Users/Desktop/MSBTM/commands/ban.js:18:32) 在客户处。 (/Users/Desktop/MSBTM/bot.js:56:36)


这是我的代码:

const client = new Discord.Client();

module.exports = {
    name: 'ban',
    description: "ban peoples ;D",
    execute(message, args) {
    if (!message.member.hasPermission("BAN_MEMBERS") || 
    !message.member.hasPermission("ADMINISTRATOR")) return message.channel.send("You don't have 
    a permissions to do this, maybe later ;)");

    const user = message.mentions.users.first();
    const member = message.guild.member(user);

    const reason = args.slice(1).join(" ");

    if (!user) return message.channel.send("Please mention the user to make this action");

    if (user.id === message.author.id) return message.channel.send("You can't ban yourself, I tried :(");
    if (user.id === client.user.id) return message.channel.send("You can't ban me, I tried :(");

    if (!reason) reason = "No reason provided, please provide an reason to make this active";
      member.ban(reason).then(() => {
      message.channel.send(`Successfully banned **${user.tag}**`);
    }).catch(err => {
      message.reply("I was unable to ban the member :(");
    }) 
  } 
}

有人可以帮我吗?

2 个答案:

答案 0 :(得分:2)

这是因为您创建了一个未登录的new客户端对象。我建议您将客户端作为参数传递给函数或使用message.client属性。在下面的示例中,我将其用作函数参数:

module.exports = {
    name: 'ban',
    description: "ban peoples ;D",
    execute(message, args, client) {
        if (!message.member.hasPermission("BAN_MEMBERS") ||
            !message.member.hasPermission("ADMINISTRATOR")) return message.channel.send("You don't have a permissions to do this, maybe later ;) ");

        const user = message.mentions.users.first();
        const member = message.guild.member(user);

        const reason = args.slice(1).join(" ");

        if (!user) return message.channel.send("Please mention the user to make this action");

        if (user.id === message.author.id) return message.channel.send("You can't ban yourself, I tried :(");
        if (user.id === client.user.id) return message.channel.send("You can't ban me, I tried :(");

        if (!reason) reason = "No reason provided, please provide an reason to make this active";
        member.ban(reason).then(() => {
            message.channel.send(`Successfully banned **${user.tag}**`);
        }).catch(err => {
            message.reply("I was unable to ban the member :(");
        })
    }
}

然后您将像execute(message, args, client)这样调用此函数。

答案 1 :(得分:1)

构造新的Client实例不会立即为您提供Client.user。 登录ClientUser时,将填充Client.user:

client.login('token');

here

了解更多信息