Account Handles
If you are unfamiliar with Go it may be helpful from this point on to keep the Go Tour, Effective Go, and Go By Example open for reference.
Creating A Handle
Handles for Reddit accounts, and the logged out Reddit API are provided via the graw/reddit package.
This line will create a handle from your agent file (replace "reminderbot.agent" with the path to the agent file you prepared in the previous chapter):
bot, err := reddit.NewBotFromAgentFile("reminderbot.agent", 0)
The 0 argument is a minimum time between requests. graw automatically restricts us to a legal request limit according to the Reddit API rules, but we could pass a higher minimum such as 2*time.Minute
if we knew our bot would only watch low traffic subreddits.
What Handles Are
Let's use the bot handle to do a simple thing and get an idea of how it works. The Bot type from the graw/reddit package is an interface composed of three other interfaces: Account, Lurker, and Scanner:
type Bot interface {
Account
Lurker
Scanner
}
Scanner has a method called Listing which returns the elements from a listing after a reference point. A "listing" is a type of endpoint at Reddit with a feed of similar elements, such as a user page or subreddit post feed. This code will output the first five posts on the front page of /r/golang:
harvest, err := bot.Listing("/r/golang", "")
if err != nil {
fmt.Println("Failed to fetch /r/golang: ", err)
return
}
for _, post := range harvest.Posts[:5] {
fmt.Printf("[%s] posted [%s]\n", post.Author, post.Title)
}
That second parameter after the path to /r/golang expects a reference point in the listing. To get only posts after this, we could pass the id of the last post we received in this listing to that parameter. If we kept track of new posts in this way, we would need to decide when to ask for updates, and error correct if the post we were using as a reference point were deleted or caught in a spam filter. Thankfully we don't have to! In the next chapter we will ask graw to take care of that for us.
All together we have this program:
package main
import (
"fmt"
"github.com/turnage/graw/reddit"
)
func main() {
bot, err := reddit.NewBotFromAgentFile("reminderbot.agent", 0)
if err != nil {
fmt.Println("Failed to create bot handle: ", err)
return
}
harvest, err := bot.Listing("/r/golang", "")
if err != nil {
fmt.Println("Failed to fetch /r/golang: ", err)
return
}
for _, post := range harvest.Posts[:5] {
fmt.Printf("[%s] posted [%s]\n", post.Author, post.Title)
}
}