Discord.js – Magic 8 ball!

Discord.js – Magic 8 ball!

Remember that old Magic 8 ball that launched in the 1950’s? Well, I’m not that old, but I remember them from the movies in the 80’s and 90’s. I remember I always wanted one, but I have never bought one, and probably never will. I have, however, created and online version of the game – in my bot CodeLog.

Right, now for some code. I will simply post the code, and there are comments in the code:
Note: I assume you use a command handler and that you implement this code into that.

        let answers = [
            'As I see it, yes.',
            'Ask again later.',
            'Better not tell you now.',
            'Cannot predict now.',
            'Concentrate and ask again.',
            `Don't count on it.`,
            `It is certain.`,
            `It is decidedly so.`,
            `Most likely.`,
            `My reply is no.`,
            `My sources say no.`,
            `Outlook not so good.`,
            `Outlook good.`,
            `Reply hazy, try again.`,
            `Signs point to yes.`,
            `Very doubtful.`,
            `Without a doubt.`,
            `Yes.`,
            `Yes - definitely.`,
            `You may rely on it.`
        ] // This array holds the 20 original answers that was found on the icosahedron dice inside the magic 8 ball !

        const BallNumber = Math.floor(Math.random() * answers.length); // We have to select a number that ranges in from 0 to the number of elements in the answers array
        const delay = (msec) => new Promise((resolve) => setTimeout(resolve, msec)); //New promise to create a delay (in milliseconds) to wait before moving on.
        msg = await message.channel.send(`Hmm, you ask a difficult questions!\nLet me think about it!`); // This sends a message to the channel and we await so we can edit the message later
        await delay(4000); //We await for 4 seconds before an answer is given
        msg.edit(answers[BallNumber]); //This simply edits the previously sent message, and instead gives you an answer from the answers array.

As you can see, there isn’t much to it really. All we do is give the answers in an array and then use a random function to give a number that’s between 0 and the number of elements in the answers array. We do however use the await feature and thus, we have to make sure this code is run in an async function.

If you have questions about this code, feel free to contact me on Discord (join my server, which is linked here), or simply leave it as a comment below this article.

Leave a Reply

Your email address will not be published. Required fields are marked *