Home > OS >  How do I add or remove roles on my Discord JS server, through a button click I have on my website or
How do I add or remove roles on my Discord JS server, through a button click I have on my website or

Time:04-11

I have 2 buttons on my localhost currently, which on click sends a post request along with my discord ID. Add role and remove role

This is my post request:

app.post('/addUser', urlencodedParser, (req,res) => {
    const discordID=req.body.discordID;
    const roleID= GOLD_ROLE_ID;          // this is my role ID
    // code to what I want to achieve"   // BOT assigns user[discordID] with roleID
    res.send("User " discordID " role added to discord!");
})

app.post('/removeUser', urlencodedParser, (req,res) => {
    const discordID=req.body.discordID;
    res.send("User " discordID " role removed from discord!");
})

When I click either *"Add role" or "remove role", I want to raise a post request (which sends my discord ID as well) for my bot, so that I get assigned a role.

I'm new to making discord bot using discord.js but all I found was that bot can only reply on events happening in guild like (new message, guildMembersAdd). Is it possible to create an API request to my bot, and achieve this?

Is it possible to do it externally?

CodePudding user response:

You can connect with Discord bot endpoints and run, otherwise, In your node server you can directly import clients from your discord file and use something like this:

app.post('/addUser', urlencodedParser, async(req,res) => {
    const discordID=req.body.discordID;
    const currGuild = client.guilds.cache.get(serverID);
    try{
        let user=await currGuild.members.fetch(discordID);
        user.roles.add(your_role_id);
    }
    catch(e){
       console.log(e);
    }
    res.send("User " discordID " role added to discord!");
})

Similarly for removing role, you can go with .remove

  • Related