簡體   English   中英

發送多個圖像(Discord JS)

[英]Sending more than one image (Discord JS)

我試圖制作一個命令,從一組圖像中發送多個隨機選擇的圖像。

以下代碼有效,但它只發送一個圖像:

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',
        },
      ],
    });
  }
});

如何更改此設置以發送兩個或更多圖像?

files選項接受一個數組,因此您可以在其中添加更多項目。 如果您想從列表中選擇隨機圖像,您可以創建一個助手 function,如下面的pick()

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

結果:

機器人

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM