【发布时间】:2019-06-18 01:10:00
【问题描述】:
我最近一直在制作我的第一个不和谐机器人,今天我遇到了一个小要求的问题。 我需要我的机器人连接到服务器的所有语音通道并播放 mp3 文件。这是一条警报消息。
我首先用这个代码做了一个基本的测试,在启动命令的用户连接的频道中播放 mp3:
exports.run = async (client, message, args, level) => {
if (message.member.voiceChannel) {
message.member.voiceChannel.join()
.then(connection => {
const dispatcher = connection.playFile('/home/pi/.discordbots/TARVIS/1.mp3');
dispatcher.on("end", end => {message.member.voiceChannel.leave()});
})
.catch(console.error);
}
};
上面的代码运行良好
所以我尝试为所有语音频道制作它:
let voiceChannels = message.guild.channels.filter(channel => channel.type == 'voice');
voiceChannels.forEach(channel =>
channel.join()
.then(connection => {
const dispatcher = connection.playFile('/home/pi/.discordbots/TARVIS/1.mp3');
dispatcher.on("end", end => { channel.leave() });
})
.catch(console.error)
);
问题是机器人连接到第一个通道,然后直接连接到第二个,而没有时间播放第一个通道中的文件。
我想我必须看看client.createVoiceBroadcast(); 方法。我尝试使用它,但找不到一个很好的例子。这是我尝试过的,但它也不起作用:
exports.run = (client, message, args, level) => {
let voiceChannels = message.guild.channels.filter(channel => channel.type == 'voice');
const broadcast = client.createVoiceBroadcast();
broadcast.playFile('/home/pi/.discordbots/TARVIS/1.mp3');
voiceChannels.forEach(channel =>
channel.join()
.then(connection => {
const dispatcher = connection.playBroadcast(broadcast);
dispatcher.on("end", end => { channel.leave() });
})
.catch(console.error)
);
预期的结果是机器人在每个语音通道中一个接一个地连接并播放 mp3 文件。
提前感谢您的帮助
编辑
我尝试创建一个异步函数并在 connection.playFile() 上使用 await,但我仍然遇到同样的问题。 Bot 连接到所有语音通道,但不等待文件播放。
这是我试过的代码:
exports.run = async (client, message, args, level) => {
async function play(voiceChannel) {
console.log(voiceChannel.name + ` Type:` + voiceChannel.type + ` (` + voiceChannel.id + `)`);
voiceChannel.join().then(async function (connection) {
dispatcher = await connection.playFile('/home/pi/.discordbots/TARVIS/sncf.mp3');
dispatcher.on('end', function () {
voiceChannel.leave()
});
});
}
let voiceChannels = message.guild.channels.filter(channel => channel.type == 'voice');
voiceChannels.map(vc => play(vc));
};
我很确定解决方案就在附近……但我被困住了……有人可以帮我找到正确的语法吗?
编辑 2
这是我对您的解决方案的尝试:
exports.run = async (client, message, args, level) => {
async function play(voiceChannels) {
for (let channel of voiceChannels) {
console.log('Joining channel ' + channel.name);
await channel.join().then(async (connection) => {
console.log('Joined channel');
let dispatcher = connection.playFile('/home/pi/.discordbots/TARVIS/sncf.mp3');
await dispatcher.on('end', function () {
channel.leave();
});
});
}
}
let channels = message.guild.channels.filter(channel => channel.type == 'voice');
console.log(channels);
play(channels);
};
【问题讨论】:
-
也许this answer 可能有助于检查
-
谢谢@T.Dirks 我看了看,是的,我认为它与 async/await 有关,但找不到正确的语法。我会尝试用这个答案来调整我的代码
-
我仍在努力让它工作我看到p-iteration 可能会帮助我。我会试试看,但我很想知道如何在本机中做到这一点
标签: javascript bots discord discord.js