DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

Cover image for PR Update
Antonio-Bennett
Antonio-Bennett

Posted on • Updated on

PR Update

Hey everyone! As usual the previous relevant post is here :)

What will we be covering?

Well....I got the code working!! So this blog will go into the code I needed to get this PR done. Honestly it was quite easy but I will get into why in the next blog of my final thoughts. Lets stick to the good stuff in this one :)

Code

So as I said in the previous blog I had to find a way to check if the server where the command request is sent has the DJ role. To do this I have this code

    let guild = msg.guild(&ctx.cache).await.unwrap();
    let mut roleid = RoleId::default();

    for (_, role) in guild.roles {
        if role.name == "DJ" {
            roleid = role.id;
        }
    }
Enter fullscreen mode Exit fullscreen mode

We need the Role id to check if the user has the DJ role. This is how we do that

    let user = &msg.author;
    user.has_role(&ctx.http, guild.id, roleid).await.unwrap()
Enter fullscreen mode Exit fullscreen mode

Now lets discuss the 2 strange variables in there. ctx and msg. ctxis the context of the event fired. This is used when the user tries to use a command to get guild information. msg is the message sent in the discord chat so you can find who sent it and their info.

What I did is then put this code into a utility function so it can be called to conditionally run a command if the user has the required role.

pub async fn author_is_dj(ctx: &Context, msg: &Message) -> bool {
    let guild = msg.guild(&ctx.cache).await.unwrap();
    let mut roleid = RoleId::default();

    for (_, role) in guild.roles {
        if role.name == "DJ" {
            roleid = role.id;
        }
    }

    let user = &msg.author;
    user.has_role(&ctx.http, guild.id, roleid).await.unwrap()
}
Enter fullscreen mode Exit fullscreen mode

It is then used like this in code

    if !author_is_dj(ctx, msg).await {
        //Inform user they do not have the required role
        //return
    } else {
        //Run command
    }
Enter fullscreen mode Exit fullscreen mode

What's next?

Well that was all for this blog! Hope you enjoyed it :) The next blog will be my final thoughts on this experience :)

Top comments (0)

New programmer and javascript

Stop by this week's meme thread!