简体   繁体   中英

Sending more than one image (Discord JS)

I have tried to make a command that sends more than one randomly picked images from an array of images.

The following code works, but it only sends one single image:

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

How can I change this to make that send two or more images?

The files option accepts an array, so you can just add more items in there. If you want to pick random images from a list, you can create a helper function, like pick() below.

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

And the result:

机器人

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM