Issue with base64 in Discord.js captcha channel system

Greetings everyone, and a special welcome to those willing to assist me. I am currently working on a project that involves verifying users through a hash decryption challenge system (base64). However, I've encountered an issue where the verification process is not working as expected, even though there are no errors in the code. The bot connects successfully, but the verification does not happen in the desired channel; instead, it occurs in DMs. I would appreciate any help to rectify this issue. Thank you.

const Discord = require('discord.js')
const client = new Discord.Client();
const prefix = "&";

let rawdata = fs.readFileSync('config.json');
let object = JSON.parse(rawdata);
var channel_id = object['verification_channelID']
var guild_id = object['guild_ID']
var role_name = object['verification_role_name']
var server_invite = object['server_invite']
var token = object['bot_token']
var questions = object['questions']

var dict = {};

var encodingQuestions = []
questions.forEach(element => {
    encodingQuestions.push(element)
});

client.on('ready', function(){
    console.log("Login : " + client.user.tag);
})


client.on('guildMemberAdd', member => {
    var uname = member.user.username
    var disc = member.user.discriminator
    var memberID = member.user.id
    var rand = Math.random();
    rand *= encodingQuestions.length;
    rand = Math.floor(rand);
    var question = encodingQuestions[rand]
    dict[uname] = [Buffer.from(question, 'base64').toString('utf-8'), 3];
    const embed = new Discord.MessageEmbed()
        .setTitle(uname + "#" + disc)
        .setColor(0x1e90ff)
        .addField(uname='Welcome', value='Welcome <@' + memberID + '> Déchiffrer le code , vous avez 3 essais ! Utilisez ``&answer {decoded message}`` ', inline=false)
        .addField(uname='Question', value=question, inline=false)
    member.send(embed)
    member.guild.channels.cache.get(channel_id).send("Welcome <@" + memberID + "> Regarder vos DM pour accédez au serveur !");
});

client.on('message', message => {
    var memberid = message.author.id;
    var memberuname = message.author.username;
    var messagecontent = message.content;
    var messageID = message.id;
    var disc = message.author.discriminator;
    if (!message.content.startsWith(prefix)) return;

    if (message.content.startsWith(prefix + 'answer') && message.channel.type === "dm"){
        var msg = message.toString().replace('&answer ', '')
        for (var key in dict){
            if (key == message.author.username){
                if (msg == dict[key][0]){
                    message.channel.send("Vous avez passer le test !")
                    var role = client.guilds.cache.get(guild_id).roles.cache.find(role => role.name === role_name)
                    client.guilds.cache.get(guild_id).members.cache.get(message.author.id).roles.add(role);
                    var memberID = message.author.id
                    client.channels.cache.get(channel_id).send("Trés bien <@" + memberID + "> vous avez réussis le test avec succèes !")
                    
                    delete dict[key];
                } else{
                    dict[key][1] = dict[key][1] - 1
                    if (dict[key][1] == 0){
                        memberID = message.author.id
                        message.channel.send("Vous avez pas réussis le test vous allez êtres exclus ! Revenir sur Paradox : " + server_invite)
                        client.channels.cache.get(channel_id).send("<@" + memberID + "> Vous avez échoué le test...")
                        setTimeout(function(){
                            client.guilds.cache.get(guild_id).members.cache.get(message.author.id).kick()
                        }, 5000)
                    } else{
                        message.channel.send("Réessayer !")
                    }
                }
            }
        } 
    }
})
client.login(token);

The database config.json: 

{
    "bot_token": "TOKEN",
    "verification_channelID": "",
    "guild_ID": "",
    "verification_role_name": "",
    "server_invite": "",
    "questions": ["eW91IHBhc3NlZA==", "dGhpcyB3YXMgZWFzeQ==", "dGhhbmtzIGZvciBqb2luaW5n", "ZW5qb3kgeW91ciBzdGF5", "dGhhbmtzIGZvciBub3QgYmVpbmcgYW5vbnltb3Vz", "ZW5qb3kgeW91ciBzdGF5", "aW52aXRlIHlvdXIgZnJpZW5kcyE="]
}

Answer №1

Here is the recommended code snippet:

client.on('guildMemberAdd', member => {
    var uname = member.user.username
    var disc = member.user.discriminator
    var memberID = member.user.id
    var rand = Math.random();
    rand *= encodingQuestions.length;
    rand = Math.floor(rand);
    var question = encodingQuestions[rand]
    dict[uname] = [Buffer.from(question, 'base64').toString('utf-8'), 3];
    const embed = new Discord.MessageEmbed()
        .setTitle(uname + "#" + disc)
        .setColor(0x1e90ff)
        .addField('Welcome', 'Welcome <@' + memberID + '> Decode the code, you have 3 tries! Use ``&answer {decoded message}`` ', true) // Updated part here
        .addField('Question', question, true) // Updated part here
    member.send(embed)
    member.guild.channels.cache.get(channel_id).send("Welcome <@" + memberID + "> Check your DM to access the server!")
});

I made a small adjustment in the embed section, replacing

.addField(name='coucou', value='name', inline=true)
with
.addField('coucou', 'salut', true);
. This aligns with the correct javascript function parameters syntax.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible for (variable or {}) to function seamlessly across all web browsers when using Javascript

