reddit

package module
v0.0.0-...-682b83c Latest Latest
Warning

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

Go to latest
Published: Aug 18, 2016 License: Apache-2.0 Imports: 10 Imported by: 0

README

Minimal Reddit API wrapper for Go.

This is a work in progress and may contain bugs. It has only been tested for the top posts query.

The GoDoc contains detailed documentation. The package examples contain details on how to use the package.

Please read the reddit API documentation first before reading these docs. Some useful links are:

This currently only supports OAuth for script apps. It does not support refreshing OAuth tokens. It provides the following:

  • Code to save and load authorization credentials (client id, client secret, etc).
  • A simple API to obtain and store an OAuth token for a script app using these credentials.
  • An API to perform GET requests using the obtained token.
  • An API to stream listings.

Example Usage

cfg, err := reddit.LoadConfig(reddit.DefaultConfigFile)
if err != nil {
    log.Fatal(err)
}
if err := cfg.AuthScript(http.DefaultClient); err != nil {
    log.Fatal(err)
}
// Print top posts of the day from /r/golang
stream := cfg.Stream(http.DefaultClient, &reddit.TopPosts{SubReddit: "golang", Duration: reddit.TopDay})
for stream.Next() {
    thing := stream.Thing()
    link := thing.Data.(*reddit.Link)
    fmt.Println(link.Title, link.URL)
}
if err := stream.Error(); err != nil {
    log.Fatal(err)
}

Documentation

Overview

Package reddit provides wrappers to the Reddit API for Go.

Please read the reddit API documentation first before reading these docs. Some useful links are:

This currently only supports OAuth for script apps. It does not support refreshing OAuth tokens. It provides the following:

  • Code to save and load authorization credentials (client id, client secret, etc).
  • A simple API to obtain and store an OAuth token for a script app using these credentials.
  • An API to perform GET requests using the obtained token.
  • An API to stream listings.

Please see the package examples for details on how to use the above functionality.

Index

Examples

Constants

