This repository has been archived on 2023-07-05. You can view files and clone it, but cannot push or open issues or pull requests.
clessy/mods/config.go

70 lines
1.6 KiB
Go

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[int64]*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, "<b>Formato:</b> /tz <i>nome_timezone</i>", &update.MessageID)
return
}
loc, err := time.LoadLocation(parts[1])
if err != nil {
broker.SendTextMessage(update.Chat, "<b>Errore:</b> non sono riuscito a trovare una timezone chiamata <b>"+parts[1]+"</b>", &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)
}