A step-by-step guide on finding out your Discord server's members using Javascript

Unlock the Power of Discord Bots!

·

7 min read

A step-by-step guide on finding out your Discord server's members using Javascript

We are transitioning into an era where web3 is dominating the internet. Many collaboration tools are being used in this space, and Discord is among the top. It is where a project or company can organize its community efficiently. As a developer, you'd be required to work with Discord APIs some of the time and you have to be ready.
In this article, I will use the Discord oauth2 to build an application that checks if a user is on a particular Discord server.

Approach:

First off we have to create a discord bot application for the project.

Then we have to build a form in a frontend that collects the user's discord username, then sends it to the backend, which now runs the username through the discord bot to confirm if it is present in the discord server.

Prerequisites:

  • Code editor and browser.

  • Basic knowledge of JavaScript events and Event Handlers.

  • Basic knowledge of React and React Hooks.

  • Basic knowledge of Git, and package managers (npm or yarn).

    Packages to Install:

  • Nodejs

  • Nodemon

  • ExpressJs

  • Axios

  • cors package

  • ReactJs

  • dotenv

Creating the discord bot application

Step 1

Head to the developer portal, and create a new application at the top right. Give the bot a name of your choice and click "create".

Step 2

Next, we head to the "bot" part of the application, and there you copy the bot code. Please keep it in a safe place, as it is important.

Step 3

Add the discord bot to your server:

Go to the OAuth2 tab of your discord bot and select the scopes section. Check the "bot" checkbox to enable bot authentication.

In the "Bot Permissions" section, select the "manage server" and "read messages" checkboxes.

Please scroll below and copy the generated OAuth2 URL and open it in your web browser. Select the server you want to add the bot to and click on the "Authorize" button.

You now have the bot on your server.

Coding Session

Up next, is the coding sesh!

We would be using the discord library discord.js to work with the API.

  • Create two folders for both your backend and your front end.

We'd be using the discord.js package to be able to interact with the bot, so we'd go into the server folder and install discord.js

Note: This comes with the assumption that you have node.js and nodemon installed in your machine for easy use.

npm install discord.js

  • create an index.js file in your server folder.

  • Import your Client, and GatewayIntentBits from the package (Would explain its use later)

  • Create an .env file, in the root of the folder. This is where you'd assign your bot token a variable name, sort of like this:

    BOT_CODE ="your discord bot code"

  • If you don't know what this does, you can check this article about env files here.

  • Now we install dotenv in our root folder. Head to the root folder in the terminal and run:

    npm install dotenv

    this automatically packages your env file and makes whatever is stored in your env file accessible to you at any point in your code.

    Back to the index.js file:

  • Import config from dotenv, and specify the path where the env file is

    import {config} from "dotenv"

    config({path:"file-directory"})

  • First off, we create the port which the server runs on:
    const port = 3001

  • We create an instance of Client from the discord.js package:

    const client = new Client({ intents: [GatewayIntentBits.Guilds] })

Now to explain what this is for:
This line of code creates a new Client object with a single intent specified, GatewayIntentBits.Guilds. The purpose is to configure a new Discord bot client with the required permissions and settings to access and interact with the Discord API.

