【发布时间】: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