xp: Implement level role

master 0.2
Luther Wen Xu 2019-11-18 13:11:36 +07:00
parent f1112c2fbf
commit 5ce16fcbd0
Signed by: chanbakjsd
GPG Key ID: B7D77E3E9D102B70
4 changed files with 56 additions and 0 deletions

1
.gitignore vendored

@ -1,2 +1,3 @@
token.txt token.txt
roles.txt
bot.db bot.db

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

@ -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)
}
}

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