Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event messageCreate not firing/emitting when I send a DM to my bot (discord.js v13)

I made this code for logging the DMs that are sent to my bot:

client.on('messageCreate', async message => {

    if (message.author.bot) return;

    const attachment = message.attachments.first()

    if (message.channel.type === 'DM') {
        console.log(message.content)

        const dmLogEmbed = new MessageEmbed()
            .setColor("RANDOM")
            .setTitle(`${message.author.tag} dmed the bot and said: `)
            .setDescription(message.content)
            .setFooter(`User's id: ${message.author.id}`)

        if (message.attachments.size !== 0) {
            dmLogEmbed.setImage(attachment.url)

        }

        client.channels.fetch("852220016249798756").then((channel) => {

            channel.send({ embeds: [dmLogEmbed] })

        })
    }

});

But when updating to discord.js v13 it didn't work anymore, for what I understood the only change is that the 'dm' channel type isn't 'dm' anymore but 'DM', so I changed it in my code, but it is still not working and I don't really know why.

like image 894
tom.js Avatar asked Nov 29 '22 05:11

tom.js


1 Answers

Make sure you have DIRECT_MESSAGES in your client's intents.

const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES", "DIRECT_MESSAGES"] });

There is a breaking change in the Discord API v8. For reference see here.

On Discord API v8 and later, DM Channels do not emit the CHANNEL_CREATE event, which means discord.js is unable to cache them automatically. In order for your bot to receive DMs, the CHANNEL partial must be enabled.

So we need to enable the partial CHANNEL as well. Keep in mind that when dealing with partial data, you often want to fetch the data, because it is not complete. However this doesn't seem to be your case, if you are using the messageCreate event. The message received is not partial nor message.channel. To check if something is partial, you can use the .partial property. For example Message.partial or Channel.partial.

const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES", "DIRECT_MESSAGES"], partials: ["CHANNEL"] });

Now it should work as good old discord.js v12.

like image 147
Skulaurun Mrusal Avatar answered Dec 06 '22 11:12

Skulaurun Mrusal