DEV Community

Cover image for Code Fully Fledged Trivia Games in Discord.JS
Elitezen
Elitezen

Posted on • Edited on

Code Fully Fledged Trivia Games in Discord.JS

Trivia is often one of the most engaging group games to play, but programming a trivia match requires patience and a strong knowledge of programming.

Luckily, I have created an NPM module that implements fully fledged and polished trivia games straight out of the box with Discord.JS with just a few lines of code!

Full package guide: https://elitezen.github.io/discord-trivia-website/

Github Repo., includes a condensed form of this article in the README.
NPM Page,
Discord Server

👉 What you will need to get started:

Note: This guide uses slash commands, but messages work too!

Getting Started

Open a terminal inside your Discord bot's root directory and install discord-trivia with the following command:

npm install discord-trivia
Enter fullscreen mode Exit fullscreen mode

Then, create a new slash command file:

const { SlashCommandBuilder } = require('discordjs');

module.exports = {
 data: new SlashCommandBuilder()
  .setName('Trivia')
  .setDescription('Lets play some trivia!'),
 async execute(interaction) {

 },
};
Enter fullscreen mode Exit fullscreen mode

At the top of your command file require the GameManager class from Discord Trivia. Create a new trivia manager instance and name it trivia.

const { GameManager } = require('discord-trivia');
const trivia = new GameManager();
Enter fullscreen mode Exit fullscreen mode

Then, inside your execute() function create a new game using trivia.createGame() and supply the channel. Use game.start() to start a match as soon as this command is ran. Make sure to add a .catch() callback to catch any errors.

async execute(interaction) {
    // Create the game
    const game = trivia.createGame(interaction.channel); 

    // Start the game
    game
       .startQueue()
       .catch(console.error);
},
Enter fullscreen mode Exit fullscreen mode

Your code so far should look like this:

const { SlashCommandBuilder } = require('discordjs');
const { GameManager } = require('discord-trivia');
const trivia = new GameManager();

module.exports = {
 data: new SlashCommandBuilder()
  .setName('Trivia')
  .setDescription('Lets play some trivia!'),
 async execute(interaction) {
        const game = trivia.createGame(interaction.channel); 

        game
           .startQueue()
           .catch(console.error);
 },
};
Enter fullscreen mode Exit fullscreen mode

And that's all! Your bot will start a trivia match within the
channel the command was started 🎉🎉🎉

For customization and configuration of the package, visit the guide: https://elitezen.github.io/discord-trivia-website/

Top comments (0)