我正在为Discord创建一个机器人来播放我的收音机/播客但是我被卡住了。我正试图让机器人从./stations文件中发送站点列表,如下面的代码所示。
从第
行开始if(command == 'stations') {
message.channel.createMessage(``); // Stuck at this point.
我尝试过此方法,但未定义文本文件内容。
{message.channel.createMessage(open("./stations.txt").readlines());
所以命令是!它应该从txt文件中返回站点列表。
const Eris = require('eris');
const client = new Eris(require('./config.json').token, {
maxShards: 1
});
fs = require('fs')
var stations = fs.readFileSync("./stations.txt", {
"encoding": "utf-8"
});
client.connect();
client.on('ready', () => {
console.log('Ready to go!')
})
client.on('messageCreate', message => {
if (message.author.bot) return;
if (message.content.startsWith('!')) {
let command = message.content.substring(1).split(" ")[0];
let args = message.content.substring(2 + command.length);
if (command == 'stations') {
message.channel.createMessage(`STUCK AT THIS POINT`);
} else if (command == 'radio') {
if (args == '')
return message.channel.createMessage(`Please specify the radio station example: **!radio <station name>**`);
if (require('./stations.json')[args]) {
if (!message.member.voiceState)
return message.channel.createMessage(`:warning: **You need to be in a voice channel.**`);
client.joinVoiceChannel(message.member.voiceState.channelID).then(vc => {
if (vc.playing)
vc.stopPlaying();
message.channel.createMessage(`:radio: You are now streaming **${args}**.`);
vc.play(require('./stations.json')[args]);
})
} else {
return message.channel.createMessage(`**Cannot find a radio station with that name.** Make sure it has capitals and the correct spelling. See pinned messages for stream list.`);
}
}
}
})
我们将不胜感激。
答案 0 :(得分:-1)
将文本文件读入node.js中的变量的最简单方法是
fs.readFileSync(path, options).toString()
您已在代码顶部的代码中分配stations
变量,只需添加.toString()
调用(最后添加进一步的文字处理,例如.replace(/\n/g, ', ')
以替换换行符使用逗号)并在需要时使用stations
变量。您可以使用try / catch检查读取文件时是否有错误。