-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
226 lines (187 loc) · 5.27 KB
/
main.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
package main
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"time"
"github.com/broothie/qst"
"github.com/spf13/pflag"
)
const ApiVersion = "5.131"
var version = "" // Set during build via -ldflags
func main() {
configPath := pflag.StringP("config-path", "c", "./config.yaml", "path to config.yaml, file name can not be omitted")
shouldPrintVersion := pflag.BoolP("version", "v", false, "prints version")
pflag.Parse()
if *shouldPrintVersion {
fmt.Printf("%s\n", version)
return
}
config, err := LoadConfig(*configPath, true)
if err != nil {
fmt.Printf("Failed to load config from %q: %v\n", *configPath, err)
os.Exit(1)
}
if err := ValidateConfigValues(config); err != nil {
fmt.Printf("%v\n", err)
os.Exit(1)
}
tshockConfig, err := LoadTShockConfig(config.TShockConfigPath)
if err != nil {
fmt.Printf("Could not load read TShock config from (%q): %v\n", config.TShockConfigPath, err)
os.Exit(1)
}
if tshockConfig.RestApiEnabled == false {
fmt.Printf("Rest API is not enabled in TShock config (%q)\n", config.TShockConfigPath)
os.Exit(1)
}
if config.CommandPrefix == "" {
config.CommandPrefix = tshockConfig.CommandSpecifier
}
if config.RestAddr == "" {
config.RestAddr = fmt.Sprintf("http://127.0.0.1:%d", tshockConfig.RestApiPort)
}
http.HandleFunc("/", Handler(config, tshockConfig))
fmt.Printf("Starting callback server on port %d\n", config.Port)
if err := http.ListenAndServe(fmt.Sprintf(":%d", config.Port), nil); err != nil {
fmt.Printf("Failed to start callback server on port %d: %v\n", config.Port, err)
os.Exit(1)
}
}
func Handler(c Config, tc TShockConfig) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
// Deny all requests coming to an invalid path
if r.URL.Path != "/" {
w.WriteHeader(http.StatusNotFound)
return
}
req := struct {
EventType string `json:"type"`
Version string `json:"v"`
Secret string `json:"secret"`
Object struct {
Message struct {
FromID int `json:"from_id"`
PeerID int `json:"peer_id"`
MessageID int `json:"id"`
Text string `json:"text"`
} `json:"message"`
} `json:"object"`
}{}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
if req.Version != ApiVersion {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "unsupported callback api version; set it to %q", ApiVersion)
return
}
if req.Secret != c.VK.Secret {
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprintf(w, "incorrect secret")
return
}
if req.EventType == "confirmation" {
fmt.Fprintf(w, c.VK.ConfirmationToken)
return
}
fmt.Fprintf(w, "ok")
if req.EventType != "message_new" {
return
}
if !strings.HasPrefix(req.Object.Message.Text, c.CommandPrefix) {
return
}
for token, d := range tc.ApplicationRestTokens {
if d.VKId != req.Object.Message.FromID {
continue
}
output, err := ExecRESTCommand(c.RestAddr, token, req.Object.Message.Text)
if err != nil {
fmt.Printf("Failed to execute %q: %v\n", req.Object.Message.Text, err)
if err := SendVKMessage(
c.VK.Token,
req.Object.Message.PeerID,
req.Object.Message.MessageID,
c.Messages.RestRequestFailed,
c.VK.Keyboard,
); err != nil {
fmt.Printf("Failed to send VK reply: %v", err)
}
return
}
if output == "" {
output = c.Messages.NoCommandOutput
}
if c.RemoveChatTags {
output = regexp.MustCompile(`(?:\[c\/.+?:(.+?)\])|(?:\[i:.*?\])`).ReplaceAllString(output, "$1")
}
fmt.Printf("%s (%s) executed %s\n", d.Username, d.UserGroupName, req.Object.Message.Text)
if err := SendVKMessage(
c.VK.Token,
req.Object.Message.PeerID,
req.Object.Message.MessageID,
output,
c.VK.Keyboard,
); err != nil {
fmt.Printf("Failed to send VK reply: %v", err)
}
return
}
}
}
func SendVKMessage(token string, peerId, replyTo int, message string, keyboard any) error {
kb := ""
if keyboard != nil {
keyboardBytes, err := json.Marshal(keyboard)
if err != nil {
return err
}
kb = string(keyboardBytes)
}
r, err := qst.Get("https://api.vk.com/method/messages.send",
qst.QueryValue("access_token", token),
qst.QueryValue("message", message),
qst.QueryValue("peer_id", strconv.Itoa(peerId)),
qst.QueryValue("reply_to", strconv.Itoa(replyTo)),
qst.QueryValue("keyboard", kb),
qst.QueryValue("random_id", strconv.FormatInt(time.Now().UnixNano(), 10)),
qst.QueryValue("v", ApiVersion),
)
if err != nil {
return err
}
resp := struct {
Error map[any]any `json:"error"`
}{}
if err := json.NewDecoder(r.Body).Decode(&resp); err != nil {
return err
}
if resp.Error != nil {
b, _ := json.Marshal(resp.Error)
return errors.New(string(b))
}
return nil
}
func ExecRESTCommand(restAddr, token, command string) (string, error) {
data := struct {
OutputLines []string `json:"response"`
}{}
resp, err := qst.Get(strings.TrimSuffix(restAddr, "/")+"/v3/server/rawcmd",
qst.QueryValue("token", token),
qst.QueryValue("cmd", command),
)
if err != nil {
return "", err
}
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
return "", err
}
return strings.Join(data.OutputLines, "\n"), nil
}