2019-10-12 09:45:43 +07:00
|
|
|
package backend
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/bwmarrin/discordgo"
|
|
|
|
|
2019-10-16 04:35:02 +07:00
|
|
|
"TerraOceanBot/db"
|
2019-10-12 09:45:43 +07:00
|
|
|
"TerraOceanBot/discord/config"
|
|
|
|
)
|
|
|
|
|
|
|
|
var ErrMemberNotFound = errors.New("discord/backend: the requested member was not found")
|
|
|
|
|
|
|
|
func GetAllMembers(s *discordgo.Session) ([]*discordgo.Member, error) {
|
2019-10-18 15:56:14 +07:00
|
|
|
err := s.RequestGuildMembers(config.GuildID, "", 0)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2019-10-18 04:20:11 +07:00
|
|
|
guild, err := s.State.Guild(config.GuildID)
|
|
|
|
if err != nil {
|
|
|
|
guild, err = s.Guild(config.GuildID)
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2019-10-12 09:45:43 +07:00
|
|
|
}
|
2019-10-18 04:20:11 +07:00
|
|
|
return guild.Members, nil
|
2019-10-12 09:45:43 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
func GetMemberFromUserFriendlyName(s *discordgo.Session, user string) (*discordgo.Member, error) {
|
|
|
|
allMembers, err := GetAllMembers(s)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if strings.HasPrefix(user, "@") {
|
|
|
|
user = strings.TrimPrefix(user, "@")
|
|
|
|
} else if strings.HasSuffix(user, ">") {
|
|
|
|
if strings.HasPrefix(user, "<@!") {
|
|
|
|
user = strings.TrimSuffix(strings.TrimPrefix(user, "<@!"), ">")
|
|
|
|
} else if strings.HasPrefix(user, "<@") {
|
|
|
|
user = strings.TrimSuffix(strings.TrimPrefix(user, "<@"), ">")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if strings.ContainsRune(user, '#') {
|
|
|
|
list := strings.Split(user, "#")
|
|
|
|
username := strings.Join(list[:len(list)-1], "#")
|
|
|
|
discriminator := list[len(list)-1]
|
|
|
|
for _, v := range allMembers {
|
|
|
|
if v.User.Username == username && v.User.Discriminator == discriminator {
|
|
|
|
return v, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for _, v := range allMembers {
|
|
|
|
if v.User.ID == user {
|
|
|
|
return v, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for _, v := range allMembers {
|
|
|
|
if v.Nick == user {
|
|
|
|
return v, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for _, v := range allMembers {
|
|
|
|
if v.User.Username == user {
|
|
|
|
return v, nil
|
|
|
|
}
|
|
|
|
}
|
2019-10-16 04:35:02 +07:00
|
|
|
for _, v := range allMembers {
|
|
|
|
mcUsername, err := db.GetMinecraftUsername(v.User.ID)
|
|
|
|
if err == db.ErrNotFound {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if mcUsername == user {
|
|
|
|
return v, nil
|
|
|
|
}
|
|
|
|
}
|
2019-10-12 09:45:43 +07:00
|
|
|
return nil, ErrMemberNotFound
|
|
|
|
}
|