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

@ -70,3 +70,27 @@ func FormatRows(rows *sql.Rows) (string, error) {
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)
}
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 {
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)
}
}
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