The Developer
The Developer

Reputation: 379

How do I put info about messages fetched from the channel to a JSON file?

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

Answers (4)

mohammadreza berneti
mohammadreza berneti

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

Hubi
Hubi

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

user128511
user128511

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

AlonL
AlonL

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

Related Questions