Chabz
Chabz

Reputation: 25

How do I add a role to new members discord

I've tried different things but they never work. I tried to add the code to my new user joined task

public async Task AnnounceJoinedUser(SocketGuildUser user) //welcomes New Players
{
    var channel = Client.GetChannel(447147292617736203) as SocketTextChannel; //gets channel to send message in
    await channel.SendMessageAsync("Welcome " + user.Mention + " to the server! Have a great time"); //Welcomes the new user
}

But I dont know how to add a role to new user

Upvotes: 1

Views: 887

Answers (1)

WQYeo
WQYeo

Reputation: 4056

Get the role from the guild that the user joined in first, then add the role to the user using user.AddRoleAsync().

private async Task UserJoined(SocketGuildUser socketGuildUser) {
    ulong roleID = 123; //Some hard-coded roleID
    var role = socketGuildUser.Guild.GetRole(roleID);
    await socketGuildUser.AddRoleAsync(role);

    //Without ID...
    string roleName = "The role name to add to user"; //Or some other property
    //Get the list of roles in the guild.
    var guildRoles = socketGuildUser.Guild.Roles;
    //Loop through the list of roles in the guild.
    foreach(var guildRole in guildRoles) {
        //If the current iteration of role matches the rolename
        if(guildRole.Name.Equals(roleName, StringComparison.OrdinalIgnoreCase)) {
            //Assign the role to the user.
            await socketGuildUser.AddRoleAsync(guildRole);
            //Exit Loop.
            break;
        }
    }
}

Upvotes: 1

Related Questions