Created
June 27, 2022 14:47
-
-
Save lazuee/4b969e2c8556eda600aced2720f14e30 to your computer and use it in GitHub Desktop.
discord split message
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Discord = require("discord.js"); | |
const splitMessage = (text, { maxLength = 2_000, char = "\n", prepend = "", append = "" } = {}) => { | |
text = Discord.Util.verifyString(text); | |
if (text.length <= maxLength) return [text]; | |
let splitText = [text]; | |
if (Array.isArray(char)) { | |
while (char.length > 0 && splitText.some((elem) => elem.length > maxLength)) { | |
const currentChar = char.shift(); | |
if (currentChar instanceof RegExp) splitText = splitText.flatMap((chunk) => chunk.match(currentChar)); | |
else splitText = splitText.flatMap((chunk) => chunk.split(currentChar)); | |
} | |
} else splitText = text.split(char); | |
if (splitText.some((elem) => elem.length > maxLength)) throw new RangeError("SPLIT_MAX_LEN"); | |
const messages = []; | |
let msg = ""; | |
for (const chunk of splitText) { | |
if (msg && (msg + char + chunk + append).length > maxLength) { | |
messages.push(msg + append); | |
msg = prepend; | |
} | |
msg += (msg && msg !== prepend ? char : "") + chunk; | |
} | |
return messages.concat(msg).filter((m) => m); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment