-
Notifications
You must be signed in to change notification settings - Fork 49
Tutorial
graw works like this:
- Reddit is a source of events
- graw connects to reddit with an api handle
- graw creates a stream of the events you want
- graw feeds this stream of events to your bot
We'll cover these one at a time.
An api handle allows you make requests to the Reddit API. The handlers in the graw/reddit package handle rate limiting and issuing requests so that you don't have to worry about breaking Reddit's API rules.
You can get two kinds of handles, a Script handle for logged out actions only, and a Bot handle for logged in actions such as posting or reading from an inbox. If you plan to only read data from public parts of Reddit, you can skip ahead. If you plan to have your bot run under an account, please create an agent file following this tutorial and come back.
Once you've gotten your handle with NewScript or NewBotFromAgentFile, it's time to move on.
bot, err := reddit.NewBotFromAgentFile("agentfile", 5*time.Second)
Note you can also use NewBot if getting your credentials in is easier that way, but don't accidentally check your credentials in to your repo!
Prepare a configuration that details all of the event sources you want to listen to. See the config struct here. Note that inbox events required a Bot handle. Here is an example config that requests a stream of new posts from /r/self and /r/golang:
cfg := graw.Config{
Subreddits: []string{"self","golang"},
}
Each event type has a corresponding handler defined in botfaces. graw will give you an error if you request an event stream but cannot handle it. For the config we defined above, we need to implement the PostHandler interface. We have an example from the readme:
type announcer struct {}
func (a *announcer) Post(post *reddit.Post) error {
fmt.Printf(`%s posted "%s"\n`, post.Author, post.Title)
return nil
}
Once all of this is together, we can start a graw run. It's simple:
stop, wait, err := graw.Run(&announcer{}, bot, cfg)
These return values, stop and wait, are functions. stop()
will terminate the graw run going on in the background when it is invoked. wait()
will block until the graw run stops and return the error if it fails.