package telegram import ( "bufio" "encoding/json" "fmt" "log" "os" "github.com/fsnotify/fsnotify" tg "github.com/go-telegram-bot-api/telegram-bot-api/v5" ) const ( modsecLogFile = "/home/vomitblood/build/cspj-application/docker/chungus/logs/host-fs-auditlog.log" telegramToken = "7215466800:AAGwjZnXEfbbjQiA0y7qtSzbSZNUWQJnyjo" telegramChatID = 622943829 ) var lastReadPosition int64 = 0 type LogEntry struct { AuditData struct { Messages []string `json:"messages"` } `json:"audit_data"` } func TelegramBotInit() { bot, err := tg.NewBotAPI(telegramToken) if err != nil { log.Fatal("Failed to create Telegram bot:", err) } log.Println("Telegram bot connected") // send init message on startup testMsg := tg.NewMessage(telegramChatID, "I'm in") _, err = bot.Send(testMsg) if err != nil { log.Fatal("Failed to send test message:", err) } // Start watching the log file for changes watchLogFile(bot) } func watchLogFile(bot *tg.BotAPI) { watcher, err := fsnotify.NewWatcher() if err != nil { log.Fatal("Failed to initialize watcher:", err) } defer watcher.Close() // Add log file to watcher err = watcher.Add(modsecLogFile) if err != nil { log.Fatal("Failed to watch log file:", err) } log.Println("🔍 Monitoring log file for changes...") for { select { case event, ok := <-watcher.Events: if !ok { return } if event.Op&fsnotify.Write == fsnotify.Write { log.Println("📄 Log file updated, reading new entries...") readNewLines(bot) } case err, ok := <-watcher.Errors: if !ok { return } log.Println("⚠️ Watcher error:", err) } } } func readNewLines(bot *tg.BotAPI) { file, err := os.Open(modsecLogFile) if err != nil { log.Println("❌ Failed to reopen log file:", err) return } defer file.Close() // Move to the last read position file.Seek(lastReadPosition, os.SEEK_SET) scanner := bufio.NewScanner(file) for scanner.Scan() { line := scanner.Text() var logEntry LogEntry // Try to parse JSON if err := json.Unmarshal([]byte(line), &logEntry); err != nil { log.Println("⚠️ Failed to parse JSON:", err) continue // Skip invalid JSON lines } // Send only the first message from messages[] if len(logEntry.AuditData.Messages) > 0 { sendTelegramAlert(bot, logEntry.AuditData.Messages[0]) } } // Update last read position lastReadPosition, _ = file.Seek(0, os.SEEK_CUR) if err := scanner.Err(); err != nil { log.Println("❌ Error reading log file:", err) } } func sendTelegramAlert(bot *tg.BotAPI, message string) { msg := tg.NewMessage(telegramChatID, fmt.Sprintf("🚨 *WEEWOO ALERT* 🚨\n%s", message)) _, err := bot.Send(msg) if err != nil { log.Println("❌ Failed to send Telegram message:", err) } }