BeeBot/cmd/beebot/main.go

68 lines
1.3 KiB
Go

package main
import (
"flag"
"fmt"
"log"
"math/rand"
"net/http"
"strconv"
"github.com/jzelinskie/geddit"
)
const version = 1.0
var clientID = flag.String("id", "", "Client ID")
var clientSecret = flag.String("secret", "", "Client Secret")
var baseAddr = flag.String("url", "127.0.0.1:9595", "Base address")
var o *geddit.OAuthSession
func main() {
flag.Parse()
log.Printf("BeeBot v%.2f", version)
var err error
o, err = geddit.NewOAuthSession(
*clientID,
*clientSecret,
"BeeBot",
fmt.Sprintf("http://%s/cb", *baseAddr),
)
if err != nil {
log.Fatal(1, err)
}
state := strconv.Itoa(rand.Intn(10000) * 1000)
url := o.AuthCodeURL(state, []string{"identity read edit"})
log.Printf("Visit %s to obtain auth code", url)
http.HandleFunc("/cb", mkCb(state))
log.Fatal(http.ListenAndServe(*baseAddr, nil))
}
func mkCb(startState string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
state := r.URL.Query().Get("state")
code := r.URL.Query().Get("code")
if state != startState {
log.Fatalf("Unexpected state, %s != %s", startState, state)
}
err := o.CodeAuth(code)
if err != nil {
log.Fatal(2, err)
}
me, err := o.AboutRedditor("_beebot_")
if err != nil {
log.Fatal(3, err)
}
log.Printf("%+v", me)
}
}