首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Discord.js在.json文件中搜索商品并显示其价格

使用Discord.js在.json文件中搜索商品并显示其价格
EN

Stack Overflow用户
提问于 2020-04-16 19:52:47
回答 1查看 744关注 0票数 0

我想要做的是:

用户做!价格(项)

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

代码语言:javascript
复制
[
    {
        "hi": 700000,
        "low": 650000,
        "name": "football"
    }

]

然后,机器人将回复为

代码语言:javascript
复制
Name: Football
High:650000
Low:70000

我在网上找不到任何使用discord.js搜索json文件的文档。如果有人能帮上忙,我会帮你的!

EN

回答 1

Stack Overflow用户

发布于 2020-04-16 20:50:32

在JSON文件中查找对象并不是Discord.js特有的事情。您可以require一个JSON文件,然后使用find获取name与输入匹配的第一个条目。

代码语言:javascript
复制
// 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')

完整的示例:

代码语言:javascript
复制
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')
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61249570

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档