The GatewayIntentBits.Guilds intent is used to receive events related to guilds, essentially Discord servers. By specifying this intent, the bot will be able to receive events related to the creation, update, or deletion of guilds, as well as events related to guild members joining or leaving.

  • Now to test if the bot is working, you can write these lines of code:
    client.on('ready', () => {
    if (client.user) {
    console.log(`Logged in as ${client.user.tag}!`)
    } })

  • Then run your file in the terminal (if you are using nodemon, you don't need to do it every time you make changes to the file). If you have done it right, you should get this in the console:

    in your case "birbs-bot#6287" would be replaced by the bot name and id you created.

    Note: we'd be installing CORS package to be able to avoid those pesky CORS errors

    run npm install CORS in the terminal, then import cors from 'cors' in the backend file. Then app.use(cors())

  • Then we add this block of code just below :

    ``javascript client.on('ready', () => { if (client.user) { console.log(Logged in as ${client.user.tag}!`); } });

app.get('/check/:username', async (req, res) => { const { username } = req.params; const guildId = '' //YOUR DISCORD SERVER ID ; try { const guild = await client.guilds.fetch(guildId); const member = await guild.members.fetch({ query: username, limit: 1 }); if (member.size > 0) { res.send({ success: true, message: ${username} is a member of the server }); } else { res.send({ success: false, message: ${username} is not a member of the server }); } } catch (error) { console.log(error); res.status(500).send({ success: false, message: 'Server error' }); } })

client.login(process.env.BOT_CODE).then((e)=>{ app.listen(port, () => { console.log(Example app listening at http://localhost:${port}); }); }).catch(e=>{ console.error("Big error ", e); });


    Explaining each block of code:

    `app.get('/check/:username', async (req, res) => { const { username } = req.params; const guildId = '' //YOUR SERVER ID;`

    `// Code continues...`

* This code sets up a new HTTP GET route at the `/check/:username` endpoint. When a client requests this endpoint with a username parameter in the URL, the server retrieves the value of the `username` parameter and sets the `guildId` variable to a specific Discord server's ID (link on how to get your server ID [here](https://support.discord.com/hc/en-us/articles/206346498-Where-can-I-find-my-User-Server-Message-ID-#:~:text=On%20Android%20press%20and%20hold,name%20and%20select%20Copy%20ID.) )

* `try { const guild = await client.guilds.fetch(guildId);`  
    `const member = await guild.members.fetch({ query: username, limit: 1 });`

    `// Code continues...`

    This code uses the `guilds.fetch()` and `members.fetch()` methods to retrieve information about the user in the specific Discord server. It first retrieves the `Guild` object for the specified guild ID using the `guilds.fetch()` method. It then uses the `members.fetch()` method with a `query` parameter set to the username to retrieve a `GuildMemberManager` collection of members that match the specified username.

* `if (member.size > 0) {`  
    `res.send({ success: true, message: ${username} is a member of the server }) }`  
    `else {`  
    `res.send({ success: false, message: ${username} is not a member of the server }); }`  
    This block of code checks if the `GuildMemberManager` collection has at least one member and sends a response back to the client with a success message if the user is a member of the server, or a failure message if the user is not a member of the server.

* `}`

    `catch (error) {`  
    `console.log(error); res.status(500).send({ success: false, message: 'Server error' }); }`

    This code catches any errors while fetching user information and sends a 500 internal server error response to the client.

* `client.login(`[`process.env.BOT`](http://process.env.BOT)`_CODE)`  
    `.then((e)=>{ app.listen(port, () => {`  
    `console.log(Example app listening at` [`http://localhost:${port}`](http://localhost:$%7Bport%7D)`);`  
    `});`  
    `}).catch(e=>{`  
    `console.error("Big error ", e) //whatever you want to do with the error`  
    `});`  
    This code logs in to the Discord client using the bot token provided in the [`process.env.BOT`](http://process.env.BOT)`_CODE` environment variable. If the login is successful, the code starts the server listening on the specified port. If an error occurs during login or server startup, the code logs the error to the console.

    Okay, we are done with the backend.

* We head back to the frontend folder, and in the App.jsx, and we create a form to collect the user's discord username.


```javascript

const App =()=>{
    const [username, setUsername] = useState("");
    const [result, setResult] = useState("");


    const verifyDiscord = async (e) => {
        e.preventDefault();
        console.log(username, "submit")
        try {
          const response = await                         axios.get(`http://127.0.0.1:3001/check/${username}`);
           setResult(response.data);
          } catch (error) {
            console.log(error);
           }
      };

  return (
    <div>
       <button className='Buttons'>Join Discord</button>
           <form className="Discord-form" onSubmit={verifyDiscord}>
               <input type="text"
                   value={username}
                   onChange={(e) => setUsername(e.target.value)}
                    />
        <button type="submit">Check</button>
    </form>
 </div>
)
}

When the form submits, it triggers the verifyDiscord async function which sends the username to the backend, runs the check, and sends back the response as either true or false. The response is being set to the result state using setResult . Now with this result, you could use this to display something:

result.success ?<p>user is in the discord server</p>: <p>user is not in the server</p>

or better still, render another component.

That's all!
You have successfully used the discord bot to check for users in a discord server. That's all, folks! I hope this was helpful. Please do well to leave some feedback, share the article with friends, and connect with me on Twitter or Linkedin.

Cover photo by Alexander Shatov on Unsplash