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/tz.go

80 lines
1.9 KiB
Go
Raw Permalink Normal View History

2018-11-08 18:55:48 +00:00
package main
import (
"encoding/json"
2019-05-23 08:01:38 +00:00
"fmt"
2018-11-08 18:55:48 +00:00
"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)
2018-11-08 19:03:05 +00:00
tzlocs = make(map[int64]*time.Location)
2018-11-08 18:55:48 +00:00
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 {
2018-12-13 10:29:45 +00:00
broker.SendTextMessage(update.Chat, "<b>Formato:</b> /tz <i>nome_timezone</i>", &tg.MessageOptions{
ReplyID: &update.MessageID,
})
2018-11-08 18:55:48 +00:00
return
}
loc, err := time.LoadLocation(parts[1])
if err != nil {
2018-12-13 10:29:45 +00:00
broker.SendTextMessage(update.Chat, "<b>Errore:</b> non sono riuscito a trovare una timezone chiamata <b>"+parts[1]+"</b>", &tg.MessageOptions{
ReplyID: &update.MessageID,
})
2018-11-08 18:55:48 +00:00
return
}
tzlocs[update.User.UserID] = loc
timezones[update.User.UserID] = parts[1]
tz_save()
2019-05-23 08:01:38 +00:00
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,
})
2018-11-08 18:55:48 +00:00
}
}
func tz_save() error {
file, err := os.Create(*tzpath)
if err != nil {
return err
}
defer file.Close()
return json.NewEncoder(file).Encode(timezones)
}