1

我正在开发一个机器人来获取用户的头像,try...catch用于用户提及检测,但它仍然会引发错误。

我尝试了一个简单try...catch的,它抛出了一个错误SyntaxError: Identifier 'x' has already been declared

try {
    let x = 1;
    let x = 2; // Variable already been declared
} catch (e) {
    console.log(e)
}

这是我的代码:

// Get avatar by mention
try {
    client.users.fetch(msg.content.substr(prefix.length + 6, msg.content.length - prefix.length - 7)).then(result => {
        embeds.avatar
            .setTitle(`The avatar of ${msg.author.tag}`)
            .setImage(result.avatarURL({ dynamic: true }));
        msg.channel.send(embeds.avatar);
    });
} catch (e) {
    // Invalid user id
    logConsole('commandInvalidParam', msg);
    if (msg.content.length <= prefix.length + 14)
        embeds.commandInvalidParam.setDescription(`\`\`\`Invalid parameter at\n${msg.content}\n`);
    else
        embeds.commandInvalidParam.setDescription(`\`\`\`Invalid parameter at\n${msg.content.substr(0, prefix.length + 14)} ...\n`);
    for (let index = -4; index < prefix.length; index++)
        embeds.commandInvalidParam.setDescription(embeds.commandInvalidParam.description + ' ');
    embeds.commandInvalidParam.setDescription(embeds.commandInvalidParam.description + `^\`\`\`Type '${prefix}' for help`);
    msg.channel.send(embeds.commandInvalidParam);
}

IDE 使用:

虚拟工作室代码

版本:1.54.3(用户设置)

提交:2b9aebd5354a3629c3aba0a5f5df49f43d6689f8

日期:2021-03-15T10:55:45.459Z

电子:11.3.0

铬:87.0.4280.141

Node.js:12.18.3

V8:8.7.220.31-电子.0

操作系统:Windows_NT x64 10.0.18363

4

2 回答 2

1

对于简单的 try...catch,您已经x在代码中声明了变量。没有 2 个变量可以被命名为相同的东西,所以它会给你一个语法错误。如果您想更改 的值x,只需执行x = 2.

对于您的代码,它无法在 fetch 方法中找到用户 ID。这可能是因为前缀长度不正确,或者您的 substr 方法没有获取方法内容的正确部分。无论哪种方式,您都应该尝试使用该子字符串声明一个变量,然后console.log对该变量进行 ing。

于 2021-03-25T17:21:20.670 回答
-1

所以,这里是一个 userinfo 命令应该是什么样子的例子。我用一个安装了 discord.js 的 index.js 文件快速完成了这个。

代码:


module.exports = {
    name: 'userinfo',
    description: 'Get info on a user',
    execute(message, client) {
        const split = message.content.split(/ +/);
        const args = split.slice(1);

        const user = getUserFromMention(args[0], client);
        message.channel.send(`Name: ${user.username}, ID: ${user.id}, Avatar: ${user.displayAvatarURL({ dynamic: true })}`);
        // Other possible information
        // USER OBJECTS @ discord.js
        // ${user.id} ${user.username} ${user.discriminator}(AKA THE LAST 4 NUMBERS OF A DISCORD USERS ACCOUNT) ${user.bot?} ${user.system?} ${user.mfa_enabled}
        // ${user.locale?} ${user.verified?} ${user.email?} ${user.flags?} ${user.public_flags} ${user.premium}
        // src https://discord.com/developers/docs/resources/user#get-user
    }
};
于 2021-03-25T21:13:34.887 回答