From db2f9eb29b0dbc41ca49b8947741e9b6f834a845 Mon Sep 17 00:00:00 2001 From: Chris Rhodes Date: Sat, 10 Dec 2016 21:37:11 -0800 Subject: [PATCH] Support getting the color of a user. (#299) --- state.go | 42 ++++++++++++++++++++++++++++++++++++++++++ structs.go | 14 ++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/state.go b/state.go index 1403d47..c7bd4c3 100644 --- a/state.go +++ b/state.go @@ -14,6 +14,7 @@ package discordgo import ( "errors" + "sort" "sync" ) @@ -749,3 +750,44 @@ func (s *State) UserChannelPermissions(userID, channelID string) (apermissions i return memberPermissions(guild, channel, member), nil } + +// UserColor returns the color of a user in a channel. +// While colors are defined at a Guild level, determining for a channel is more useful in message handlers. +// 0 is returned in cases of error, which is the color of @everyone. +// userID : The ID of the user to calculate the color for. +// channelID : The ID of the channel to calculate the color for. +func (s *State) UserColor(userID, channelID string) int { + if s == nil { + return 0 + } + + channel, err := s.Channel(channelID) + if err != nil { + return 0 + } + + guild, err := s.Guild(channel.GuildID) + if err != nil { + return 0 + } + + member, err := s.Member(guild.ID, userID) + if err != nil { + return 0 + } + + roles := Roles(guild.Roles) + sort.Sort(roles) + + for _, role := range roles { + for _, roleID := range member.Roles { + if role.ID == roleID { + if role.Color != 0 { + return role.Color + } + } + } + } + + return 0 +} diff --git a/structs.go b/structs.go index 548ee52..80022ad 100644 --- a/structs.go +++ b/structs.go @@ -252,6 +252,20 @@ type Role struct { Permissions int `json:"permissions"` } +type Roles []*Role + +func (r Roles) Len() int { + return len(r) +} + +func (r Roles) Less(i, j int) bool { + return r[i].Position > r[j].Position +} + +func (r Roles) Swap(i, j int) { + r[i], r[j] = r[j], r[i] +} + // A VoiceState stores the voice states of Guilds type VoiceState struct { UserID string `json:"user_id"`