[英]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.