package main import ( "errors" "fmt" "os" "strings" "time" "git.bullercodeworks.com/brian/helperbot" "github.com/br0xen/boltease" "github.com/nlopes/slack" ) type BotModel struct { db *boltease.DB messages chan helperbot.Message slackApiToken string slackApi *slack.Client slackRTM *slack.RTM slackRTMLatency time.Duration slackIdToFriendly map[string]string IncomingSlackMessages chan *slack.MessageEvent OtherRTMEvents chan *slack.RTMEvent dataCache map[string][]byte } func NewBotModel() (*BotModel, error) { var err error m := new(BotModel) m.dataCache = make(map[string][]byte) m.messages = make(chan helperbot.Message, 100) m.db, err = boltease.Create("helperbot.db", 0600, nil) if err != nil { return nil, err } if err = m.NewSlack(); err != nil { return nil, err } return m, nil } func (m *BotModel) SendMessage(src, dst string, msg slack.Message) { m.messages <- NewBotMessage(src, dst, msg) } func (m *BotModel) getPluginDir() string { ret, err := m.GetString([]string{"config", "plugin_dir"}) if err != nil || strings.TrimSpace(ret) == "" { ret = "./plugins/" if err = m.SetString([]string{"config", "plugin_dir"}, ret); err != nil { fmt.Println("Error setting plugin directory") fmt.Println(err.Error()) os.Exit(1) } } fmt.Println("Plugin Dir: ", ret) return ret } func (m *BotModel) GetBytes(path []string) ([]byte, error) { var err error var v []byte var ok bool joinedPath := strings.Join(path, "/") if v, ok = m.dataCache[joinedPath]; !ok { // Value is not cached, try to pull it from the DB if len(path) > 2 { path, key := path[:len(path)-1], path[len(path)-1] v, err = m.db.GetBytes(path, key) if err != nil { return nil, err } m.dataCache[joinedPath] = v } } return v, nil } func (m *BotModel) SetBytes(path []string, val []byte) error { if len(path) > 1 { joinedPath := strings.Join(path, "/") path, key := path[:len(path)-1], path[len(path)-1] err := m.db.SetBytes(path, key, val) if err != nil { return err } // Update the cache m.dataCache[joinedPath] = val return nil } return errors.New("Invalid path") } func (m *BotModel) GetString(path []string) (string, error) { bts, err := m.GetBytes(path) if err != nil { return "", err } if len(bts) == 0 { return "", nil } return string(bts), nil } func (m *BotModel) SetString(path []string, val string) error { return m.SetBytes(path, []byte(val)) }