检查图像是否存在到.setImage In Embed

问题描述 投票:0回答:1

我正在尝试做一个“推文”系统。我检查链接是否正确并且有图像,但如果您输入类似

https://askhdkjahs.png
的内容,程序会认为是图像并放入嵌入中,从而出现错误。

我需要处理错误并放置默认图像或回复说“图像给出错误”。

这是我的代码:

if (comando === `${prefix}atwt`) {
    msg.delete({ timeout: 100 });
    if (!argumento[0]) {
        msg.reply('pon algo').then(msg => {
            msg.delete({ timeout: 10000 });
        }).catch(console.error);
    }
    else if(argumento !== null && argumento !== '') {
        const TweetAnon = new Discord.MessageEmbed()
            .setAuthor('Anonimo!', 'https://i.imgur.com/wSTFkRM.png')
            .setColor('BLUE')
            .setTimestamp();
        const url = argumento[0].toString();
        if (url.match(/^https.*\.(png|jpeg|jpg|gif|bmp)$/i)) {
            TweetAnon.setImage(argumento[0]);
            TweetAnon.setDescription(`**${argumento.slice(1).join(' ')}**`);
        }
        else{
            TweetAnon.setDescription(`**${argumento.join(' ')}**`);
        }
        const msgEmbed = await msg.channel.send(TweetAnon).catch(TweetAnon.setImage('https://i.imgur.com/wSTFkRM.png'));
        await msgEmbed.react('👍');
        await msgEmbed.react('👎');
        await msgEmbed.react('🔄');
    }
}

我看到类似的东西,我尝试过但不起作用

if (comando === `${prefix}atwt`) {
    const url = argumento[0].toString();
    const TweetAnon = new Discord.MessageEmbed()
        .setAuthor('Anonimo!', 'https://cdn.discordapp.com/attachments/769965806850670634/854834517709422602/anon.png')
        .setColor('BLUE')
        .setTimestamp();
    msg.delete({ timeout: 100 });
    try {
        if (!url.match(/^https.*\.(png|jpeg|jpg|gif|bmp)$/i)) {
            throw new Error('Invalid URL');
        }
        TweetAnon.setImage(argumento[0]);
        TweetAnon.setDescription(`**${argumento.slice(1).join(' ')}**`);
    }
    catch (error) {
        TweetAnon.setImage('https://i.imgur.com/wSTFkRM.png');
    }
    // else
    //     TweetAnon.setDescription(`**${argumento.join(' ')}**`);
    // }
    const msgEmbed = await msg.channel.send(TweetAnon).catch(err => console.log(err));
    await msgEmbed.react('👍');
    await msgEmbed.react('👎');
    await msgEmbed.react('🔄');
}
discord discord.js
1个回答
0
投票

您可以像这样检查图像是否存在:

function imageExists(image_url){

    var http = new XMLHttpRequest();

    http.open('HEAD', image_url, false);
    http.send();

    return http.status != 404;

}

用途:

if(imageExists(argumento[0])){
    TweetAnon.setImage(argumento[0]);
}
© www.soinside.com 2019 - 2024. All rights reserved.