Search code examples
javascriptdiscorddiscord.jsbotsembed

How can I embed messages using a Discord bot?


I want to code a bot that will embed a user's sent message in a specific channel. If you know anything about GTA RP servers, it's like a Twitter or Instagram bot.

Here's an example:

screenshot of example embeds

I think it's something about the console.log and the author's name, but I'm not sure so that's why I'm here. How can I embed users' messages like this?


Solution

  • You can use a MessageEmbed, like programmerRaj said, or use the embed property in MessageOptions:

    const {MessageEmbed} = require('discord.js')
    
    const embed = new MessageEmbed()
      .setTitle('some title')
      .setDescription('some description')
      .setImage('image url')
    
    // Discord.js v13
    // These two are the same thing
    channel.send({embeds: [embed]})
    channel.send({
      embeds: [{
        title: 'some title',
        description: 'some description',
        image: {url: 'image url'}
      }]
    })
    
    // Discord.js v12
    // These two are the same thing
    channel.send(embed)
    channel.send({
      embed: {
        title: 'some title',
        description: 'some description',
        image: {url: 'image url'}
      }
    })
    

    To send an embed of users' message in a particular channel, you can do something like this, where client is your Discord.js Client:

    // The channel that you want to send the messages to
    const channel = client.channels.cache.get('channel id')
    
    client.on('message',message => {
      // Ignore bots
      if (message.author.bot) return
      // Send the embed
      const embed = new MessageEmbed()
        .setDescription(message.content)
        .setAuthor(message.author.tag, message.author.displayAvatarURL())
      channel.send({embeds: [embed]}).catch(console.error)
      // Discord.js v12:
      // channel.send(embed).catch(console.error)
    })
    

    Note that the above code will send the embed for every message not sent by a bot, so you will probably want to modify it so that it only sends it when you want it to.

    I recommend reading Discord.js' guide on embeds (archive) or the documentation linked above for more information on how to use embeds.