A modification-free API for Minecraft utilizing log parsing
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

116 lines
2.0 KiB

package rcon
import (
"encoding/json"
"fmt"
log "github.com/sirupsen/logrus"
"github.com/tystuyfzand/mcgorcon"
"time"
)
const (
pingDuration = 30 * time.Second
)
type Session struct {
host string
port int
password string
Debug bool
client *mcgorcon.Client
lastUse time.Time
}
func NewSession(host string, port int, password string) *Session {
return &Session{host: host, port: port, password: password}
}
func (r *Session) Disconnect() {
if r.client != nil {
r.client.Close()
}
}
func (r *Session) connection() *mcgorcon.Client {
if r.client != nil {
if time.Since(r.lastUse) > pingDuration {
_, err := r.client.SendCommand("seed")
if err == nil {
r.lastUse = time.Now()
return r.client
}
} else {
return r.client
}
}
// Open new connection
r.client = r.openConnection()
r.lastUse = time.Now()
return r.client
}
func (r *Session) openConnection() *mcgorcon.Client {
var c *mcgorcon.Client
var err error
for c == nil || err != nil {
c, err = mcgorcon.Dial(r.host, r.port, r.password)
if err == nil {
break
}
<-time.After(10 * time.Second)
}
log.WithFields(log.Fields{
"host": r.host,
"port": r.port,
}).Info("Connection opened")
return c
}
func (r *Session) SendCommand(command string) (string, error) {
log.WithField("command", command).Debug("Sending command")
return r.connection().SendCommand(command)
}
func (r *Session) ServerMessage(message string) error {
_, err := r.SendCommand(fmt.Sprintf("say %s", message))
return err
}
func (r *Session) SendMessage(user, message string) error {
_, err := r.SendCommand(fmt.Sprintf("msg %s %s", user, message))
return err
}
type colorMessage struct {
Text string `json:"text"`
Color string `json:"color"`
}
func (r *Session) SendColorfulMessage(target, color, message string) error {
messages := []colorMessage{
{Text: message, Color: color},
}
b, err := json.Marshal(messages)
if err != nil {
return err
}
_, err = r.SendCommand(fmt.Sprintf("tellraw %s %s", target, string(b)))
return err
}