node.js - 使用 Discord.js 在 .json 文件中搜索商品并显示其价格
问题描述
我想要的是:
用户执行 !price (item)
该机器人将搜索一个 json 文件,例如。
[
{
"hi": 700000,
"low": 650000,
"name": "football"
}
]
然后机器人将回复
Name: Football
High:650000
Low:70000
我在网上找不到任何使用 discord.js 搜索 json 文件的文档。如果有人可以提供帮助,将appriciate它!
解决方案
在 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')
推荐阅读
- c++ - 如何解释 CDC::DrawText 返回负值?
- java - 在线程中访问变量?
- java - 进度条值未更新
- vue.js - vuetify vee-validate 滚动到第一个验证错误
- asp.net - Visual Studio Code 无法调试
- sql - Oracle SQL中如何在不加入的情况下,基于另一个表减少一个表的行数?
- shiny - reactiveValues 中的反应性环境(RShiny)
- sql-server - SQLWatch - 未发送通知
- gcc - 为什么在考虑所有需要的库和引用时,我会收到“未定义的 xxx 引用”错误?
- python - SWIG 不支持 include_next GNU 指令