Stack Overflow Asked by Saisekiba on February 28, 2021
The purpose of this code is to run a bot on a Discord server. Right now it is able to search for images, but I would like to randomize the results.
I have the following variable –
var rnd = Math.floor(Math.random() * search.results.length);
but I’m not sure that it’s formatted correctly, or where exactly to put it.
So here is my code:
var cheerio = require("cheerio"); /* Used to extract html content, based on jQuery || install with npm install cheerio */
var request = require("request"); /* Used to make requests to URLs and fetch response || install with npm install request */
var discord = require("discord.js");
var client = new discord.Client();
// Login into discord using bot token (do not share token with anyone!).
client.login("");
client.on("ready", function() {
console.log("logged in");
});
client.on("message", function(message) {
var parts = message.content.split(" ");
/* Simple command manager */
if (parts[0] === "search.") {
// call the image function
image(message, parts); // Pass requester message to image function
}
});
function image(message, parts) {
/* extract search query from message */
var search = parts.slice(1).join(" ");
var options = {
url: "http://results.dogpile.com/serp?qc=images&q=" + search,
method: "GET",
headers: {
"Accept": "text/html",
"User-Agent": "Chrome"
}
};
request(options, function(error, response, responseBody) {
if (error) {
// handle error
return;
}
$ = cheerio.load(responseBody);
var urls = new Array(links.length).fill(0).map((v, i) => links.eq(i).attr("href"));
console.log(urls);
if (!urls.length) {
// Handle no results
return;
}
// Send result
message.channel.send( urls[0] );
});
client.on('message', msg => {
if (msg.content === 'ping') {
msg.reply('pong');
} else if (msg.content === '') {
msg.reply('');
} else if (msg.content === '') {
msg.reply('');
} else if (msg.content === '') {
msg.reply('');
} else if (msg.content === '') {
msg.reply('');
}
});
}
Thank you
I was able to get it to work with the following:
message.channel.send( urls[Math.floor((Math.random() * 50) + 1)] );
Answered by Saisekiba on February 28, 2021
I suppose you are trying to get a random image out of the results you have fetched and stored in var urls. (If its something different, please expand your question)
Since you already have generated the variable rnd limited with a max value of results length.
You can return a random result, by changing the following line.
message.channel.send( urls[rnd] );
Answered by RPDP on February 28, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP