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

84 lines
2.1 KiB
Go
Raw Normal View History

2017-01-09 21:58:12 +00:00
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"strings"
"time"
2018-11-08 18:55:34 +00:00
"git.fromouter.space/hamcha/tg"
2017-01-09 21:58:12 +00:00
)
type Macro struct {
Value string
Author tg.APIUser
Time time.Time
}
var macropath *string
var macros map[string]Macro
2018-05-24 15:48:35 +00:00
func macro_init() {
2017-01-09 21:58:12 +00:00
macros = make(map[string]Macro)
file, err := os.Open(*macropath)
if err != nil {
return
}
defer file.Close()
err = json.NewDecoder(file).Decode(&macros)
if err != nil {
2017-03-15 20:20:07 +00:00
log.Println("[macro] WARN: Could not load macros (malformed or unreadable file): " + err.Error())
2017-01-09 21:58:12 +00:00
return
}
2017-03-15 20:20:07 +00:00
log.Printf("[macro] Loaded %d macros from %s\n", len(macros), *macropath)
2017-01-09 21:58:12 +00:00
}
2018-05-24 15:48:35 +00:00
func macro_message(broker *tg.Broker, update tg.APIMessage) {
2017-01-09 21:58:12 +00:00
if isCommand(update, "macro") {
parts := strings.SplitN(*(update.Text), " ", 3)
switch len(parts) {
case 2:
var out string
macroname := strings.ToLower(parts[1])
item, ok := macros[macroname]
if ok {
out = fmt.Sprintf("<b>%s</b>\n%s\n<i>%s - %s</i>", macroname, item.Value, item.Author.Username, item.Time.Format("02-01-06 15:04"))
} else {
out = fmt.Sprintf("<b>%s</b>\n<i>macro inesistente</i>\n(configura con /macro %s <i>contenuto</i>)", macroname, macroname)
}
2018-12-13 10:29:45 +00:00
broker.SendTextMessage(update.Chat, out, &tg.MessageOptions{
ReplyID: &update.MessageID,
})
2017-01-09 21:58:12 +00:00
case 3:
macroname := strings.ToLower(parts[1])
macros[macroname] = Macro{
Value: parts[2],
Author: update.User,
Time: time.Now(),
}
savemacros()
2018-12-13 10:29:45 +00:00
broker.SendTextMessage(update.Chat, fmt.Sprintf("<b>%s</b> → %s", macroname, parts[2]), &tg.MessageOptions{
ReplyID: &update.MessageID,
})
2017-01-09 21:58:12 +00:00
default:
2018-12-13 10:29:45 +00:00
broker.SendTextMessage(update.Chat, "<b>Sintassi</b>\n<b>Leggi</b>: /macro <i>nome-macro</i>\n<b>Scrivi</b>: /macro <i>nome-macro</i> <i>contenuto macro</i>", &tg.MessageOptions{
ReplyID: &update.MessageID,
})
2017-01-09 21:58:12 +00:00
}
}
}
func savemacros() {
file, err := os.Create(*macropath)
if err != nil {
2017-03-15 20:20:07 +00:00
log.Println("[macro] WARN: Could not open macro db: " + err.Error())
2017-01-09 21:58:12 +00:00
return
}
err = json.NewEncoder(file).Encode(macros)
if err != nil {
2017-03-15 20:20:07 +00:00
log.Println("[macro] WARN: Could not save macros into file: " + err.Error())
2017-01-09 21:58:12 +00:00
}
}