【问题标题】:Discord.js | How do I make my bot send a random image?不和谐.js |如何让我的机器人发送随机图像?
【发布时间】:2022-02-14 00:38:37
【问题描述】:

我已经尝试了很多我见过的东西,但似乎没有一个对我有用。我使用的是当你执行命令时它会激活命令文件夹中的文件,而大多数其他脚本不使用它。

【问题讨论】:

  • 呃,抱歉这里的图片描述,我是新手;)
  • 使用.json存储大量图片

标签: javascript node.js discord discord.js


【解决方案1】:

没有看到任何代码,很难为您指明正确的方向。这将有助于更多地定义您遇到的问题(实际错误和/或功能)以及查看您正在使用的代码。解决方案还取决于图像的来源。

假设您的图像位于本地文件夹中,这是一个基本示例:

if (message.content === '!random') {
    // get a random index between 0 and length
    const idx = (len) => Math.floor(Math.random() * (len));

    // get all the files in the directory
    const files = fs.readdirSync('/images/');

    // get file from directory
    const myImage = files[idx(files.length)];
    
    // send image to channel
    message.channel.send({ files: [`/images/${myImage}`] });
}

假设图片来自https://picsum.photos/,这是一个基本示例:

if (message.content === '!random') {
    const seed = Math.floor(Math.random() * 1000);
    const h = Math.floor(Math.random() * 400) + 100;
    const w = Math.floor(Math.random() * 400) + 100;
    
    // create embed with random image
    const embed = new MessageEmbed().setImage(`https://picsum.photos/seed/${seed}/${h}/${w}`);
    
    // send embed
    message.channel.send({ embeds: [embed] });

    // delete command
    message.delete();
}

【讨论】:

  • 我正在尝试从 dogpile / 图像网站获取图像。我已经尝试了很多代码,但它们似乎都没有工作。我没有收到任何错误,它只是不起作用。我使用的是勇敢而不是 chrome,它说它使用 chrome 获取图片,所以我不确定这是否有帮助?
  • 嗯,这可能是你的困难的一部分,因为 Dogpile 似乎没有提供 API,所以我假设你正试图从 HTML 或其他东西中抓取图像?我将更新我的答案以包含一个用于提取随机图像的不同站点。
  • 行得通!但现在它每次都发送相同的图像。有什么方法可以让它在我每次输入命令时发送不同的图像?
  • 我实际上注意到了同样的事情。 unsplash 提供图像的方式。虽然 picsum 做同样的事情,但我想通了。我再次更新了我的答案。
  • 非常感谢 :) 你帮了大忙!
猜你喜欢
  • 2021-06-04
  • 2022-01-07
  • 2019-06-08
  • 2020-10-01
  • 2021-04-26
  • 2021-02-12
  • 2021-04-30
  • 2021-05-08
  • 2020-12-26
相关资源
最近更新 更多