From d273102aa2762f17f45c84bdaaa60beb75d854f8 Mon Sep 17 00:00:00 2001 From: Luther Wen Xu Date: Sat, 30 May 2020 22:50:26 +0800 Subject: [PATCH] feat: Add level roles --- commands/{recalcLevel.go => migrate.go} | 0 config.go | 1 + level/listener.go | 5 +++ level/roles.go | 47 +++++++++++++++++++++++++ main.go | 3 ++ 5 files changed, 56 insertions(+) rename commands/{recalcLevel.go => migrate.go} (100%) create mode 100644 level/roles.go diff --git a/commands/recalcLevel.go b/commands/migrate.go similarity index 100% rename from commands/recalcLevel.go rename to commands/migrate.go diff --git a/config.go b/config.go index ebbfda5..b289b7d 100644 --- a/config.go +++ b/config.go @@ -9,6 +9,7 @@ import ( type config struct { Token string ReportTarget string `toml:"report_target"` + LevelRoles []string `toml:"level_roles"` MacroReplace map[string]string `toml:"macro_replace"` Macro map[string]string } diff --git a/level/listener.go b/level/listener.go index 11190ad..c231653 100644 --- a/level/listener.go +++ b/level/listener.go @@ -31,4 +31,9 @@ func Event(dg *discordgo.Session, m *discordgo.MessageCreate) { xp = 0 } db.IncrementXP(m.Author.ID, xp, nextTime) + + if _, ok := ShouldCheck[m.GuildID]; !ok { + ShouldCheck[m.GuildID] = make(map[string]bool) + } + ShouldCheck[m.GuildID][m.Author.ID] = true } diff --git a/level/roles.go b/level/roles.go new file mode 100644 index 0000000..6024a70 --- /dev/null +++ b/level/roles.go @@ -0,0 +1,47 @@ +package level + +import ( + "time" + + "github.com/bwmarrin/discordgo" + + "gitea.teamortix.com/chanbakjsd/Milen/db" + "gitea.teamortix.com/chanbakjsd/Milen/util" +) + +var Roles []string + +var ShouldCheck = make(map[string]map[string]bool) + +func QueueRoles(dg *discordgo.Session) { + for { + time.Sleep(5 * time.Second) + for guildID, v := range ShouldCheck { + for userID, _ := range v { + rank, _ := GetLevelFromXP(db.GetXP(userID)) + AssignRoles(dg, guildID, userID, rank) + delete(v, userID) + } + } + } +} + +func AssignRoles(dg *discordgo.Session, guildID string, userID string, rank Rank) { + member, err := util.GetMember(dg, guildID, userID) + if err != nil { + util.ReportError(dg, err) + return + } +OuterLoop: + for i := 0; i <= int(rank); i++ { + if i >= len(Roles) { + return + } + for _, v := range member.Roles { + if v == Roles[i] { + continue OuterLoop + } + } + dg.GuildMemberRoleAdd(guildID, userID, Roles[i]) + } +} diff --git a/main.go b/main.go index 3998daf..80894e2 100644 --- a/main.go +++ b/main.go @@ -19,6 +19,7 @@ func main() { cfg := LoadConfig() commands.CommonReplacement = cfg.MacroReplace commands.Macro = cfg.Macro + level.Roles = cfg.LevelRoles util.ReportTarget = cfg.ReportTarget dg, err := discordgo.New("Bot " + cfg.Token) @@ -32,6 +33,8 @@ func main() { dg.AddHandler(reactrole.EventAdd) dg.AddHandler(reactrole.EventRemove) + go level.QueueRoles(dg) + err = dg.Open() if err != nil { fmt.Println("error opening connection,", err)