96 lines
1.9 KiB
Go
96 lines
1.9 KiB
Go
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()
|
|
}
|
|
|
|
const timezoneOffset = -3
|
|
|
|
func cycle() {
|
|
date := getDate()
|
|
if time.Now().After(date) {
|
|
err := createIfNotExists(date.Format("semana 2006-01-02"))
|
|
if err != nil {
|
|
log.Fatalln(err)
|
|
}
|
|
}
|
|
|
|
time.Sleep(time.Minute * 10)
|
|
cycle()
|
|
}
|
|
|
|
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))
|
|
}
|
|
|
|
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
|
|
}
|