DiscordJS验证命令

时间:2020-08-20 13:53:17

标签: javascript node.js discord.js

我想用discord.js v12创建一个verify命令,该命令为您提供一个在Configfile中定义的经过验证的角色。

配置文件:

{
"token": "my-token",
"status": "a game",
"statusurl": "",
"statustype": 0,
"botmanager": ["285470267549941761", "743136148293025864"],
"prefix": "m!",
"server": {
    "343308714423484416": {
        "active": true,
        "hasBeta": true,
        "adminroles": ["533646738813353984"],
        "modroles": ["744589796361502774"],
        "premiumtoken": "",
        "welcomechannel": "653290718248435732",
        "welcomemessage": "Hey Hey %user% at %server%",
        "welcomemsgenabled": true,
        "leavechannel": "653290718248435732",
        "leavemessage": "Bye %user% at %server%",
        "leavemsgenabled": true,
        "verifiedrole": "533646700712296448",
        "ruleschannel": "382197929605201920"
    }
}

}

我的代码:

const Discord = require('discord.js')
const client = new Discord.Client()
const config = require('./config.json')

client.on('ready', () => {
    client.user.setStatus('online')
    client.user.setActivity("m!help")
    console.log(`Bot started successfully in ${client.guilds.cache.size} Guilds with ${client.users.cache.size} Users and ${client.channels.cache.size} Channels`)
})

client.on("message", async message => {
    if(message.author.bot) return;
    if(!message.content.startsWith(config.prefix)) return;
    const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
    const command = args.shift().toLowerCase();
            if(command === "verify") {
                if(args.length == 0) {
                    let member = message.mentions.members.first();
                    if(message.member.roles.cache.some(r=>[config.server[(message.guild.id)].modroles].includes(r.id))) {
                        if(!member) {
                            return message.channel.send(new Discord.MessageEmbed().setColor(0xd35400).setTitle("Invalid User").setDescription("Please use the following Syntax:\n `m!verify <Nutzer>`"))
                        } else {
                            var role = message.guild.roles.find(role => role.id === config.server[(message.guild.id)].verifiedrole);
                            member.roles.cache.add(config.guild[(message.guild.id)].verifiedrole)
                        }
                    } else {
                        message.channel.send(new Discord.MessageEmbed().setTitle("Missing Perms!").setDescription("You're missing the permission to execute this command!").setColor(0xe74c3c))               
                    }
                }
            }

            console.log("Command used: " + command + " " + args + " | User: " + message.author.id + " | Guild: " + message.guild.id)
        }
    }
})

client.login(config.token)

我删除了最多的代码,所以只剩下该命令。重要的是,该Bot必须同时能够在多个服务器上使用。

这是怎么了?

3 个答案:

答案 0 :(得分:0)

好的,所以让它作为一个多部分的答案。首先是“这是怎么了?”好吧,在很大程度上,您当前的代码不起作用,因为您没有正确使用方括号。您正在尝试关闭没有打开的方括号。您也可以在不需要的地方使用过多的“ if”语句。

接下来是您对多台服务器的关注。如果您编写的代码是动态的,那么这实际上不是问题。该命令的执行速度足够快,您不必担心两个人都在尝试使用该命令,并且角色会变得混乱。

我真正建议您做的是看看这个https://discordjs.guide/和这个https://discord.js.org/#/docs/main/stable/general/welcome

现在是这个问题的主题,这就是如何执行这样的“验证”命令。我还向代码中添加了一些符号来解释我们在做什么

client.on("message", message => { // You don't need the async here
    
    // This is all working correctly
    if (message.author.bot) return;
    if (!message.content.startsWith(config.prefix)) return;
    
    const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
    const command = args.shift().toLowerCase();

    if (command === "verify") {

        // We define the server constant as the part of the JSON that deals with the server the message came from
        // This makes accessing those values easier
        const server = config.server[message.guild.id];
        
        // Your code here was also working
        let member = message.mentions.members.first();

        // Here we first define the moderator role
        // Technicaly this is not needed but it makes the whole code a little easier to understand
        // We need modrole[0] here because the modrole entry in your JSON is an array
        let modrole = message.guild.roles.cache.find(r => r.id === server.modroles[0]);

        // Here we check if the member who calls this command has the needed role
        // We need to use the ID of the role to check
        if (!message.member.roles.cache.has(modrole.id)) {
            // If the user does not have the required role we return here
            // That way you don't need to use the 'else' statement
            // Creating the embed object in multiple lines improves readability
            return message.channel.send(new Discord.MessageEmbed()
                .setTitle("Missing Perms!")
                .setDescription("You're missing the permission to execute this command!")
                .setColor(0xe74c3c)
            );
        }

        if (!member) {
            // Here we check if a member was tagged in the command and if that user exists
            // Same reasons as above
            return message.channel.send(new Discord.MessageEmbed()
                .setColor(0xd35400)
                .setTitle("Invalid User")
                .setDescription(`Please use the following Syntax:\n '${config.prefix}verify <Nutzer>'`)
            );
        }

        // Now we define the role that we want the bot to give
        // Here we also don't need to do this but it improves readability and makes working with the role a little easier
        var role = message.guild.roles.cache.find(role => role.id === server.verifiedrole);

        // Here we add the role to the specified member
        // We don't need to use the .cache here
        member.roles.add(role.id);
        // We can use something called "template strings" here so we don't need to combine multiple strings
        // They allow us to put predefined values into the string
        console.log(`Command used: ${command} ${args} | User: ${message.author.id} | Guild: ${message.guild.id}`)
    }


})

答案 1 :(得分:-1)

如果需要,该命令可以在需要在async/await中编写代码时在多个服务器上执行。如果您想了解有关异步的更多信息,则可以在这里获得非常好的帮助,特别是对于discord.js v12:Understanding async/await

答案 2 :(得分:-1)

您可以获取用于指定频道的命令,并为服务器分配访问权限