我曾尝试创建一个命令,用于发送从图像数组中随机挑选的多个图像。
下面的代码可以工作,但它只发送一个图像:
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',
},
],
});
}
});如何更改此设置以使其发送两个或更多图像?
发布于 2020-12-09 19:25:44
files选项接受一个数组,因此您可以在其中添加更多项。如果你想从列表中随机选择图片,你可以创建一个助手函数,就像下面的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
});结果是:

https://stackoverflow.com/questions/65215164
复制相似问题