all repos — cameraman @ ab6a293f1e350018013a6eb54105b1e9210b0cc1

notify.go (view raw)

 1package main
 2
 3import (
 4	"fmt"
 5	"log"
 6	"os"
 7	"time"
 8
 9	"github.com/go-resty/resty/v2"
10)
11
12var notificationWindow = 3
13
14func notifyTelegram(occurrence Occurrence) {
15	client := resty.New()
16	telegramToken := os.Getenv("TELEGRAM_BOT_TOKEN")
17	chatID := os.Getenv("TELEGRAM_CHAT_ID")
18	threadID := os.Getenv("TELEGRAM_THREAD_ID")
19
20	message := fmt.Sprintf("*Giorno %02d/%02d*:\n\n_%s_\n%s",
21		occurrence.Day, occurrence.Month, occurrence.Name, occurrence.Description)
22
23	url := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", telegramToken)
24
25	// Create the payload
26	payload := map[string]interface{}{
27		"message_thread_id": threadID,
28		"chat_id":           chatID,
29		"text":              message,
30		"parse_mode":        "markdown",
31	}
32
33	// Send the POST request
34	resp, err := client.R().
35		SetHeader("Content-Type", "application/json").
36		SetBody(payload).
37		Post(url)
38
39	if err != nil {
40		log.Printf("Failed to send notification: %v", err)
41		return
42	}
43	log.Printf("Notification sent: %s, Response: %s", message, resp)
44}
45
46func resetNotifications() {
47	if err := db.Model(&Occurrence{}).Where("notified = ?", true).Update("notified", false).Error; err != nil {
48		log.Printf("Failed to reset notifications: %v", err)
49	} else {
50		log.Println("Notifications have been reset for the new year.")
51	}
52}
53
54func CheckOccurrences() {
55	const sleepDuration = 12 * time.Hour
56
57	for {
58		now := time.Now()
59		var occurrences []Occurrence
60		endWindow := now.AddDate(0, 0, notificationWindow)
61
62		db.Where("notified = ? AND ((month = ? AND day >= ?) OR (month = ? AND day <= ?))",
63			false, now.Month(), now.Day(), endWindow.Month(), endWindow.Day()).Find(&occurrences)
64
65		for _, occurrence := range occurrences {
66			occurrenceDate := time.Date(now.Year(), time.Month(occurrence.Month), occurrence.Day, 0, 0, 0, 0, time.Local)
67			if occurrenceDate.Before(now) || occurrenceDate.After(endWindow) {
68				continue
69			}
70
71			if occurrence.Notify {
72				notifyTelegram(occurrence)
73				occurrence.Notified = true
74				db.Save(&occurrence)
75			}
76		}
77
78		// Check if New Year's Eve is within the next sleep cycle
79		nextCheck := now.Add(sleepDuration)
80		if now.Month() == 12 && now.Day() == 31 || (nextCheck.Month() == 1 && nextCheck.Day() == 1) {
81			resetNotifications()
82		}
83
84		time.Sleep(sleepDuration)
85	}
86}