TerraOceanPlugin/GoBot/discord/backend/trust.go

97 lines
1.9 KiB
Go

2019-10-12 09:45:43 +07:00
package backend
2019-10-10 13:59:00 +07:00
import (
"errors"
"github.com/bwmarrin/discordgo"
2019-10-12 08:07:10 +07:00
"TerraOceanBot/db"
2019-10-12 09:45:43 +07:00
"TerraOceanBot/discord/config"
)
2019-10-11 12:25:09 +07:00
var trustCache map[string]float64
2019-10-12 09:45:43 +07:00
var ErrNotMember = errors.New("trust: only members have trust value")
2019-10-12 09:45:43 +07:00
func GetTrust(s *discordgo.Session, discordID string) (float64, error) {
2019-10-11 12:25:09 +07:00
if v, ok := trustCache[discordID]; ok {
return v, nil
}
2019-10-12 09:45:43 +07:00
member, err := s.GuildMember(config.GuildID, discordID)
if err != nil {
return 0.0, err
}
isMember := false
for _, role := range member.Roles {
2019-10-12 09:45:43 +07:00
if role == config.MemberRoleID {
isMember = true
}
}
if !isMember {
2019-10-12 09:45:43 +07:00
return 0.0, ErrNotMember
}
2019-10-12 08:07:10 +07:00
votes, err := db.GetTrustVote(discordID)
2019-10-11 12:25:09 +07:00
if err != nil {
return 0.0, err
}
if len(votes) == 0 {
return 0.0, nil
}
2019-10-11 12:25:09 +07:00
var total float64
for _, v := range votes {
total += float64(v)
}
voteResult := total / float64(len(votes))
//Calculate active level
totalLevel, err := db.GetTotalActiveLevel()
if err != nil {
return voteResult, nil
}
if totalLevel < 1000000 {
return voteResult, 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 voteResult * (1 + activeBuff), nil
2019-10-11 12:25:09 +07:00
}
2019-10-12 09:45:43 +07:00
func GetTotalTrust(s *discordgo.Session) (float64, error) {
members, err := GetAllMembers(s)
2019-10-11 12:25:09 +07:00
if err != nil {
return 0.0, err
}
var total float64
for _, member := range members {
isMember := false
for _, role := range member.Roles {
2019-10-12 09:45:43 +07:00
if role == config.MemberRoleID {
isMember = true
}
}
if !isMember {
continue
}
2019-10-12 09:45:43 +07:00
trust, err := GetTrust(s, member.User.ID)
2019-10-11 12:25:09 +07:00
if err != nil {
return 0.0, err
}
total += trust
}
return total, nil
2019-10-10 13:59:00 +07:00
}
2019-10-12 09:45:43 +07:00
func UpdateTrust(sourceID, targetID string, voteValue int) error {
2019-10-12 08:07:10 +07:00
err := db.UpdateTrust(sourceID, targetID, voteValue, false)
if err != nil {
return err
}
delete(trustCache, targetID)
return nil
}