Search code examples
discorddiscord.jsbotsembed

How to prevent Discord bot copying and paste GIFs and images from a channel to another ? (discord.js)


I'm trying to code a bot able to copy the messages which specifically include URLs and attachments (.pdf, .docx, etc...) from a channel to another.

But, I'd also like it to ignore the messages containing GIFs and images. I tried to use message.embeds[0].type === and the console displays TypeError: Cannot read property 'type' of undefined.

Here is the whole code :

const Discord = require('discord.js');
const bot = new Discord.Client();

bot.login('TOKEN')
bot.on('ready', () => {
    console.log('The Librarian is online');
});

bot.on('message', message => {
    if (message.author.bot || message.embeds[0].type === 'gifv' || message.embeds[0].type === 'image') return;

    if (message.channel.id === 'channel1-ID' && (message.content.includes("http") || message.attachments.size >0)) {

        let ressourcesChannel = bot.channels.cache.get('channel2-ID');

        if (ressourcesChannel) {
            let embed = new Discord.MessageEmbed()
              .setAuthor(`${message.author.tag} nous transmet un peu de sa connaissance` , message.author.displayAvatarURL())
              .setColor('#FFAB32');

        ressourcesChannel.send(embed);
        ressourcesChannel.send(message.content , {files: message.attachments.array() })
            .then(message2 => {
             message.react('📖'); 
                })
            .then(() => console.log('Document filed : ' + message.content))
            .catch(console.error);
        }
    }
})

Could you please, point out what could be wrong in this code?


Solution

  • Your code will fail if the message doesn't have an embed at all.
    If you use NodeJS ≥ v14.0.0 you can use optional chaining:

    if (
        message.author.bot
        || message.embeds[0]?.type === 'gifv'
        || message.embeds[0]?.type === 'image'
    ) return;
    

    otherwise, check if there is an embed first:

    if (
        message.author.bot
        || message.embeds
        && (message.embeds[0].type === 'gifv' || message.embeds[0].type === 'image')
    ) return;