-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathteamspeak.go
87 lines (70 loc) · 2.02 KB
/
teamspeak.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package main
import (
"cmp"
"fmt"
"log"
"slices"
"strings"
"time"
"github.com/ziutek/telnet"
)
const (
tsPrefix = "[TeamSpeak]\t"
)
// newTeamSpeakConn initiates the telnet connection to a TeamSpeak server
func (tsConfig *TeamSpeak) newTeamSpeakConn() *telnet.Conn {
conn, err := telnet.DialTimeout("tcp", tsConfig.Address, 5*time.Second)
if err != nil {
log.Fatal(err)
}
// skip until banner end is reached
if err = conn.SkipUntil("command."); err != nil {
log.Fatal(err)
}
conn.Write([]byte(fmt.Sprintf("login %s %s\n", tsConfig.Username, tsConfig.Password)))
if err = conn.SkipUntil("msg=ok"); err != nil {
log.Fatal(err)
}
conn.Write([]byte(fmt.Sprintf("use %s\n", tsConfig.VirtualServerId)))
if err = conn.SkipUntil("msg=ok"); err != nil {
log.Fatal(err)
}
log.Printf("%s connected to telnet", tsPrefix)
return conn
}
// getOnlineUsers checks the online users and filters by favorites if they're defined
func (tsConfig *TeamSpeak) getOnlineUsers(conn *telnet.Conn) []string {
// login, select server and return clientlist
conn.Write([]byte("clientlist\n"))
time.Sleep(1 * time.Second)
// get clientlist
result, err := conn.ReadUntil("msg=ok")
if err != nil {
log.Fatal(err)
}
// log.Printf("%s received clientlist", tsPrefix)
// parse clientlist
clients := strings.Split(string(result), "|")
var users []string
for _, client := range clients {
fields := strings.Fields(client)
if clientType := strings.Split(fields[4], "=")[1]; clientType != "0" {
continue
}
username := strings.Split(fields[3], "=")[1]
username = strings.ReplaceAll(username, "\\s", " ")
if len(tsConfig.FavoriteUsers) != 0 {
if slices.Contains(tsConfig.FavoriteUsers, username) {
users = append(users, username)
}
continue
}
users = append(users, username)
}
// sort by name length to display as much as possible on smaller screens
slices.SortFunc(users, func(a, b string) int {
return cmp.Compare(len(a), len(b))
})
// log.Printf("%s %d connected users", tsPrefix, len(users))
return users
}