Tips for transferring information from a JSON document to an embed?

I'm new to coding and I'm currently working on creating a Discord.js bot from scratch with no coding experience. It's a learning process for me as I go along.
Our current project involves developing a bot that can respond with a Discord embed message. The bot is designed for a online game guild where various characters exist, each with unique stats, skills, and types.
The goal is to populate a JSON file with details of all units, so when users use the .unitname command, the bot will generate an embed containing all relevant information about that unit.
It should resemble this:
https://i.sstatic.net/aeH9b.png

In order to streamline the functionality, creating numerous commands for each individual unit doesn't seem efficient. Therefore, I am considering having the bot scan every message for potential unit requests instead.
While this method may seem inefficient, I am wondering if it will affect the bot's performance in practice?
How can I program the bot to identify inputs like .OneOfDozensFoPossibleUnits?
Perhaps maintaining a separate list with all unit names and triggering them with .AnyOfThose would be a more optimal approach, but I am uncertain.

For instance, if the bot identifies .Lucius as a unit request, it needs to extract the input message, remove the "." prefix (I hope this is achievable, as "." + "input" seems cumbersome).
Next, it must search the JSON file for Lucius' data specifically among many other units. How do I accomplish this?
After acquiring data such as stats, they need to fill designated placeholders (as indicated in the code), but what is the syntax for this?
Additionally, I want to include conditional checks using if statements (e.g., if unit type == "defense", change color to blue). I believe I can find the syntax for this, but your guidance would be greatly appreciated.

Apologies for the somewhat lazy approach by asking for assistance, but due to the collaborative nature of this project, I am exploring unfamiliar territory. Please share any tips or point out any flaws you might discover. Thank you in advance!

client.on('message', message => {
  if (message.content === '.' + "unit") {
    const embed = new Discord.RichEmbed()
      .setAuthor("Author", "https://lh3.googleusercontent.com/rA0lKRGI_-bP-Jj4nkVc5lm6WJfO3nYlAz089otvQnLeevIoao1CTvaU0l0dqnnWIvLZTSOTaEwj6W04IZSRHQz3NYWiePtJnW3bANh54aI=w120")
      .setColor(0xFF0000)
      .addField("<:stats:545991150486421514> Stats", "⧫ ATK: " + "variable" + "\r\n ⧫ HP: " + "variable" + "\r\n ⧫ DEF: " + "variable", true)
      .addField("\u200B", "⧫ CRIT RATE: " + "variable" + "\r\n ⧫ CRIT DMG: " + "variable" + "\r\n ⧫ AGI: " + "variable", true)
      .addField("<:skills:545991578355761152> Skills", "Skill descriptions")
      .setImage("https://lh3.googleusercontent.com/rA0lKRGI_-bP-Jj4nkVc5lm6WJfO3nYlAz089otvQnLeevIoao1CTvaU0l0dqnnWIvLZTSOTaEwj6W04IZSRHQz3NYWiePtJnW3bANh54aI=w120", 2, 2)
      .setThumbnail("https://lh3.googleusercontent.com/rA0lKRGI_-bP-Jj4nkVc5lm6WJfO3nYlAz089otvQnLeevIoao1CTvaU0l0dqnnWIvLZTSOTaEwj6W04IZSRHQz3NYWiePtJnW3bANh54aI=w120")
      .setFooter("Footer", "https://lh3.googleusercontent.com/rA0lKRGI_-bP-Jj4nkVc5lm6WJfO3nYlAz089otvQnLeevIoao1CTvaU0l0dqnnWIvLZTSOTaEwj6W04IZSRHQz3NYWiePtJnW3bANh54aI=w120");
    message.channel.send(embed);
  }
});

Answer №1

It's very possible to retrieve data from a JSON file, and the process is actually quite straightforward. You can refer to a well-documented guide by MDN here for more information.

I share your sentiment on the inefficiency of checking each command individually. By removing the prefix and using the .slice() method, you can streamline this process. Learn more about it here. For instance,

<message>.content.slice(1);
would return unitname when inputting .unitname, which can then be used to search in a separate JSON object file.

If you extract unit information from the JSON file and determine its type, you can dynamically change the color of an embed message. Simply create a variable to store the desired color and include it when sending the embed (e.g., .setColor(myColourVariable)), ensuring that the color variable follows the format 0x[hex_colour_code]. Feel free to reach out if you need further assistance.

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

Determine if there are multiple values that meet the specified search criteria within a JSON file using

