zulip-checkin-cyborg/main.go

96 lines
1.9 KiB
Go
Raw Permalink Normal View History

2023-03-01 18:39:46 +00:00
package main
import (
"log"
"os"
"time"
"gitea.nulo.in/Nulo/zulip-checkin-cyborg/zulip"
"golang.org/x/exp/slices"
)
var bot zulip.Bot
var stream string
var message string
func main() {
bot.Url = os.Getenv("ZULIP_URL")
if len(bot.Url) == 0 {
log.Fatalln("Falta ZULIP_URL")
}
bot.Email = os.Getenv("ZULIP_BOT_EMAIL")
if len(bot.Email) == 0 {
log.Fatalln("Falta ZULIP_BOT_EMAIL")
}
bot.Key = os.Getenv("ZULIP_BOT_KEY")
if len(bot.Key) == 0 {
log.Fatalln("Falta ZULIP_BOT_KEY")
}
stream = os.Getenv("ZULIP_STREAM")
if len(stream) == 0 {
stream = "check-in bot test"
}
message = os.Getenv("ZULIP_MESSAGE")
if len(message) == 0 {
message = "prueba de mensaje"
}
cycle()
}
2023-05-31 20:15:27 +00:00
const timezoneOffset = -3
2023-03-01 18:39:46 +00:00
func cycle() {
2023-07-28 14:08:59 +00:00
date := getDate()
if time.Now().After(date) {
err := createIfNotExists(date.Format("semana 2006-01-02"))
2023-03-21 00:38:42 +00:00
if err != nil {
log.Fatalln(err)
}
2023-03-01 18:39:46 +00:00
}
2023-05-31 20:15:27 +00:00
time.Sleep(time.Minute * 10)
2023-03-01 18:39:46 +00:00
cycle()
}
2023-07-28 14:08:59 +00:00
func getDate() time.Time {
year, month, day := time.Now().Date()
currentZeroDay := time.Date(year, month, day, 0, 0, 0, 0, time.UTC)
now := time.Now()
zeroMonday := currentZeroDay.Add(time.Duration(-time.Hour * 24 * time.Duration(now.Weekday()-time.Monday)))
return zeroMonday.Add(time.Hour * (8 - timezoneOffset))
}
2023-03-01 18:39:46 +00:00
func createIfNotExists(topicName string) (err error) {
streamId, err := bot.GetStreamId(stream)
if err != nil {
log.Fatalln(err)
}
topics, err := bot.GetStreamTopics(streamId)
if err != nil {
log.Fatalln(err)
}
names := mapSlice(topics, func(t zulip.GetStreamTopicsResStream) string {
return t.Name
})
if slices.Contains(names, topicName) {
return
}
err = bot.SendMessage(stream, topicName, message)
if err != nil {
return
}
return
}
// https://gosamples.dev/generics-map-function/
func mapSlice[T any, M any](a []T, f func(T) M) []M {
n := make([]M, len(a))
for i, e := range a {
n[i] = f(e)
}
return n
}