Reputation: 43
I'm trying to make a command whereas it fetches another bot's embed title and checks if it exists in my JSON file. In my code, I'm trying to get my bot answer a riddle by another bot.
This is what I'm trying to do:
This is my code (in the @456 bot):
const riddle = [
{
"riddle": "What has to be broken before you can use it?",
"answer": "egg"
},
{
"riddle": "I’m tall when I’m young, and I’m short when I’m old. What am I?",
"answer": "candle"
},
{
"riddle": "What month of the year has 28 days?",
"answer": "all of them"
},
{
"riddle": "What is full of holes but still holds water?",
"answer": "sponge"
},
{
"riddle": "What question can you never answer yes to?",
"answer": "Are you asleep yet?"
}
]
const id = args[0]
if (isNaN(id)) return;
const msg = await message.channel.messages.fetch(id);
if (!msg) return;
const answer = riddle.filter((obj) => obj.riddle === msg.embeds[0].title).answer
const emb = new MessageEmbed()
.setAuthor(msg.embeds[0].title)
.setDescription(msg.embeds[0].description)
.setColor(msg.embeds[0].color)
message.channel.send({content: `__**Answer:**__ ${answer}`, embeds: [emb]})
I get an error Cannot read properties of undefined (reading 'answer')
whenever I try to run this code. I also tried separating the riddle to a JSON file before. It worked but it gave me an undefined
answer. How do I fix this?
Upvotes: 0
Views: 44
Reputation: 375
I simplified the case so you can study the filter, and understand the return behavior, as well as the output you want, which I show in the console.log:
const riddle = [
{
"riddle": "What has to be broken before you can use it?",
"answer": "egg"
},
{
"riddle": "I’m tall when I’m young, and I’m short when I’m old. What am I?",
"answer": "candle"
},
{
"riddle": "What month of the year has 28 days?",
"answer": "all of them"
},
{
"riddle": "What is full of holes but still holds water?",
"answer": "sponge"
},
{
"riddle": "What question can you never answer yes to?",
"answer": "Are you asleep yet?"
}
];
const msg = {
embeds:
[
{
title: 'What question can you never answer yes to?',
}
]
};
const answer = riddle.filter((obj) => obj.riddle === msg.embeds[0].title);
console.log(answer[0].answer);
you can make this more robust, but this will show you how the structures and filters work, which is your problem at hand.
Upvotes: 1