1

I have a Discord bot project with lots of variables (numbers, strings etc). I now use .ENV to store my variables. I would like to change that. I learned that you can use .ENV for sensitive variables. For example (Discord.js), your bot token. I have tried searching online, but couldn't find the right answer. Ideally, I would like to have just one file with all my strings. For example:

botcolor = #ffffff

New:

const botcolor = ./config.js

botcolor = ${botcolor}

A different example with a string (when you do ?ping)

message.channel.send("Pong!")

New:

const answer = ./config.js

message.channel.send(`${answer}`)

Something like that. I'm not very experienced with JS. So I'm sorry if im not very clear. Since I have multiple bots, I want to have one config file. My bot is like a template, I can add different types of configs, so that the whole bot (color, answers) changes. My bot is on Discord.js v12 btw, since updating would mean almost rewritting my bots.

So does anyone have a solution for an external config file?

  • 1
    Does this answer your question? [What is the purpose of Node.js module.exports and how do you use it?](https://stackoverflow.com/questions/5311334/what-is-the-purpose-of-node-js-module-exports-and-how-do-you-use-it) – Zsolt Meszaros Jan 18 '22 at 19:37

1 Answers1

2

Since you're using Node.JS, you can use CommonJS requires. I imagine at the top of your main JavaScript file you have a snippet that goes something like:

const discord = require("discord.js");

You can do that for your own files too!
Consider this basic file setup:

- config.js
- index.js <-- entry file

Inside config.js, you export data for another file to use. We can do it like this:

module.exports = {
  answer: "blah blah blah",
  botColor: "#fff",
};

You can export anything, but the most common is either a function or object (which we just did). Now we can use the config file like this:

// index.js
const config = require("./config");

It's important to add ./ in front of your file or Node will try to import from /node_modules. Then after you imported it your could just use it as it were an object:

message.channel.send(config.answer); // <-- "blah blah blah"

You can export multiple objects:

// config.js
exports.bot = {
  answer: "blah blah blah"
};
exports.colors = {
  main: "#fff"
};

Then you use it like:

// index.js
const config = require("./config");
const answer = config.bot.answer;

Or with destructuring:

// index.js
const { bot, colors } = require("./config");
bot.answer; // <-- "blah blah blah"
colors.main // <-- "#fff"

Note: You can also do require("./config.js"), but I find the syntax without .js simpler to understand. You can also require json files as objects.

code
  • 5,690
  • 4
  • 17
  • 39