首页 > 解决方案 > 使用 Discord.js 在 .json 文件中搜索商品并显示其价格

问题描述

我想要的是:

用户执行 !price (item)

该机器人将搜索一个 json 文件,例如。

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

]

然后机器人将回复

Name: Football
High:650000
Low:70000

我在网上找不到任何使用 discord.js 搜索 json 文件的文档。如果有人可以提供帮助,将appriciate它!

标签: node.jsjsonfull-text-searchdiscorddiscord.js

解决方案


在 JSON 文件中查找对象并不是 Discord.js 特有的事情。您可以require使用 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')

推荐阅读