javascriptdiscorddiscord.js

how to send 2 messages by splitting 1 message which is more than 4096 characters in discord.js


if (lyrics.length > 4095)
        return message.channel.send('Lyrics are too long to be returned as embed');
      if (lyrics.length < 2048) {
        const lyricsEmbed = new MessageEmbed()
          .setColor('GREEN')
          .setDescription(lyrics.trim());
        return sentMessage.edit(`Lyrics for ${songName}`, lyricsEmbed);
      } else {
        // lyrics.length > 2048
        const firstLyricsEmbed = new MessageEmbed()
          .setColor('GREEN')
          .setDescription(lyrics.slice(0, 2048));
        const secondLyricsEmbed = new MessageEmbed()
          .setColor('')
          .setDescription(lyrics.slice(2048, lyrics.length));
        sentMessage.edit(`Lyrics for ${songName}`, firstLyricsEmbed);
        message.channel.send(secondLyricsEmbed);
        return;
      }

how can i send lyrics of a song which is more than 4096 characters im thinking of sending it in two messages or by doing the reaction thing. can anybody help. it is at

if(lyrics.length > 4096) return message.channel.send('bla bla bla)


Solution

  • The send methods accepts various options, see Here. One of the options it accepts is split:

    Whether or not the message should be split into multiple messages if it exceeds the character limit. If an object is provided, these are the options for splitting the message
    

    There are multiple options for split as well (see the documentation), the easiest would be to set it to true

    message.channel.send(lyrics, { split: true })
    

    Edit: I just noticed you are trying to split plain text inside a embed, in this case you can use Util.splitMessage

    const { Util, MessageEmbed } = require("discord.js")
    
    // Returns an array of strings
    const [first, ...rest] = Util.splitMessage(lyrics, { maxLength: 4096 })
    
    // Set base options for embed, initially it has the first 4096 characters of the lyrics
    const embed = new MessageEmbed()
      .setColor("BLUE")
      .setDescription(first)
    
    // Max characters were not reached so there is no "rest" in the array
    if (!rest.length) {
      // Send just the embed with the first element from the array
      return message.channel.send(embed)
    }
    
    // Get the other parts of the array with max char count
    for (const text of rest) {
      // Add new description to the base embed
      embed.setDescription(text)
    
      await message.channel.send(embed)
    }