rego

package module
Version: v0.0.0-...-90015df Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 31, 2015 License: MIT Imports: 11 Imported by: 0

README

Rego Gopher

Reddit API bindings for Go. The primary focus of this package is to be a tool for writing bots and not a full API implementation.

Documentation

Browse the online reference documentation:

GoDoc Go Walker.

session := rego.NewSession("RegoBot/1.0")
page := session.Listing("r/worldnews/new")
page.SetLimit(5)
list, err := page.Next()
if err != nil {
        log.Print(err)
}
for _, l := range list.Links() {
        if l.Selfpost {
                continue
        }
        fmt.Printf("Title: %30s, Url: %s\n", l.Title, l.Url)
}

TODO

  • Unauthenticated sessions should use http by default to take advantage of Reddit caches
    • Hitting Reddit caches are 'free' requests and do not count against rate limits
    • This will be configurable for cases where TLS is desired

Documentation

Index

Examples

Constants

View Source
const (
	TypeComment   = "t1"
	TypeAccount   = "t2"
	TypeLink      = "t3"
	TypeMessage   = "t4"
	TypeSubreddit = "t5"
	TypeAward     = "t6"
	TypePromo     = "t8" // Promo campain
	TypeListing   = "Listing"
)

Thing types (kind)

View Source
const (
	// MaxLimit is the upper maximum limit for Session.Listing() requests
	MaxLimit = 100
)

Variables

View Source
var (
	ErrBadCookie = errors.New("bad cookie")
)

Functions

This section is empty.

Types

type APIError

type APIError struct {
	// contains filtered or unexported fields
}

APIError represents a Reddit API error

Example
session := NewSession("RegoBot/1.0")
retry:
_, err := session.Comment("t3_xxxxx", "This is a demo")
if err != nil {
	if apierr, ok := err.(APIError); ok {
		if apierr.IsRatelimited() {
			fmt.Printf("We are being ratelimited for %d minutes\n", int(apierr.Duration().Minutes()))
			time.Sleep(apierr.Duration())
			goto retry
		}
	}
}
Output:

func (APIError) Duration

func (e APIError) Duration() time.Duration

Duration returns the time remaining of active ratelimit for the error

func (APIError) Error

func (e APIError) Error() string

Error returns a descriptive string of the error

func (APIError) IsRatelimited

func (e APIError) IsRatelimited() bool

IsRatelimited returns true if a ratelimit is in effect for the error

type Account

type Account struct {
	CommentKarma  int    `json:"comment_karma"` // User's comment karma
	GoldCredits   int    `json:"gold_creddits,omitempty"`
	HasMail       bool   `json:"has_mail"`     // User has unread mail?
	HasModMail    bool   `json:"has_mod_mail"` // User has unread mod mail?
	HideRobots    bool   `json:"hide_from_robots,omitempty"`
	ID            string `json:"id"`                 // ID of the account; prepend t2_ to get fullname
	IsFriend      bool   `json:"is_friend"`          // Logged-in user has this user set as a friend
	IsGold        bool   `json:"is_gold"`            // Reddit gold status
	IsMod         bool   `json:"is_mod"`             // This account moderates a subreddits
	LinkKarma     int    `json:"link_karma"`         // User's link karma
	Modhash       string `json:"modhash"`            // Current modhash, not present if not your account
	Name          string `json:"name"`               // The username of the account
	Over18        bool   `json:"over_18"`            // If this account is set to be over 18
	VerifiedEmail bool   `json:"has_verified_email"` // User has a verified email address
	Created
}

Account represents a Reddit user account

type Comment

