Home > Net >  How can I make my code log all things sent in one channel to a text file?
How can I make my code log all things sent in one channel to a text file?

Time:11-30

I have been trying for days but cant find a way to log all messages into a text file

Here is the code:

 module.exports = {
  name: 'log',
  description: "",
  async execute(message, args) {
    const fetched = await client.channels.get("907278968212824164")
    .fetchMessages({limit: 1})
    .then(messages => writeFile('.\MessageLog.txt.')); 
  }
}

CodePudding user response:

to get the messages, you need to get the messages from messageCreate and use fs to write it to your text file.

client.on("messageCreate", message => {
            if (message.channel.id == "id") {
                fs.writeFile("chat.txt", `${message.author}: ${message}`, function(err) {
                    if (err) {
                        throw err;
                    } 
                })
            }
        }

Replace chat.txt with the path of your supposed text file. And its done!

CodePudding user response:

Heyo, the best way imo to do this is to start fetching messages in the desired channel then push them to an Array.

You can find the code below i modified from this answer on another post

 module.exports = {
  name: 'log',
  description: "",
  async execute(message, args) {
    const fetched = await client.channels.cache.get("907278968212824164");
    fetched.fetchMessages().then(async messages => {
      console.log(`${messages.size}.`);

      let finalArray = []; // define array

      const putInArray = async (data) => finalArray.push(data); // this will place items in array
      const handleTime = (timestamp) => moment(timestamp).format("DD/MM/YYYY - hh:mm:ss a").replace("pm", "PM").replace("am", "AM"); // this will format the timestamps

      for (const message of messages.array().reverse()) await putInArray(`${handleTime(message.createdTimestamp)} ${message.author.username} : ${message.content}`); 

      console.log(finalArray); // content in array
      console.log(finalArray.length); // length of array

    }).catch(console.error);
  }
}

Of course you can change this code around as needed, and add in the "write to text file" where you need it to be.

  • Related