When writing code in JavaScript, the if(variable) clause is used to check if a list or array is not null or undefined in order to avoid exceptions. Here's an example: if (list) for (var k in list) { ... if (array) for (var i = array.l ...

Using jQuery to enhance the functionality of the drop-down select feature

I am facing an issue with my index file code. When I select something from the drop-down menu, I expect to see a related dropdown appear. Although I have added this code to my file, I am unable to get the drop down to show after selecting the main type. ...

Unable to define an object within the *ngFor loop in Angular

In order to iterate through custom controls, I am using the following code. These controls require certain information such as index and position in the structure, so I am passing a config object to keep everything organized. <div *ngFor="let thing of ...

What does the "listen EACCESS localhost" error in the code signify and why is it occurring?

const express = require('express'); const morgan = require('morgan'); const host = 'localhost'; const port = 3000; const app = express(); app.use(morgan('dev')); app.use(express.static(__dirname + '/public&ap ...

Is there a way to modify the CSS display property upon clicking a link or button?

I have a ul with the id of "menu-list". The display property is set to "none" in my CSS file, but I want it to switch to "flex" when a link is clicked. I am trying to use the click event on the link to change the display prop ...

Fix surface orientations on potentially corrupted .stl files

I am facing a challenge in Three.js where I need to fix the normals on files that are coming in with potential issues. It's unclear whether the problem lies in the scanning process or during the file uploads. While we are investigating the upload func ...

Exploring the Live Search Functionality on an HTML Webpage

I am attempting to create a live search on dive elements within an HTML document. var val; $(document).ready(function() { $('#search').keyup(function() { var value = document.getElementById('search').value; val = $.trim(val ...

Discover the DOM events present in an HTML response

When sending multiple HTTP requests to a server and receiving a HTML + JS response, I need to determine which responses trigger JS alerts or DOM-based events. Node.js is being used to send the requests. Especially in cases where there is local JS on the c ...

Tips on how to iterate through a JSON object and store its values in an array

I am attempting to extract values from an external JSON file and store certain values in an array. Here is my code : $.getJSON("https://link.to.my.json", function(data) { console.log(data); // this will display the information in the console }); I am ...

Enable the server to accept requests from localhost containing parameters

I am facing an issue with my application running locally on my computer, trying to connect to a remote nodeJS/Express server. The headers have been set on the remote server. Main inquiry: How can I configure my remote server to accept requests from my loc ...

Retrieve the v-id-xx attribute value for scoped styling in a Vue Single File Component

When using pure JavaScript to add elements in a Vue Single File Component, the added elements are missing the v-id-xx attribute for scoped CSS. Is there a way to retrieve the component's v-id-hash value using only JavaScript? ...

Collect all wallet objects and store them in an array of objects within BitGO for Bitcoin

My Setup: Using the Mongoose module to handle all MongoDB operations, we generate and store a wallet inside a Mongo collection for each new user. METHOD: By using User.find({}, function(err, docs) {, we can retrieve each user object. User.find({}, functi ...

What is the reason behind utilizing arrow functions in React event handlers?

function ButtonIncrement(){ const [count,setCount] = useState(0); render(){ <div> <h3> <button onClick={() => setCount(count+1)}>Increase count for amusement</button> <p>Total C ...

The technique of binding methods in React

When working with React.js, it's recommended to define your method binding in the constructor for better performance. Here's an example: constructor(props){ this.someFunction = this.someFunction.bind(this); } This approach is more efficient t ...

What could be causing Mathjax to generate multiple copies?

I have integrated MathJax into my application to render MathML. The code snippet below is used to ensure that the MathML is typeset properly: $rootScope.$watch(function() { MathJax.Hub.Queue(["Typeset", MathJax.Hub]); return true; }); However, I ...

Creating personalized Stop and Play controls for Swiper.js Autoplay feature in a React/Next project

My quest to create a Swiper in React with autoplay functionality using Swiper.js has been quite a challenge. Despite following the instructions diligently and researching extensively, I couldn't find a solution. I even tried referencing a jQuery examp ...

Can you place more than one Twitter Bootstrap carousel on a single webpage?

Latest Version of Twitter Bootstrap: 2.0.3 Sample HTML Code: <!DOCTYPE html> <html dir="ltr" lang="en-US" xmlns:og="http://opengraphprotocol.org/schema/"> <head> <link rel="stylesheet" type="text/css" media="all" href="reddlec/style. ...

The filter functionality is not functioning properly in AngularJS

Currently, I am working on an AngularJS extension and encountering an issue with the filter functionality. In the popup page of my extension, there is a button. Upon clicking this button, the ancestor node of the button gets blocked, and its relevant info ...

Parsing JSON data with new line characters

What is the reason behind being unable to parse a json with a \n character in javascript? JSON.parse('{"x": "\n"}') Surprisingly, when you use JSON.parse(JSON.stringify({"x" : "\n"})), it works perfectly fine. indicates that {" ...

What is causing this JavaScript alert to malfunction?

My current project involves working with ASP.NET and in the view, I have a code snippet that is causing some issues. When I attempt to use Sweet Alert outside of the function, it works perfectly fine. Similarly, if I switch out Sweet Alert for a regular al ...