From 5ce16fcbd0cce8bcc5d60f475edbfe41d62d21b0 Mon Sep 17 00:00:00 2001 From: Luther Wen Xu Date: Mon, 18 Nov 2019 13:11:36 +0800 Subject: [PATCH] xp: Implement level role --- .gitignore | 1 + main.go | 1 + roles.go | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ xp.go | 1 + 4 files changed, 56 insertions(+) create mode 100644 roles.go diff --git a/.gitignore b/.gitignore index 850f576..1c90908 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ token.txt +roles.txt bot.db diff --git a/main.go b/main.go index 4bf0b8f..e294c4e 100644 --- a/main.go +++ b/main.go @@ -24,6 +24,7 @@ func main() { if err != nil { fmt.Println("Error opening Discord session:", err) } + go assignRole(dg) sc := make(chan os.Signal, 1) signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill) diff --git a/roles.go b/roles.go new file mode 100644 index 0000000..e1a44b8 --- /dev/null +++ b/roles.go @@ -0,0 +1,53 @@ +package main + +import ( + "io/ioutil" + "strings" + "sync" + "time" + + "github.com/bwmarrin/discordgo" +) + +const guildID = "645550569573842945" + +var roleMutex sync.Mutex +var roleQueue = make(map[string]bool) +var assignedRoles = make(map[string]int) +var roleFromLevel []string + +func init() { + roles, _ := ioutil.ReadFile("roles.txt") + roleFromLevel = strings.Split(string(roles), "\n") + for k, v := range roleFromLevel { + roleFromLevel[k] = strings.TrimSpace(v) + } +} + +func addToRoleQueue(discordID string) { + roleMutex.Lock() + defer roleMutex.Unlock() + roleQueue[discordID] = true +} + +func assignRole(dg *discordgo.Session) { + for { + roleMutex.Lock() + for k, v := range roleQueue { + if !v { + continue + } + roleQueue[k] = false + level, _ := getLevelAndXP(dg, k) + if assignedRoles[k] != level { + assignedRoles[k] = level + err := dg.GuildMemberRoleAdd(guildID, k, roleFromLevel[level-1]) + if err != nil { + logError(dg, "assignRole", err) + } + } + } + roleMutex.Unlock() + time.Sleep(5 * time.Second) + } +} diff --git a/xp.go b/xp.go index 3998790..09be34e 100644 --- a/xp.go +++ b/xp.go @@ -51,6 +51,7 @@ func incrementXP(dg *discordgo.Session, discordID string) { logError(dg, "incrementXP", "commit", discordID, err) return } + addToRoleQueue(discordID) } func getLevelAndXP(dg *discordgo.Session, discordID string) (int, int) {