From f75d834aa5470329d5adace32671e326f1326052 Mon Sep 17 00:00:00 2001 From: ozraru Date: Sun, 13 Apr 2025 22:55:15 +0900 Subject: [PATCH] feat(User): add DisplayName method (#1609) --- structs.go | 2 +- structs_test.go | 5 +++-- user.go | 8 ++++++++ user_test.go | 21 +++++++++++++++++++++ 4 files changed, 33 insertions(+), 3 deletions(-) diff --git a/structs.go b/structs.go index 3b251c0..52900eb 100644 --- a/structs.go +++ b/structs.go @@ -1635,7 +1635,7 @@ func (m *Member) DisplayName() string { if m.Nick != "" { return m.Nick } - return m.User.GlobalName + return m.User.DisplayName() } // ClientStatus stores the online, offline, idle, or dnd status of each device of a Guild member. diff --git a/structs_test.go b/structs_test.go index cde5520..dea29c4 100644 --- a/structs_test.go +++ b/structs_test.go @@ -20,8 +20,9 @@ func TestMember_DisplayName(t *testing.T) { Nick: "", User: user, } - if dn := m.DisplayName(); dn != user.GlobalName { - t.Errorf("Member.DisplayName() = %v, want %v", dn, user.GlobalName) + want := user.DisplayName() + if dn := m.DisplayName(); dn != want { + t.Errorf("Member.DisplayName() = %v, want %v", dn, want) } }) t.Run("server nickname set", func(t *testing.T) { diff --git a/user.go b/user.go index 5dda456..9cf4802 100644 --- a/user.go +++ b/user.go @@ -152,3 +152,11 @@ func (u *User) DefaultAvatarIndex() int { id, _ := strconv.Atoi(u.Discriminator) return id % 5 } + +// DisplayName returns the user's global name if they have one, otherwise it returns their username. +func (u *User) DisplayName() string { + if u.GlobalName != "" { + return u.GlobalName + } + return u.Username +} diff --git a/user_test.go b/user_test.go index 22b1bd7..20c7f4f 100644 --- a/user_test.go +++ b/user_test.go @@ -35,3 +35,24 @@ func TestUser_String(t *testing.T) { }) } } + +func TestUser_DisplayName(t *testing.T) { + t.Run("no global name set", func(t *testing.T) { + u := &User{ + GlobalName: "", + Username: "username", + } + if dn := u.DisplayName(); dn != u.Username { + t.Errorf("User.DisplayName() = %v, want %v", dn, u.Username) + } + }) + t.Run("global name set", func(t *testing.T) { + u := &User{ + GlobalName: "global", + Username: "username", + } + if dn := u.DisplayName(); dn != u.GlobalName { + t.Errorf("User.DisplayName() = %v, want %v", dn, u.GlobalName) + } + }) +}