Skip to content

Commit

Permalink
state: Add MemberRoles and SortedRoles helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
diamondburned committed Jan 3, 2024
1 parent 1782301 commit 966d966
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions state/state.go
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,46 @@ func MemberColor(m *discord.Member, role func(discord.RoleID) *discord.Role) (di
return c, pos != -1
}

// SortedRoles returns a list of roles sorted by their position.
// The roles are fetched using (*State).Roles.
func (s *State) SortedRoles(guildID discord.GuildID) ([]discord.Role, error) {
roles, err := s.Roles(guildID)
if err != nil {
return nil, err
}
discord.SortRolesByPosition(roles)
return roles, nil
}

// MemberRoles returns a list of roles that the given member has.
// The returned roles are sorted by their position.
func (s *State) MemberRoles(guildID discord.GuildID, userID discord.UserID) ([]discord.Role, error) {
roles, err := s.Roles(guildID)
if err != nil {
return nil, fmt.Errorf("failed to get roles for guild: %w", err)
}

member, err := s.Member(guildID, userID)
if err != nil {
return nil, fmt.Errorf("failed to get member: %w", err)
}

filtered := make([]discord.Role, 0, len(member.RoleIDs))
roleSearch:
for _, roleID := range member.RoleIDs {
for _, role := range roles {
if role.ID == roleID {
filtered = append(filtered, role)
continue roleSearch
}
}
return nil, fmt.Errorf("failed to find role %d for member", roleID)
}

discord.SortRolesByPosition(filtered)
return filtered, nil
}

////

// Permissions gets the user's permissions in the given channel. If the channel
Expand Down

0 comments on commit 966d966

Please sign in to comment.