1

I was following a tutorial YT here's the link https://www.youtube.com/watch?v=7rU_KyudGBY&t=726s to create a discord bot. But I have an error that I can't figure out how to fix. It says "cannot read the property of q". The only q I have in my code is in the getQuote function. What I'm trying to do is when I type $inspire, the bot will give an inspiring quote. But when I do that it gives the error "cannot read the property of q" and also "

const Discord = require("discord.js")

const fetch = require("node-fetch")

const client = new Discord.Client()

const mySecret = process.env['TOKEN']

function getQuote() {
  return fetch("https://zenquotes.io/api/random")
.then(res => {
  return res.json
})
.then(data => {
  return data[0]["q"] + " -" + data[0]["a"]
})
}

client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`)
})

client.on("message", msg => {
  if(msg.content === "ping")  {
    msg.reply("pong")
  }
})

client.on("message", msg => {
  if(msg.author.bot)return

  if(msg.content === "$inspire") {
    getQuote().then(quote => msg.channel.send(quote))
  }
})

client.login(process.env.TOKEN)

its a bit outdated(it was made on March 8, 2021). I coded this in repl. Any ideas of how it would work? Thanks in advance

Ethan Agar
  • 92
  • 9

1 Answers1

1

unhandledPromiseRejection errors occur when you don't "handle" the case where Promises are rejected. This means that you should look at your code to find implementations of Promises, and make sure you handle the failure case – with Promises, that usually means implementing a catch or a finally case in the chain.

Looking at your code, it's most probably because you're not catching potential errors in your fetch call.

function getQuote() {
  return fetch("https://zenquotes.io/api/random")
    .then(res => {
      return res.json() // <- careful here too.. `json()` is a method.
    })
    .then(data => {
      return data[0]["q"] + " -" + data[0]["a"]
    })
    
    // +
    .catch((error) => {
      // Catch errors :)
    });
}
Labu
  • 2,572
  • 30
  • 34
  • I was looking more into .catch(), and I had to put the function name before .catch. But when I put getQuote it says getQuote.catch is not a function. Everything else if good. For the catch errors part i just put `` console.error(error)`` Any ideas how to fix that problem? – Ethan Agar Jun 17 '21 at 18:09
  • I'm dumb sry, I forgot to put the .catch() in the get quote function – Ethan Agar Jun 17 '21 at 18:12
  • You're not dumb! The struggle is part of the learning. A big part of mastery comes from understanding what _not_ to do. – Labu Jun 18 '21 at 12:15