How to modify a variable in the Config.json using a Discord.js command

Lately, I enhanced my bot's functionality by allowing it to retrieve the color for embeds from a file specified in my config.json. All I need to do is modify something like:

"embedcolor": "00A950"
to
"embedcolor": "00000"
. However, I am curious about how I can create a command to update this variable. Perhaps it could be triggered as: -embedcolorset [HexCode] so that the bot can update the color value in the config file.

I appreciate any assistance on this matter :)

Answer №1

To read the content of a file, you can utilize the fs.readFile function and for writing data to a file (replacing it if already exists), you can use fs.writeFile.

If you need to verify a user-provided color, you can employ Util.resolveColor.

Ensure that you create a config.json file with at least an empty object ({}) to avoid receiving a SyntaxError.

Feel free to refer to the code snippet below:

const { Client, Util } = require('discord.js');
const fs = require('fs');
const path = require('path');

const TOKEN = 'BOT TOKEN';
const client = new Client();
const prefix = '!';

// Function to read JSON file
function jsonRead(filePath) {
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, 'utf-8', (err, content) => {
      if (err) {
        reject(err);
      } else {
        try {
          resolve(JSON.parse(content));
        } catch (err) {
          reject(err);
        }
      }
    });
  });
}

// Function to write JSON file
function jsonWrite(filePath, data) {
  return new Promise((resolve, reject) => {
    fs.writeFile(filePath, JSON.stringify(data), (err) => {
      if (err) {
        reject(err);
      }
      resolve(true);
    });
  });
}

client.on('message', async (msg) => {
  const args = msg.content.slice(prefix.length).split(/ +/);
  const command = args.shift().toLowerCase();

  if (command === 'embedcolorset') {
    // Path to config.json file
    // Assuming it's in the same folder as this file
    const filePath = path.resolve(__dirname, './config.json');

    // Check if provided colour is valid
    if (isNaN(Util.resolveColor(args[0]))) {
      return msg.channel.send('You need to provide a valid color');
    }

    try {
      // Read file content, currently just a simple object
      const config = await jsonRead(filePath);
      // Update embedcolor property
      config.embedcolor = args[0];

      // Save file with updated settings
      jsonWrite(filePath, config);

      msg.channel.send(`Embed color set to ${config.embedcolor}`);
    } catch (err) {
      console.log(err);
    }
  }
});

client.once('ready', () => {
  console.log('Bot connected...');
});

client.login(TOKEN);

https://i.stack.imgur.com/TWQKT.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

jQuery if statement appears to be malfunctioning

When the condition operates alone, everything works fine. However, when I introduce an 'and' operation, it does not function correctly. If only one of them is true, the code works. It also successfully takes input values. <!DOCTYPE HTML Code ...

Initialize React Native project

Which ruby command shows the path to Ruby: /Users/User/.rbenv/shims/ruby Ruby -v command displays the version of Ruby installed: ruby 2.7.5p203 (2021-11-24 revision f69aeb8314) [x86_64-darwin21] Which bundle command reveals the path to Bundler: /Users/Us ...

Implement Stripe API mocking using Jest in Node.js with Typescript

I'm having trouble simulating the Stripe API for testing purposes. Although I don't have much experience with mocking functions using jest, I've already extensively researched how to mock the Stripe API without success. My file structure is ...

Issues arise when attempting to delete messages that have already been retrieved

Having trouble removing messages from a specific user without any success: bot.js client.on("message", (message) => { if (message.content === '$deleteuser') { message.channel.fetchMessages({limit: 10}).then(collec ...

Using jQuery to target a specific item from a retrieved list of elements

I'm currently working on a photo gallery feature that is reminiscent of Instagram or Facebook user photos. My goal is to enable users to view details about each image (such as the date) in a box that appears over the image when they hover over it. E ...

Organizing numerical values within for loops

I'm having trouble determining prime numbers and non-prime numbers. When I follow the logic of looping through numbers from 2 to 100, it makes sense for primes. However, when I start at 0 and loop by y + itself, it seems counterintuitive to me. For ex ...

Implementing Materialize CSS functionality for deleting chips

I've been attempting to extract the tag of a deleted chip from the div within the Materialize chips class, but I'm hitting roadblocks. My failed attempts so far: $('.chips').on('chip.delete', function(e, chip){ console.lo ...

Is the callback of $.post not being executed until the loop it's contained in finishes?

I'm working on a stock table that allows users to input the quantity of stock to issue. I have a function that verifies whether or not the database has sufficient stock for each entry in the table. When debugging through the code in Chrome, I noticed ...

Configuring proxy settings in npm-yeoman package

I'm currently developing my Angular application using Yeoman. I've configured proxies and registry settings as shown below: npm config set proxy http://proxy.tcs.com:8080 npm config set https-proxy http://proxy.tcs.com:8080 npm config set reg ...

Rearrange element's placement using Jquery Drag & Drop

I am experiencing difficulties in positioning my elements after a drop event. Within my "list" of divs... In order to keep the divs together and update the list, I utilize jQuery's append function to move the element from the list to its designated ...

Access a webpage whose URL has been dynamically assigned using JavaScript

I have a website that consists of a single page and features four tabs. Whenever a tab is clicked, it displays the corresponding content in a div while hiding the other three divs along with their respective content. To ensure a smooth user experience, I u ...

Checking if a certain function has been called within my express controller function

As a testing newcomer, I am still learning the necessary skills. I have been working on testing my error handler controller and after some time, I finally got it up and running. However, I would appreciate some feedback on the implementation. There seems ...

The entered value in the <input> field is not valid

I am encountering an issue where the input value is auto-filled, but when I click the submit button, the input field value is not recognized unless I modify something in it, such as deleting and adding the last word to the first name. Is there a way to m ...

Easily integrating a JavaScript file into an HTML document when utilizing a NodeJS Express server

Currently in the process of developing a chat application, utilizing the Express server with NodeJS and AngularJS for client-side management. Encountering an issue when attempting to include /js/code.js in my html, as it cannot be found due to not being p ...

What is the process for rendering a React class component using React HashRouter and Apollo client?

I've run into an issue with my project that involves using only React class components and fetching data from an Apollo server. The problem I'm facing is that, in Chrome, only the Navbar.jsx component is rendering. Even when I navigate to one o ...

What are some strategies for sorting information from a list that is constantly changing?

I have been working on a web application built in asp.net that receives data from a web service in JSON format. The current task is to dynamically develop controls for this application. I achieved this by creating a list of labels with stored values using ...

Running cy.task after all test suites can be done by adding the task in a

I need some guidance on running cy.task after executing all test suites. I have a file generated at the start of the tests that I would like to remove once they are completed. Regardless of whether any tests passed or failed, I want to trigger cy.task im ...

Utilize the effectiveness of the Ajax Success Handler for retrieving a distinct JSON entity

One of the features I am currently using involves an Ajax command that enables me to query data from a local server. In order to ensure smooth execution, it is crucial for me to return a JSON object through the success handler. The specific structure of m ...

Using Node.js: Only bring in the necessary function, don't execute the entire file

Today, I stumbled upon an interesting observation and I'm curious about the peculiar behavior of node in this scenario. I have two files structured as follows: src/api/index-api.ts src/worker/index-worker.ts Both of these files contain a simple con ...

Using dangerouslySetInnerHTML in React within a Fragment

In my current project, I have a specific requirement where I need to format text in React and also include HTML rendering. Here's an example of what I'm trying to accomplish: import React, {Fragment} from "react"; import {renderToString} from " ...