【发布时间】:2021-02-22 13:31:55
【问题描述】:
我正在使用 Discord.JS 编写一个 Discord 机器人,并且对它相当陌生。 (从今年夏天开始)
我有一个无线电机器人供我和我的朋友使用,我让它加入频道并从 JSON 读取并正常播放音乐。
我想要它做的是,我可以通过命令添加到stations.json 文件,然后一切都会从那里更新。
这是stations.json:
{
"b101":
{
"command":"b101",
"link":"https://playerservices.streamtheworld.com/api/livestream-redirect/WBEBFMAAC.aac",
"name":"Philly's B101"
},
}
这是每个站的格式
这里是play.js:
module.exports = {
name: "music!play",
description: "Find a music stream and play it",
execute(msg, args, client) {
function validURL(str) {
var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name
'((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
'(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
'(\\#[-a-z\\d_]*)?$','i'); // fragment locator
return !!pattern.test(str);
}
if (args.length === 0)
return msg.reply('supply a station please');
if (msg.member.voice.channel) {
let stationsJson = require('./stations.json');
const isStation = stationsJson.hasOwnProperty(args[0])
if (isStation) {
const station = args[0]
msg.member.voice.channel.join()
.then(connection => {
const link = stationsJson[station].link
const title = stationsJson[station].name
msg.reply(`Connected! Playing ${title}`)
connection.play(link);
});
} else {
// this is just manual link input here
}
} else {
msg.reply('You are not in a voice channel!');
}
}
}
最后,这里是add.js。添加电台的命令。
const fs = require('fs')
var command = args[0]
var link = args[1]
var name = args.slice(2,20).join(" ")
fs.readFile('./commands/stations.json', function (err, data) {
if (err) throw err
var json = JSON.parse(data)
json.stations.push(
{
"${command}": {
"command": command,
"link": link,
"name": name
}
});
json = JSON.stringify(json);
fs.writeFile('./commands/stations.json', json, 'utf8', function (err) {
if (err) throw err
});
这是我迄今为止尝试过的,但我必须将它放在一个数组中,当我尝试从 play.js 播放时这不起作用。
感谢您的帮助!
【问题讨论】:
-
在你的 add 函数中,当你推送到数组时,你用引号写了这个 "${command}",如果你希望你的变量被附加到你应该替换的字符串中,这将不起作用${command}" by `${command}` 无论如何这在您的情况下不是必需的,因为您的字符串仅包含命令名称,因此您可以只写变量的名称
-
当您发布问题时,请尝试添加更简洁的代码。删除代码中所有不必要的部分,以便每个想要提供帮助的人都可以专注于重要部分。例如,您不需要在 .json 文件中添加所有内容。您可以删除所有验证码等,因为它们与您的问题无关。
-
好的,谢谢!问这些问题我有点陌生。我现在就修复它
标签: javascript node.js json discord discord.js