Cannot read property 'data' of undefined discord.js - discord

Making a command to take a random photo of a waifu in this case, and posting it in the channel
Code here:
if (command === 'waifu') {
const waifu = new Discord.MessageEmbed()
got('https://waifu.pics/api/sfw/waifu').then(response => {
let content = JSON.parse(response.body);
let waifuUrl = content[0].data.children[0].data.url;
let waifuImage = content[0].data.children[0].data.url;
waifu.setImage(`${waifuImage}`)
waifu.setURL(`${waifuUrl}`)
waifu.setColor('#ffb9f4')
waifu.setFooter(`Requested by ${message.author.user}`)
waifu.setTimestamp()
waifu.setAuthor(`waifu.pics`, `https://waifu.pics/`)
message.channel.send(waifu)
});
};
The API should be correct. After a few small changes, I tried console logging the JSON and it did output the correct thing. But when running the code in discord, it outputted a TypeError: Cannot read property 'data' of undefined error. I cannot seem to figure out the problem

if (command === 'waifu') {
const waifu = new Discord.MessageEmbed()
get('https://waifu.pics/api/sfw/waifu').then(response => {
let content = response.body;
let waifuUrl = content.url;
let waifuImage = content.url;
waifu.setImage(`${waifuImage}`)
waifu.setURL(`${waifuUrl}`)
waifu.setColor('#ffb9f4')
waifu.setFooter(`Requested by ${message.author.username}`)
waifu.setTimestamp()
waifu.setAuthor(`waifu.pics`, `https://waifu.pics/`)
message.channel.send(waifu)
});
};
You thought a little bit complicated ^^ You had something with children and data, although the API just gives an URL. You don't even have to parse it. And you have used the function got(), which you have to replace with get().
I fixed your code just copy it from above.

Related

web3.js how can i save value in variable from function?

I am trying to get started with web3.js. There are two different examples for getBlockNumber or getBalance:
web3.eth.getBlockNumber(function (error, result) {
console.log(result);
});
or shorter
web3.eth.getBlockNumber()
.then(console.log);
But how do I save the output to process it further? No matter how I try, I only get "Promise { }".
I have read many posts on this but have not found a solution that works for me.
let result;
const blockNumber = async () => {
result = await web3.eth.getBlockNumber();
};
blockNumber();
Let me know if that solve your problem. Actually "everything" it's a promise in web3 that's why you need async/await
^ console.log the result variable ofc.

Bot - DisTubeError [INVALID_TYPE]: Expected 'Discord.Message'

I made a music bot, but I'm looking to turn this into interactions, but I'm having a problem calling the play function.
With "message" it works, but with "interaction" it doesn't. I tried to pass on some information, I searched but I couldn't.
I even found a different way, but it didn't work.
The error returned is this:
DisTubeError [INVALID_TYPE]: Expected 'Discord.Message' for 'message', but got undefined (undefined)
Play.js
const { SlashCommandBuilder } = require('#discordjs/builders');
module.exports = {
data: new SlashCommandBuilder()
.setName('play')
.setDescription('Play a song!')
.addStringOption(option => option.setName('song').setDescription('Enter name of the music.')),
async execute (interaction, client){
// if(!interaction.member.voice.channel) return interaction.reply("Please, join a voice channel!");
const music = interaction.options.getString('song');
if(!music) return interaction.reply("Please, provide a song!");
await client.distube.play(interaction, music);
// await client.distube.playVoiceChannel(
// interaction.member.voice.channel,
// music,
// {
// textChannel: interaction.channel,
// member: interaction.member
// }
// );
}
}
DisTube, at the time of this question being posted, doesn't support slash commands, and it looks like the creator doesn't have any plans on supporting it officially. As a workaround, you can use the Distube#playVoiceChannel method instead of the Distube#play method, like so:
await client.distube.playVoiceChannel(interaction.member.voice.channel, music);
But before you do any of that, it looks like interaction is undefined - that's probably a problem with your command handler, so look there.
Edit: Also docs for Distube#playVoiceChannel if you're interested

How do I display local image with discord.js message embed?

