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(¯os) 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("%s\n%s\n%s - %s", name, item.Value, item.Author.Username, item.Time.Format("02-01-06 15:04")) } else { out = fmt.Sprintf("%s\nmacro inesistente\n(configura con /macro %s contenuto)", 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("%s → %s", name, parts[2]), ReplyID: &update.Message.MessageID, }) default: m.client.SendTextMessage(tg.ClientTextMessageData{ ChatID: update.Message.Chat.ChatID, Text: "Sintassi\nLeggi: /macro nome-macro\nScrivi: /macro nome-macro contenuto macro", 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()) } }