Поиск файла. json для предмета и отображение его цены с помощью Discord. js - PullRequest
0 голосов
/ 16 апреля 2020

Я пытаюсь:

Пользователь делает! Цена (предмет)

Бот будет искать файл json, например,

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

]

Затем бот ответит

Name: Football
High:650000
Low:70000

Я не могу найти в Интернете никакой документации для поиска файла json с использованием discord. js. Если бы кто-то мог помочь, оценили бы это!

1 Ответ

0 голосов
/ 16 апреля 2020

Поиск объекта в файле JSON - это не Discord. js -specifi c вещь. Вы можете require a JSON файл и затем использовать find, чтобы получить первый элемент, чей name соответствует вводу.

// the path has to be relative because it's not an npm module
const json = require('./path/to/json.json')
const item = json.find(object => object.name === 'football')

Полный пример:

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') {
    // if the user sent just !price
    if (!args.length) return channel.send('You must specify an item!')

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

    // if you want to make the first letter of the name uppercased you can do
    // item.name[0].toUpperCase() + item.name.slice(1)
    channel.send(`Name: ${item.name}
High: ${item.hi}
Low: ${item.low}`)
  }
})

client.login('your token')
...