UNPKG

discordcaptcha

Version:

Add a captcha verification to your Discord bot

80 lines (68 loc) 3.34 kB
const { Client } = require('discord.js'); const captchapng = require('captchapng'); class DiscordCaptcha { /** * Create an instance of DiscordCaptcha * @class * @param {Client} client The client you want to install the captcha on */ constructor(client) { this.client = client; this.guilds = {}; // Triggered when a user joins a guild client.on("guildMemberAdd", async (member) => { // Check if the guild uses captcha verification, or if the member is a bot if (!this.guilds[member.guild.id] || member.user.bot) return; // Create the captcha image var code = parseInt(Math.random() * 9000 + 1000); let img_data = new captchapng(80, 30, code); img_data.color(100, 80, 255, 255); let img = new Buffer(img_data.getBase64(), "base64"); member.send({ embed: { title: 'Captcha Verification (Powered by DiscordCaptcha)', // Please don't modify this line to support us url: 'https://www.npmjs.com/package/discordcaptcha', // Same with this one description: this.guilds[member.guild.id].welcome_message = '' ? `Welcome on ${member.guild.name} ! Please verify this captcha to make sure you aren't a bot. You have 2 minutes.` : this.guilds[member.guild.id].welcome_message, }, file: img }).then(async (message) => { let channel = message.channel; let filter = m => m.content === code.toString(); channel.awaitMessages(filter, { max: 1, time: 120000, errors: [ 'time' ] }).then((collected) => { member.send('Congratulations ! You are allowed to access the server'); member.addRole(this.guilds[member.guild.id].role); }).catch((collected) => { member.send('Verification failed. You have to leave the server to pass the test again.'); }); }); }); } /** * @function init * @description Add a guild to the captcha manager * @param {String} guild_id The guild's id * @param {String} member_role The role's id to assign when captcha test is completed * @param {?String} welcome_message The message to send when a user joins the guild */ init(guild_id, member_role, welcome_message = '') { if (this.guilds[guild_id]) return; // Check if the client is in the guild let guild = this.client.guilds.get(guild_id); if (!guild) throw new Error(`Attempt to init captcha manager on ${guild_id}, but the client isn't in this guild.`); // Check if the role exists let role = guild.roles.get(member_role); if (!role) throw new Error(`Attempt to init captcha manager on ${guild_id}, but the role ${member_role} doesn't exist.`); this.guilds[guild_id] = { guild: guild, role: role, welcome_message: welcome_message || '' }; } } module.exports.manager = DiscordCaptcha;