【问题标题】:discord.js random image is always the samediscord.js 随机图像总是一样的
【发布时间】:2021-05-02 07:09:24
【问题描述】:

当有人使用 g!comic 时,我正在制作一个 grogu discord 机器人,并希望在嵌入中发送随机漫画图片。

到目前为止,我有这个:

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)];

*更新:重新启动机器人后,它会显示不同的图片,但在我重新启动机器人之前,它总是发布相同的内容

【问题讨论】:

  • image 变量来自哪里?

标签: javascript node.js random discord.js


【解决方案1】:

确保您在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);
  }
});

【讨论】:

  • 嗨,它工作!非常感谢!现在我可以向这个命令发送垃圾邮件了! xD
猜你喜欢
  • 2020-08-10
  • 2020-12-25
  • 1970-01-01
  • 1970-01-01
  • 2019-03-11
  • 1970-01-01
  • 2013-06-07
相关资源
最近更新 更多