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.
This commit is contained in:
Chris Sexton 2014-04-20 21:07:55 -04:00
parent a07a6adc0d
commit 49939d62c0
1 changed files with 19 additions and 6 deletions

View File

@ -4,16 +4,17 @@ package plugins
import ( import (
"fmt" "fmt"
"github.com/chrissexton/alepale/bot"
"html/template" "html/template"
"labix.org/v2/mgo"
"labix.org/v2/mgo/bson"
"log" "log"
"math/rand" "math/rand"
"net/http" "net/http"
"regexp" "regexp"
"strings" "strings"
"time" "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 // 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 return false
} }
var funcres bson.M // definite error here if no func setup
err := p.Bot.Db.Run(bson.M{"eval": "return counter(\"factoid\");"}, &funcres) // 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 { if err != nil {
panic(err) panic(err)
} }
id := int(funcres["retval"].(float64)) id := count["idx"].(int) + 1
newfact := Factoid{ newfact := Factoid{
Id: bson.NewObjectId(), Id: bson.NewObjectId(),
@ -432,6 +444,7 @@ func (p *FactoidPlugin) randomFact() *Factoid {
return nil return nil
} }
// Possible bug here with no db
if err := p.Coll.Find(nil).Skip(rand.Intn(nFacts)).One(&fact); err != nil { if err := p.Coll.Find(nil).Skip(rand.Intn(nFacts)).One(&fact); err != nil {
log.Println("Couldn't get next...") log.Println("Couldn't get next...")
} }