124 lines
2.3 KiB
Go
124 lines
2.3 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"os"
|
|
"os/exec"
|
|
"os/user"
|
|
"strconv"
|
|
//"strings"
|
|
"time"
|
|
|
|
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
|
)
|
|
|
|
const (
|
|
telegramTokenID = "TELEGRAM_BOT_TOKEN"
|
|
telegramChatID = "TELEGRAM_CHAT_ID"
|
|
)
|
|
|
|
type HostInfo struct {
|
|
hostname string
|
|
date string
|
|
}
|
|
|
|
func sendInfo() HostInfo{
|
|
hostname, err := os.Hostname()
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
Info := HostInfo {
|
|
hostname: hostname,
|
|
date: time.Now().Format("2006-05-05 15:04:05"),
|
|
}
|
|
return Info
|
|
}
|
|
|
|
func checkId() bool {
|
|
currentUser, err := user.Current()
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
if currentUser.Uid == "0" {
|
|
return true
|
|
} else {
|
|
return false
|
|
}
|
|
}
|
|
|
|
func telegramBot(botToken string, chatID int64) {
|
|
theHostInfo := sendInfo()
|
|
bot, err := tgbotapi.NewBotAPI(botToken)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
updateConfig := tgbotapi.NewUpdate(0)
|
|
updateConfig.Timeout = 30
|
|
updates := bot.GetUpdatesChan(updateConfig)
|
|
|
|
|
|
for update := range updates {
|
|
if update.Message.Chat.ID != chatID {
|
|
continue
|
|
}
|
|
if update.Message == nil {
|
|
continue
|
|
}
|
|
if !update.Message.IsCommand() {
|
|
continue
|
|
}
|
|
|
|
var out string
|
|
switch update.Message.Command() {
|
|
case "umount":
|
|
out = umount(theHostInfo)
|
|
case "default":
|
|
out = fmt.Sprintf("Comando %s no reconocido", update.Message.Command())
|
|
}
|
|
data := fmt.Sprintf("Mensaje de host %s: %s\n", theHostInfo.hostname, out)
|
|
msg := tgbotapi.NewMessage(chatID, data)
|
|
_, err := bot.Send(msg)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func umount(h HostInfo) string {
|
|
if h.hostname == "alfa" {
|
|
cmd := exec.Command("umount", "/home/kar/pelis/pelis")
|
|
output, err := cmd.CombinedOutput()
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
return string(output)
|
|
} else if h.hostname == "jellyfin" {
|
|
cmd := exec.Command("umount", "/mnt/pelis")
|
|
output, err := cmd.CombinedOutput()
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
return string(output)
|
|
}
|
|
}
|
|
return "Error"
|
|
}
|
|
|
|
|
|
func main() {
|
|
botToken := os.Getenv(telegramTokenID)
|
|
tgChatId := os.Getenv(telegramChatID)
|
|
|
|
chatID, err := strconv.ParseInt(tgChatId, 10, 20)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
|
|
if checkId() {
|
|
telegramBot(botToken, chatID)
|
|
} else {
|
|
return
|
|
}
|
|
}
|