Querying a .json document for a specific item and showcasing its price with the help of Discord.js

My current goal is:

User inputs !price (item)

The bot will look up the item in a JSON file, for example:

[
    {
        "hi": 700000,
        "low": 650000,
        "name": "football"
    }

]

The bot will then respond with

Name: Football
High: 650000
Low: 70000

I've searched extensively online but couldn't find any documentation on searching a JSON file using discord.js. Any assistance would be greatly appreciated!

Answer №1

Locating an item within a JSON file is not exclusive to Discord.js. By using the require function, you can import a JSON file and then utilize the find method to retrieve the first object matching a specific criteria.

// Ensure the path is relative since it is not an npm package
const json = require('./path/to/json.json')
const item = json.find(object => object.name === 'football')

Here is a complete example:

const {Client} = require('discord.js')
const json = require('./path/to/json.json')

const client = new Client()
const prefix = '!'

client.on('message', ({author, channel, content}) => {
  if (author.bot || !content.startsWith(prefix)) return

  const args = content.slice(prefix.length).split(' ')
  const command = args.shift()

  if (command === 'price') {
    // Handle case when user only sends !price
    if (!args.length) return channel.send('Please specify an item!')

    const input = args.join(' ')
    const item = json.find(object => object.name === input)
    if (!item) return channel.send(`${input} is not a valid item!`)

    // To capitalize the first letter of name: item.name[0].toUpperCase() + item.name.slice(1)
    channel.send(`Name: ${item.name}
High: ${item.hi}
Low: ${item.low}`)
  }
})

client.login('your token')

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

Encountering an error while attempting to launch an AngularJS application on Node.js? Let's

Currently, I am in the process of learning Angular. Whenever I attempt to run my code, an error message pops up: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f7a737a7c6b6d70715f2b312f3115">[email protected]< ...

Expressing the power of multiple nested routers

Can multiple nested routers be implemented in an Express server? Imagine running a vehicle servicing business and wanting to organize the API into different services, each with its own set of actions: app.use('/clean', cleanRoutes); app.use(&apo ...

Transmitting command-line arguments while utilizing node-windows for service creation

Recently, I developed some custom middleware in Node.js for a client that functions well in user space. However, I am now looking to turn it into a service. To achieve this, I utilized node-windows, which has been effective so far. The only issue is that ...

Is it possible to have separate ports for front-end and back-end in NODEJS?

As I develop my NodeJS website, incorporating both front-end and back-end components, it is recommended to organize the files in such a way that the front-end specifically requests data from the back-end via an API. I am curious whether it is considered a ...

Having trouble with loading images from the assets folder, keep encountering a 304 error

While attempting to load a PNG file from the assets folder, I encountered a 304 error. My goal is to load images from the assets folder. const path = require('path'); const express = require('express'); const webpack = require('we ...

What steps should I follow to set up mongo morgan in my express application?

I've been experimenting with the mongo-morgan package. I have been using it in a similar manner to the original morgan package, but I am not seeing any output in my terminal logs. I attempted the following (replacing 'url' with my actual da ...

Updating a field in Mongoose by referencing an item from another field that is an array

I have developed an innovative Expense Tracker Application, where users can conveniently manage their expenses through a User Collection containing fields such as Name, Amount, Expenses Array, Incomes Array, and more. The application's database is p ...

"Exploring JSON data with jQuery: A guide to efficient search techniques

I have a local file containing JSON data which I successfully loaded using jQuery. My current task is to specifically find the pId with the value of "foo1". The JSON data { "1":{ "id": "one", "pId": "foo1", "cId": "bar1" }, "2":{ ...

Leveraging NodeJs Environment Variables within ViteJS React Components

When using ViteJs to build a ReactJs Project, the vite.config.ts file contains the following: const isDev = process.env["DFX_NETWORK"] !== "ic" const network = process.env.DFX_NETWORK || (process.env.NODE_ENV === "production&quo ...

Communicate your thoughts effectively by tuning in to various pathways

I am in the process of developing a REST API using express, and I'm looking to implement a feature that notifies users when they use an incorrect HTTP verb for their requests. Currently, I've been adding the following snippet after each route: ...

Show a dynamic highchart graph displaying linear data retrieved from the database

I am attempting to present data retrieved from a database in a linear highchart format. Here is the JSON response from my database: [{"protocol":"tcp","date":"01/02/20","time":"00:10:20","total":281}, {"protocol":"udp","date":"01/02/20","time":"00:10:30", ...

Having trouble with my React component timer not functioning properly

How can I utilize the Header Component as a Clock timer for my webpage to update every second? Despite searching on Google, I couldn't find examples that match my requirements. Why is the tick() function not functioning properly even though there are ...

Passing data between pages in Node.js/Express without disrupting the flow of RESTful routing

Within my Express app, the initial landing page prompts visitors to input their email address and then choose between "Sign Up" or "Log In", depending on whether they have an existing account. Following this input, users are directed to either "/signup" o ...

What could be causing the data retrieved from the JSON action to appear as "undefined"?

Have you examined the console.log() outputs and table structure for correctness? I suspect an error in one of them. I am fetching data from the database and using console.log() to display both the data in the loadData() function and value in the $.each(). ...

The dilemma between installing Electron or installing Electron-Builder: which one

When it comes to installing Electron for an Electron app with React, the method can vary depending on the tutorial. Some tutorials use electron-builder while others do not, but there is little explanation as to why. First: npx create-react-app app cd app ...

Sending a POST request using Node.js Express: A step-by-step guide

Looking for help on sending a post request from node.js Express with data passing and retrieval. Preferably a straightforward method like cURL in PHP. Can anyone assist? ...

Google-play-scraper encounters an unhandled promise rejection

I'm trying to use the google-play-scraper library with Node.js, but I keep encountering an error when passing a variable as the 'appId'. How can I resolve this issue? Example that works: var gplay = require('google-play-scraper') ...

Implement a feature to run code on shutdown of a nodejs server using express framework

Is there a method to run a specific block of code in Node.js Express right before the Node.js process terminates, regardless of whether it was triggered by an error, pressing Ctrl+C, or any other cause? ...

Express failing to deliver static content

I am currently facing an issue while trying to host a vue.js single page app using a node.js server. The problem seems to be related to some express middleware. Specifically, my struggle lies in serving two components - my index.html file and a dist folde ...

Tips for extracting key/value pairs from a column containing JSON data in PostgreSQL

How can I extract values from a json column in my database? The values in this particular column are structured like the example below: column1 --------------------------------------------- "[{'name': 'Kate', 'po ...