clessy-ng/modules/remind/mod.go

101 lines
2.1 KiB
Go
Raw Permalink Normal View History

2022-03-25 14:29:14 +00:00
package remind
import (
"errors"
"log"
"time"
2022-03-25 19:06:13 +00:00
"git.fromouter.space/crunchy-rocks/clessy-ng/modules"
2022-03-25 14:29:14 +00:00
"git.fromouter.space/crunchy-rocks/clessy-ng/utils"
2022-03-25 19:06:13 +00:00
2022-03-25 14:29:14 +00:00
"git.fromouter.space/hamcha/tg"
"git.sr.ht/~hamcha/containers"
2022-03-25 19:06:13 +00:00
"github.com/cockroachdb/pebble"
2022-03-25 14:29:14 +00:00
)
type Reminder struct {
ReminderID string
TargetID int64
When int64
Text string
Reference *ReminderReference
2022-03-25 14:29:14 +00:00
}
type ReminderReference struct {
Chat int64
Message int64
}
2022-03-25 19:06:13 +00:00
const reminderKey = "mod/reminder/pending"
2022-03-25 14:29:14 +00:00
const reminderMaxDuration = time.Hour * 24 * 30 * 3
var defaultLocation *time.Location = nil
var pending = containers.NewRWSyncMap[string, Reminder]()
type Module struct {
client *tg.Telegram
name string
2022-03-25 19:06:13 +00:00
kv *pebble.DB
2022-03-25 14:29:14 +00:00
}
2022-03-25 19:06:13 +00:00
func (m *Module) Initialize(options modules.ModuleOptions) error {
m.client = options.API
m.name = options.Name
m.kv = options.KV
2022-03-25 14:29:14 +00:00
var err error
defaultLocation, err = time.LoadLocation("Europe/Rome")
if err != nil {
log.Fatalf("[remind] Something is really wrong: %s\n", err.Error())
return err
}
2022-03-25 19:06:13 +00:00
var reminders map[string]Reminder
err = utils.ReadJSON(m.kv, reminderKey, &reminders)
2022-03-25 14:29:14 +00:00
if err != nil {
2022-03-25 19:06:13 +00:00
if !errors.Is(err, pebble.ErrNotFound) {
log.Println("[remind] WARN: Could not load pending reminders (db error): " + err.Error())
2022-03-25 14:29:14 +00:00
return err
}
}
// Fix old reminders
dirty := false
for reminderID, reminder := range reminders {
if reminder.ReminderID == "" {
reminder.ReminderID = reminderID
dirty = true
}
}
if dirty {
m.save()
}
// Set schedule
2022-03-25 14:29:14 +00:00
for id, reminder := range reminders {
pending.SetKey(id, reminder)
go m.schedule(id)
}
2022-03-25 19:06:13 +00:00
log.Printf("[remind] Loaded %d pending reminders\n", len(reminders))
2022-03-25 14:29:14 +00:00
return nil
}
func (m *Module) OnUpdate(update tg.APIUpdate) {
// Check for updates to existing messages
if update.Callback != nil {
m.handleCallback(update.Callback)
2022-03-25 14:29:14 +00:00
}
if utils.IsCommand(update, m.name, "ricordami") || utils.IsCommand(update, m.name, "remind") {
m.cmdRicordami(update.Message)
2022-03-25 14:29:14 +00:00
return
}
if utils.IsCommand(update, m.name, "reminders") {
m.cmdReminder(update.Message)
2022-03-25 19:06:13 +00:00
return
2022-03-25 14:29:14 +00:00
}
}