Discord JS-命令输出随机数组值作为命令

时间:2020-10-02 20:40:11

标签: javascript arrays discord

我当前正在尝试为我的机器人制作一条命令,该命令每次运行时都会从以下数组中随机给出答案:

const valMapsList = ['Ascent', 'Bind', 'Split', 'Haven'];

我尝试这样做:

const Discord = require('discord.js');
const client = new Discord.Client();

const prefix = '>!';

client.once('ready', () => {
    console.log('Bot is now ONLINE!')
});

let valMapsList = ['Ascent', 'Bind', 'Split', 'Haven'];
let map = valMapsList[Math.floor(Math.random() * valMapsList.length)];

client.on('message', message =>{
    if(!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).split(/ +/);
    const command = args.shift().toLowerCase();

    if(command === 'map'){
        message.channel.send("Selected Map: " + map);
    } else if (command == 'ping') {
        message.channel.send('Pong!');
    }
});

此方法有效,但始终仅在启动时执行代码时始终给出相同的答案。所以我需要一个可以在

中调用的函数
if(command === 'map'){
            message.channel.send("Selected Map: " + map);

将重新运行随机分组的部分。

1 个答案:

答案 0 :(得分:1)

它始终是相同的值,因为您已经释放了消息侦听器。

您需要具备以下条件:

const Discord = require('discord.js');
const client = new Discord.Client();

const prefix = '>!';

client.once('ready', () => {
    console.log('Bot is now ONLINE!')
});

const valMapsList = ['Ascent', 'Bind', 'Split', 'Haven'];


client.on('message', message =>{
    if(!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).split(/ +/);
    const command = args.shift().toLowerCase();

    if(command === 'map'){
        let map = valMapsList[Math.floor(Math.random() * valMapsList.length)];
        message.channel.send("Selected Map: " + map);
    } else if (command == 'ping') {
        message.channel.send('Pong!');
    }
});