geddit

package module
v0.0.0-...-78c28c1 Latest Latest
Warning

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

Go to latest
Published: May 21, 2020 License: BSD-3-Clause Imports: 16 Imported by: 37

README

geddit

GoDoc Go Report Card Build Status

Geddit is a convenient abstraction for the reddit.com API in Go. This library is a WIP. It should have some API coverage, but does not yet include things like the new OAuth model.

examples

See godoc for OAuth examples.

Here is an example usage of the old, cookie authentication method:

(NOTE: You will be heavily rate-limited by reddit's API when using cookies. Consider switching to OAuth).

package main

import (
	"fmt"

	"github.com/jzelinskie/geddit"
)

// Please don't handle errors this way.
func main() {
	// Login to reddit
	session, _ := geddit.NewLoginSession(
		"novelty_account",
		"password",
		"gedditAgent v1",
	)

	// Set listing options
	subOpts := geddit.ListingOptions{
		Limit: 10,
	}

	// Get reddit's default frontpage
	submissions, _ := session.DefaultFrontpage(geddit.DefaultPopularity, subOpts)

	// Get our own personal frontpage
	submissions, _ = session.Frontpage(geddit.DefaultPopularity, subOpts)

	// Get specific subreddit submissions, sorted by new
	submissions, _ = session.SubredditSubmissions("hockey", geddit.NewSubmissions, subOpts)

	// Print title and author of each submission
	for _, s := range submissions {
		fmt.Printf("Title: %s\nAuthor: %s\n\n", s.Title, s.Author)
	}

	// Upvote the first post
	session.Vote(submissions[0], geddit.UpVote)
}

Documentation

Overview

Package geddit implements an abstraction for the reddit.com API.

Index

Examples

Constants

View Source
const (
	UpVote     Vote = "1"
	DownVote        = "-1"
	RemoveVote      = "0"
)
View Source
const (
	DefaultPopularity        PopularitySort = ""
	HotSubmissions                          = "hot"
	NewSubmissions                          = "new"
	RisingSubmissions                       = "rising"
	TopSubmissions                          = "top"
	ControversialSubmissions                = "controversial"
)
View Source
const (
	DefaultAge ageSort = ""
	ThisHour           = "hour"
	ThisDay            = "day"
	ThisMonth          = "month"
	ThisYear           = "year"
	AllTime            = "all"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Captcha

type Captcha struct {
	Iden     string
	Response string
}

type Comment

type Comment struct {
	Author              string  //`json:"author"`
	Body                string  //`json:"body"`
	BodyHTML            string  //`json:"body_html"`
	Subreddit           string  //`json:"subreddit"`
	LinkID              string  //`json:"link_id"`
	ParentID            string  //`json:"parent_id"`
	SubredditID         string  //`json:"subreddit_id"`
	FullID              string  //`json:"name"`
	Permalink           string  //`json:"permalink"`
	Score               float64 //`json:"score"`
	UpVotes             float64 //`json:"ups"`
	DownVotes           float64 //`json:"downs"`
	Created             float64 //`json:"created_utc"`
	Edited              bool    //`json:"edited"`
	BannedBy            *string //`json:"banned_by"`
	ApprovedBy          *string //`json:"approved_by"`
	AuthorFlairTxt      *string //`json:"author_flair_text"`
	AuthorFlairCSSClass *string //`json:"author_flair_css_class"`
	NumReports          *int    //`json:"num_reports"`
	Likes               *int    //`json:"likes"`
	Replies             []*Comment
}

Comment represents a reddit comment.

func (c Comment) FullPermalink() string

FullPermalink returns the full URL of a Comment.

func (Comment) String

func (c Comment) String() string

type Deleter

type Deleter interface {
	// contains filtered or unexported methods
}

Deleter represents something that can be deleted on reddit.com.

type Friend

type Friend struct {
	Date float32 `json:"date"`
	Name string  `json:"name"`
	ID   string  `json:"id"`
}

type Karma

type Karma struct {
	CommentKarma int `json:"comment_karma"`
	LinkKarma    int `json:"link_karma"`
}

type ListingOptions

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

type LoginSession

type LoginSession struct {
	Session
	// contains filtered or unexported fields
}

LoginSession represents an HTTP session with reddit.com -- all authenticated API calls are methods bound to this type.

func NewLoginSession

func NewLoginSession(username, password, useragent string) (*LoginSession, error)

NewLoginSession creates a new session for those who want to log into a reddit account.

func (LoginSession) Clear

func (s LoginSession) Clear() error

Clear clears all session cookies and updates the current session with a new one.

func (LoginSession) Delete

func (s LoginSession) Delete(d Deleter) error

Delete deletes a Submission or Comment.

func (LoginSession) Frontpage

func (s LoginSession) Frontpage(sort PopularitySort, params ListingOptions) ([]*Submission, error)

Frontpage returns the submissions on the logged-in user's personal frontpage.

func (LoginSession) Listing

func (s LoginSession) Listing(username, listing string, sort PopularitySort, after string) ([]*Submission, error)

Listing returns a listing for an user

func (LoginSession) Me

func (s LoginSession) Me() (*Redditor, error)

Me returns an up-to-date redditor object of the logged-in user.

func (LoginSession) MyComments

func (s LoginSession) MyComments(sort PopularitySort, after string) ([]*Submission, error)

Fetch the Comments listing for the logged-in user

func (LoginSession) MyDisliked

func (s LoginSession) MyDisliked(sort PopularitySort, after string) ([]*Submission, error)

Fetch the Disliked listing for the logged-in user

func (LoginSession) MyGilded

func (s LoginSession) MyGilded(sort PopularitySort, after string) ([]*Submission, error)

Fetch the Gilded listing for the logged-in user

func (LoginSession) MyHidden

func (s LoginSession) MyHidden(sort PopularitySort, after string) ([]*Submission, error)

Fetch the Hidden listing for the logged-in user

func (LoginSession) MyLiked

func (s LoginSession) MyLiked(sort PopularitySort, after string) ([]*Submission, error)

Fetch the Liked listing for the logged-in user

func (LoginSession) MyOverview

func (s LoginSession) MyOverview(sort PopularitySort, after string) ([]*Submission, error)

Fetch the Overview listing for the logged-in user

func (LoginSession) MySaved

func (s LoginSession) MySaved(sort PopularitySort, after string) ([]*Submission, error)

Fetch the Saved listing for the logged-in user

func (LoginSession) MySubmitted

func (s LoginSession) MySubmitted(sort PopularitySort, after string) ([]*Submission, error)

Fetch the Submitted listing for the logged-in user

func (LoginSession) NeedsCaptcha

func (s LoginSession) NeedsCaptcha() (bool, error)

NeedsCaptcha returns true if captcha is required, false if it isn't

func (LoginSession) NewCaptchaIden

func (s LoginSession) NewCaptchaIden() (string, error)

NewCaptchaIden gets a new captcha iden from reddit

func (LoginSession) Reply

func (s LoginSession) Reply(r Replier, comment string) error

Reply posts a comment as a response to a Submission or Comment.

func (LoginSession) Submit

func (s LoginSession) Submit(ns *NewSubmission) error

func (LoginSession) Vote

func (s LoginSession) Vote(v Voter, vote Vote) error

Vote either votes or rescinds a vote for a Submission or Comment.

type NewSubmission

type NewSubmission struct {
	Subreddit   string
	Title       string
	Content     string
	Self        bool
	SendReplies bool
	Resubmit    bool
	Save        bool
	Captcha     *Captcha
}

NewSubmission contains the data needed to submit

func NewLinkSubmission

func NewLinkSubmission(sr, title, link string, replies bool, c *Captcha) *NewSubmission

NewLinkSubmission returns a NewSubmission with parameters appropriate for a link submission

func NewTextSubmission

func NewTextSubmission(sr, title, text string, replies bool, c *Captcha) *NewSubmission

NewTextSubmission returns a NewSubmission with parameters appropriate for a text submission

type OAuthSession

type OAuthSession struct {
	Client       *http.Client
	ClientID     string
	ClientSecret string
	OAuthConfig  *oauth2.Config
	//TokenExpiry  time.Time
	UserAgent string
	// contains filtered or unexported fields
}

OAuthSession represents an OAuth session with reddit.com -- all authenticated API calls are methods bound to this type.

func NewOAuthSession

func NewOAuthSession(clientID, clientSecret, useragent, redirectURL string) (*OAuthSession, error)

NewOAuthSession creates a new session for those who want to log into a reddit account via OAuth.

Example (Login)
package main

import (
	"log"

	"github.com/jzelinskie/geddit"
)

func main() {
	o, err := geddit.NewOAuthSession(
		"client_id",
		"client_secret",
		"Testing OAuth Bot by u/my_user v0.1 see source https://github.com/jzelinskie/geddit",
		"http://redirect.url",
	)
	if err != nil {
		log.Fatal(err)
	}

	// Create new auth token for confidential clients (personal scripts/apps).
	err = o.LoginAuth("my_user", "my_password")
	if err != nil {
		log.Fatal(err)
	}

	// Ready to make API calls!
}
Output:

Example (Url)
package main

import (
	"fmt"
	"log"

	"github.com/jzelinskie/geddit"
)

func main() {
	o, err := geddit.NewOAuthSession(
		"client_id",
		"client_secret",
		"Testing OAuth Bot by u/my_user v0.1 see source https://github.com/jzelinskie/geddit",
		"http://redirect.url",
	)
	if err != nil {
		log.Fatal(err)
	}

	// Pass a random/unique state string which will be returned to the
	//   redirect URL. Ideally, you should verify that it matches to
	//   avoid CSRF attack.
	url := o.AuthCodeURL("random string", []string{"identity", "read"})
	fmt.Printf("Visit %s to obtain auth code", url)

	var code string
	fmt.Scanln(&code)

	// Create and set token using given auth code.
	err = o.CodeAuth(code)
	if err != nil {
		log.Fatal(err)
	}

	// Ready to make API calls!
}
Output:

func (*OAuthSession) AboutRedditor

func (o *OAuthSession) AboutRedditor(user string) (*Redditor, error)

AboutRedditor returns a Redditor for the given username using OAuth.

func (*OAuthSession) AboutSubreddit

func (o *OAuthSession) AboutSubreddit(name string) (*Subreddit, error)

AboutSubreddit returns a subreddit for the given subreddit name using OAuth.

func (*OAuthSession) AuthCodeURL

func (o *OAuthSession) AuthCodeURL(state string, scopes []string) string

AuthCodeURL creates and returns an auth URL which contains an auth code.

func (*OAuthSession) CodeAuth

func (o *OAuthSession) CodeAuth(code string) error

CodeAuth creates and sets a token using an authentication code returned from AuthCodeURL.

func (*OAuthSession) Comments

func (o *OAuthSession) Comments(h *Submission, sort PopularitySort, params ListingOptions) ([]*Comment, error)

Comments returns the comments for a given Submission using OAuth.

func (*OAuthSession) Delete

func (o *OAuthSession) Delete(d Deleter) error

Delete deletes a link or comment using the given full name ID.

func (*OAuthSession) Frontpage

func (o *OAuthSession) Frontpage(sort PopularitySort, params ListingOptions) ([]*Submission, error)

Frontpage returns the submissions on the default reddit frontpage using OAuth.

func (*OAuthSession) Listing

func (o *OAuthSession) Listing(username, listing string, sort PopularitySort, params ListingOptions) ([]*Submission, error)

Listing returns a slice of Submission pointers. See https://www.reddit.com/dev/api#listings for documentation.

func (*OAuthSession) LoginAuth

func (o *OAuthSession) LoginAuth(username, password string) error

LoginAuth creates the required HTTP client with a new token.

func (*OAuthSession) Me

func (o *OAuthSession) Me() (*Redditor, error)

func (*OAuthSession) MyFriends

func (o *OAuthSession) MyFriends() ([]Friend, error)

func (*OAuthSession) MyKarma

func (o *OAuthSession) MyKarma() ([]Karma, error)

func (*OAuthSession) MyPreferences

func (o *OAuthSession) MyPreferences() (*Preferences, error)

func (*OAuthSession) MySavedComments

func (o *OAuthSession) MySavedComments(params ListingOptions) ([]*Comment, error)

MySavedComments fetches comments saved by current user using OAuth.

func (o *OAuthSession) MySavedLinks(params ListingOptions) ([]*Submission, error)

MySavedLinks fetches links saved by current user using OAuth.

func (*OAuthSession) MySubreddits

func (o *OAuthSession) MySubreddits() ([]*Subreddit, error)

MySubreddits fetchs subreddits the current user subscribes to. TODO support other endpoints https://www.reddit.com/dev/api/#GET_subreddits_mine_{where}

func (*OAuthSession) MyTrophies

func (o *OAuthSession) MyTrophies() ([]*Trophy, error)

func (*OAuthSession) MyUpvoted

func (o *OAuthSession) MyUpvoted(sort PopularitySort, params ListingOptions) ([]*Submission, error)

func (*OAuthSession) NeedsCaptcha

func (o *OAuthSession) NeedsCaptcha() (bool, error)

NeedsCaptcha check whether CAPTCHAs are needed for the Submit function.

func (*OAuthSession) NewCaptcha

func (o *OAuthSession) NewCaptcha() (string, error)

NewCaptcha returns a string used to create CAPTCHA links for users.

func (OAuthSession) Reply

func (o OAuthSession) Reply(r Replier, comment string) (*Comment, error)

Reply posts a comment as a response to a Submission or Comment using OAuth.

func (*OAuthSession) Save

func (o *OAuthSession) Save(v Voter, category string) error

Save saves a link or comment using OAuth.

func (*OAuthSession) SavedComments

func (o *OAuthSession) SavedComments(user string, params ListingOptions) ([]*Comment, error)

SavedComments fetches comments saved by given username using OAuth.

func (o *OAuthSession) SavedLinks(username string, params ListingOptions) ([]*Submission, error)

SavedLinks fetches links saved by given username using OAuth.

func (*OAuthSession) Submit

func (o *OAuthSession) Submit(ns *NewSubmission) (*Submission, error)

Submit accepts a NewSubmission type and submits a new link using OAuth. Returns a Submission type.

func (*OAuthSession) SubredditComments

func (o *OAuthSession) SubredditComments(subreddit string) ([]*Comment, error)

SubredditComments fetches all the new comments in a subreddit, and returns them in a slice of Comment structs This function uses www.reddit.com instead of the OAuth API as the latter doesn't have an endpoint for a particular subreddit's comments

func (*OAuthSession) SubredditSubmissions

func (o *OAuthSession) SubredditSubmissions(subreddit string, sort PopularitySort, params ListingOptions) ([]*Submission, error)

SubredditSubmissions returns the submissions on the given subreddit using OAuth.

func (*OAuthSession) Throttle

func (o *OAuthSession) Throttle(interval time.Duration)

Throttle sets the interval of each HTTP request. Disable by setting interval to 0. Disabled by default. Throttling is applied to invidual OAuthSession types.

func (*OAuthSession) Unsave

func (o *OAuthSession) Unsave(v Voter, category string) error

Unsave saves a link or comment using OAuth.

func (*OAuthSession) Upvoted

func (o *OAuthSession) Upvoted(username string, sort PopularitySort, params ListingOptions) ([]*Submission, error)

func (*OAuthSession) UserTrophies

func (o *OAuthSession) UserTrophies(user string) ([]*Trophy, error)

func (*OAuthSession) Vote

func (o *OAuthSession) Vote(v Voter, dir Vote) error

Vote either votes or rescinds a vote for a Submission or Comment using OAuth.

type PopularitySort

type PopularitySort string

PopularitySort represents the possible ways to sort submissions by popularity.

type Preferences

type Preferences struct {
	Research               bool   `json:"research"`
	ShowStylesheets        bool   `json:"show_stylesheets"`
	ShowLinkFlair          bool   `json:"show_link_flair"`
	ShowTrending           bool   `json:"show_trending"`
	PrivateFeeds           bool   `json:"private_feeds"`
	IgnoreSuggestedSort    bool   `json:"ignore_suggested_sort"`
	Media                  string `json:"media"`
	ClickGadget            bool   `json:"clickgadget"`
	LabelNSFW              bool   `json:"label_nsfw"`
	Over18                 bool   `json:"over_18"`
	EmailMessages          bool   `json:"email_messages"`
	HighlightControversial bool   `json:"highlight_controversial"`
	ForceHTTPS             bool   `json:"force_https"`
	Language               string `json:"lang"`
	HideFromRobots         bool   `json:"hide_from_robots"`
	PublicVotes            bool   `json:"public_votes"`
	ShowFlair              bool   `json:"show_flair"`
	HideAds                bool   `json:"hide_ads"`
	Beta                   bool   `json:"beta"`
	NewWindow              bool   `json:"newwindow"`
	LegacySearch           bool   `json:"legacy_search"`
}

type Redditor

type Redditor struct {
	ID            string  `json:"id"`
	Name          string  `json:"name"`
	Created       float64 `json:"created_utc"`
	Employee      bool    `json:"is_employee"`
	Gold          bool    `json:"is_gold"`
	IconImageURL  string  `json:"icon_img"`
	Mod           bool    `json:"is_mod"`
	Mail          bool    `json:"has_mail"`
	ModMail       bool    `json:"has_mod_mail"`
	Verified      bool    `json:"verified"`
	VerifiedEmail bool    `json:"has_verified_email"`
	Karma
}

func (*Redditor) String

func (r *Redditor) String() string

String returns the string representation of a reddit user.

type Replier

type Replier interface {
	// contains filtered or unexported methods
}

Replier represents something that can be replied to on reddit.com.

type Session

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

Session represents an HTTP session with reddit.com without logging into an account.

func NewSession

func NewSession(useragent string) *Session

NewSession creates a new unauthenticated session to reddit.com.

func (Session) AboutRedditor

func (s Session) AboutRedditor(username string) (*Redditor, error)

AboutRedditor returns a Redditor for the given username.

func (Session) AboutSubreddit

func (s Session) AboutSubreddit(subreddit string) (*Subreddit, error)

AboutSubreddit returns a subreddit for the given subreddit name.

func (Session) CaptchaImage

func (s Session) CaptchaImage(iden string) (image.Image, error)

CaptchaImage gets the png corresponding to the captcha iden and decodes it

func (Session) Comments

func (s Session) Comments(h *Submission) ([]*Comment, error)

Comments returns the comments for a given Submission.

func (Session) DefaultFrontpage

func (s Session) DefaultFrontpage(sort PopularitySort, params ListingOptions) ([]*Submission, error)

DefaultFrontpage returns the submissions on the default reddit frontpage.

func (Session) RedditorComments

func (s Session) RedditorComments(username string, params ListingOptions) ([]*Comment, error)

RedditorComments returns a slice of Comments from a given Reddit user name.

func (Session) RedditorSubmissions

func (s Session) RedditorSubmissions(username string, params ListingOptions) ([]*Submission, error)

RedditorSubmissions returns a slice of Submissions from a given Reddit user name.

func (Session) SubmissionsComments

func (s Session) SubmissionsComments(submissionID string) ([]*Comment, error)

SubmissionComments returns the comments on a submission given it's ID.

func (Session) SubredditComments

func (s Session) SubredditComments(subreddit string, params ListingOptions) ([]*Comment, error)

SubredditComments gets all the new comments from a subreddit, returning them in a slice of Comment structs

func (Session) SubredditSubmissions

func (s Session) SubredditSubmissions(subreddit string, sort PopularitySort, params ListingOptions) ([]*Submission, error)

SubredditSubmissions returns the submissions on the given subreddit.

type Submission

type Submission struct {
	Author        string  `json:"author"`
	Title         string  `json:"title"`
	URL           string  `json:"url"`
	Domain        string  `json:"domain"`
	Subreddit     string  `json:"subreddit"`
	SubredditID   string  `json:"subreddit_id"`
	FullID        string  `json:"name"`
	ID            string  `json:"id"`
	Permalink     string  `json:"permalink"`
	Selftext      string  `json:"selftext"`
	SelftextHTML  string  `json:"selftext_html"`
	ThumbnailURL  string  `json:"thumbnail"`
	DateCreated   float64 `json:"created_utc"`
	NumComments   int     `json:"num_comments"`
	Score         int     `json:"score"`
	Ups           int     `json:"ups"`
	Downs         int     `json:"downs"`
	IsNSFW        bool    `json:"over_18"`
	IsSelf        bool    `json:"is_self"`
	WasClicked    bool    `json:"clicked"`
	IsSaved       bool    `json:"saved"`
	BannedBy      *string `json:"banned_by"`
	LinkFlairText string  `json:"link_flair_text"`
}

Submission represents an individual post from the perspective of a subreddit. Remember to check for nil pointers before using any pointer fields.

func (h *Submission) FullPermalink() string

FullPermalink returns the full URL of a submission.

func (*Submission) String

func (h *Submission) String() string

String returns the string representation of a submission.

type Subreddit

type Subreddit struct {
	Name        string  `json:"display_name"`
	Title       string  `json:"title"`
	Desc        string  `json:"description"`
	PublicDesc  string  `json:"public_description"`
	URL         string  `json:"url"`
	FullID      string  `json:"name"`
	ID          string  `json:"id"`
	HeaderImg   string  `json:"header_img"`
	DateCreated float64 `json:"created_utc"`
	NumSubs     int     `json:"subscribers"`
	IsNSFW      bool    `json:"over18"`
}

Subreddit represents a subreddit from reddit.com.

func (*Subreddit) String

func (s *Subreddit) String() string

String returns the string representation of a subreddit.

type Trophy

type Trophy struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	Icon        string `json:"icon_70"`
}

type Vote

type Vote string

vote represents the three possible states of a vote on reddit.

type Voter

type Voter interface {
	// contains filtered or unexported methods
}

Voter represents something that can be voted on reddit.com.

Jump to

Keyboard shortcuts

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