如何从消息创建参数

How to create arguments from a message

我正在尝试为我的 discord 服务器制作一个音乐机器人,我已将其设置为播放音乐,但我不知道如何让它播放用户输入的 link

client.on("message", message => {
  if (message.content.startsWith("^play")) {
    let channel = client.channels.get('496722898858278912');
    const ytdl = require('ytdl-core');
    const streamOptions = {
      seek: 0,
      volume: 1
    };
    const broadcast = client.createVoiceBroadcast();

    channel.join()
      .then(connection => {
        const stream = ytdl(('https://www.youtube.com/watch?v=XAWgeLF9EVQ'), {filter: 'audioonly'});
        broadcast.playStream(stream);
        const dispatcher = connection.playBroadcast(broadcast);
      });
  }
});

代码中的 link 将替换为用户提交的 link。

要创建参数,您可以使用 ' ' 作为分隔符来拆分消息的内容,参数是该数组的元素,除了第一个(即命令):

// message.content: "^play https://youtube.com/blablabla other arguments"
let args = message.content.split(' '); // ["^play", "https://youtube.com/blablabla", "other", "arguments"]: the string got splitted into different parts
args.shift(); // remove the first element (the command)
// you can do all your stuff, when you need the link you find it in args[0]
const stream = ytdl((args[0]), { filter : 'audioonly' });

请注意,第一个参数未被授予有效的 youtube link,因此请检查它或准备您的代码来处理无效参数。