TerraOceanPlugin/GoBot/discord/backend/trust.go

107 lines
2.2 KiB
Go

package backend
import (
"errors"
"github.com/bwmarrin/discordgo"
"TerraOceanBot/db"
"TerraOceanBot/discord/config"
)
var trustCache = make(map[string]float64)
var ErrNotMember = errors.New("trust: only members have trust value")
func GetTrust(s *discordgo.Session, discordID string) (float64, error) {
rawScore, err := GetRawTrust(s, discordID)
if err != nil {
return 0.0, err
}
//Calculate active level
totalLevel, err := db.GetTotalActiveLevel()
if err != nil {
return rawScore, nil
}
if totalLevel < 1000000 {
return rawScore, nil
}
activeLevel, err := db.GetActiveLevel(discordID)
if err != nil && err != db.ErrNotFound {
//ErrNotFound is allowed. It just means the player hasn't played yet.
return 0.0, err
}
activeBuff := float64(activeLevel) / float64(totalLevel)
return rawScore * (1 + activeBuff), nil
}
func GetRawTrust(s *discordgo.Session, discordID string) (float64, error) {
if v, ok := trustCache[discordID]; ok {
return v, nil
}
member, err := s.GuildMember(config.GuildID, discordID)
if err != nil {
return 0.0, err
}
isMember := false
for _, role := range member.Roles {
if role == config.MemberRoleID {
isMember = true
}
}
if !isMember {
return 0.0, ErrNotMember
}
votes, err := db.GetTrustVote(discordID)
if err != nil {
return 0.0, err
}
if len(votes) == 0 {
return 0.0, nil
}
var total float64
for _, v := range votes {
total += float64(v)
}
rawScore := total / float64(len(votes))
trustCache[discordID] = rawScore
return rawScore, nil
}
func GetTotalTrust(s *discordgo.Session) (float64, error) {
members, err := GetAllMembers(s)
if err != nil {
return 0.0, err
}
var total float64
for _, member := range members {
isMember := false
for _, role := range member.Roles {
if role == config.MemberRoleID {
isMember = true
}
}
if !isMember {
continue
}
trust, err := GetTrust(s, member.User.ID)
if err != nil {
return 0.0, err
}
total += trust
}
return total, nil
}
func UpdateTrust(sourceID, targetID string, voteValue int) error {
err := db.UpdateTrust(sourceID, targetID, voteValue, false)
if err != nil {
return err
}
delete(trustCache, targetID)
return nil
}