首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >发送多张图片(Discord JS)

问发送多张图片(Discord JS)
EN

Stack Overflow用户
提问于 2020-12-09 18:40:36
回答 1查看 329关注 0票数 1

我曾尝试创建一个命令,用于发送从图像数组中随机挑选的多个图像。

下面的代码可以工作,但它只发送一个图像:

代码语言:javascript
复制
client.on('message', (message) => {
  if (message.content.startsWith("es!jefelegion")) {
    let jefe = [...];
    let image = jefe[Math.floor(Math.random() * jefe.length)];

    console.log(image);
    message.channel.send(image.text, {
      files: [
        {
          attachment: image.link,
          name: 'name.jpg',
        },
      ],
    });
  }
});

如何更改此设置以使其发送两个或更多图像?

EN

回答 1

Stack Overflow用户

发布于 2020-12-09 19:25:44

files选项接受一个数组,因此您可以在其中添加更多项。如果你想从列表中随机选择图片,你可以创建一个助手函数,就像下面的pick()。

代码语言:javascript
复制
function pick(arr, size) {
  if (typeof size === 'undefined') {
    return arr[Math.floor(Math.random() * arr.length)];
  }

  if (size > arr.length) {
    size = arr.length;
  }

  const copy = arr.slice();
  const items = [];

  while (size--) {
    const i = Math.floor(Math.random() * copy.length);
    const item = copy.splice(i, 1)[0];
    items.push(item);
  }

  return items;
}

const images = [
  {
    attachment: './path/to/image1.jpg',
    name: 'Image #1',
  },
  {
    attachment: './path/to/image2.jpg',
    name: 'Image #2',
  },
  {
    attachment: './path/to/image3.jpg',
    name: 'Image #3',
  },
  // ... rest of images
];

message.channel.send('Wooo, more than one files ?', {
  files: pick(images, 3), // picks 3 random images from the `images` array
});

结果是:

​

​

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65215164

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档