-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
312 lines (262 loc) · 7.17 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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"strconv"
"strings"
"time"
)
const (
telegramAPIURL = "https://api.telegram.org/bot"
)
var (
telegramBotToken string
configFilePath string
configuration Config
services string
pollingRate time.Duration
)
//**********//
// CONFIG //
//**********//
type Config struct {
AdminId int `json:"adminTelegramId"`
Whitelist map[int]User `json:"whitelist"`
Localization map[string]map[string]Status `json:"localization"`
Hub map[string]Service `json:"hub"`
}
type User struct {
Username string `json:"username"`
Locale string `json:"locale"`
}
type Status struct {
Text string `json:"text"`
}
type Service struct {
Path string `json:"path"`
}
//************//
// TELEGRAM //
//************//
type Update struct {
UpdateID int `json:"update_id"`
Message Message `json:"message"`
CallbackQuery CallbackQuery `json:"callback_query,omitempty"`
}
type CallbackQuery struct {
Data string `json:"data"`
Message Message `json:"message"`
}
type Message struct {
MessageId int `json:"message_id"`
Chat Chat `json:"chat"`
Text string `json:"text"`
}
type Chat struct {
Id int `json:"id"`
Username *string `json:"username,omitempty"`
Firstname *string `json:"first_name,omitempty"`
Lastname *string `json:"last_name,omitempty"`
}
//********//
// main //
//********//
func main() {
telegramBotToken = os.Getenv("TELEGRAM_BOT_TOKEN")
if telegramBotToken == "" {
fmt.Println("Error: TELEGRAM_BOT_TOKEN must be set")
os.Exit(1)
}
configFilePath = os.Getenv("CONFIG_FILE_PATH")
if configFilePath == "" {
fmt.Println("Error: CONFIG_FILE_PATH must be set")
os.Exit(1)
}
loadConfigFile()
offset := 0
pollingRate = 5 * time.Second
fmt.Println("Starting polling...")
for {
updates, err := getUpdates(offset)
if err != nil {
fmt.Println("Error getting updates:", err)
time.Sleep(pollingRate)
continue
}
for _, update := range updates {
go processUpdate(update)
offset = update.UpdateID + 1
}
time.Sleep(pollingRate)
}
}
func getUpdates(offset int) ([]Update, error) {
resp, err := http.Get(telegramAPIURL + telegramBotToken + "/getUpdates?offset=" + strconv.Itoa(offset))
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var result struct {
OK bool `json:"ok"`
Result []Update `json:"result"`
}
err = json.Unmarshal(body, &result)
if err != nil {
return nil, err
}
return result.Result, nil
}
func processUpdate(update Update) {
fmt.Println("Found an update from telegram...")
var chatId int
if update.CallbackQuery.Data != "" {
chatId = update.CallbackQuery.Message.Chat.Id
} else {
chatId = update.Message.Chat.Id
}
_, isAuthorizedUser := configuration.Whitelist[chatId]
if !isAuthorizedUser {
fmt.Printf("Unauthorized telegram id %d tried to access the bot\n", chatId)
return
}
if update.CallbackQuery.Data != "" {
handleCallbackQuery(update.CallbackQuery.Data, chatId)
return
}
handleInput(update.Message.Text, chatId)
}
func handleInput(input string, chatId int) {
if strings.HasPrefix(input, "/") {
handleCommand(strings.ToLower(input[1:]), chatId)
} else {
sendMessage(chatId, configuration.Localization[configuration.Whitelist[chatId].Locale]["malformed"].Text)
}
}
func handleCommand(input string, chatId int) {
switch input {
case "start":
err := sendLanguageSelectionButtons(chatId, "ㅤㅤ( ノ ゚ー゚)ノ")
if err != nil {
fmt.Println("Error sending message: ", err)
}
return
case "help":
sendMessage(chatId, services)
return
default:
if strings.HasPrefix(input, "stop") {
if chatId == configuration.AdminId {
if len(input) >= 6 && input[5] != ' ' {
handleService(input[5:], chatId, "stop.sh")
} else {
sendMessage(chatId, configuration.Localization[configuration.Whitelist[chatId].Locale]["malformed"].Text)
}
} else {
sendMessage(chatId, configuration.Localization[configuration.Whitelist[chatId].Locale]["unauthorized"].Text)
}
} else {
handleService(input, chatId, "start.sh")
}
return
}
}
func handleService(input string, chatId int, command string) {
service, supported := configuration.Hub[input]
if !supported {
sendMessage(chatId, configuration.Localization[configuration.Whitelist[chatId].Locale]["unimplemented"].Text)
} else {
err := commandService(service, command)
if err != nil {
sendMessage(chatId, configuration.Localization[configuration.Whitelist[chatId].Locale]["failure"].Text)
return
}
sendMessage(chatId, configuration.Localization[configuration.Whitelist[chatId].Locale]["success"].Text)
}
}
func commandService(service Service, scriptName string) error {
cmd := exec.Command("sudo", "-u", "root", service.Path+scriptName)
return cmd.Run()
}
func loadConfigFile() {
file, _ := os.ReadFile(configFilePath)
json.Unmarshal(file, &configuration)
servicesArray := make([]string, len(configuration.Hub))
i := 0
for s := range configuration.Hub {
servicesArray[i] = s
i++
}
services = "/" + strings.Join(servicesArray, " /")
}
func sendMessage(chatID int, text string) {
text = strings.ReplaceAll(text, "%s", configuration.Whitelist[chatID].Username)
url := fmt.Sprintf("%s%s/sendMessage?chat_id=%d&text=%s", telegramAPIURL, telegramBotToken, chatID, text)
resp, err := http.Get(url)
if err != nil {
fmt.Println("Error sending message: ", err)
} else {
defer resp.Body.Close()
}
}
func handleCallbackQuery(locale string, chatId int) {
switch locale {
case "it":
updateLocale("it", chatId)
default:
updateLocale("en", chatId)
}
}
func updateLocale(locale string, chatId int) {
if userEntry, ok := configuration.Whitelist[chatId]; ok {
userEntry.Locale = locale
configuration.Whitelist[chatId] = userEntry
}
writeToConfigFile()
sendMessage(chatId, configuration.Localization[locale]["welcome"].Text)
}
func writeToConfigFile() error {
updatedJSON, err := json.MarshalIndent(configuration, "", " ")
if err != nil {
return err
}
return os.WriteFile(configFilePath, updatedJSON, 0644)
}
func sendLanguageSelectionButtons(chatID int, text string) error {
keyboard := struct {
InlineKeyboard [][]struct {
Text string `json:"text"`
CallbackData string `json:"callback_data"`
} `json:"inline_keyboard"`
}{
InlineKeyboard: [][]struct {
Text string `json:"text"`
CallbackData string `json:"callback_data"`
}{
{
{Text: "🇮🇹", CallbackData: "it"},
{Text: "🇬🇧", CallbackData: "en"},
},
},
}
keyboardJSON, err := json.Marshal(keyboard)
if err != nil {
return err
}
formData := fmt.Sprintf("chat_id=%d&text=%s&reply_markup=%s", chatID, text, keyboardJSON)
contentType := "application/x-www-form-urlencoded"
url := fmt.Sprintf("%s%s/sendMessage", telegramAPIURL, telegramBotToken)
resp, err := http.Post(url, contentType, strings.NewReader(formData))
if err != nil {
return err
}
defer resp.Body.Close()
return nil
}