Created
January 21, 2019 17:53
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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