I came across this code snippet: import requests from bs4 import BeautifulSoup import urllib, json url = "https://exec85.pythonanywhere.com/static/data_xbox.JSON" response = urllib.request.urlopen(url) json_data_xbox = json.loads(response.read( ...

What could be the reason for the active class not being triggered by Bootstrap?

After making an Ajax call to a PHP file from jQuery, I am trying to loop through the information and format it within table rows and cells. Specifically, I want to use the <tr class="active"> class and the <tr><td> structure provided by B ...

Navigating Parse object attributes within AngularJS

Currently, I am in the process of developing an AngularJS application that utilizes data from a parse-server backend. To retrieve this data, I use services that are called from my controllers. However, as Parse objects require all properties to be accessed ...

Can you verify my comprehension of the process for iteratively displaying numerous custom Tree components in Vue.js 3?

While exploring the Vue.js documentation, I came across an example of iteratively rendering a Tree using the v-for directive. My aim was to modify the code to render multiple TreeItems in the App.vue file. I am puzzled by the fact that it is possible to i ...

Json with ExtJs columns data is fully populated

I am having trouble with displaying columns in my jsp which fetches json data. I am retrieving this json data in my javascript and using Ext.data.JsonStore but the columns are not showing up as expected. Here is the code for the store: store = new Ext.da ...

Creating a unique custom "Ask Seller" button on Ebay can be done by

Currently in the process of revamping a custom sales page for my store and I'm interested in adding a button that says "Inquire With Seller". Despite my efforts to search online, there hasn't been much information available on how to approach thi ...

Is it possible to enable a button as soon as input is entered?

I'm encountering a minor issue with my button's functionality. I am attempting to have the button enabled as soon as text input is entered into the text field, but currently it only becomes enabled after the focus has changed from the text field. ...

What is the reasoning behind storing type definitions in the @types namespace within npm?

Have you ever wondered why type definitions in npm are stored under the @types namespace which isn't directly linked to a specific organization, user, or library? Wouldn't it make more sense for npm libraries to have their types located under @[o ...

Loop through the AJAX response containing JSON data

Need assistance in extracting specific information from each hotel key and its rates within this JSON structure using JavaScript: [ { "auditData": { "processTime": "1545", "timestamp": "2016-04-08 04:33:17.145", ...

Utilizing ChartJS to convert a chart into a Base64 image within a Vue environment

I am currently utilizing the PrimeVue chart component, which is built on top of ChartJS. The configuration is very similar. The documentation indicates that I need to instantiate a new Chart() and then call toBase64Image(); https://i.sstatic.net/NMHjV.p ...

Incorporate XHR into a JavaScript Function

Upon running the code below, a GET message is displayed in the Firebug Console. However, the variable appears as undefined, most likely due to its limited scope within the function. The objective here is to click on a table row, fetch relevant data from t ...

Retrieving information within a Vue component

I am struggling to access some data I have bound to a component without success. How can I achieve this? Below is my component: export default { name: 'component-vallingby', data() { return { } }, created() {}, methods: {} } And h ...

Exploring the behavior of Object.assign in for loops and forEach loops

I've come across an interesting anomaly with Object.assign in the following scenario. function sampleFunction(index, myList) { myList.forEach((element, i) => { if (i === index) { console.log(Object.assign({}, {"newKey": " ...

Imitate the act of pasting content into a Textarea using JavaScript

When data is copied from the clipboard and pasted into an html textarea, there is some interesting parsing that occurs to maintain the formatting, especially with newlines. For instance, suppose I have the following code on a page that I copy (highlightin ...

What steps can be taken to fix the 500 error that occurs while attempting to send JSON data from Postman to MongoDB

I am currently experimenting with a Python scraper that generates JSON output. Some of the variables in the JSON are empty at this stage and will be modified later in a database. Therefore, I need to set them as null. However, I am encountering an issue wh ...

Changing the InnerHTML of a tag in JavaScript using class and id attributes

When it comes to handling these links <div class="post_actions"> <a class="color-transition article_delete" href=""><i class="fa fa-pencil"></i></a> <a class="color-transition article_edit" href="#" id="1">< ...

Display the variable on the document by clicking the button

Hello, I'm new here so please forgive me if I make any mistakes. I am working with the following PHP code: <?php $quoteFile = "quotes.txt"; //Store quotes in this file $fp = fopen($quoteFile, "r"); //Open file for reading $content = fread ...

What is the best way to retrieve information from an API and save it in an array within a MongoDB schema?

My current challenge involves querying an API in node.js, storing the obtained data in an array, and then pushing that array to a MongoDB schema. However, I am encountering difficulties as I am receiving an 'unhandledpromiserejection' warning err ...

Transform your Angular Framework Application into a desktop application with the power of Electron

Project Description: I currently have a fully functional front-end angularjs application that is connected to a back-end Java application deployed on Tomcat, running on a different port (8443). Up until now, I have been accessing the application through a ...

The middleware for express body-parser stores information in the "name" property

I'm just starting out with the nodeJS Express framework and I'm currently working on consuming a POST request that I sent using the code snippet below: router.post('/', function(req, res) { var data = Object.getOwnPropertyNames(req ...