clessy-ng/modules/macro/mod.go
2022-03-24 16:28:00 +01:00

119 lines
2.9 KiB
Go

package macro
import (
"errors"
"fmt"
"io/fs"
"log"
"os"
"strings"
"time"
"git.fromouter.space/crunchy-rocks/clessy-ng/utils"
"git.fromouter.space/hamcha/tg"
jsoniter "github.com/json-iterator/go"
)
type Macro struct {
Value string
Author tg.APIUser
Time time.Time
}
var macropath string
var macros map[string]Macro
type Module struct {
client *tg.Telegram
name string
}
func (m *Module) Initialize(api *tg.Telegram, name string) error {
m.client = api
m.name = name
macros = make(map[string]Macro)
macropath = os.Getenv("CLESSY_MACRO_FILE")
if macropath == "" {
return fmt.Errorf("CLESSY_MACRO_FILE empty or unset, set to a valid file path")
}
file, err := os.Open(macropath)
if err != nil {
if !errors.Is(err, fs.ErrNotExist) {
return err
}
log.Println("[macro] WARN: Could not load macros (file doesnt exist): " + err.Error())
return nil
}
defer file.Close()
err = jsoniter.ConfigFastest.NewDecoder(file).Decode(&macros)
if err != nil {
log.Println("[macro] WARN: Could not load macros (malformed or unreadable file): " + err.Error())
return err
}
log.Printf("[macro] Loaded %d macros from %s\n", len(macros), macropath)
return nil
}
func (m *Module) OnUpdate(update tg.APIUpdate) {
// Not a message? Ignore
if update.Message == nil {
return
}
if utils.IsCommand(*update.Message, m.name, "macro") {
parts := strings.SplitN(*(update.Message.Text), " ", 3)
switch len(parts) {
case 2:
name := strings.ToLower(parts[1])
item, ok := macros[name]
var out string
if ok {
out = fmt.Sprintf("<b>%s</b>\n%s\n<i>%s - %s</i>", name, 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>)", name, name)
}
m.client.SendTextMessage(tg.ClientTextMessageData{
ChatID: update.Message.Chat.ChatID,
Text: out,
ReplyID: &update.Message.MessageID,
})
case 3:
name := strings.ToLower(parts[1])
macros[name] = Macro{
Value: parts[2],
Author: update.Message.User,
Time: time.Now(),
}
save()
m.client.SendTextMessage(tg.ClientTextMessageData{
ChatID: update.Message.Chat.ChatID,
Text: fmt.Sprintf("<b>%s</b> → %s", name, parts[2]),
ReplyID: &update.Message.MessageID,
})
default:
m.client.SendTextMessage(tg.ClientTextMessageData{
ChatID: update.Message.Chat.ChatID,
Text: "<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>",
ReplyID: &update.Message.MessageID,
})
}
return
}
}
func save() {
file, err := os.Create(macropath)
if err != nil {
log.Println("[macro] WARN: Could not open macro db: " + err.Error())
return
}
err = jsoniter.ConfigFastest.NewEncoder(file).Encode(macros)
if err != nil {
log.Println("[macro] WARN: Could not save macros into file: " + err.Error())
}
}