Save JSON file to grab other data from it later - javascript

I want to be able to save my json file with new data and then call upon that data so that I can save new data again. Right now all it is doing is it is, when I call upon any part of the JSON file's data, staying the same the last time I manually saved it. (I did edit some code and a better description of my problem) Thank you in advance! Here is my code there is no error log:
const Discord = require('discord.js');
const botconfig = require("./botconfig.json");
const fs = require("fs");
const bot = new Discord.Client();
bot.on("message", async message => {
let prefix = botconfig.prefix;
let messageArray = message.content.split(" ");
let cmd = messageArray[0];
let args = messageArray.slice(1);
console.log(message.member.id)
var playerFile = require(`./playerData/${message.member.id}.json`);
if (message.author.bot) return;
if (message.channel.type === "dm") return;
if (cmd.charAt(0) === prefix) {
if(cmd === `${prefix}fc`){
fs.exists(`./playerData/${message.member.id}.json`, function(exists) {
if(exists){
let ar = args[0];
let ninConsole = args[1];
let code = args[2];
if(ar === "add" || ar === "remove"){
if(code){
if(ar === "add"){
console.log("Add");
if(ninConsole === "switch"){
console.log("Switch " + code);
let fileContent = `{"switch": "${code}","threeDS": "${playerFile.threeDS}"}`
fs.writeFile(`./playerData/${message.member.id}.json`, fileContent, (err) => {
if (err) {
console.error(err);
return;
};
});
}
if(ninConsole === "3ds"){
let fileContent = `{"switch": "${playerFile.switch}","threeDS": "${code}"}`
fs.writeFile(`./playerData/${message.member.id}.json`, fileContent, (err) => {
if (err) {
console.error(err);
return;
};
});
}
}
if(ar === "remove"){
if(ninConsole === "switch"){
let fileContent = `{"switch": "None","threeDS": "${playerFile.threeDS}"}`
fs.writeFile(`./playerData/${message.member.id}.json`, fileContent, (err) => {
if (err) {
console.error(err);
return;
};
});
}
if(ninConsole === "3ds"){
let fileContent = `{"switch": "${playerFile.switch}","threeDS": "None"}`
fs.writeFile(`./playerData/${message.member.id}.json`, fileContent, (err) => {
if (err) {
console.error(err);
return;
};
});
}
}
}
}
}else{
return;
}
});
}

Here is an example of saving data to a JSON file using fs:
JSON.parse(fs.readFileSync("./points.json", "utf8"));
There is an example on how to use this code to make a points system for a discord bot here: https://anidiotsguide_old.gitbooks.io/discord-js-bot-guide/content/coding-guides/storing-data-in-a-json-file.html
Here is the code for this example:
const Discord = require("discord.js");
const fs = require("fs");
const client = new Discord.Client();
let points = JSON.parse(fs.readFileSync("./points.json", "utf8"));
const prefix = "+";
client.on("message", message => {
if (!message.content.startsWith(prefix)) return;
if (message.author.bot) return;
if (!points[message.author.id]) points[message.author.id] = {
points: 0,
level: 0
};
let userData = points[message.author.id];
userData.points++;
let curLevel = Math.floor(0.1 * Math.sqrt(userData.points));
if (curLevel > userData.level) {
// Level up!
userData.level = curLevel;
message.reply(`You"ve leveled up to level **${curLevel}**! Ain"t that dandy?`);
}
if (message.content.startsWith(prefix + "level")) {
message.reply(`You are currently level ${userData.level}, with ${userData.points} points.`);
}
fs.writeFile("./points.json", JSON.stringify(points), (err) => {
if (err) console.error(err)
});
});
client.login("SuperSecretBotTokenHere");
I hope this helps!

Related

How would I go about programming a "stop/start" command for a chatbot in discord.js?

The Problem-
I've been working on a small project (A discord chatbot named AEIOU), and the people I'm working with tend to find that she interrupts conversations by reacting to trigger words every time. I've been looking for ways to add in a !stop and !start command so she'd only react to trigger words when active, and would only listen to commands when the trigger word activation is disabled.
The problem: I have no clue how to go about it, and when I try to code in "if (command === stop/start)", the console log displays an error "can't run commands before initialization".
But, I have to put the trigger words before the commands of the bot will not work at all.
The Code-
console.clear();
const prefix = "au>";
const Me = "865241446335512616";
const Secondary = "589180215956078612"
const Zach = "755977853518086244"
const AEIOU = "792278833877221416"
const Discord = require("discord.js");
const fs = require('fs');
const chalk = require('chalk');
const ytdl = require('ytdl-core');
const GIFEncoder = require('gifencoder')
const Canvas = require ('canvas')
const client = new Discord.Client();
const hi = require("./chatbot/hi.js")
const horny = require("./chatbot/horny.js")
const cute = require("./chatbot/cute.js")
const funny = require("./chatbot/funny.js")
const loli = require("./chatbot/loli.js")
const food = require("./chatbot/food.js")
const drink = require("./chatbot/drink.js")
const hotdog = require("./chatbot/hotdog.js")
client.commands = new Discord.Collection();
const sleep = function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
const getRandomInt = function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
var totalCommands = 0;
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
async function load() {
await console.log(chalk.green('AEIOU, Here to sing for you!'))
await console.log('\n\n');
await console.log('Booting up ' + chalk.cyan(__filename));
await sleep(250);
await console.log(chalk.bgCyan(chalk.black('[Command Loader]')), 'Loading Abilities...');
await sleep(1000);
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
await sleep(10);
await console.log(chalk.bgGreen(chalk.black('[Command Loader]')), 'Got this one! ' + chalk.magentaBright(file));
totalCommands++;
}
console.log(chalk.cyan(totalCommands), 'commands loaded');
client.login("TOKEN_HERE");
}
load();
console.log(chalk.yellow(commandFiles))
client.once('ready', () => {
console.log(chalk.blueBright('AEIOU, here to talk to you!'))
});
process.on('unhandledRejection', error => console.error('Uncaught Promise Rejection', error));
client.on("message", async message => {
if (message.author.id == client.user.id) { return }
var msg = [];
var placeholder = message.content.toLowerCase().split(' ');
placeholder.forEach(string => {
string = string.replace(',', '');
string = string.replace('?', '');
string = string.replace('!', '');
string = string.replace('"', '');
msg.push(string);
});
if (msg.some(r => hi.messages.includes(r))) {
return message.channel.send(hi.responses[getRandomInt(hi.responses.length)]);
}
if (msg.some(r => funny.messages.includes(r))) {
return message.channel.send(funny.responses[getRandomInt(funny.responses.length)]);
}
if (msg.some(r => drink.messages.includes(r))) {
return message.channel.send(drink.responses[getRandomInt(drink.responses.length)]);
}
if (msg.some(r => food.messages.includes(r))) {
return message.channel.send(food.responses[getRandomInt(food.responses.length)]);
}
if (msg.some(r => cute.messages.includes(r))) {
return message.channel.send(cute.responses[getRandomInt(cute.responses.length)]);
}
if (msg.some(r => horny.messages.includes(r))) {
return message.channel.send(horny.responses[getRandomInt(horny.responses.length)]);
}
if (msg.some(r => loli.messages.includes(r))) {
return message.channel.send(loli.responses[getRandomInt(loli.responses.length)]);
}
if (message.mentions.has(client.user)) {
message.channel.send("Hi! I'm AEIOU, and I do have a prefix. It's `au>[command]`. Thanks for mentioning me!")
}
const commandBody = message.content.slice(prefix.length);
const args = commandBody.split(' ');
const command = args.shift().toLowerCase();
if (!message.content.startsWith(prefix) || message.author.bot) return;
if (command == 'credit' || command == 'credits') {
client.commands.get('credits').execute(message, args, Discord, client);
}
if (command == 'help' || command == 'menu') {
client.commands.get('help').execute(message, args, Discord, client);
}
if (command == 'link' || command == 'invite') {
client.commands.get('invite').execute(message, args, Discord, client);
}
if (command == 'headpat' || command == 'pat') {
client.commands.get('pet').execute(message, args, Discord, client);
}
if (command === "repeat") {
const echoMessage = args.join(" ");
message.delete();
message.channel.send(echoMessage);
};
if (command == 'suggest') {
const suggestionmsg = args.join(' ');
if (!args.length) {
return message.channel.send(`You didn't provide a suggestion, ${message.author}!`);
} else {
client.users.cache.get(me).send(message.author.tag + ' suggests: ' + suggestionmsg);
message.channel.send("Thanks for your suggestion, and for helping with my development! I'm always looking for ways to be a better bot!");
console.error();
}
}
});
I removed the actual key, and any names that aren't bots.
You can add a database wheres it has a key for enable/disable
and you can put the condition and then put the i assumed a chat if statement
inside that condition scope
for example
let db = require('quick.db');
let chatStatus = db.get('chatStatus')
// inside message event
if(chatStatus === null) chatStatus = false
if(chatStatus === true)
{
if (msg.some(r => hi.messages.includes(r))) {
return message.channel.send(hi.responses[getRandomInt(hi.responses.length)]);
}
/*
other chat code
*/
if (message.mentions.has(client.user)) {
message.channel.send("Hi! I'm AEIOU, and I do have a prefix. It's `au>[command]`. Thanks for mentioning me!")
}
}
// code for enabling or disabling it
if (command === "status") {
let status = db.get('chatStatus')
if(status === null) status = false
if(args[0] === undefined) return message.channel.send('true/false')
if(args[0] == 'true') {
db.set('chatStatus', true)
message.channel.send(`Successfully set Chatbot to ${args[0]}`);
}
if(args[0] == 'false') {
db.set('chatStatus', false)
message.channel.send(`Successfully set Chatbot to ${args[0]}`);
}
};
P.S: if theres a better way or remove some useless variables, whoever are you freely edit this answer

Make discord bot join a vc using an id from json file

So I want my bot for everytime it boots up I want it to join a specific vc and to play some music! Although, I have come accross a problem. I tried doing this with an id and it worked fine but doing it with json causes some errors and keeps saying that it can't join of undefined. Here is my code:
Processor:
const ytdl = require('ytdl-core-discord');
const editJsonFile = require("edit-json-file");
var fs = require('file-system');
var path = require('path');
const ytfps = require('ytfps');
const prefix = "v_";
let value = true;
let temp;
exports.run = async (client, message, args, ops) => {
const idchannel = client.channels.cache.find(channel => channel.id === "815183065843499008");
const ytchannel = client.channels.cache.find(channel => channel.id === "815183091244597248");
let song = editJsonFile(`live/song.json`);
song.save();
let channelid = editJsonFile(`live/channelid.json`);
song.save();
let count = editJsonFile(`live/count.json`);
count.save();
let cloud = editJsonFile(`live/could.json`);
cloud.save();
let v = count.get(`v`);
let check = cloud.get(`${v}`);
let ope = channelid.get(`${v}`);
if (ope == undefined){
setTimeout(function() {
delete require.cache[require.resolve(`./liveplay.js`)];
let commandFile = require(`./liveplay.js`);
commandFile.run(client, message);
}, 1000);
}
const voiceChannel = client.channels.cache.find(channel => channel.id === `${ope}`);
if (voiceChannel == undefined){
setTimeout(function() {
delete require.cache[require.resolve(`./liveplay.js`)];
let commandFile = require(`./liveplay.js`);
commandFile.run(client, message);
}, 1000);
}
console.log(`${ope}`);
setTimeout(async function() {
try {
console.log("BIP");
setTimeout(async function() {
connection = await voiceChannel.join();
}, 100);
} catch (error) {
console.log(error);
const embed = {
"url": "https://discordapp.com",
"color": 16747962,
"fields": [
{
"name": "🛑 Error ",
"value": "There was an error connecting to the voice channel!"
}
]
};
return message.channel.send({ embed });
}
}, 5000);
setTimeout(async function() {
let ope2 = song.get(`${v}`);
dispatcher = connection.play(await ytdl(ope2), { type: 'opus' })
.on('finish', () => {
voiceChannel.leave();
})
.on('error', error => {
console.log(error);
});
dispatcher.setVolumeLogarithmic(5 / 5);
}, 7000);
count.set(`v`, v-1);
count.save();
v = count.get(`v`);
if (v < 0){
count.set(`v`, v+1);
count.save();
} else {
setTimeout(function() {
delete require.cache[require.resolve(`./liveplay.js`)];
let commandFile = require(`./liveplay.js`);
commandFile.run(client, message);
}, 8000);
}
}
Here is the join command where it actually works:
const ytdl = require('ytdl-core-discord');
const editJsonFile = require("edit-json-file");
var fs = require('file-system');
var path = require('path');
const ytfps = require('ytfps');
const prefix = "v_";
exports.run = async (client, message, args, ops) => {
var value = false;
let number = editJsonFile(`premium/premium.json`);
number.save();
let count = editJsonFile(`premium/count.json`);
count.save();
let v = count.get(`v`)
for(var i = 0; i <= v; i++){
let check = number.get(`${i}`)
if (check == message.author.id){
value = true;
}
}
if(value == false){
return message.channel.send("You do not have premium so you cant run this command");
} else {
args = message.content.substring(prefix.length).split(" ");
const voiceChannel = client.channels.cache.find(channel => channel.id === "809466736491233294");
try {
setTimeout(async function() {
connection = await voiceChannel.join();
}, 500);
} catch(e) {
console.log(e);
}
}
}
EDIT: ope is suppose to equal to the channel id!
i might not be right on this but it seems like your not properly catching the error!
it says that the channel is undefined, that can mean a lot of things. maybe you gave a wrong channel id, maybe a wrong guild id, only way to know for sure is to closely check your code for typos.
as for the error catching, try this:
const channel = client.channels.cache.get("ChannelIDhere");
if (!channel) return console.error("The channel does not exist!");
channel.join().then(connection => {
// Yay, it worked!
console.log("Successfully connected.");
}).catch(e => {
// Oh no, it errored! Let's log it to console :)
console.error(`Failed to connect to the channel! Error:\n${e}`
oh and you forgot to put var before you defined connection
If you wanna export the data from a json file you need to do editJsonFile = require('edit-json-file') then channel.id === ${editJsonFilewhat.channelid} or what ever u define the vc as in json file
in this example in the json file is
{
"channelid":"815183065843499008"
}

I want a command that sends an embed with all the servers that the bot is in

I created a discord.js bot and after some time I wanted to add a servers list command
that sends a message with an embed for each server containing: Server Name, Member Count, Server Avatar (As The Embed Thumbnail), Server Owner ID and Most importantly I don't want anyone to be able to use this command except for me so maybe I add a constant with my ID?,
I can't really come up with a code for it, but anyways... here's the format of one of the commands:
if((args[0] === settings.prefix + "deletereactions" || args[0] === settings.prefix + "dr") && msg.member.hasPermission("ADMINISTRATOR")){
//deletereactions #channel
let channel = msg.mentions.channels.array()[0];
if(!channel) return;
let db = client1.db("rbot");
let collection = db.collection("reactions");
collection.deleteOne({channel : channel.id}, function(err){
if(err) console.log(err);
msg.reply("**✅ Done!**");
})
}
})
and here's my command handler:
const settings = require("./settings.json");
const Discord = require("discord.js");
const client = new Discord.Client();
const fs = require("fs");
const MongoClient = require("mongodb").MongoClient;
const url = "my_mongodb_url";
const mongoClient = new MongoClient(url, { useUnifiedTopology: true });
const moment = require("moment");
const { CommandCursor } = require("mongodb");
let client1;
client.login(settings.token);
client.on("ready", ready =>{
console.log("Ready");
mongoClient.connect(function(err, cli){
client1 = cli;
})
client.user.setActivity(`${settings.activity}`, { type: 'LISTENING' })
})
client.on("message", async msg =>{
let args = msg.content.split(' ');
if(msg.channel.type !== "text") return;
if(msg.channel.type === "text"){
let db = client1.db("rbot");
let collection = db.collection("reactions");
collection.findOne({channel : msg.channel.id}, function(err, result){
if(err) console.log(err);
if(result){
for(let i = 0; i < result.reactions.length; i++){
msg.react(result.reactions[i]).catch(err =>{
if(err) collection.deleteOne({channel : msg.channel.id}, function(err){
if(err) console.log(err);
})
});
In Your Command (Run Or Execute Function):
For 1 User:
if (message.author.id != "YOUR ID") return;
For 2+ Users:
let Owners = ["ID 1", "ID 2"];
if (!Owners.includes(message.author.id)) return;
Ex:
module.exports = {
name: "eval",
run: async (client, message, args) => {
if (message.author.id != "696969696969") return message.channel.send("Only Owners Can Use Eval Command!");
//...
}
};
Links:
User#id
Array

Discord.js Cannot read property 'name'

can someone help me fix this error? It's causing me some critical damage.
const Discord = require('discord.js');
const config = require('./config.json');
const bot = new Discord.Client();
const cooldowns = new Discord.Collection();
const fs = require('fs');
bot.commands = new Discord.Collection();
fs.readdir('./commands/', (err, files) => {
if (err) console.log(err);
let jsfile = files.filter((f) => f.split('.').pop() === 'js');
if (jsfile.length <= 0) {
console.log('No Commands fonud!');
return;
}
jsfile.forEach((f, i) => {
let props = require(`./commands/${f}`);
console.log(`${f} loaded!`);
bot.commands.set(props.help.name, props);
});
fs.readdir('./events/', (error, f) => {
if (error) console.log(error);
console.log(`${f.length} Loading events...`);
f.forEach((f) => {
const events = require(`./events/${f}`);
const event = f.split('.')[0];
client.on(event, events.bind(null, client));
});
});
});
let statuses = ['By LeRegedit#1281', 'Prefix => !', 'V1.0', 'Coming Soon'];
bot.on('ready', () => {
console.log(bot.user.username + ' is online !');
setInterval(function() {
let status = statuses[Math.floor(Math.random() * statuses.length)];
bot.user.setPresence({ activity: { name: status }, status: 'online' });
}, 10000);
});
bot.on('message', async (message) => {
if (message.author.bot) return;
if (message.channel.type === 'dm') return;
let content = message.content.split(' ');
let command = content[0];
let args = content.slice(1);
let prefix = config.prefix;
let commandfile = bot.commands.get(command.slice(prefix.length));
if (commandfile) commandfile.run(bot, message, args);
if (!message.content.startsWith(prefix)) return;
});
bot.login(config.token);
Type Error: Cannot read property 'name' of undefined

How do I send downloaded .mp3 with a Discord.js bot using ytdl-core?

Here is what it currently looks like:
const Discord = require("discord.js")
const client = new Discord.Client()
const fs = require("fs")
const ytdl = require("ytdl-core")
const config = require("./config.json")
fs.readdir("./events/", (err, files) => {
if (err) return console.error(err)
files.forEach(file => {
let eventFunction = require(`./events/${file}`)
let eventName = file.split(".")[0]
client.on(eventName, (...args) => eventFunction.run(client, ...args))
})
})
client.on("message", message => {
if (message.author.bot) return
if(message.content.indexOf(config.prefix) !== 0) return
const args = message.content.slice(config.prefix.length).trim().split(/ +/g)
const command = args.shift().toLowerCase()
try {
let commandFile = require(`./commands/${command}.js`)
commandFile.run(client, message, args)
} catch (err) {
console.error(err)
}
if(command === "test"){
let url = args[0]
ytdl(url, {filter:'audioonly', format:'mp3'}).pipe(fs.createWriteStream("audio.mp3"))
message.channel.sendFile("./audio.mp3")
}
});
client.login(config.token)
commands are stored in seperate files, but I write in the
if(command === "test")
for testing commands
Any help is appreciated, thanks
You're using Stream and it's asynchronous. To make it work you need to check is the file's writing process completed or not!
ytdl(url, {filter: 'audioonly', format: 'mp3'})
.pipe(fs.createWriteStream('audio.mp3'))
// End of writing
.on('end', () => {
message.sendFile('./audio.mp3');
});

Categories