residentsleeper/rcon/players.go

82 lines
1.5 KiB
Go

package rcon
import (
"errors"
"fmt"
"regexp"
"strconv"
"strings"
)
var (
userRegexp = regexp.MustCompile("There are (\\d+) of a max of (\\d+) players online: (.*?)$")
teleportedRegexp = regexp.MustCompile("^Teleported (.*?) to (.*?)$")
)
func (r *Session) OnlinePlayers() (int, int, []string, error) {
res, err := r.connection().SendCommand("list")
if err != nil {
return -1, -1, nil, err
}
m := userRegexp.FindStringSubmatch(res)
if m == nil {
return -1, -1, nil, errors.New("unexpected response")
}
online, _ := strconv.Atoi(m[1])
max, _ := strconv.Atoi(m[2])
names := strings.Split(m[3], ", ")
return online, max, names, nil
}
func (r *Session) GetLocation(user string) []float32 {
res, err := r.connection().SendCommand(fmt.Sprintf("execute at %s run tp %s ~ ~ ~", user, user))
if err != nil {
return nil
}
m := teleportedRegexp.FindStringSubmatch(res)
pos, err := SliceToFloats(strings.Split(m[2], ","))
if err != nil {
return nil
}
ret := make([]float32, 3)
for i, v := range pos {
ret[i] = float32(v)
}
return ret
}
func (r *Session) Teleport(user, destination string) (string, error) {
return r.connection().SendCommand(fmt.Sprintf("tp %s %s", user, destination))
}
func SliceToFloats(str []string) ([]float64, error) {
ret := make([]float64, len(str))
var err error
for i, s := range str {
s = strings.TrimSpace(s)
ret[i], err = strconv.ParseFloat(s, 64)
if err != nil {
return nil, err
}
}
return ret, err
}