From 7749800e1e305962adf4d1aed98ba919159cb3fa Mon Sep 17 00:00:00 2001 From: kar Date: Mon, 13 Oct 2025 20:16:41 -0600 Subject: [PATCH] Agregando bot --- umounting.go | 123 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 123 insertions(+) create mode 100644 umounting.go diff --git a/umounting.go b/umounting.go new file mode 100644 index 0000000..ba6e4ca --- /dev/null +++ b/umounting.go @@ -0,0 +1,123 @@ +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 + } +}