Skip to content

Instantly share code, notes, and snippets.

@vegeta897
Created January 21, 2019 17:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vegeta897/95bd7761868db70195b6965983e1b910 to your computer and use it in GitHub Desktop.
Save vegeta897/95bd7761868db70195b6965983e1b910 to your computer and use it in GitHub Desktop.
Saving and loading data from disk for persistence in a Discord.js bot
const fs = require('fs');
const Discord = require('discord.js');
const client = new Discord.Client();
let saveData;
try {
saveData = JSON.parse(fs.readFileSync('./save-data.json', 'utf8')); // Load save data
} catch(e) {
saveData = { caseCount: 0 }; // Init if no save data found
}
client.on('ready', () => {
// Client ready
});
client.on('message', message => {
if(message.author.bot) return; // Ignore bots
saveData.caseCount++; // Increment case count
message.channel.send(`${saveData.caseCount}. Hello`); // Send message with case number
fs.writeFileSync('./save-data.json', JSON.stringify(saveData)); // Save count to file
});
client.login('bot_token');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment