level: Generalize level processing instead of labelling it as roles

master
Luther Wen Xu 2019-11-18 15:30:21 +07:00
parent 5a20314f4f
commit 38a9d2eda2
Signed by: chanbakjsd
GPG Key ID: B7D77E3E9D102B70
4 changed files with 55 additions and 55 deletions

@ -0,0 +1,53 @@
package main
import (
"io/ioutil"
"strings"
"sync"
"time"
"github.com/bwmarrin/discordgo"
)
const guildID = "645550569573842945"
var levelMutex sync.Mutex
var levelQueue = make(map[string]bool)
var assignedLevels = make(map[string]int)
var rolesFromLevel []string
func init() {
levels, _ := ioutil.ReadFile("levels.txt")
rolesFromLevel = strings.Split(string(levels), "\n")
for k, v := range rolesFromLevel {
rolesFromLevel[k] = strings.TrimSpace(v)
}
}
func addToLevelQueue(discordID string) {
levelMutex.Lock()
defer levelMutex.Unlock()
levelQueue[discordID] = true
}
func listenToLevelUpdate(dg *discordgo.Session) {
for {
levelMutex.Lock()
for k, v := range levelQueue {
if !v {
continue
}
levelQueue[k] = false
level, _ := getLevelAndXP(dg, k)
if assignedLevels[k] != level {
assignedLevels[k] = level
err := dg.GuildMemberRoleAdd(guildID, k, rolesFromLevel[level-1])
if err != nil {
logError(dg, "assignlevel", err)
}
}
}
levelMutex.Unlock()
time.Sleep(5 * time.Second)
}
}

@ -24,7 +24,7 @@ func main() {
if err != nil {
fmt.Println("Error opening Discord session:", err)
}
go assignRole(dg)
go listenToLevelUpdate(dg)
sc := make(chan os.Signal, 1)
signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)

@ -1,53 +0,0 @@
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)
}
}

@ -51,7 +51,7 @@ func incrementXP(dg *discordgo.Session, discordID string) {
logError(dg, "incrementXP", "commit", discordID, err)
return
}
addToRoleQueue(discordID)
addToLevelQueue(discordID)
}
func getLevelAndXP(dg *discordgo.Session, discordID string) (int, int) {