type Comment struct {
	ApprovedBy       string          `json:"approved_by"`            // Who approved this comment, null if not a mod
	AuthorFlairClass string          `json:"author_flair_css_class"` // CSS class of the author's flair
	AuthorFlairText  string          `json:"author_flair_text"`      // Text of the author's flair
	Author           string          `json:"author"`                 // Account name of the poster
	BannedBy         string          `json:"banned_by"`              // Who removed this comment, null if not a mod
	BodyHTML         string          `json:"body_html"`              // Formatted HTML text as displayed on Reddit
	Body             string          `json:"body"`                   // Raw unformatted text of the comment
	Distinguished    string          `json:"distinguished"`          //
	Edited           json.RawMessage `json:"edited"`                 //
	Likes            bool            `json:"likes"`                  // How the logged-in user has voted on the link
	LinkAuthor       string          `json:"link_author"`            // Author of the parent link
	LinkID           string          `json:"id"`                     // ID of the link this comment is in
	LinkTitle        string          `json:"link_title"`             // Title of the parent link
	LinkURL          string          `json:"title_url"`              // Link URL of the parent link
	Name             string          `json:"name"`                   // Fullname of item, e.g. "t3_c3v7f8u"
	NumReports       int             `json:"num_reports"`            // Number of times comment has been reported, null if not a mod
	ParentID         string          `json:"parent_id"`              // ID of the thing this comment is a reply to
	Saved            bool            `json:"saved"`                  // True if this post is saved by the logged in user
	ScoreHidden      bool            `json:"score_hidden"`           // Whether the comment's score is currently hidden.
	Score            int             `json:"score"`                  // The net-score of the link
	SubredditID      string          `json:"subreddit_id"`           // ID of the subreddit
	Subreddit        string          `json:"subreddit"`              // Subreddit name
	Created
	Votable
}

Comment represents a subreddit post comment

type CommentResult

type CommentResult struct {
	ID          string `json:"id"`          // UNKNOWN
	Name        string `json:"link"`        // Full name of item, e.g. "t3_c3v7f8u"
	ContentHTML string `json:"contentHTML"` // Comment text HTML formatted
	Content     string `json:"contentText"` // Comment text plain
	Replies     string `json:"replies"`     // UNKNOWN
	Parent      string `json:"parent"`      // Parent item
}

CommentResult is returned when submitting a new comment

type Created

type Created struct {
	Local json.Number `json:"created"`     // Time of creation in local epoch-second format
	UTC   json.Number `json:"created_utc"` // Time of creation in UTC epoch-second format
}

Created implements the Created class.

func (*Created) Time

func (c *Created) Time() time.Time

Time returns created time in local format

type Edited

type Edited struct {
	// Post has been edited false/true
	Status bool
	// Time last edited in UTC epoch-second format
	UTC time.Time
}

func (*Edited) UnmarshalJSON

func (e *Edited) UnmarshalJSON(b []byte) error
type Link struct {
	AuthorFlairClass string          `json:"author_flair_css_class"` // CSS class of the author's flair
	AuthorFlairText  string          `json:"author_flair_text"`      // Text of the author's flair
	Author           string          `json:"author"`                 // Account name of the poster
	Clicked          bool            `json:"clicked"`                //
	Distinguished    string          `json:"distinguished"`          //
	Domain           string          `json:"domain"`                 // The domain of this link
	Edited           Edited          `json:"edited"`                 //
	Hidden           bool            `json:"hidden"`                 // True if the post is hidden by user
	ID               string          `json:"id"`                     // Item identifier, e.g. "c3v7f8u"
	IsNsfw           bool            `json:"over_18"`                // True if the post is tagged as NSFW
	Likes            bool            `json:"likes"`                  // How the logged-in user has voted on the link
	LinkFlairClass   string          `json:"link_flair_css_class"`   //
	LinkFlairText    string          `json:"link_flair_text"`        //
	MediaEmbed       json.RawMessage `json:"media_embed"`            //
	Media            json.RawMessage `json:"media"`                  //
	Name             string          `json:"name"`                   // Fullname of item, e.g. "t3_c3v7f8u"
	NumComments      int             `json:"num_comments"`           //
	Permalink        string          `json:"permalink"`              // Relative URL of the permanent link for this link
	Saved            bool            `json:"saved"`                  // True if this post is saved by the logged in user
	Score            int             `json:"score"`                  // The net-score of the link
	Selfpost         bool            `json:"is_self"`                // True if this link is a selfpost
	SelftextHTML     string          `json:"selftext_html"`          //
	Selftext         string          `json:"selftext"`               //
	Stickied         bool            `json:"stickied"`               //
	SubredditID      string          `json:"subreddit_id"`           //
	Subreddit        string          `json:"subreddit"`              //
	Thumbnail        string          `json:"thumbnail"`              //
	Title            string          `json:"title"`                  //
	URL              string          `json:"url"`                    //
	Visited          bool            `json:"visited"`                //
	Created
	Votable
}

Link represents a subreddit post link

type Lister

type Lister interface {
	Comments() []Comment
	Items() []interface{}
	Links() []Link
}

The Lister interface wraps methods used to extract Thing items from a Reddit Listing class.

