I’m working on a Discord bot that should read from a text file but I keep running into problems. The bot needs to access a local .txt file and process the data but something isn’t working right.
Here’s what I have so far:
const { Client, GatewayIntentBits, Partials } = require('discord.js');
const fs = require('fs');
const bot = new Client({ intents: [GatewayIntentBits.Guilds], partials: [Partials.Channel] });
const authToken = 'hidden_for_security';
bot.on('ready', () => {
console.log(`Bot is online as ${bot.user.tag}!`);
});
bot.on('messageCreate', async msg => {
if (msg.content.startsWith('!alert')) {
try {
const fileContent = fs.readFileSync('D:\\Projects\\BotData\\alerts.txt', 'utf8');
const alertList = JSON.parse(fileContent);
const params = msg.content.split(' ');
const mentionedUser = params[1];
const alertMessage = params.slice(2).join(' ');
const newAlert = {
username: mentionedUser,
message: alertMessage
};
alertList.push(newAlert);
fs.writeFileSync('D:\\Projects\\BotData\\alerts.txt', JSON.stringify(alertList, null, 2));
msg.channel.send(`Alert sent to ${mentionedUser}: ${alertMessage}`);
} catch (error) {
console.error(error);
msg.channel.send('File reading failed.');
}
}
});
bot.login(authToken);
I want it to respond in the #general-chat channel. This is just for testing purposes. Not sure if the file format is correct either.