all repos — cameraman @ 3a770ca6153b7f66da3bdce12cae18c1bed29cfd

notify.go (view raw)

  1package main
  2
  3import (
  4	"errors"
  5	"fmt"
  6	"log"
  7	"os"
  8	"time"
  9
 10	"github.com/go-resty/resty/v2"
 11)
 12
 13var (
 14	NotificationWindow int
 15	SleepDuration      time.Duration
 16
 17	notificationClient *resty.Client
 18	telegramToken      string
 19	chatID             string
 20	threadID           string
 21)
 22
 23func notifyTelegram(occurrence Occurrence) error {
 24	log.Println("Sending notification for occurrence", occurrence.ID)
 25	message := fmt.Sprintf("*Giorno %02d/%02d*.\n\n_%s_\n%s",
 26		occurrence.Day, occurrence.Month, occurrence.Name, occurrence.Description)
 27
 28	url := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", telegramToken)
 29
 30	// Create the payload
 31	payload := map[string]interface{}{
 32		"chat_id":           chatID,
 33		"text":              message,
 34		"parse_mode":        "markdown",
 35		"message_thread_id": threadID,
 36	}
 37
 38	// Send the POST request
 39	resp, err := notificationClient.R().
 40		SetHeader("Content-Type", "application/json").
 41		SetBody(payload).
 42		Post(url)
 43
 44	if err != nil {
 45		log.Printf("Failed to send notification: %v", err)
 46		return err
 47	}
 48	log.Printf("Notification sent: %s, Response: %s", message, resp)
 49	return nil
 50}
 51
 52func resetNotifications() {
 53	if err := db.Model(&Occurrence{}).Where("notified = ?", true).Update("notified", false).Error; err != nil {
 54		log.Printf("Failed to reset notifications: %v", err)
 55	} else {
 56		log.Println("Notifications have been reset for the new year.")
 57	}
 58}
 59
 60func initNotifications() error {
 61	notificationClient = resty.New()
 62
 63	telegramToken = os.Getenv("TELEGRAM_BOT_TOKEN")
 64	chatID = os.Getenv("TELEGRAM_CHAT_ID")
 65	threadID = os.Getenv("TELEGRAM_THREAD_ID")
 66
 67	if telegramToken == "" || chatID == "" {
 68		log.Println("Warning: you should set your Telegram Bot token and chat id in .env, otherwise you won't get notifications!")
 69		return errors.New("empty telegramToken or chatId")
 70	}
 71	return nil
 72}
 73
 74func CheckOccurrences() {
 75	err := initNotifications()
 76	if err != nil {
 77		log.Println(err.Error())
 78		return
 79	}
 80
 81	for {
 82		log.Println("Checking for new occurrences.")
 83		now := time.Now()
 84		today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local)
 85		endWindow := today.AddDate(0, 0, NotificationWindow)
 86
 87		var occurrences []Occurrence
 88		db.Where("notified = ? AND ((month = ? AND day >= ?) OR (month = ? AND day <= ?))",
 89			false, today.Month(), today.Day(), endWindow.Month(), endWindow.Day()).Find(&occurrences)
 90
 91		for _, occurrence := range occurrences {
 92			occurrenceDate := time.Date(today.Year(), time.Month(occurrence.Month), occurrence.Day, 0, 0, 0, 0, time.Local)
 93			if occurrenceDate.Before(today) || occurrenceDate.After(endWindow) || !occurrence.Notify || occurrence.Notified {
 94				continue
 95			}
 96
 97			err := notifyTelegram(occurrence)
 98			if err != nil {
 99				log.Println(err.Error())
100				return
101			}
102			occurrence.Notified = true
103			db.Save(&occurrence)
104		}
105
106		// Check if New Year's Eve is within the next sleep cycle
107		nextCheck := now.Add(SleepDuration)
108		if (now.Month() == 12 && now.Day() == 31) && (nextCheck.Month() == 1 && nextCheck.Day() == 1) {
109			resetNotifications()
110		}
111
112		time.Sleep(SleepDuration)
113	}
114}