【问题标题】:How to check if embed image has a valid/working link?如何检查嵌入图像是否具有有效/工作链接?
【发布时间】:2020-10-31 01:49:43
【问题描述】:

我要做的是将嵌入的图像设置为args[0] 的值,如果它不起作用,则将嵌入的图像设置为默认的工作链接。

我有这个代码:

const exampleEmbed = new Discord.MessageEmbed();
exampleEmbed.addField('Its a title!', 'Its a value!');
try {
    exampleEmbed.setImage(args[0]);
}
catch (error) { 
    exampleEmbed.setImage('https://i.imgur.com/wSTFkRM.png');
};
message.channel.send(exampleEmbed);
 

问题是,当 args[0] 不是有效的 url 时(例如,'https://' 或 'https://.com' 之类的东西),try 块仍将成功执行,并且catch不会被执行。 但是,由于链接无效,当我想发送我的嵌入时,我会收到以下错误消息:

(node:19196) UnhandledPromiseRejectionWarning: DiscordAPIError: Invalid Form Body embed.image.url: Not a well formed URL.

【问题讨论】:

    标签: javascript node.js discord discord.js


    【解决方案1】:

    您可以使用正则表达式匹配器检查 args[0] 内容,如果它与 URI 模式不匹配,您可能会抛出错误。

    const exampleEmbed = new Discord.MessageEmbed();
    exampleEmbed.addField('Its a title!', 'Its a value!');
    try {
    
        if (!(/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g).test(args[0])) {
            throw new Error(`Invalid URL`);
        }
        exampleEmbed.setImage(args[0]);
    }
    catch (error) { 
        exampleEmbed.setImage('https://i.imgur.com/wSTFkRM.png');
    };
    message.channel.send(exampleEmbed);
    

    【讨论】:

    • 不确定这是否是最干净的方式,但可以肯定它可以通过https://sometexthere/ 之类的链接解决我的问题,谢谢 :)
    【解决方案2】:

    使用URL 类验证args[0]

    const exampleEmbed = new Discord.MessageEmbed();
    exampleEmbed.addField('Its a title!', 'Its a value!');
    
    let url = validateURL(args[0]);
    
    if (url) {
      exampleEmbed.setImage(url);
    } else {
      exampleEmbed.setImage('https://i.imgur.com/wSTFkRM.png');
    }
    
    message.channel.send(exampleEmbed);
    
    
    function validateURL(url) {
      try {
        return (new URL(url)).toString();
      } catch (e) {
        console.error(e);
        return null;
      }
    }
    

    【讨论】:

    • 问题是,当args[0] 只是类似于https://sometexthere 时,程序仍然会说它是一个有效的url,但是嵌入说它不是并且嵌入不会被发送到频道。
    猜你喜欢
    • 2014-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    • 2014-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多