JavaScript querySelector in Discord bot throwing error

I’m working on a Discord bot and trying to add a number guessing game. I found some code online and wanted to use querySelector, but I’m running into problems. Here’s what I’m trying:

if (msg.content === "!GuessNumber") {
  let randomNum = Math.floor(Math.random() * 100) + 1;
  const guessBox = document.querySelector('.guessBox');
  const resultDisplay = document.querySelector('.resultDisplay');
  const hintText = document.querySelector('.hintText');
  const submitGuess = document.querySelector('.submitGuess');
  const guessInput = document.querySelector('.guessInput');
  let guessCounter = 1;
  let resetBtn;

But I’m getting this error:

ReferenceError: document is not defined

Can anyone help me figure out what’s wrong? I’m trying to adapt a browser-based game for my Discord bot. How can I make this work? Thanks for any help!

As someone who’s built a few Discord bots, I can tell you that trying to use querySelector in a bot is a common mistake for newcomers. The issue is that Discord bots operate in a completely different environment than web browsers—there is no DOM to manipulate. Instead, you need to handle interactions using the Discord API and events.

For a number guessing game, using a message collector is often the best approach. This technique lets you wait for user input and respond accordingly. The example code shows how to initiate a game, wait for guesses, and provide feedback based on the guess. This should better suit a Discord environment and help you move forward with your project. Good luck!

The error you’re encountering is because Discord bots run in a Node.js environment, not a browser. There’s no ‘document’ object in Node, so querySelector won’t work here. For Discord bots, you need to handle interactions differently. Instead of DOM manipulation, you’ll use Discord.js methods to send messages and handle responses. You might want to look into message collectors or button interactions for your number guessing game. These allow you to create interactive experiences within Discord. I’d suggest checking out the Discord.js guide for examples on how to implement games in a bot context. It’ll require a different approach, but it’s definitely doable!

hey bellagarcia, i ran into the same issue when i first started with discord bots. querySelector won’t work cuz there’s no DOM in Node.js. for ur game, try using message collectors instead. they let u wait for user input and respond. it’s a bit different from browser stuff, but once u get the hang of it, it’s pretty cool. good luck with ur bot!