I'm working on semi-gacha bot command where you can pull characters and so on. I want to display the characters image after the user pulls and here is where I get stuck, it just doesn't display anything and I found what looked like the answer on here, but it didn't help, as I would get the same result and I don't get any errors, so I don't know what exactly is wrong. I have tried printing out the result of MessageAttachment first:
const attachment = new Discord.MessageAttachment('./chars/1.Jakku.png', '1.Jakku.png');
console.log(attachment);
and I get: undefined, anybody has any ideas of what am I doing wrong? And yes, I have discord.js library imported.
Relevant part of the code:
collector.on('collect', reaction => {
//new embd
const newEmbd = new Discord.MessageEmbed();
// gacha logic
if (reaction.emoji.name === '✅') {
const values = Object.values(chars);
const randomChar = values[parseInt(Math.floor(Math.random()*values.length))];
const attachment = new Discord.MessageAttachment('./chars/1.Jakku.png', '1.Jakku.png');
const charData = randomChar.split('.');
newEmbd
.setTitle(`You pulled: ${charData[1]}!`)
.setColor('YELLOW')
.attachFiles(attachment)
.setImage(`attachment://1.Jakku.png`);
embdReact.edit(newEmbd);
pulled = true;
} else if (reaction.emoji.name === '❌') {
newEmbd
.setTitle('Time for gacha!')
.setColor('YELLOW')
.addFields(
{ name: 'Result:', value: 'You decided against pulling' }
);
embdReact.edit(newEmbd);
};
});
You need to use the correct syntax for attaching files as per this guide
const exampleEmbed = new Discord.MessageEmbed()
.setTitle('Some title')
.attachFiles(['./chars/1.Jakku.png'])
message.channel.send(exampleEmbed);

Firestore Snapshot Read only last document

fire.firestore().collection('Customer').get()
.then(data=>{
data.docs.forEach(doc=>{
let db = fire.firestore().collection(`Customer`)
db.where("updated", ">=", 0).limit(100).onSnapshot(async doc=>{
try {
await doc.docs.map(each=>{
setDatas([...datas, {...each.data()}])
})
}
})
})
I am trying to append the object in the array to query from firestore.
However, somehow it only reads last document.
Please help me if you could store state without using array.
Checking your code and running this data as sample I could notice your code is getting all the results and not just the last one, so there could be something else. Also it seems like a double unnecessary query.
Instead you can query all the docs you may want to get them using .. where("updated", ">=", 0).limit(100) .. and not a query inside a query.
You can use the sample code from here to make something more simpler:
const admin = require('firebase-admin');
admin.initializeApp();
let db = admin.firestore();
const citiesRef = db.collection('Customer');
const snapshot = await citiesRef.where('updated', '>=', 100).limit(100).get();
if (snapshot.empty) {
console.log('No matching documents.');
return;
}
snapshot.forEach(doc => {
//Your code here to add to your array
});
This code is for NodeJS but you can adapt it to ReactJS

Array undefined error for my Angular 2 application

I am facing the below issue where I am trying to save JSON data coming from my API into an array of my Model object. However, when I console.log the array it prints "undefined". I even tried to print a simple array and it still says "undefined". I am not sure if I am missing anything here. My code is given below. Can some one please help as I am new to Angular 2 and TypeScript.
results : Array<Recipes> = new Array(20);
sample = ['one','two','three'];
getResults(): Observable<Recipes[]>{
return this.http.get('<my API here which works perfectly.>')
.map(this.extractData)
.catch(this.handleErrorObservable);
}
private extractData(res: Response) {
let body = res.json();
console.log(this.sample); **---> This prints undefined in console**
console.log(body);
console.log(body.pagination.count);
let total_no_of_results = body.pagination.count;
let no_of_results;
for(no_of_results = 0; no_of_results < total_no_of_results; no_of_results++) {
//this.results[no_of_results] = new Recipes();
this.results[no_of_results] = body.data[no_of_results].embed_url; **---> This gives "Cannot set property '0' of undefined" error and program exits**
//this.results.push(image);
}
console.log(this.results);
return this.results;
}
private handleErrorObservable (error: Response | any) {
console.error(error.message || error);
return Observable.throw(error.message || error);
}
If you want to use this inside extractData you need
.map(this.extractData.bind(this))
or
.map((data) => this.extractData(data))
otherwise this won't point to the current class' instance.

Resources