I want to create a bot that picks a random image from an array of links, but I don't know what's wrong with it, here's the code and error
const arg = message.content.slice(prefix.lenght).split(/ /);
const command = arg.shift().toLowerCase();
if(command === 'jtoh'){
const rando_imgs = [
'https://media.giphy.com/media/CZpro4AZHs436/giphy.gif',
'https://media.giphy.com/media/CZpro4AZHs436/giphy2.gif',
'https://media.giphy.com/media/CZpro4AZHs436/giphy3.gif',
]
message.channel.send( {
file: rando_imgs[Math.floor(Math.random() * rando_imgs.length)]
});
}
CodePudding user response:
It's just the way you pick the image. Wrong algorithm for picking an image from the array randomly.
Math.random()
in javascript generates a number between 0 and 1. Multiply it with 10 and then apply Math.floor()
to get an integer between 0 and 9.
const integerBetweenZeroAndNine = Math.floor(Math.random()*10);
After that, you could just get a remainder by the array length that you can use as index to access to the image:
const index = integerBetweenZeroAndNine % rando_imgs.length;
Now, index
could only be 0, 1 or 2
which covers all the possible values you could possibly choose from rando_imgs
. All you have to do is
message.channel.send({
file: rando_imgs[index]
})
What if the array length becomes bigger than 9?
Then I can give you a more generic answer. A simple javascript function that picks and integer between min
and max
.
function getRandomInteger(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min 1)) min;
}
In this case the index is the result of this function:
message.channel.send({
file: rando_imgs[ getRandomInteger(0, rando_imgs.length) ]
})
P.S. welcome to stackoverflow
CodePudding user response:
The error is that the send()
method accepts an object with a files
property (not file
). This should be an array where you can add your random image. The following will work for you:
if (command === 'jtoh') {
const rando_imgs = [
'https://media.giphy.com/media/CZpro4AZHs436/giphy.gif',
'https://media.giphy.com/media/CZpro4AZHs436/giphy2.gif',
'https://media.giphy.com/media/CZpro4AZHs436/giphy3.gif',
];
message.channel.send({
files: [rando_imgs[Math.floor(Math.random() * rando_imgs.length)]],
});
}
If you want to display the message, you could just use the content
property instead. In this case, you don't have to send an array.
message.channel.send({
content: rando_imgs[Math.floor(Math.random() * rando_imgs.length)],
});
Also, there is a typo; prefix.lenght
should be prefix.length
.
const arg = message.content.slice(prefix.length).split(/ /);