From 49939d62c0c07920227e6f0766f08c7154deda1d Mon Sep 17 00:00:00 2001 From: Chris Sexton Date: Sun, 20 Apr 2014 21:07:55 -0400 Subject: [PATCH] Fixes #35: Remove dependency on count function Using aggregation to check the largest count instead of basically doing the same amount of work using a server side function. The bot should install without incident for other users now. --- plugins/factoid.go | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/plugins/factoid.go b/plugins/factoid.go index a54fd19..7c2206f 100644 --- a/plugins/factoid.go +++ b/plugins/factoid.go @@ -4,16 +4,17 @@ package plugins import ( "fmt" - "github.com/chrissexton/alepale/bot" "html/template" - "labix.org/v2/mgo" - "labix.org/v2/mgo/bson" "log" "math/rand" "net/http" "regexp" "strings" "time" + + "github.com/chrissexton/alepale/bot" + "labix.org/v2/mgo" + "labix.org/v2/mgo/bson" ) // The factoid plugin provides a learning system to the bot so that it can @@ -111,12 +112,23 @@ func (p *FactoidPlugin) learnFact(message bot.Message, trigger, operator, fact s return false } - var funcres bson.M - err := p.Bot.Db.Run(bson.M{"eval": "return counter(\"factoid\");"}, &funcres) + // definite error here if no func setup + // let's just aggregate + var count map[string]interface{} + query := []bson.M{{ + "$group": bson.M{ + "_id": nil, + "idx": bson.M{ + "$max": "$idx", + }, + }, + }} + pipe := p.Coll.Pipe(query) + err := pipe.One(&count) if err != nil { panic(err) } - id := int(funcres["retval"].(float64)) + id := count["idx"].(int) + 1 newfact := Factoid{ Id: bson.NewObjectId(), @@ -432,6 +444,7 @@ func (p *FactoidPlugin) randomFact() *Factoid { return nil } + // Possible bug here with no db if err := p.Coll.Find(nil).Skip(rand.Intn(nFacts)).One(&fact); err != nil { log.Println("Couldn't get next...") }