This post and code assumes that you have used the following command handler in your index.js file: static: https://discordjs.guide/command-handling/ and for dynamic: https://discordjs.guide/command-handling/dynamic-commands.html This is a basic feature and gives great and simple command handling using one file for each additional command. Command aliases can be found in the command .js file. The code is from the YouTuber CodeLyon, link to video: https://www.youtube.com/watch?v=EFtTTCbGwYY
In a new .js file (I called it random.js) because I have given aliases inside the file (see code below).
const { prefix } = require('../config.json'); const cheerio = require('cheerio'); const request = require('request'); module.exports = { name: 'random', description: 'Send random image from the webl!', guildOnly: true, args: true, aliases: 'rand,rimg,image,rimage', usage: 'Sends a random image of the given search you specify!', cooldown: 60, async execute(message, args) { srch = args.join(' '); image(message); } } function image(message){ var options = { url: 'http://results.dogpile.com/serp?qc=images&q=' + srch, 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)]); }); }
There really isn’t much to this code, it uses the two additional npm packages: cheerio and request.
In Visual Studio Code, open a terminal and type the following two commands: npm install –save cheerio and npm install –save request
This adds the packages to your bot. I use Heroku to host my bot at the moment, along with GitHub. Simple, easy and best of all free for one bot.
If you have a look at the code, there is use of args, and what ever you put as args, is what the engine searches for.
In my case, the prefix is: g$ so the command would be: g$random Hellfire – This would return a random image from a Hellfire search.
If you have any questions about this code, please put it in a comment below, or you could always add me on discord: Lord GeirAndersen#0001.