首页 > 解决方案 > discord.js 随机图像总是一样的

问题描述

我正在制作一个 grogu discord 机器人,并希望在有人使用g!comic.

到目前为止,我有这个:

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 === 'ping'){
        client.commands.get('ping').execute(message, args);
    }else if (command === 'comic') {    
        const random = new Discord.MessageEmbed()
          .setTitle('Here is your random grogu comic')
          .setImage(image)
    
        message.channel.send(random);
    }
});

问题是,当我测试它时,它总是发送相同的图片/链接,我不知道如何修复它。

这是存储图像的位置:

const images = ["https://i.pinimg.com/originals/4d/2e/f3/4d2ef3052fab7b613733f56cd224118b.jpg", "https://red.elbenwald.de/media/image/a5/f8/e9/E1064005_1_600x600.jpg", "https://i.pinimg.com/736x/29/43/39/2943397229b5fb42cf12e8a1302d1821.jpg", "https://i.kym-cdn.com/photos/images/original/001/755/387/09f.jpg" ];
const image = images[Math.floor(Math.random() * images.length)];

*更新:重新启动机器人后,它显示了不同的图片,但在我重新启动机器人之前它总是一样的

标签: javascriptnode.jsrandomdiscord.js

解决方案


确保你在里面生成一个新的随机图像if (command === 'comic')。如果你在on('message'监听器之外声明它,它总是一样的。您可以/应该将images数组放在它之外,但是您需要在每个传入的命令上生成一个随机数组。

const images = [
  'https://i.pinimg.com/originals/4d/2e/f3/4d2ef3052fab7b613733f56cd224118b.jpg',
  'https://red.elbenwald.de/media/image/a5/f8/e9/E1064005_1_600x600.jpg',
  'https://i.pinimg.com/736x/29/43/39/2943397229b5fb42cf12e8a1302d1821.jpg',
  'https://i.kym-cdn.com/photos/images/original/001/755/387/09f.jpg',
];

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 === 'ping') {
    client.commands.get('ping').execute(message, args);
  } else if (command === 'comic') {
    const image = images[Math.floor(Math.random() * images.length)];
    const random = new Discord.MessageEmbed()
      .setTitle('Here is your random grogu comic')
      .setImage(image);

    message.channel.send(random);
  }
});

推荐阅读