refactor notify func, add slice to english formatter

William Perron 1 year ago
parent bbaf7f0f40
commit 6e7c4520b1
Signed by: wperron
GPG Key ID: BFDB4EF72D73C5F2

@ -524,33 +524,30 @@ func main() {
cancel() cancel()
}() }()
go func() { go notifier.NotifyFunc(ctx, func() {
for { absentees, err := store.GetAbsentees(ctx, themis.NextMonday())
select { if err != nil {
case <-ctx.Done(): log.Error().Err(err).Msg("failed to get absentees for next session")
return return
case <-notifChan: }
absentees, err := store.GetAbsentees(ctx, themis.NextMonday())
if err != nil {
log.Error().Err(err).Msg("failed to get absentees for next session")
return
}
var msg string for i, a := range absentees {
if len(absentees) == 0 { a = fmt.Sprintf("<@%s>", a)
msg = "Everybody can make it next Monday, see you then!" absentees[i] = a
} else { }
msg = fmt.Sprintf("%s can't make it next Monday.", strings.Join(absentees, ", "))
}
_, err = discord.ChannelMessageSend(channelId, msg) var msg string
if err != nil { if len(absentees) == 0 {
log.Error().Err(err).Msg("failed to send scheduled notification") msg = "Everybody can make it next Monday, see you then!"
} } else {
} msg = fmt.Sprintf("%s can't make it next Monday.", themis.FormatStringSlice(absentees))
time.Sleep(5 * time.Minute)
} }
}()
_, err = discord.ChannelMessageSend(channelId, msg)
if err != nil {
log.Error().Err(err).Msg("failed to send scheduled notification")
}
})
<-ctx.Done() <-ctx.Done()
log.Info().Msg("context cancelled, exiting") log.Info().Msg("context cancelled, exiting")

@ -70,3 +70,27 @@ func FormatRows(rows *sql.Rows) (string, error) {
return sb.String(), nil return sb.String(), nil
} }
func FormatStringSlice(s []string) string {
if len(s) == 0 {
return ""
}
sb := strings.Builder{}
for len(s) > 0 {
curr, rest := s[0], s[1:]
sb.WriteString(curr)
if len(rest) == 0 {
break
}
if len(rest) > 1 {
sb.WriteString(", ")
} else {
sb.WriteString(" and ")
}
s = rest
}
return sb.String()
}

@ -29,7 +29,7 @@ func (n *Notifier) Start(ctx context.Context) {
sat = sat.AddDate(0, 0, 7) sat = sat.AddDate(0, 0, 7)
} }
t, err := time.ParseInLocation(time.DateTime, fmt.Sprintf("%s 16:35:00", sat.Format(time.DateOnly)), loc) t, err := time.ParseInLocation(time.DateTime, fmt.Sprintf("%s 17:00:00", sat.Format(time.DateOnly)), loc)
if err != nil { if err != nil {
panic("failed to parse next monday notif time. this is likely a bug.") panic("failed to parse next monday notif time. this is likely a bug.")
} }
@ -54,3 +54,15 @@ func (n *Notifier) Start(ctx context.Context) {
time.Sleep(time.Hour) time.Sleep(time.Hour)
} }
} }
func (n *Notifier) NotifyFunc(ctx context.Context, f func()) {
for {
select {
case <-ctx.Done():
return
case <-n.c:
f()
}
time.Sleep(5 * time.Minute)
}
}

Loading…
Cancel
Save