I'm trying to code a bot in discord.js
that generates random images. So far, I did this with cursed images, but when I copy and paste the code and change the case for 'mcimage' and the url to + "minecraft image", mcimage does work. However, cursedimage also brings up a minecraft image. How do I make it so that cursedimage brings up only cursed images and mcimage brings up only minecraft? This is my code:
client.on('message', (message) => {
let args = message.content.substring(prefix.length).split(' ');
switch (args[0]) {
case 'cursedimage':
image(message);
break;
}
});
function image(message) {
var options = {
url: 'http://results.dogpile.com/serp?qc=images&q=' + 'cursed image',
method: 'GET',
headers: {
Accept: 'text/html',
'User-Agent': 'Chrome',
},
};
request(options, function(error, response, responseBody) {
if (error) {
return;
}
$ = cheerio.load(responseBody);
var links = $('.image a.link');
var urls = new Array(links.length)
.fill(0)
.map((v, i) => links.eq(i).attr('href'));
console.log(urls);
if (!urls.length) {
return;
}
message.channel.send(urls[Math.floor(Math.random() * urls.length)]);
});
}
You can just pass a variable with the search term for both commands like so:
switch (args[0]) {
case "cursedimage":
image(message, "cursed image");
break;
case "mcimage":
image(message, "minecraft image");
break;
}
And then on your image function you can pass the search term to the url in options
function image(message, searchTerm) {
var options = {
url: "http://results.dogpile.com/serp?qc=images&q=" + searchTerm,
method: "GET",
headers: {
Accept: "text/html",
"User-Agent": "Chrome",
},
};
// ...
}
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.