View Source
const (
	// RedditAuthURL is the URL used to obtain an authentication token.
	RedditAuthURL = "https://www.reddit.com/api/v1/access_token"
	// RedditAPIURL is the base URL used to make API calls.
	RedditAPIURL = "https://oauth.reddit.com"
	// DefaultConfigFile is the default file used to store API credentials.
	DefaultConfigFile = "~/.reddit_creds"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Account

type Account struct {
	Created
	CommentKarma     int    `json:"comment_karma"`
	HasMail          bool   `json:"has_mail"`
	HasModMail       bool   `json:"has_mod_mail"`
	HasVerifiedEmail bool   `json:"has_verified_email"`
	ID               string `json:"id"`
	InboxCount       int    `json:"inbox_count"`
	IsFriend         bool   `json:"is_friend"`
	IsGold           bool   `json:"is_gold"`
	IsMod            bool   `json:"is_mod"`
	LinkKarma        int    `json:"link_karma"`
	Modhash          string `json:"modhash"`
	Name             string `json:"name"`
	Over18           bool   `json:"over_18"`
}

Account represents a single account on reddit.

See https://github.com/reddit/reddit/wiki/JSON

type AuthToken

type AuthToken struct {
	Expires int64  `json:"expires"` // Expirations time as seconds since the unix epoch
	Token   string `json:"token"`   // OAuth token
	Type    string `json:"type"`    // Type of token (usually just bearer)
}

AuthToken contains an authentication token obtained via OAuth.

type Comment

type Comment struct {
	Votable
	Created
	ApprovedBy          string  `json:"approved_by"`
	Author              string  `json:"author"`
	AuthorFlairCSSClass string  `json:"author_flair_css_class"`
	AuthorFlairText     string  `json:"author_flair_text"`
	BannedBy            string  `json:"banned_by"`
	Body                string  `json:"body"`
	BodyHTML            string  `json:"body_html"`
	Edited              Edited  `json:"edited"`
	Gilded              int     `json:"gilded"`
	Likes               bool    `json:"likes"`
	LinkAuthor          string  `json:"link_author"`
	LinkID              string  `json:"link_id"`
	LinkTitle           string  `json:"link_title"`
	LinkURL             string  `json:"link_url"`
	NumReports          int     `json:"num_reports"`
	ParentID            string  `json:"parent_id"`
	Replies             []Thing `json:"replies"`
	Saved               bool    `json:"saved"`
	Score               int     `json:"score"`
	ScoreHidden         bool    `json:"score_hidden"`
	Subreddit           string  `json:"subreddit"`
	SubredditID         string  `json:"subreddit_id"`
	Distinguished       string  `json:"distinguished"`
}

Comment represents a single reddit comment.

See https://github.com/reddit/reddit/wiki/JSON

type Config

type Config struct {
	Credentials Credentials `json:"credentials"`
	AuthToken   AuthToken   `json:"token"`
}

Config contains configuration needed to perform reddit API requests. This consists of credentials used to obtain a token and the current token. The credentials must be provided by the user of this library. Calling AuthScript then authenticates the client and populates the AuthToken.

func LoadConfig

func LoadConfig(file string) (*Config, error)

LoadConfig loads and validates a Config structure stored as JSON from a configuration file. If the file path starts with ~ this is expanded to the home directory of the user. All fields in the Credentials field must be non-empty.

func (*Config) AuthScript

func (c *Config) AuthScript(client *http.Client) error

AuthScript authenticates the client against reddit's API servers using the method described in https://github.com/reddit/reddit/wiki/OAuth2-Quick-Start-Example. If Config.AuthToken holds a valid token, no authentication is performed.

If authentication is successful Config.AuthToken is populated with the received authentication token. Use Config.Save to save this authentication token.

func (*Config) Get

func (c *Config) Get(client *http.Client, url string, val interface{}) error

Get performs an authentication GET request to the provided URL using the provided http.Client instance. Responses are unmarshalled into val.

func (*Config) Save

func (c *Config) Save(file string) error

Save saves a config in JSON format to the provided file. If the file path starts with ~ this is expanded to the home directory of the user. No validation is performed on the Config prior to saving.

func (*Config) Stream

func (c *Config) Stream(client *http.Client, lister Lister) *Stream

Stream returns a Stream that pages through a Listing. The provided lister is automatically updated to hold the correct After and Count values for paging. All requests are performed using the provided http.Client instance.

Example
cfg, err := reddit.LoadConfig(reddit.DefaultConfigFile)
if err != nil {
	log.Fatal(err)
}
if err := cfg.AuthScript(http.DefaultClient); err != nil {
	log.Fatal(err)
}
// Print top posts of the day from /r/golang
stream := cfg.Stream(http.DefaultClient, &reddit.TopPosts{SubReddit: "golang", Duration: reddit.TopDay})
for stream.Next() {
	thing := stream.Thing()
	link := thing.Data.(*reddit.Link)
	fmt.Println(link.Title, link.URL)
}
if err := stream.Error(); err != nil {
	log.Fatal(err)
}
Output:

type Created

type Created struct {
	Created    float64 `json:"created"`
	CreatedUTC float64 `json:"created_utc"`
}

Created holds creation time information.

See https://github.com/reddit/reddit/wiki/JSON

type Credentials

type Credentials struct {
	Username     string `json:"username"`      // Reddit username of the developer account.
	Password     string `json:"password"`      // Password for the above user.
	ClientID     string `json:"clientID"`      // Client ID for the script app.
	ClientSecret string `json:"client_secret"` // Client secret for the script app.
	UserAgent    string `json:"user_agent"`    // User Agent to use when making requests.
}

Credentials contains script credentials for a reddit developer account.

type Edited

type Edited struct {
	Unix   float64
	Edited bool
}

Edited denotes the current edit state of a Thing. If Edited is true, Unix will hold the last edited time as seconds since the unix epoch.

func (*Edited) MarshalJSON

func (e *Edited) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for Edited. It returns false if e.Edited is false and a float timestamp if not.

func (*Edited) UnmarshalJSON

func (e *Edited) UnmarshalJSON(b []byte) error

UnmarshalJSON implement json.Unmarshaller for Edited. It expects false if no edits were performed, or a float timestamp of when the last edit was performed.

type HeaderSize

type HeaderSize struct {
	Width  int
	Height int
}

HeaderSize is a header size for a subreddit.

func (*HeaderSize) MarshalJSON

func (h *HeaderSize) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for HeaderSize. It converts HeaderSize into an array of ints.

func (*HeaderSize) UnmarshalJSON

func (h *HeaderSize) UnmarshalJSON(b []byte) error

UnmarshalJSON implements json.Unmarshaler for HeaderSize. It converts an array of ints into a HeaderSize.

type Link struct {
	Votable
	Created
	Author              string          `json:"author"`
	AuthorFlairCSSClass string          `json:"author_flair_css_class"`
	AuthorFlairText     string          `json:"author_flair_text"`
	Clicked             bool            `json:"clicked"`
	Domain              string          `json:"domain"`
	Hidden              bool            `json:"hidden"`
	IsSelf              bool            `json:"is_self"`
	Likes               bool            `json:"likes"`
	LinkFlairCSSClass   string          `json:"link_flair_css_class"`
	LinkFlairText       string          `json:"link_flair_text"`
	Locked              bool            `json:"locked"`
	Media               json.RawMessage `json:"media"`
	MediaEmbed          json.RawMessage `json:"media_embed"`
	NumComments         int             `json:"num_comments"`
	Over18              bool            `json:"over_18"`
	Permalink           string          `json:"permalink"`
	Saved               bool            `json:"saved"`
	Score               int             `json:"score"`
	Selftext            string          `json:"selftext"`
	SelftextHTML        string          `json:"selftext_html"`
	Subreddit           string          `json:"subreddit"`
	SubredditID         string          `json:"subreddit_id"`
	Thumbnail           string          `json:"thumbnail"`
	Title               string          `json:"title"`
	URL                 string          `json:"url"`
	Edited              Edited          `json:"edited"`
	Distinguished       string          `json:"distinguished"`
	Stickied            bool            `json:"stickied"`
}

Link represents a single link on reddit.

See https://github.com/reddit/reddit/wiki/JSON

type Lister

type Lister interface {
	URLer
	List() *ListingOptions
}

Lister provides access to a modifiable ListingOptions instance which is used to stream Listings.

type Listing

type Listing struct {
	Before   string  `json:"before"`
	After    string  `json:"after"`
	Modhash  string  `json:"modhash"`
	Children []Thing `json:"children"`
}

Listing contains paginated content from an API request.

See https://github.com/reddit/reddit/wiki/JSON

type ListingOptions

type ListingOptions struct {
	After  string `url:"after,omitempty"`
	Before string `url:"before,omitempty"`
	Count  int    `url:"count,omitempty"`
	Limit  int    `url:"limit,omitempty"`
	Show   string `url:"show,omitempty"`
}

ListingOptions control the size and position of a streamed listing. See https://www.reddit.com/dev/api for more information on what these parameters mean.

type Message

type Message struct {
	Created
	Author           string `json:"author"`
	Body             string `json:"body"`
	BodyHTML         string `json:"body_html"`
	Context          string `json:"context"`
	FirstMessage     string `json:"first_message"`
	FirstMessageName string `json:"first_message_name"`
	Likes            bool   `json:"likes"`
	LinkTitle        string `json:"link_title"`
	Name             string `json:"name"`
	New              bool   `json:"new"`
	ParentID         string `json:"parent_id"`
	Replies          string `json:"replies"`
	Subject          string `json:"subject"`
	Subreddit        string `json:"subreddit"`
	WasComment       bool   `json:"was_comment"`
}

Message represents a single message on reddit.

See https://github.com/reddit/reddit/wiki/JSON

type More

type More struct {
	Children []string `json:"children"`
}

More holds a list of Thing IDs that are present but not included in full in a response.

See https://github.com/reddit/reddit/wiki/JSON

type Stream

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

Stream represents a stream of Thing values obtained from a Listing url.

func (*Stream) Error

func (s *Stream) Error() error

Error returns a non-nil error if there were any errors when fetching the listing.

func (*Stream) Next

func (s *Stream) Next() bool

Next returns true iff there are more Things to read. It automatically fetches a new Listing when the current one is exhausted. Always call Error() after Next returns false to check if any errors are present.

func (*Stream) Thing

func (s *Stream) Thing() Thing

Thing returns the current Thing. Call Next to advance to the next Thing in the stream. This will return the zero value for Thing if Stream.Error() is non-nil or the end of the stream has been reached.

type SubReddit

type SubReddit struct {
	AccountsActive       int         `json:"accounts_active"`
	CommentScoreHideMins int         `json:"comment_score_hide_mins"`
	Description          string      `json:"description"`
	DescriptionHTML      string      `json:"description_html"`
	DisplayName          string      `json:"display_name"`
	HeaderImg            string      `json:"header_img"`
	HeaderSize           *HeaderSize `json:"header_size"`
	HeaderTitle          string      `json:"header_title"`
	Over18               bool        `json:"over18"`
	PublicDescription    string      `json:"public_description"`
	PublicTraffic        bool        `json:"public_traffic"`
	Subscribers          int64       `json:"subscribers"`
	SubmissionType       string      `json:"submission_type"`
	SubmitLinkLabel      string      `json:"submit_link_label"`
	SubmitTextLabel      string      `json:"submit_text_label"`
	SubredditType        string      `json:"subreddit_type"`
	Title                string      `json:"title"`
	URL                  string      `json:"url"`
	UserIsBanned         bool        `json:"user_is_banned"`
	UserIsContributor    bool        `json:"user_is_contributor"`
	UserIsModerator      bool        `json:"user_is_moderator"`
	UserIsSubscriber     bool        `json:"user_is_subscriber"`
}

SubReddit represents a single subreddit.

See https://github.com/reddit/reddit/wiki/JSON

type Thing

type Thing struct {
	ID   string      `json:"id"`
	Name string      `json:"name"`
	Kind string      `json:"kind"`
	Data interface{} `json:"data"`
}

Thing holds attributes common to all reddit api entities.

See https://github.com/reddit/reddit/wiki/JSON

func (*Thing) UnmarshalJSON

func (t *Thing) UnmarshalJSON(b []byte) error

UnmarshalJSON implements json.Unmarshaller for Thing. It performs this in two passes. In the first pass the data is left unmarshalled. The value of kind is then used to determine the struct type for Data.

type TopDuration

type TopDuration string

TopDuration represents a sort value for fetching top posts.

const (
	TopHour  TopDuration = "hour"
	TopDay   TopDuration = "day"
	TopWeek  TopDuration = "week"
	TopMonth TopDuration = "month"
	TopYear  TopDuration = "year"
	TopAll   TopDuration = "all"
)

TopHour, TopDay, TopWeek, TopMonth, TopYear and TopAll are supported sort values for a TopPosts request.

type TopPosts

type TopPosts struct {
	ListingOptions
	SubReddit string      `url:"-"`
	Duration  TopDuration `url:"t,omitempty"`
}

TopPosts is a query for the top posts of a specified subreddit. It implements URLer and Lister and can be used with Config.Stream to stream the top posts of a subreddit.

func (*TopPosts) List

func (t *TopPosts) List() *ListingOptions

List returns the ListingOptions for TopPosts

func (*TopPosts) URL

func (t *TopPosts) URL() (string, error)

URL returns the URL to use when fetching the top posts.

type URLer

type URLer interface {
	URL() (string, error)
}

URLer returns a URL to be used for an API call.

type Votable

type Votable struct {
	Ups   int  `json:"ups"`
	Downs int  `json:"downs"`
	Likes bool `json:"likes"`
}

Votable holds attributes related to voting.

See https://github.com/reddit/reddit/wiki/JSON

Jump to

Keyboard shortcuts

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