79 lines
1.9 KiB
Go
79 lines
1.9 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"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>", &tg.MessageOptions{
|
|
ReplyID: &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>", &tg.MessageOptions{
|
|
ReplyID: &update.MessageID,
|
|
})
|
|
return
|
|
}
|
|
|
|
tzlocs[update.User.UserID] = loc
|
|
timezones[update.User.UserID] = parts[1]
|
|
tz_save()
|
|
testTime := time.Now().In(loc)
|
|
msg := fmt.Sprintf("Ok, la tua nuova timezone è <b>%s</b> (%s) [ora: %s]", parts[1], testTime.Format("-0700 MST"), testTime.Format("15:04:05"))
|
|
broker.SendTextMessage(update.Chat, msg, &tg.MessageOptions{
|
|
ReplyID: &update.MessageID,
|
|
})
|
|
}
|
|
}
|
|
|
|
func tz_save() error {
|
|
file, err := os.Create(*tzpath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer file.Close()
|
|
return json.NewEncoder(file).Encode(timezones)
|
|
}
|