None of the methods return errors, as the data contained has already been unmarshalled once. It is assumed that the data is syntactically correct JSON and errors can safely be ignored.

Any malformed/unrecognised Thing item will be silently dropped.

type Listing

type Listing struct {
	Data struct {
		After    string  `json:"after"`
		Before   string  `json:"before"`
		Children []Thing `json:"children"`
		Modhash  string  `json:"modhash"`
	} `json:"data"`
	Kind string `json:"kind"` // Always "Listing"
}

Listing represents the Reddit Listing class documented at https://github.com/reddit/reddit/wiki/JSON#listing.

func (*Listing) Comments

func (l *Listing) Comments() []Comment

Comments return a slice of Comment types

func (*Listing) Items

func (l *Listing) Items() []interface{}

Items return a slice of interface{} items for cases where the caller want to do type assertions.

func (l *Listing) Links() []Link

Links return a slice of Link types

type Page

type Page struct {
	// contains filtered or unexported fields
}

func (*Page) Next

func (p *Page) Next() (*Listing, error)

Next returns a set of Thing items resulting from the requested API call.

Consecutive calls will return subsequent items indefinitely.

func (*Page) Previous

func (p *Page) Previous() (*Listing, error)

Previous returns a set of Thing items resulting from the requested API call.

Consecutive calls will return preceding items until source is exhausted.

func (*Page) SetLimit

func (p *Page) SetLimit(limit int)

SetLimit sets the max number of links returned from calls to Previous and Next

type Paginator

type Paginator interface {
	Next() (Lister, error)
	Previous() (Lister, error)
	SetLimit(int)
}

Paginator is the interface that wraps methods for pagination of the Listing type

type RateLimit

type RateLimit struct {
	Remaining int
	Reset     int
	Used      int
}

RateLimit provides access to the Reddit ratelimit values for a session

type Session

type Session struct {
	Cookie string // Session cookie (empty if not logged in)

	RateLimit RateLimit // RateLimit usage is updated on each API request
	// contains filtered or unexported fields
}

Session is an active Reddit session that initially is unauthenticated. An authenticated session can be set up using Session.Login or Session.SetCookie.

func NewSession

func NewSession(ua string) *Session

NewSession creates an unauthenticated Reddit session

func (*Session) Comment

func (s *Session) Comment(p string, t string) (*CommentResult, error)

Comment posts a reply to parent post p using the raw text t. A successfull post will return the new comments fullname id.

func (*Session) Listing

func (s *Session) Listing(sub string) *Page

Listing returns a paginated Listing wrapped in a Page type

Example
session := NewSession("RegoBot/1.0")
page := session.Listing("r/worldnews/new")
page.SetLimit(5)
list, err := page.Next()
if err != nil {
	log.Print(err)
}
for _, l := range list.Links() {
	if l.Selfpost {
		continue
	}
	fmt.Printf("Title: %30s Url: %s\n", l.Title, l.URL)
}
Output:

func (*Session) Login

func (s *Session) Login(u string, p string) error

Login authenticates the current session using username and password

Example
session := NewSession("RegoBot/1.0")
err := session.Login("username", "password")
if err != nil {
	log.Fatal(err)
}
Output:

func (*Session) Me

func (s *Session) Me() (*Account, error)

Me returns Account type populated with data for the currently authenticated user. This is equivalent to using Session.User() and providing the authenticated username.

func (*Session) SetCookie

func (s *Session) SetCookie(c string) error

SetCookie authenticates the current session using a pre-authenticated cookie

func (*Session) User

func (s *Session) User(u string) (*Account, error)

User returns Account type populated with data for user u.

type Thing

type Thing struct {
	Data json.RawMessage `json:"data"` // A data structure formatted based on kind
	ID   string          `json:"id"`   // Item identifier, e.g. "c3v7f8u"
	Kind string          `json:"kind"` // Kind denotes the item's type.
	Name string          `json:"name"` // Fullname of item, e.g. "t1_c3v7f8u"
}

Thing endpoint represents the Reddit thing base class. https://github.com/reddit/reddit/wiki/JSON#thing-reddit-base-class

type Votable

type Votable struct {
	Downs int  `json:"downs"`           // Number of downvotes. (includes own)
	Likes bool `json:"likes,omitempty"` // True if thing is liked by the user
	Ups   int  `json:"ups"`             // Number of upvotes. (includes own)
}

Votable implements the Votable class

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL