// © 2013 the CatBase Authors under the WTFPL. See AUTHORS for the list of authors. package bot import ( "html/template" "log" "net/http" "strings" "github.com/jmoiron/sqlx" "github.com/velour/catbase/bot/msg" "github.com/velour/catbase/bot/msglog" "github.com/velour/catbase/bot/user" "github.com/velour/catbase/config" ) // bot type provides storage for bot-wide information, configs, and database connections type bot struct { // Each plugin must be registered in our plugins handler. To come: a map so that this // will allow plugins to respond to specific kinds of events plugins map[string]Plugin pluginOrdering []string // Users holds information about all of our friends users []user.User // Represents the bot me user.User config *config.Config conn Connector logIn chan msg.Message logOut chan msg.Messages version string // The entries to the bot's HTTP interface httpEndPoints map[string]string // filters registered by plugins filters map[string]func(string) string callbacks CallbackMap } // Variable represents a $var replacement type Variable struct { Variable, Value string } // New creates a bot for a given connection and set of handlers. func New(config *config.Config, connector Connector) Bot { logIn := make(chan msg.Message) logOut := make(chan msg.Messages) msglog.RunNew(logIn, logOut) users := []user.User{ user.User{ Name: config.Get("Nick", "bot"), }, } bot := &bot{ config: config, plugins: make(map[string]Plugin), pluginOrdering: make([]string, 0), conn: connector, users: users, me: users[0], logIn: logIn, logOut: logOut, httpEndPoints: make(map[string]string), filters: make(map[string]func(string) string), callbacks: make(CallbackMap), } bot.migrateDB() http.HandleFunc("/", bot.serveRoot) addr := config.Get("HttpAddr", "127.0.0.1:1337") go http.ListenAndServe(addr, nil) connector.RegisterEvent(bot.Receive) return bot } // Config gets the configuration that the bot is using func (b *bot) Config() *config.Config { return b.config } func (b *bot) DB() *sqlx.DB { return b.config.DB } // Create any tables if necessary based on version of DB // Plugins should create their own tables, these are only for official bot stuff // Note: This does not return an error. Database issues are all fatal at this stage. func (b *bot) migrateDB() { if _, err := b.DB().Exec(`create table if not exists variables ( id integer primary key, name string, value string );`); err != nil { log.Fatal("Initial DB migration create variables table: ", err) } } // Adds a constructed handler to the bots handlers list func (b *bot) AddPlugin(name string, h Plugin) { b.plugins[name] = h b.pluginOrdering = append(b.pluginOrdering, name) if entry := h.RegisterWeb(); entry != nil { b.httpEndPoints[name] = *entry } } func (b *bot) Who(channel string) []user.User { names := b.conn.Who(channel) users := []user.User{} for _, n := range names { users = append(users, user.New(n)) } return users } var rootIndex = `
Plugin |
---|
{{$key}} |