discord.js-x-captcha
Version:
A powerful package for Discord.js v14 that allows you to easily create CAPTCHAs for Discord Servers.
131 lines (120 loc) • 3.18 kB
JavaScript
const shuffle = (arr) => {
let i = arr.length;
while (i) {
let j = Math.floor(Math.random() * i--);
[arr[j], arr[i]] = [arr[i], arr[j]];
}
return arr;
};
/**
* @typedef {Object} CaptchaImageData
* @prop {Buffer} image The CAPTCHA Image.
* @prop {String} text The Answer to the CAPTCHA.
*/
/**
* Asynchronously Generates a CAPTCHA.
* @param {Number} [length=6] The Text Length of the CAPTCHA. Defaults to 6.
* @param {String} [blacklist=""] A List of Characters to Exclude from the CAPTCHA.
* @returns {CaptchaImageData} The CAPTCHA Image Data.
*/
module.exports = async function createCaptcha(length = 6, blacklist = "") {
const {
CaptchaGenerator
} = require('captcha-canvas')
let chars = [
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
"q",
"r",
"s",
"t",
"u",
"v",
"w",
"x",
"y",
"z",
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Y",
"Z",
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9"
];
if (Number.isNaN(length)) throw new Error("Discord.js Captcha Generation Error: Length must be a Number.");
if (length < 1) throw new Error("Discord.js Captcha Generation Error: The CAPTCHA Length must be at least 1 character.\nNeed Help? Join our Discord Server at 'https://discord.gg/P2g24jp'");
// Validate blacklist param
if (typeof blacklist !== "string") throw new Error("Discord.js Captcha Generation Error: The blacklist parameter must be a string.\nNeed Help? Join our Discord Server at 'https://discord.gg/P2g24jp'");
if (blacklist.match(/[^a-zA-Z0-9]/)) throw new Error("Discord.js Captcha Generation Error: The blacklist parameter must only contain alphanumeric characters.\nNeed Help? Join our Discord Server at 'https://discord.gg/P2g24jp'");
// Remove blacklisted characters from the character list
chars.splice(0, chars.length, ...chars.filter(c => !blacklist.includes(c)));
chars = shuffle(chars);
function generateCaptcha(charset, length) {
var retVal = "";
for (let i = 0; i < length; i++) retVal += charset[Math.floor(Math.random() * charset.length)];
return retVal;
}
const genCaptcha = generateCaptcha(chars, length)
const captcha = new CaptchaGenerator()
.setDimension(150, 450)
.setCaptcha({
text: genCaptcha,
size: 60,
color: "deeppink"
})
.setDecoy({
opacity: 1
})
.setTrace({
color: "deeppink"
})
const buffer = captcha.generateSync()
return {
image: buffer,
text: genCaptcha
};
}