From 547506036ed53cc003d29b00e2962aef46e1ab5e Mon Sep 17 00:00:00 2001 From: nomadics9 Date: Tue, 24 Dec 2024 01:48:23 +0300 Subject: [PATCH] Webhook added for kubewatch notifcation --- .gitignore | 1 + main.go | 43 ++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index ca445e8..4fa932f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ .env .botenv +api-server diff --git a/main.go b/main.go index d09bd83..e5b59bd 100644 --- a/main.go +++ b/main.go @@ -80,7 +80,6 @@ func bumpVersionTv(repoPath string) { if err := scanner.Err(); err != nil { fmt.Errorf("error reading %s: %w", filePath, err) } - // Write the updated content back to the file if err := os.WriteFile(filePath, []byte(updatedContent), 0644); err != nil { fmt.Errorf("failed to write to %s: %w", filePath, err) } @@ -89,6 +88,46 @@ func bumpVersionTv(repoPath string) { } +func notifyHandler(c *gin.Context) { + var data struct { + Name string `json:"name"` + Image string `json:"image"` + } + + if err := c.ShouldBindJSON(&data); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid JSON"}) + return + } + + if data.Name == "" { + data.Name = "unknown" + } + if data.Image == "" { + data.Image = "unknown" + } + + godotenv.Load(".botenv") + botToken := os.Getenv("BOT_TOKEN") + chatid := os.Getenv("CHAT_ID") + + telegramToken := botToken + chatID := chatid + message := fmt.Sprintf("Service '%s' was updated to image '%s'", data.Name, data.Image) + + telegramAPI := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", telegramToken) + resp, err := http.PostForm(telegramAPI, url.Values{ + "chat_id": {chatID}, + "text": {message}, + }) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to send Telegram message"}) + return + } + defer resp.Body.Close() + + c.JSON(http.StatusOK, gin.H{"message": "Notification sent"}) +} + func main() { router := gin.Default() @@ -119,6 +158,8 @@ func main() { c.String(http.StatusOK, "Bumped AlaskarTV!") }) + router.POST("/notify", notifyHandler) + fmt.Println("Webhook server running on port 8080") router.Run(":8080") }