handledPromiseRejectionWarning: TypeError: Cannot read property 'add' of undefined (Discord Bot)

handledPromiseRejectionWarning: TypeError: Cannot read property 'add' of undefined (Discord Bot)

我一直在处理我的 discord 机器人验证码的问题。验证码工作得很好,但是当涉及到添加角色时,如果他们验证了它,我会用

handledPromiseRejectionWarning: TypeError: Cannot read property 'add' of undefined

这是我的代码:

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

const client = new Discord.Client();

const prefix = 'ri-';

const Captcha = require("@haileybot/captcha-generator");

client.once('ready', () => {
    console.log('Ready!');
});
let captcha = new Captcha();
console.log(captcha.value);
 

const path = require("path"),
    fs = require("fs")
 
client.on('message', async message => {
    if (!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).trim().split(/ +/);

    const command = args.shift().toLowerCase();

    if (command === 'verification') {
 
            let captcha = new Captcha();
            message.channel.send(
                "**Enter the text shown in the image below:**",
                new Discord.MessageAttachment(captcha.JPEGStream, "captcha.jpeg")
            );
            let collector = message.channel.createMessageCollector(m => m.author.id === message.author.id);
            collector.on("collect", m => {
                if (m.content.toUpperCase() === captcha.value){ message.channel.send("Verified Successfully!");
                let role = message.guild.roles.cache.find(r => r.id === "Verified");
                message.author.roles.add(role);
                }else{ message.channel.send("Failed Verification!");}
                collector.stop();
    });
        

    }
});
        

client.login('you don't need this.');

感谢任何帮助! ^^

错误:

我发现你的代码有两个问题。

  1. message.author 指的是不持有角色的用户。使用 message.member 代替

  2. 将r.id替换为r.name,id不是字符串。

祝你有美好的一天:)