├── .gitignore
├── LICENSE
├── README.md
├── jsconfig.json
├── package-lock.json
├── package.json
└── src
├── Captcha.js
├── createCaptcha.js
├── handleChannelType.js
├── images
└── captchaExample.jpg
└── index.js
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | 🎓 Discord.js Captcha 🎓
3 |
4 |
5 | A powerful package for Discord.js v14 that allows you to easily create CAPTCHAs for Discord Servers.
6 |
7 | [](https://npmjs.com/package/discord.js-captcha)
8 |
9 | [](https://npmjs.com/package/discord.js-captcha) [](https://diamonddigital.dev/discord)
10 |
11 |
12 |
13 | Creating a CAPTCHA system on Discord can be quite challenging for some, but it doesn't have to be that way. Discord.js Captcha handles everything for you, from CAPTCHA generation and sending, to handling user responses and validity.
14 |
15 | ### What is a **CAPTCHA**?
16 |
17 | Put simply, a **CAPTCHA** is a question you have to answer to prove you are not a robot.
18 |
19 | **CAPTCHA** is an acronym for:
20 |
21 | **C**ompletely
22 |
23 | **A**utomated
24 |
25 | **P**ublic
26 |
27 | **T**uring Test (to tell)
28 |
29 | **C**omputers (and humans)
30 |
31 | **A**part
32 |
33 | To learn more about what a CAPTCHA is, you can [watch this video](https://www.youtube.com/watch?v=o1zNIm8GVPY&ab_channel=TomScott) by Tom Scott.
34 |
35 | # Install Package
36 |
37 | To install this awesome module, type the command shown below into your Terminal.
38 |
39 | `npm i discord.js-captcha --save`
40 |
41 | For versions 3.0.0 and above, you'll also need Discord.js v14.
42 |
43 | `npm i discord.js@14 --save`
44 |
45 | For versions **earlier than 3.0.0**, you'll need Discord.js v13 instead. However it is recommended you update to gain access to more customisation options, as well as to patch bugs and security vulnerabilities!
46 |
47 | `npm i discord.js@13 --save`
48 |
49 | # Example Code
50 |
51 | ## Initial Setup:
52 |
53 | ```js
54 | const { Client, IntentsBitField, EmbedBuilder } = require("discord.js");
55 | const client = new Client({
56 | intents: [
57 | IntentsBitField.Flags.Guilds,
58 | IntentsBitField.Flags.GuildMessages,
59 | IntentsBitField.Flags.MessageContent, //IMPORTANT: make sure you enable "Message Content Intent" in the dev portal!
60 | IntentsBitField.Flags.GuildMembers,
61 | IntentsBitField.Flags.DirectMessages,
62 | ]
63 | });
64 |
65 | client.login("Discord Bot Token");
66 |
67 | const { Captcha } = require("discord.js-captcha");
68 |
69 | const captcha = new Captcha(client, {
70 | roleID: "Role ID Here", //optional
71 | channelID: "Text Channel ID Here", //optional
72 | sendToTextChannel: false, //optional, defaults to false
73 | addRoleOnSuccess: true, //optional, defaults to true. whether you want the bot to add the role to the user if the captcha is solved
74 | kickOnFailure: true, //optional, defaults to true. whether you want the bot to kick the user if the captcha is failed
75 | caseSensitive: true, //optional, defaults to true. whether you want the captcha responses to be case-sensitive
76 | attempts: 3, //optional, defaults to 1. number of attempts before captcha is considered to be failed
77 | timeout: 30000, //optional, defaults to 60000. time the user has to solve the captcha on each attempt in milliseconds
78 | showAttemptCount: true, //optional, defaults to true. whether to show the number of attempts left in embed footer
79 | customPromptEmbed: new EmbedBuilder(), //customise the embed that will be sent to the user when the captcha is requested
80 | customSuccessEmbed: new EmbedBuilder(), //customise the embed that will be sent to the user when the captcha is solved
81 | customFailureEmbed: new EmbedBuilder(), //customise the embed that will be sent to the user when they fail to solve the captcha
82 | });
83 | ```
84 |
85 | ### **`channelID`** Option Explained
86 | The `channelID` option is the ID of the Discord Text Channel to Send the CAPTCHA to if the user's Direct Messages are locked.
87 |
88 | Use the option `sendToTextChannel`, and set it to `true` to always send the CAPTCHA to the Text Channel.
89 |
90 | ### **`sendToTextChannel`** Option Explained
91 | The `sendToTextChannel` option determines whether you want the CAPTCHA to be sent to a specified Text Channel instead of Direct Messages, regardless of whether the user's DMs are locked.
92 |
93 | Use the option `channelID` to specify the Text Channel.
94 |
95 | ## Presenting a CAPTCHA to a Member (With Built-In CAPTCHA Creation):
96 |
97 | Discord.js Captcha can automatically create a CAPTCHA for you, if you don't want to create one yourself.
98 |
99 | **Note:** Built-In CAPTCHA Creation requires you to install the `canvas` package. (`npm i canvas --save`)
100 |
101 | ```js
102 | client.on("guildMemberAdd", async member => {
103 | //in your bot application in the dev portal, make sure you have intents turned on!
104 | captcha.present(member); //captcha is created by the package, and sent to the member
105 | });
106 | ```
107 |
108 | ## Presenting a CAPTCHA to a Member (With Custom CAPTCHA Image Data):
109 |
110 | Don't like how the automatically created CAPTCHA looks? Simply pass in your own `CaptchaImageData` to the `present` method! You can also use Discord.js Captcha's Built-In CAPTCHA Creation to create your own CAPTCHA, and pass that in instead. (More on this [below](#manually-creating-a-captcha))
111 |
112 | ```js
113 | client.on("guildMemberAdd", async member => {
114 | //in your bot application in the dev portal, make sure you have intents turned on!
115 | const captchaImageBuffer = //custom image as buffer
116 | const captchaImageText = //answer to the captcha as string
117 | captcha.present(member, { image: captchaImageBuffer, text: captchaImageText });
118 | });
119 | ```
120 |
121 | **Note:** When displaying a CAPTCHA to the user, the CAPTCHA image will automatically be attached to the `customPromptEmbed` for you.
122 |
123 | In addition, if you have the `showAttemptCount` option enabled, any embed footer text on the `customPromptEmbed` will be overwritten with the number of attempts left.
124 |
125 | ## Manually Creating a CAPTCHA
126 |
127 | You can use the `createCaptcha` method to easily create your own CAPTCHA using Discord.js Captcha's Built-In CAPTCHA Creation. It also comes with broader control over the length of the CAPTCHA, and the characters you would like to use by using a blacklist.
128 |
129 | **Note:** Built-In CAPTCHA Creation uses `A-Z`, `a-z` and `0-9`.
130 |
131 | ```js
132 | const { createCaptcha } = require("discord.js-captcha");
133 |
134 | (async () => {
135 | //creating a CAPTCHA with 4 characters, and EXCLUDING numbers
136 | const myCaptcha = await createCaptcha(4, "0123456789");
137 | console.log(myCaptcha);
138 | // => { image: Buffer, text: "aBCd" }
139 |
140 | //createCaptcha resolves to an object that can be passed into the present method
141 | captcha.present(member, myCaptcha);
142 | })();
143 | ```
144 |
145 | # CAPTCHA Events
146 |
147 | There are five events that you can use to log CAPTCHA actions, responses, and other details. They are:
148 |
149 | - `prompt` - Emitted when a CAPTCHA is presented to a user.
150 | - `answer` - Emitted when a user responds to a CAPTCHA.
151 | - `success` - Emitted when a CAPTCHA is successfully solved.
152 | - `failure` - Emitted when a CAPTCHA is failed to be solved.
153 | - `timeout` - Emitted when a user does not solve the CAPTCHA in time.
154 |
155 | All of these events are emitted by the `Captcha` class. Here's an example of how to use them:
156 |
157 | ```js
158 | captcha.on("success", data => {
159 | console.log(`A Member has Solved a CAPTCHA!`);
160 | console.log(data);
161 | });
162 | ```
163 |
164 | # What do the CAPTCHAs look like?
165 | Below is an image of what answering a CAPTCHA will look like when using the default settings:
166 |
167 | 
168 |
169 | ## Contact Me
170 |
171 | - 👋 Need Help? [Join Our Discord Server](https://discord.gg/P2g24jp)!
172 |
173 | - 👾 Found a Bug? [Open an Issue](https://github.com/WillTDA/Discord.js-Captcha/issues), or Fork and [Submit a Pull Request](https://github.com/WillTDA/Discord.js-Captcha/pulls) on our [GitHub Repository](https://github.com/WillTDA/Discord.js-Captcha)!
174 |
175 |
176 | Created and maintained by
177 |
178 |
--------------------------------------------------------------------------------
/jsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "es6",
4 | "module": "commonjs"
5 | },
6 | "exclude": [
7 | "node_modules"
8 | ]
9 | }
--------------------------------------------------------------------------------
/package-lock.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "discord.js-captcha",
3 | "version": "3.0.8",
4 | "lockfileVersion": 2,
5 | "requires": true,
6 | "packages": {
7 | "": {
8 | "name": "discord.js-captcha",
9 | "version": "3.0.8",
10 | "license": "Apache-2.0"
11 | }
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "discord.js-captcha",
3 | "version": "3.0.8",
4 | "description": "A powerful package for Discord.js v14 that allows you to easily create CAPTCHAs for Discord Servers.",
5 | "main": "src/index.js",
6 | "funding": {
7 | "type": "buymeacoffee",
8 | "url": "https://www.buymeacoffee.com/willtda"
9 | },
10 | "scripts": {
11 | "test": "echo \"Error: no test specified\" && exit 1"
12 | },
13 | "repository": {
14 | "type": "git",
15 | "url": "https://github.com/WillTDA/Discord.js-Captcha"
16 | },
17 | "keywords": [
18 | "discord.js",
19 | "discord",
20 | "captcha",
21 | "discord.js-captcha",
22 | "discord.js captcha",
23 | "recaptcha",
24 | "turing",
25 | "test",
26 | "robot"
27 | ],
28 | "author": "WillTDA",
29 | "license": "Apache-2.0"
30 | }
31 |
--------------------------------------------------------------------------------
/src/Captcha.js:
--------------------------------------------------------------------------------
1 | const { Client, GuildMember, EmbedBuilder, ChannelType, version } = require("discord.js");
2 | const EventEmitter = require("events");
3 | const createCaptcha = require("./createCaptcha");
4 | const handleChannelType = require("./handleChannelType");
5 |
6 | /**
7 | * @typedef {Object} CaptchaImageData
8 | * @prop {Buffer} image The CAPTCHA Image.
9 | * @prop {String} text The Answer to the CAPTCHA.
10 | */
11 |
12 | /**
13 | * Captcha Options
14 | * @typedef {Object} CaptchaOptions
15 | * @prop {String} [roleID=undefined] (OPTIONAL): The ID of the Discord Role to Give when the CAPTCHA is complete.
16 | * @prop {String} [channelID=undefined] (OPTIONAL): The ID of the Discord Text Channel to Send the CAPTCHA to if the user's Direct Messages are locked. Use the option "sendToTextChannel", and set it to "true" to always send the CAPTCHA to the Text Channel.
17 | * @prop {Boolean} [sendToTextChannel=false] (OPTIONAL): Whether you want the CAPTCHA to be sent to a specified Text Channel instead of Direct Messages, regardless of whether the user's DMs are locked. Use the option "channelID" to specify the Text Channel.
18 | * @prop {Boolean} [addRoleOnSuccess=true] (OPTIONAL): Whether you want the Bot to Add the role to the User if the CAPTCHA is Solved Successfully.
19 | * @prop {Boolean} [kickOnFailure=true] (OPTIONAL): Whether you want the Bot to Kick the User if the CAPTCHA is Failed.
20 | * @prop {Boolean} [caseSensitive=true] (OPTIONAL): Whether you want the CAPTCHA to be case-sensitive.
21 | * @prop {Number} [attempts=1] (OPTIONAL): The Number of Attempts Given to Solve the CAPTCHA.
22 | * @prop {Number} [timeout=60000] (OPTIONAL): The Time in Milliseconds before the CAPTCHA expires and the User fails the CAPTCHA.
23 | * @prop {Boolean} [showAttemptCount=true] (OPTIONAL): Whether you want to show the Attempt Count in the CAPTCHA Prompt. (Displayed in Embed Footer)
24 | * @prop {EmbedBuilder} [customPromptEmbed=undefined] (OPTIONAL): Custom Discord Embed to be Shown for the CAPTCHA Prompt.
25 | * @prop {EmbedBuilder} [customSuccessEmbed=undefined] (OPTIONAL): Custom Discord Embed to be Shown for the CAPTCHA Success Message.
26 | * @prop {EmbedBuilder} [customFailureEmbed=undefined] (OPTIONAL): Custom Discord Embed to be Shown for the CAPTCHA Failure Message.
27 | *
28 | */
29 |
30 | class Captcha extends EventEmitter {
31 |
32 | /**
33 | * Creates a New Instance of the Captcha Class.
34 | *
35 | * __Captcha Options__
36 | *
37 | * - `roleID` - The ID of the Discord Role to Give when the CAPTCHA is complete.
38 | *
39 | * - `channelID` - The ID of the Discord Text Channel to Send the CAPTCHA to if the user's Direct Messages are locked.
40 | *
41 | * - `sendToTextChannel` - Whether you want the CAPTCHA to be sent to a specified Text Channel instead of Direct Messages, regardless of whether the user's DMs are locked.
42 | *
43 | * - `addRoleOnSuccess` - Whether you want the Bot to Add the role to the User if the CAPTCHA is Solved Successfully.
44 | *
45 | * - `kickOnFailure` - Whether you want the Bot to Kick the User if the CAPTCHA is Failed.
46 | *
47 | * - `caseSensitive` - Whether you want the the CAPTCHA to be case-sensitive.
48 | *
49 | * - `attempts` - The Number of Attempts Given to Solve the CAPTCHA.
50 | *
51 | * - `timeout` - The Time in Milliseconds before the CAPTCHA expires and the User fails the CAPTCHA.
52 | *
53 | * - `showAttemptCount` - Whether you want to show the Attempt Count in the CAPTCHA Prompt. (Displayed in Embed Footer)
54 | *
55 | * - `customPromptEmbed` - Custom Discord Embed to be Shown for the CAPTCHA Prompt.
56 | *
57 | * - `customSuccessEmbed` - Custom Discord Embed to be Shown for the CAPTCHA Success Message.
58 | *
59 | * - `customFailureEmbed` - Custom Discord Embed to be Shown for the CAPTCHA Failure Message.
60 | *
61 | * @param {CaptchaOptions} options The Options for the Captcha.
62 | * @param {Client} client The Discord Client.
63 | * @param {CaptchaOptions} options
64 | * @example
65 | * const { Client, IntentsBitField, EmbedBuilder } = require("discord.js");
66 | * const client = new Client({
67 | * intents: [
68 | * IntentsBitField.Flags.Guilds,
69 | * IntentsBitField.Flags.GuildMessages,
70 | * IntentsBitField.Flags.MessageContent, //IMPORTANT: make sure you enable "Message Content Intent" in the dev portal!
71 | * IntentsBitField.Flags.GuildMembers,
72 | * IntentsBitField.Flags.DirectMessages,
73 | * ]
74 | * });
75 | *
76 | * const { Captcha } = require("discord.js-captcha");
77 | *
78 | * const captcha = new Captcha(client, {
79 | * roleID: "Role ID Here",
80 | * channelID: "Text Channel ID Here",
81 | * sendToTextChannel: false, //defaults to false
82 | * addRoleOnSuccess: true, //defaults to true. whether you want the bot to add the role to the user if the captcha is solved
83 | * kickOnFailure: true, //defaults to true. whether you want the bot to kick the user if the captcha is failed
84 | * caseSensitive: true, //defaults to true. whether you want the captcha responses to be case-sensitive
85 | * attempts: 3, //defaults to 1. number of attempts before captcha is considered to be failed
86 | * timeout: 30000, //defaults to 60000. time the user has to solve the captcha on each attempt in milliseconds
87 | * showAttemptCount: true, //defaults to true. whether to show the number of attempts left in embed footer
88 | * customPromptEmbed: new EmbedBuilder(), //customise the embed that will be sent to the user when the captcha is requested
89 | * customSuccessEmbed: new EmbedBuilder(), //customise the embed that will be sent to the user when the captcha is solved
90 | * customFailureEmbed: new EmbedBuilder(), //customise the embed that will be sent to the user when they fail to solve the captcha
91 | * });
92 | */
93 | constructor(client, options = {}) {
94 | super();
95 |
96 | //check discord.js version
97 | if (version.split(".")[0] < 14) return console.log(`Discord.js Captcha Error: Discord.js v14 or later is required.\nPlease check the README for finding a compatible version for Discord.js v${version.split(".")[0]}\nNeed help? Join our Discord server at 'https://discord.gg/P2g24jp'`);
98 |
99 | if (!client) {
100 | console.log(`Discord.js Captcha Error: No Discord Client was Provided!\nNeed Help? Join our Discord Server at 'https://discord.gg/P2g24jp'`);
101 | process.exit(1)
102 | }
103 | this.client = client;
104 | /**
105 | * Captcha Options
106 | * @type {CaptchaOptions}
107 | */
108 | this.options = options;
109 |
110 | if ((options.sendToTextChannel === true) && (!options.channelID)) {
111 | console.log(`Discord.js Captcha Error: Option "sendToTextChannel" was set to true, but "channelID" was not Provided!\nNeed Help? Join our Discord Server at 'https://discord.gg/P2g24jp'`);
112 | process.exit(1)
113 | }
114 | if ((options.addRoleOnSuccess === true) && (!options.roleID)) {
115 | console.log(`Discord.js Captcha Error: Option "addRoleOnSuccess" was set to true, but "roleID" was not Provided!\nNeed Help? Join our Discord Server at 'https://discord.gg/P2g24jp'`);
116 | process.exit(1)
117 | }
118 | if (options.attempts < 1) {
119 | console.log(`Discord.js Captcha Error: Option "attempts" must be Greater than 0!\nNeed Help? Join our Discord Server at 'https://discord.gg/P2g24jp'`);
120 | process.exit(1)
121 | }
122 | if (options.timeout < 1) {
123 | console.log(`Discord.js Captcha Error: Option "timeout" must be Greater than 0!\nNeed Help? Join our Discord Server at 'https://discord.gg/P2g24jp'`);
124 | process.exit(1)
125 | }
126 | if (options.caseSensitive && (typeof options.caseSensitive !== "boolean")) {
127 | console.log(`Discord.js Captcha Error: Option "caseSensitive" must be of type boolean!\nNeed Help? Join our Discord Server at 'https://discord.gg/P2g24jp'`);
128 | process.exit(1)
129 | }
130 | if (options.customPromptEmbed && (typeof options.customPromptEmbed === "string")) {
131 | console.log(`Discord.js Captcha Error: Option "customPromptEmbed" is not an instance of EmbedBuilder!\nNeed Help? Join our Discord Server at 'https://discord.gg/P2g24jp'`);
132 | process.exit(1)
133 | }
134 | if (options.customSuccessEmbed && (typeof options.customSuccessEmbed === "string")) {
135 | console.log(`Discord.js Captcha Error: Option "customSuccessEmbed" is not an instance of EmbedBuilder!\nNeed Help? Join our Discord Server at 'https://discord.gg/P2g24jp'`);
136 | process.exit(1)
137 | }
138 | if (options.customFailureEmbed && (typeof options.customFailureEmbed === "string")) {
139 | console.log(`Discord.js Captcha Error: Option "customFailureEmbed" is not an instance of EmbedBuilder!\nNeed Help? Join our Discord Server at 'https://discord.gg/P2g24jp'`);
140 | process.exit(1)
141 | }
142 |
143 | if (options.addRoleOnSuccess === undefined) options.addRoleOnSuccess = true;
144 | options.attempts = options.attempts || 1;
145 | if (options.caseSensitive === undefined) options.caseSensitive = true;
146 | options.timeout = options.timeout || 60000;
147 | if (options.showAttemptCount === undefined) options.showAttemptCount = true;
148 |
149 | Object.assign(this.options, options);
150 | }
151 |
152 | /**
153 | * Presents the CAPTCHA to a `Discord.GuildMember`.
154 | *
155 | * @param {GuildMember} member The Discord Server Member to Present the CAPTCHA to.
156 | * @param {CaptchaImageData} [customCaptcha=undefined] **(OPTIONAL):** An object consisting of a Custom CAPTCHA Image and Text Answer.
157 | * @returns {Promise} Whether or not the Member Successfully Solved the CAPTCHA.
158 | * @async
159 | * @example
160 | * const { Captcha } = require("discord.js-captcha");
161 | *
162 | * const captcha = new Captcha(client, {
163 | * roleID: "Role ID Here",
164 | * channelID: "Text Channel ID Here",
165 | * sendToTextChannel: false,
166 | * kickOnFailure: true,
167 | * caseSensitive: true,
168 | * attempts: 3,
169 | * timeout: 30000,
170 | * showAttemptCount: true,
171 | * customPromptEmbed: new EmbedBuilder(),
172 | * customSuccessEmbed: new EmbedBuilder(),
173 | * customFailureEmbed: new EmbedBuilder(),
174 | * });
175 | *
176 | * client.on("guildMemberAdd", async member => {
177 | * captcha.present(member);
178 | * });
179 | */
180 | async present(member, customCaptcha) {
181 | if (!member) return console.log(`Discord.js Captcha Error: No Discord Member was Provided!\nNeed Help? Join our Discord Server at 'https://discord.gg/P2g24jp'`);
182 | if (customCaptcha) {
183 | if (!customCaptcha.image) return console.log(`Discord.js Captcha Error: Custom Captcha Image Data does not include an Image Buffer!\nNeed Help? Join our Discord Server at 'https://discord.gg/P2g24jp'`);
184 | if (!customCaptcha.text) return console.log(`Discord.js Captcha Error: Custom Captcha Image Data does not include a Text Answer!\nNeed Help? Join our Discord Server at 'https://discord.gg/P2g24jp'`);
185 | if (!Buffer.isBuffer(customCaptcha.image)) return console.log(`Discord.js Captcha Error: Custom Captcha Image is not a Buffer!\nNeed Help? Join our Discord Server at 'https://discord.gg/P2g24jp'`);
186 | if (typeof customCaptcha.text !== "string") return console.log(`Discord.js Captcha Error: Custom Captcha Text is not of type String!\nNeed Help? Join our Discord Server at 'https://discord.gg/P2g24jp'`);
187 | }
188 | const user = member.user;
189 | const captcha = customCaptcha ? customCaptcha : await createCaptcha(6, this.options.caseSensitive ? "" : "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
190 | let attemptsLeft = this.options.attempts || 1;
191 | let attemptsTaken = 1;
192 | let captchaResponses = [];
193 |
194 | let captchaIncorrect = new EmbedBuilder()
195 | .setTitle("❌ You Failed to Complete the CAPTCHA!")
196 | .setDescription(`${member.user}, you failed to solve the CAPTCHA!\n\nCAPTCHA Text: **${captcha.text}**`)
197 | .setTimestamp()
198 | .setColor("Red")
199 | .setThumbnail(member.guild.iconURL({ dynamic: true }))
200 |
201 | if (this.options.customFailureEmbed) captchaIncorrect = this.options.customFailureEmbed
202 |
203 | let captchaCorrect = new EmbedBuilder()
204 | .setTitle("✅ CAPTCHA Solved!")
205 | .setDescription(`${member.user}, you completed the CAPTCHA successfully, and you have been given access to **${member.guild.name}**!`)
206 | .setTimestamp()
207 | .setColor("Green")
208 | .setThumbnail(member.guild.iconURL({ dynamic: true }))
209 |
210 | if (this.options.customSuccessEmbed) captchaCorrect = this.options.customSuccessEmbed
211 |
212 | let captchaPrompt = new EmbedBuilder()
213 | .setTitle(`Welcome to ${member.guild.name}!`)
214 | .addFields([{ name: "I'm Not a Robot", value: `${member.user}, to gain access to **${member.guild.name}**, please solve the CAPTCHA below!\n\nThis is done to protect the server from raids consisting of spam bots.` }])
215 | .setColor("Random")
216 | .setThumbnail(member.guild.iconURL({ dynamic: true }))
217 |
218 | if (this.options.customPromptEmbed) captchaPrompt = this.options.customPromptEmbed
219 | if (this.options.showAttemptCount) captchaPrompt.setFooter({ text: this.options.attempts == 1 ? "You have one attempt to solve the CAPTCHA." : `Attempts Left: ${attemptsLeft}` })
220 | captchaPrompt.setImage('attachment://captcha.png')
221 |
222 | await handleChannelType(this.client, this.options, member).then(async channel => {
223 | let captchaEmbed;
224 | try {
225 | if ((this.options.channelID) && this.options.sendToTextChannel == true) {
226 | channel = (await this.client.guilds.fetch(member.guild.id)).channels.resolve(this.options.channelID)
227 | }
228 | else {
229 | channel = await user.createDM()
230 | }
231 | captchaEmbed = await channel.send({
232 | embeds: [captchaPrompt],
233 | files: [
234 | { name: "captcha.png", attachment: captcha.image }
235 | ]
236 | })
237 | } catch {
238 | channel = (await this.client.guilds.fetch(member.guild.id)).channels.resolve(this.options.channelID)
239 | if (this.options.channelID) {
240 | captchaEmbed = await channel.send({
241 | embeds: [captchaPrompt],
242 | files: [
243 | { name: "captcha.png", attachment: captcha.image }
244 | ]
245 | })
246 | } else {
247 | return console.log(`Discord.js Captcha Error: User's Direct Messages are Locked!\nYou can attempt have the CAPTCHA sent to a Text Channel if it can't send to DMs by using the "channelID" Option in the Constructor.\nNeed Help? Join our Discord Server at 'https://discord.gg/P2g24jp'`);
248 | }
249 | }
250 |
251 | const captchaFilter = x => {
252 | return (x.author.id == member.user.id)
253 | }
254 |
255 | async function handleAttempt(captchaData) { //Handles CAPTCHA Responses and Checks
256 | await captchaEmbed.channel.awaitMessages({
257 | filter: captchaFilter, max: 1, time: captchaData.options.timeout
258 | })
259 | .then(async responses => {
260 |
261 | if (!responses.size) { //If no response was given, CAPTCHA is fully cancelled here
262 |
263 | //emit timeout event
264 | captchaData.emit("timeout", {
265 | member: member,
266 | responses: captchaResponses,
267 | attempts: attemptsTaken,
268 | captchaText: captcha.text,
269 | captchaOptions: captchaData.options
270 | })
271 |
272 | await captchaEmbed.delete();
273 | await channel.send({ embeds: [captchaIncorrect] })
274 | .then(async msg => {
275 | if (captchaData.options.kickOnFailure) await member.kick("Failed to Pass CAPTCHA")
276 | if (channel.type === ChannelType.GuildText) setTimeout(() => msg.delete(), 3000);
277 | });
278 | return false;
279 | }
280 |
281 | //emit answer event
282 | captchaData.emit("answer", {
283 | member: member,
284 | response: String(responses.first()),
285 | attempts: attemptsTaken,
286 | captchaText: captcha.text,
287 | captchaOptions: captchaData.options
288 | })
289 |
290 | let answer = String(responses.first()); //Converts the response message to a string
291 | if (captchaData.options.caseSensitive !== true) answer = answer.toLowerCase(); //If the CAPTCHA is case sensitive, convert the response to lowercase
292 | captchaResponses.push(answer); //Adds the answer to the array of answers
293 | if (channel.type === ChannelType.GuildText) await responses.first().delete();
294 |
295 | if (answer === captcha.text) { //If the answer is correct, this code will execute
296 | //emit success event
297 | captchaData.emit("success", {
298 | member: member,
299 | responses: captchaResponses,
300 | attempts: attemptsTaken,
301 | captchaText: captcha.text,
302 | captchaOptions: captchaData.options
303 | })
304 | if (captchaData.options.addRoleOnSuccess === true) { // Only adds to role if option is set
305 | await member.roles.add(captchaData.options.roleID)
306 | }
307 | if (channel.type === ChannelType.GuildText) await captchaEmbed.delete();
308 | channel.send({ embeds: [captchaCorrect] })
309 | .then(async msg => {
310 | if (channel.type === ChannelType.GuildText) setTimeout(() => msg.delete(), 3000);
311 | });
312 | return true;
313 | } else { //If the answer is incorrect, this code will execute
314 | if (attemptsLeft > 1) { //If there are attempts left
315 | attemptsLeft--;
316 | attemptsTaken++;
317 | if (channel.type === ChannelType.GuildText && captchaData.options.showAttemptCount) {
318 | await captchaEmbed.edit({
319 | embeds: [captchaPrompt.setFooter({ text: `Attempts Left: ${attemptsLeft}` })],
320 | files: [
321 | { name: "captcha.png", attachment: captcha.image }
322 | ]
323 | })
324 | }
325 | else if (channel.type !== ChannelType.GuildText) {
326 | await captchaEmbed.channel.send({
327 | embeds: [captchaData.options.showAttemptCount ? captchaPrompt.setFooter({ text: `Attempts Left: ${attemptsLeft}` }) : captchaPrompt],
328 | files: [
329 | { name: "captcha.png", attachment: captcha.image }
330 | ]
331 | })
332 | }
333 | return handleAttempt(captchaData);
334 | }
335 | //If there are no attempts left
336 |
337 | //emit failure event
338 | captchaData.emit("failure", {
339 | member: member,
340 | responses: captchaResponses,
341 | attempts: attemptsTaken,
342 | captchaText: captcha.text,
343 | captchaOptions: captchaData.options
344 | })
345 |
346 | if (channel.type === ChannelType.GuildText) await captchaEmbed.delete();
347 | await channel.send({ embeds: [captchaIncorrect] })
348 | .then(async msg => {
349 | if (captchaData.options.kickOnFailure) await member.kick("Failed to Pass CAPTCHA")
350 | if (channel.type === ChannelType.GuildText) setTimeout(() => msg.delete(), 3000);
351 | });
352 | return false;
353 | }
354 | })
355 | }
356 | //emit prompt event
357 | this.emit("prompt", {
358 | member: member,
359 | captchaText: captcha.text,
360 | captchaOptions: this.options
361 | })
362 | handleAttempt(this);
363 | })
364 | }
365 | }
366 |
367 | module.exports = Captcha;
--------------------------------------------------------------------------------
/src/createCaptcha.js:
--------------------------------------------------------------------------------
1 | const shuffle = (arr) => {
2 | let i = arr.length;
3 | while (i) {
4 | let j = Math.floor(Math.random() * i--);
5 | [arr[j], arr[i]] = [arr[i], arr[j]];
6 | }
7 | return arr;
8 | };
9 |
10 | /**
11 | * @typedef {Object} CaptchaImageData
12 | * @prop {Buffer} image The CAPTCHA Image.
13 | * @prop {String} text The Answer to the CAPTCHA.
14 | */
15 |
16 | /**
17 | * Asynchronously Generates a CAPTCHA.
18 | * @param {Number} [length=6] The Text Length of the CAPTCHA. Defaults to 6.
19 | * @param {String} [blacklist=""] A List of Characters to Exclude from the CAPTCHA.
20 | * @returns {CaptchaImageData} The CAPTCHA Image Data.
21 | */
22 |
23 | module.exports = async function createCaptcha(length = 6, blacklist = "") {
24 |
25 | let chars = [
26 | "a",
27 | "b",
28 | "c",
29 | "d",
30 | "e",
31 | "f",
32 | "g",
33 | "h",
34 | "i",
35 | "j",
36 | "k",
37 | "l",
38 | "m",
39 | "n",
40 | "o",
41 | "p",
42 | "q",
43 | "r",
44 | "s",
45 | "t",
46 | "u",
47 | "v",
48 | "w",
49 | "x",
50 | "y",
51 | "z",
52 | "A",
53 | "B",
54 | "C",
55 | "D",
56 | "E",
57 | "F",
58 | "G",
59 | "H",
60 | "I",
61 | "J",
62 | "K",
63 | "L",
64 | "M",
65 | "N",
66 | "O",
67 | "P",
68 | "Q",
69 | "R",
70 | "S",
71 | "T",
72 | "U",
73 | "V",
74 | "W",
75 | "X",
76 | "Y",
77 | "Z",
78 | "0",
79 | "1",
80 | "2",
81 | "3",
82 | "4",
83 | "5",
84 | "6",
85 | "7",
86 | "8",
87 | "9"
88 | ];
89 |
90 | //check for canvas installation
91 | const { Canvas } = require("canvas");
92 |
93 | // Validate length param
94 | if (Number.isNaN(length)) throw new Error("Discord.js Captcha Generation Error: Length must be a Number.");
95 | 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'");
96 |
97 | // Validate blacklist param
98 | 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'");
99 | 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'");
100 |
101 | // Remove blacklisted characters from the character list
102 | chars.splice(0, chars.length, ...chars.filter(c => !blacklist.includes(c)));
103 | chars = shuffle(chars);
104 |
105 | const canvas = new Canvas(400, 250);
106 | const ctx = canvas.getContext("2d");
107 |
108 | // Set background color
109 | ctx.globalAlpha = 1;
110 | ctx.fillStyle = "white";
111 | ctx.beginPath();
112 | ctx.fillRect(0, 0, 400, 250);
113 | ctx.save();
114 |
115 | // Set style for lines
116 | ctx.strokeStyle = "#000";
117 | ctx.lineWidth = 4;
118 |
119 | // Draw lines
120 | ctx.beginPath();
121 |
122 | const coords = [];
123 |
124 | for (let i = 0; i < 4; i++) {
125 | if (!coords[i])
126 | coords[i] = [];
127 | for (let j = 0; j < 5; j++)
128 | coords[i][j] = Math.round(Math.random() * 80) + j * 80;
129 | if (!(i % 2))
130 | coords[i] = shuffle(coords[i]);
131 | }
132 |
133 | for (let i = 0; i < coords.length; i++) {
134 | if (!(i % 2)) {
135 | for (let j = 0; j < coords[i].length; j++) {
136 | if (!i) {
137 | ctx.moveTo(coords[i][j], 0);
138 | ctx.lineTo(coords[i + 1][j], 400);
139 | }
140 | else {
141 | ctx.moveTo(0, coords[i][j]);
142 | ctx.lineTo(400, coords[i + 1][j]);
143 | }
144 | }
145 | }
146 | }
147 |
148 | ctx.stroke();
149 |
150 | // Set style for circles
151 | ctx.fillStyle = "#000";
152 | ctx.line400 = 0;
153 |
154 | // Draw circles
155 | for (let i = 0; i < 200; i++) {
156 | ctx.beginPath();
157 | ctx.arc(Math.round(Math.random() * 360) + 20, Math.round(Math.random() * 360) + 20, Math.round(Math.random() * 7) + 1, 0, Math.PI * 2);
158 | ctx.fill();
159 | }
160 |
161 | // generate text
162 | let text = "";
163 | for (let i = 0; i < length; i++) text += chars[Math.floor(Math.random() * chars.length)];
164 |
165 |
166 | // Set style for text based on length param
167 | ctx.font = `${length > 6 ? (80 / (length / 7.5)) : 80}px Sans`;
168 | ctx.fillStyle = "#000";
169 |
170 |
171 | // Set position for text
172 | ctx.textAlign = "center";
173 | ctx.textBaseline = "top";
174 | ctx.translate(0, 250);
175 | ctx.translate(Math.round(Math.random() * 100 - 50) + 200, -1 * Math.round(Math.random() * (250 / 4) - 250 / 8) - 250 / 2);
176 | ctx.rotate(Math.random() - 0.5);
177 |
178 | // Set text value and print it to canvas
179 | ctx.beginPath();
180 | ctx.fillText(text, 0, 0);
181 |
182 | // Draw foreground noise
183 | ctx.restore();
184 |
185 | for (let i = 0; i < 5000; i++) {
186 |
187 | ctx.beginPath();
188 |
189 | let color = "#";
190 | while (color.length < 7) {
191 | color += Math.round(Math.random() * 16).toString(16);
192 | }
193 |
194 | color += "a0";
195 | ctx.fillStyle = color;
196 | ctx.arc(Math.round(Math.random() * 400), Math.round(Math.random() * 250), Math.random() * 2, 0, Math.PI * 2);
197 | ctx.fill();
198 | }
199 |
200 | return {
201 | image: canvas.toBuffer(),
202 | text: text
203 | };
204 | }
--------------------------------------------------------------------------------
/src/handleChannelType.js:
--------------------------------------------------------------------------------
1 | const { Client, GuildMember, DMChannel, TextChannel } = require("discord.js");
2 |
3 | /**
4 | *
5 | * @param {Client} client
6 | * @param {any} options
7 | * @param {GuildMember} member
8 | * @returns {DMChannel | TextChannel}
9 | */
10 |
11 | module.exports = async function handleChannelType(client, options, member) {
12 | let channel;
13 | if (!options.channelID) {
14 | channel = await member.user.createDM();
15 | } else {
16 | if (options.sendToTextChannel == true) {
17 | channel = (await client.guilds.fetch(member.guild.id)).channels.resolve(options.channelID);
18 | }
19 | }
20 | return channel;
21 | }
--------------------------------------------------------------------------------
/src/images/captchaExample.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/WillTDA/Discord.js-Captcha/19568757362e013a7932221163b151b1d7a211f5/src/images/captchaExample.jpg
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | Captcha: require("./Captcha"),
3 | createCaptcha: require("./createCaptcha")
4 | }
--------------------------------------------------------------------------------