diff --git a/mods/config.go b/mods/config.go new file mode 100644 index 0000000..edd73d1 --- /dev/null +++ b/mods/config.go @@ -0,0 +1,69 @@ +package main + +import ( + "encoding/json" + "log" + "os" + "strings" + "time" + + "git.fromouter.space/hamcha/tg" +) + +var tzpath *string + +type TZFile map[int64]string + +var timezones TZFile +var tzlocs map[int64]*time.Location + +func tz_init() { + timezones = make(TZFile) + tzlocs = make(map[uint64]*time.Location) + file, err := os.Open(*tzpath) + if err != nil { + return + } + defer file.Close() + err = json.NewDecoder(file).Decode(&timezones) + if err != nil { + log.Println("[config/tz] WARN: Could not load custom timezones (malformed or unreadable file): " + err.Error()) + return + } + for uid, tzname := range timezones { + tzlocs[uid], err = time.LoadLocation(tzname) + if err != nil { + log.Printf("[config/tz] Couldn't load tz data for %d: %s\n", uid, err.Error()) + } + } + log.Printf("[config/tz] Loaded %d timezone preferences from %s\n", len(timezones), *tzpath) +} + +func tz_message(broker *tg.Broker, update tg.APIMessage) { + if isCommand(update, "tz") { + parts := strings.SplitN(*(update.Text), " ", 2) + if len(parts) < 2 { + broker.SendTextMessage(update.Chat, "Formato: /tz nome_timezone", &update.MessageID) + return + } + + loc, err := time.LoadLocation(parts[1]) + if err != nil { + broker.SendTextMessage(update.Chat, "Errore: non sono riuscito a trovare una timezone chiamata "+parts[1]+"", &update.MessageID) + return + } + + tzlocs[update.User.UserID] = loc + timezones[update.User.UserID] = parts[1] + tz_save() + } +} + +func tz_save() error { + file, err := os.Create(*tzpath) + if err != nil { + return err + } + defer file.Close() + return json.NewEncoder(file).Encode(timezones) +} diff --git a/mods/main.go b/mods/main.go index e0fe494..354f97e 100644 --- a/mods/main.go +++ b/mods/main.go @@ -81,6 +81,12 @@ var mods = map[string]Mod{ OnInit: oroscopo_init, OnMessage: oroscopo_message, }, + // Config operations + "tz": { + Description: "Configura timezone personalizzate", + OnInit: tz_init, + OnMessage: tz_message, + }, } func initmods() { @@ -158,6 +164,7 @@ func main() { sourcesans = flag.String("sourcesans", "source.ttf", "Path to source.ttf (Source Sans Pro font)") macropath = flag.String("macropath", "macros.json", "Path to macros db (JSON)") remindpath = flag.String("remindpath", "reminders.json", "Path to reminder db (JSON)") + remindpath = flag.String("tzpath", "timezones.json", "Path to timezones db (JSON)") proverbi = flag.String("proverbi", "proverbi.txt", "Path to proverbi pairs (separated by /)") talktoken = flag.String("apiai", "@apiai.token", "api.ai token") gapifile = flag.String("gapifile", "gapi.json", "Google API Service Credentials file (for STT)")