Home > database >  Discordbot read DM messages and log them
Discordbot read DM messages and log them

Time:10-20

I want my bot to read DM messages only and send them to a discord channel, but my code spam the message infinitely, spamming 5 times and then it pauses for a few seconds then spam again, also the bot don't read only DM messages and reads also guild messages so if I send anything in the guild it spams the content.

What do I want? If someone sends 'Hello!' (message content) to the bot in DM, the bot needs to send 'Hello!' (message content) to the specified channel (logs channel).

const Discord = require("discord.js");  
const client = new Discord.Client({ intents:['DIRECT_MESSAGES'],
partials: ['MESSAGE'] });


client.on('ready', () =>{
    console.log('Bot Online!'); //bot successfully logged in

});


  client.on('message', async (message) => {
    await client.channels.cache.get('CHANNEL ID').send(message.content);
    console.log(message.content); //log messages
    return;
});
// Authorizing
client.login('LOGIN');

CodePudding user response:

Checking if the message comes from a guild should stop this. Return early if message.guild is truthy (in DM message.guild is null which is a falsey value)

if (message.guild) return;

You would put this at the top of the event callback so that nothing runs if it's in a guild

CodePudding user response:

The thing is that when the bot sends the message to the log channel. It also triggers the message event again. To avoid this simply add

if(message.author.bot) return;

You code would look like

  client.on('message', async (message) => {
    if(message.author.bot) return;
    await client.channels.cache.get('CHANNEL ID').send(message.content);
    console.log(message.content); //log messages
    return;
});

If you only want to get direct messages

You can use

if(message.guild) return;
  client.on('message', async (message) => {
    if(message.guild) return;
    await client.channels.cache.get('CHANNEL ID').send(message.content);
    console.log(message.content); //log messages
    return;
});
  • Related