【问题标题】:How to loop the same command with different value in discord.js如何在 discord.js 中循环使用不同值的相同命令
【发布时间】:2021-08-10 12:37:52
【问题描述】:

我正在用 discord.js 编写一个不和谐的机器人,其中一个功能是当有人发送带有前缀 (.exe) 的消息时,后面紧跟着一个单词(例如 .exebot.exeserverinv) ,机器人返回特定消息。代码工作得很好,但我知道通过复制粘贴相同的代码超过 30 次而仅仅更改值并不是很好的优化。

有什么简单的方法可以让我使用循环或其他东西来重复命令,但使用不同的值?

这是未优化的代码:

command(client, 'command name', message => {
    message.channel.send('bot message')
})
command(client, 'random', message =>{
    message.channel.send('some text')
})
command(client, 'bot', message =>{
    message.channel.send('random text')
})
command(client, 'testing', message =>{
    message.channel.send('text')
})
command(client, 'test', message =>{
    message.channel.send('example text')
})
command(client, 'second to last test', message =>{
    message.channel.send('is almost there')
})
command(client, 'last test', message =>{
    message.channel.send('is the very last one')
})

运行此命令的命令处理程序是:

const { prefix } = require('./config.json')

module.exports = (client, aliases, callback) => {
    if (typeof aliases === 'string') {
        aliases = [aliases]
    }

    client.on('message', message => {
        const { content } = message;

        aliases.forEach(alias => {
            const command = `${prefix}${alias}`

            if (content.startsWith(`${command} `) || content === command) {
                console.log(`Running the command ${command}`)
                callback(message)
            }
        })
    })
}

请指教。

【问题讨论】:

    标签: javascript optimization discord.js


    【解决方案1】:

    您可以使用 JavaScript 的对象表示法并将命令名称映射到回复。

    const commandToReply = {
        "command name": "bot message",
        "random": "some text",
        "bot": "random text",
        "testing": "text",
        "test": "example text",
        "second to last test": "is almost there",
        "last test": "is the very last one"
    };
    
    for (const [name, reply] of Object.entries(commandToReply)) {
        command(client, name, (message) => {
            message.channel.send(reply);
        });
    }
    

    要遍历对象,请查看Object.entries() 的工作原理。

    【讨论】:

      猜你喜欢
      • 2019-10-13
      • 1970-01-01
      • 2021-06-19
      • 1970-01-01
      • 2020-03-16
      • 1970-01-01
      • 1970-01-01
      • 2021-06-02
      • 1970-01-01
      相关资源
      最近更新 更多