我正在做一个不和谐的机器人,我想从一个 json 文件中读取一些信息或消息,然后在 js 中比较它以使一切更加整洁,并且基本上在 json 文件中创建一个命令列表,但我有从我的 json 文件中读取一些字段时出现问题,当我去读取我的 json 文件时,它会显示所有内容,我怎么能得到一个文本字符串,例如在问候问题部分 这是我的代码,它向我展示了我的 json 中的所有内容,请帮助我卡住
const Discord = require('discord.js');
const client = new Discord.Client();
const FileJson =require ("./bot.json"); //this is my json fro a want to get the information
const fs = require('fs');
client.on('ready', () => {
console.log(`bot ready as ${client.user.tag}!`);
});
client.on('message', async message => {
if(message.author.bot) return;
fs.readFile('bot.json', (err, data) => {
if (err) { throw err; }
const _msgs = JSON.stringify(JSON.parse(data), null, 6);
message.channel.send(_msgs );
});
});
client.login("here is the key of my bot");
这是我的 json 文件中的“bot”我想从 Greeting/questions 中获取内容,以将其与我不和谐中的人要求然后回答他们的内容进行比较
{ "contenido":
{
"Greetings":[
{"questions": ["Hi", "hello"]},
{"answers": ["Hey, how are you?", "What's up?"]}
],
"goodbyes": [
{"questions":["see you"]},
{"answers":["see you"]}
]
}
}
答案 0 :(得分:0)
嗨,我只是想说我刚刚发现,对于遇到同样问题的人,这是我希望对您有所帮助的答案
const Discord = require('discord.js');
const client = new Discord.Client();
const bot= require ('./bot.json'); //this is my json from a want to get the information
client.on('ready', () => {
console.log(`bot ready as ${client.user.tag}!`);
});
client.on('message', async message => {
if(message.author.bot) return;
var palabras=bot.contenido.Greetings;
var questionss= palabras[0].questions;
var answerss= palabras[1].answers; //the number 1 define to the array number 1 in the file json, so that's why "answers" is 1 and "questions" is 0
var aleatorio=Math.floor(Math.random()*(answerss.length)); //here a random to get a random phrase from the json file
console.log(answerss[aleatorio]);
});
client.login("here is the key of my bot");
这就是我想要做的,从 Json 文件中获取信息,您可以添加更多答案,它会起作用