【问题标题】:discord.js bot youtube linkdiscord.js 机器人 youtube 链接
【发布时间】:2021-10-23 22:26:40
【问题描述】:

我正在 discord.js(v12 版本)中创建一个不和谐机器人,我想在其中包含一个音乐命令,但是当我在 中输入指向 YouTube 视频的链接时,它会引发错误:

UnhandledPromiseRejectionWarning:错误:未找到视频 ID:未定义

我想补充一点,当我写一个没有 的链接时,一切正常。

我的代码:

if (message.content.startsWith(`${prefix}play`)) {
    const voiceChannel = message.member.voice.channel;
    if (!voiceChannel) return message.channel.send("Musisz być na kanale głosowym!");
    const permissions = voiceChannel.permissionsFor(message.client.user);
    if (!permissions.has(`CONNECT`)) return message.channel.send("Nie mam potrzebnych permisji by wejść na kanał głosowy!");
    if (!permissions.has(`SPEAK`)) return message.channel.send("Nie mam potrzebnych permisji by wejść na kanał głosowy!");

    const songInfo = await ytdl.getInfo(args[1]);
    const song = {
        title: songInfo.videoDetails.title,
        url: songInfo.videoDetails.video_url,
    };
}

【问题讨论】:

    标签: javascript node.js discord discord.js bots


    【解决方案1】:

    错误

    “UnhandledPromiseRejectionWarning:错误:未找到视频 ID: 未定义”

    只是因为 ytdl 找不到提供链接的歌曲

    不过,这有一个简单的解决方法。

    Ytdl自带函数ytdl.validateURL("song link"),它会确保提供了一个有效的链接,如果是则返回true,如果是无效的歌曲链接则返回false

    我们可以将这三行添加到代码中:

    // If the validateURL returns as false, which means it is not a valid link
    if (!ytdl.validateURL(args[1])) {
        // Return asking the user to send a valid link
        return message.channel.send("Please send a valid song link");
    }
    

    最终代码如下所示:

    if (message.content.startsWith(`${prefix}play`)) {
        const voiceChannel = message.member.voice.channel;
        if (!voiceChannel) return message.channel.send("Musisz być na kanale głosowym!");
        const permissions = voiceChannel.permissionsFor(message.client.user);
        if (!permissions.has(`CONNECT`)) return message.channel.send("Nie mam potrzebnych permisji by wejść na kanał głosowy!");
        if (!permissions.has(`SPEAK`)) return message.channel.send("Nie mam potrzebnych permisji by wejść na kanał głosowy!");
    
        if (!ytdl.validateURL(args[1])) {
            return message.channel.send("Please send a valid song link");
        }
    
        const songInfo = await ytdl.getInfo(args[1]);
        const song = {
            title: songInfo.videoDetails.title,
            url: songInfo.videoDetails.video_url,
        };
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-26
      • 2021-07-01
      • 2018-01-29
      • 2020-08-21
      • 2022-01-07
      • 2020-10-03
      • 2022-06-25
      • 2022-12-23
      相关资源
      最近更新 更多