From e4f8f523aed3c7b06b9472c5fa244ad9f96a265b Mon Sep 17 00:00:00 2001 From: Luther Wen Xu Date: Sun, 31 May 2020 12:35:54 +0800 Subject: [PATCH] feat: Add leaderboard --- commands/commands.go | 3 ++- commands/leaderboard.go | 40 ++++++++++++++++++++++++++++++++++++++++ db/level.go | 6 ++++++ 3 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 commands/leaderboard.go diff --git a/commands/commands.go b/commands/commands.go index 4d2eab3..639bc28 100644 --- a/commands/commands.go +++ b/commands/commands.go @@ -19,8 +19,9 @@ type command struct { var commands = []command{ command{"autorole", " ", handleAutorole, 3, true}, - command{"recalclevel", "", handleRecalculateLevel, 0, false}, + command{"leaderboard", "", handleLeaderboard, 0, true}, command{"level", "", handleLevel, 0, false}, + command{"recalclevel", "", handleRecalculateLevel, 0, false}, } func Event(dg *discordgo.Session, m *discordgo.MessageCreate) { diff --git a/commands/leaderboard.go b/commands/leaderboard.go new file mode 100644 index 0000000..800dbd1 --- /dev/null +++ b/commands/leaderboard.go @@ -0,0 +1,40 @@ +package commands + +import ( + "github.com/bwmarrin/discordgo" + + "gitea.teamortix.com/chanbakjsd/Milen/db" + "gitea.teamortix.com/chanbakjsd/Milen/level" + "gitea.teamortix.com/chanbakjsd/Milen/util" +) + +var leaderboardEmoji = []string{"🏆", "🥈", "🥉", "⬛", "◼️"} + +func handleLeaderboard(dg *discordgo.Session, m *discordgo.MessageCreate, arguments []string) { + topFive := db.GetTopFive() + + fields := make([]*discordgo.MessageEmbedField, 0, len(topFive)) + for k, v := range topFive { + member, err := util.GetMember(dg, m.GuildID, v.UserID) + var displayName string + if err == nil { + if member.Nick != "" { + displayName = member.Nick + " (" + member.User.Username + "#" + member.User.Discriminator + ")" + } else { + displayName = member.User.Username + "#" + member.User.Discriminator + } + } else { + displayName = "??? (" + v.UserID + ")" + } + rank, level := level.GetLevelFromXP(v.XP) + fields = append(fields, &discordgo.MessageEmbedField{ + Name: leaderboardEmoji[k] + " " + displayName, + Value: rank.String() + " " + util.FormatRomanNumeral(level) + " (" + util.FormatPlural(v.XP, "second", "seconds") + ")", + }) + } + + util.SendEmbed(dg, m.ChannelID, &discordgo.MessageEmbed{ + Title: "Leaderboard", + Fields: fields, + }) +} diff --git a/db/level.go b/db/level.go index 4552752..d0ca916 100644 --- a/db/level.go +++ b/db/level.go @@ -12,6 +12,12 @@ type PlayerLevel struct { XP int64 } +func GetTopFive() []PlayerLevel { + var results []PlayerLevel + db.Model(&PlayerLevel{}).Order("xp desc").Limit(5).Find(&results) + return results +} + func GetXP(userID string) int64 { result := PlayerLevel{ UserID: userID,