~mendelmaleh/tg_mcstatusbot

tg_mcstatusbot/main.go -rw-r--r-- 2.3 KiB
9f359caeMendel E Use akita, use go.mod, move commands to their own functions in commands.go 11 months ago
                                                                                
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package main

import (
	"encoding/binary"
	"fmt"
	"html"
	"io/ioutil"
	"log"
	"strings"

	"git.sr.ht/~mendelmaleh/akita"
	"git.sr.ht/~mendelmaleh/mcstatus"

	"github.com/go-telegram-bot-api/telegram-bot-api/v5"
	"github.com/pelletier/go-toml"
	"github.com/prologic/bitcask"
)

type Client struct {
	*akita.Akita
	*bitcask.Bitcask
	*mcstatus.MCServerStatus
}

type Config struct {
	Bot struct {
		Token string
		DB    string
	}
}

func mcStatusString(q string, s mcstatus.Status) string {
	var b strings.Builder

	// query, hostname, isonline
	b.WriteString(fmt.Sprintf("<a href=\"%s\">%s</a> is %s\n", s.Hostname, html.EscapeString(q), mcStatusOnlineString(s)))

	if !s.IsOnline {
		return b.String()
	}

	b.WriteString(fmt.Sprintf("- players: %d/%d\n", s.PlayersOnline, s.PlayersMax)) // players
	b.WriteString(fmt.Sprintf("- version: %s (%s)\n", s.Version, s.Software))       // version, software
	b.WriteString(fmt.Sprintf("- ip: <code>%s:%d</code>\n", s.IP, s.Port))          // ip, port

	return b.String()
}

func mcStatusOnlineString(s mcstatus.Status) string {
	if s.IsOnline {
		return "online"
	}

	return "not online"
}

func int64toBytes(i int64) []byte {
	b := make([]byte, 8)
	binary.LittleEndian.PutUint64(b, uint64(i))

	return b
}

func main() {
	// get and parse config
	doc, err := ioutil.ReadFile("config.toml")
	if err != nil {
		log.Panic(err)
	}

	var config Config
	if err := toml.Unmarshal(doc, &config); err != nil {
		log.Panic(err)
	}

	// setup db
	db, err := bitcask.Open(config.Bot.DB)
	if err != nil {
		log.Panic(err)
	}
	defer db.Close()

	// setup mc
	mc := mcstatus.New()

	// setup akita
	akita, err := akita.New(config.Bot.Token)
	if err != nil {
		log.Panic(err)
	}

	// akita.Debug = true
	log.Printf("Authorized on account %s", akita.Self.UserName)

	cl := Client{akita, db, mc}

	// register commands
	akita.Register("status", "get current status of minecraft server",
		func(u tgbotapi.Update) (tgbotapi.Chattable, error) { return cmdStatus(cl, u.Message) })
	akita.Register("default", "set the default server for the group, requires admin",
		func(u tgbotapi.Update) (tgbotapi.Chattable, error) { return cmdDefault(cl, u.Message) })

	akita.InlineQuery = func(u tgbotapi.Update) (tgbotapi.Chattable, error) { return inlineQuery(cl, u.InlineQuery) }

	akita.Route()
}