Reputation: 379
So I want to fetch all embed messages from a specific channel with a tag written in their description.
I started with fetching both embedded and simple messages using channel.fetchMesssages()
and resolving the promise. I get the collection, I can print messages' values to the console one-by-one but I can't add them to the object to then save them as JSON file.
Here's the code:
var news = client.channels.get('id')
var specialMessages = new Object()
news.fetchMessages()
.then(messages => {
messages.forEach((m, i) => {
specialMessages[m.content] = m.id
})
})
console.log(specialMessages)
fs.writeFileSync('messages.json', JSON.stringify(specialMessages, null, 2))
The thing is I don't seem to add anything to the specialMessages
because it outputs just {}
to the console. What's the magic behind it?
Upvotes: 0
Views: 138
Reputation: 530
console.log()
is executed before fetching the messages, since the latter operation is asynchronous and not instantly completed (read about Promises).
You should place the console.log(...)
and fs.writeFileSync(...)
lines immediately after the forEach()
loop, but within the .then()
block's scope.
Upvotes: 5
Reputation: 104
Your specialMessages are {} cause file is not completed. Try console.log after file completed or use callback, async.
var news = client.channels.get('id')
var specialMessages = new Object()
news.fetchMessages()
.then(messages => {
messages.forEach((m, i) => {
specialMessages[m.content] = m.id
})
})
fs.writeFileSync('messages.json', JSON.stringify(specialMessages, null, 2))
console.log(specialMessages)
Upvotes: -1
Reputation:
this should work
(async () => {
const news = client.channels.get('id');
const specialMessages = {};
const messages = await news.fetchMessages();
messages.forEach((m, i) => {
specialMessages[m.content] = m.id;
});
console.log(specialMessages);
fs.writeFileSync('messages.json', JSON.stringify(specialMessages, null, 2));
})();
Upvotes: 0
Reputation: 152
Use .map()
.
var news = client.channels.get('id');
news.fetchMessages()
.then(messages => {
fs.writeFileSync('messages.json', JSON.stringify(messages.map(m => m.id), null, 2));
});
Upvotes: -2