mira

package module
Version: v1.1.2 Latest Latest
Warning

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

Go to latest
Published: Jul 27, 2019 License: Apache-2.0 Imports: 13 Imported by: 0

README

MIRA or Meme Investor Reddit Api

Go Report Card Build Status GoDoc PRs Welcome

For full documentation, please see the Godoc page

MIRA is a Reddit Api Wrapper written in beautiful Go. This is a subproject of a bigger project MemeInvestor_bot.

It is super simple to use the bot as we also provide you with simple but fully extensive structs. We utilize the best features of Go, such as closures, channels, goroutines, garbage collection, etc.

Currently, mira is a project that just began its life. We still have many new Reddit endpoints to cover. We have the basic functionality implemented, like streaming comment replies, new submissions. Comment, post, edit, reply, and delete options for our instances.

Two quick notes: all actions should be done via Reddit struct, I thought it would make it simpler to work with. Secondly, all actions require the objects full thing_id, so you have to use GetId() to get that id. Every struct has that method implemented and it will return a string in the form of t[1-6]_[a-z0-9]{5}. Refer to the following table for the classifications of the structs.

Type Prefixes

Prefix Type
t1 Comment
t2 Redditor
t3 Submission, PostListing contents
t4 Message (NOT IMPLEMENTED)
t5 Subreddit
t6 Award (NOT IMPLEMENTED)

Config file

The config file structure is very simple:

CLIENT_ID =
CLIENT_SECRET =
USERNAME =
PASSWORD =
USER_AGENT =

Examples

Streaming comment replies

Below is an example on how to make a simple bot that listens to a stream of comment replies and replies.

package main

import (
	"github.com/thecsw/mira"
	"fmt"
)

func main() {
	r, _ := mira.Init(mira.ReadCredsFromFile("login.conf"))
	c, _ := r.StreamCommentReplies()
	for {
		msg := <- c
		r.Reply(msg.GetId(), "I got your message!")
	}
}
Streaming new submissions

Streaming new submissions is very simple too. You can do it the same way as streaming comment replies.

package main

import (
	"github.com/thecsw/mira"
	"fmt"
)

func main() {
	r, _ := mira.Init(mira.ReadCredsFromFile("login.conf"))
	c, _ := r.StreamNewPosts("subredditname")
	for {
		post := <- c
		r.Comment(post.GetId(), "I saw your submission!")
	}
}
Submitting, Commenting, Replying, and Editing

It is very easy to post a submission, comment on it, reply to a message, or edit a comment.

package main

import (
	"github.com/thecsw/mira"
	"fmt"
)

func main() {
	r, _ := mira.Init(mira.ReadCredsFromFile("login.conf"))
	// Make a submission
	post, _ := r.Submit("memeinvestor_test", "mypost", "my text")
	// Comment on our new submission
	comment, _ := r.Comment(post.GetId(), "My First Comment")
	// Reply to our own comment
	reply, _ := r.Reply(comment.GetId(), "My Reply to the First Comment")
	// Delete the reply
	r.DeleteComment(reply.GetId())
	// Edit the first comment
	new_comment, _ := r.EditComment(comment.GetId(), "I Edited This!!")
	// Show the comment's body
	fmt.Println(new_comment.GetBody())
}
Composing a message

We can also send a message to another user!

package main

import (
	"github.com/thecsw/mira"
	"fmt"
)

func main() {
	r, _ := mira.Init(mira.ReadCredsFromFile("login.conf"))

	r.Compose("thecsw", "my subject", "hello, world")
	// or
	user, _ := r.GetUser("thecsw")
	r.Compose(user.GetName(), "my subject", "hello, world")
}
Going through hot, new, top, rising, controversial, and random

You can also traverse through a number of submissions using one of our methods.

package main

import (
	"github.com/thecsw/mira"
	"fmt"
)

func main() {
	r, _ := mira.Init(mira.ReadCredsFromFile("login.conf"))
	sort := "top"
	var limit int = 25
	duration := "all"
	subs, _ := r.GetSubredditPosts("subredditname", sort, duration, limit)
	
	for _, v := range subs.GetChildren() {
		fmt.Println("Submission Title: ", v.GetTitle())
	}
}

Documentation

Index

Constants

View Source
const (
	RedditBase  = "https://www.reddit.com/"
	RedditOauth = "https://oauth.reddit.com"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Comment

type Comment struct {
	Kind string                         `json:"kind"`
	Data CommentListingDataChildrenData `json:"data"`
}

func (*Comment) GetAuthor

func (ldc *Comment) GetAuthor() string

func (*Comment) GetBody

func (ldc *Comment) GetBody() string

func (*Comment) GetCreated

func (ldc *Comment) GetCreated() float64

func (*Comment) GetId

func (ldc *Comment) GetId() string

func (*Comment) GetParentId

func (ldc *Comment) GetParentId() string

func (*Comment) GetScore

func (ldc *Comment) GetScore() float64

func (*Comment) GetSubreddit

func (ldc *Comment) GetSubreddit() string

func (*Comment) IsComment

func (ldc *Comment) IsComment() bool

func (*Comment) IsCommentReply

func (ldc *Comment) IsCommentReply() bool

func (*Comment) IsRoot

func (ldc *Comment) IsRoot() bool

type CommentJson

type CommentJson struct {
	Errors []string        `json:"errors"`
	Data   CommentJsonData `json:"data"`
}

type CommentJsonData

type CommentJsonData struct {
	Things []CommentJsonDataThing `json:"things"`
}

type CommentJsonDataThing

type CommentJsonDataThing struct {
	Kind string                   `json:"kind"`
	Data CommentJsonDataThingData `json:"data"`
}

type CommentJsonDataThingData

type CommentJsonDataThingData struct {
	AuthorFlairBackgroundColor string   `json:"author_flair_background_color"`
	TotalAwardsReceived        float64  `json:"total_awards_received"`
	ApprovedAtUtc              string   `json:"approved_at_utc"`
	Distinguished              string   `json:"distinguished"`
	ModReasonBy                string   `json:"mod_reason_by"`
	BannedBy                   string   `json:"banned_by"`
	AuthorFlairType            string   `json:"author_flair_type"`
	RemovalReason              string   `json:"removal_reason"`
	LinkId                     string   `json:"link_id"`
	AuthorFlairTemplateId      string   `json:"author_flair_template_id"`
	Likes                      bool     `json:"likes"`
	Replies                    string   `json:"replies"`
	UserReports                []string `json:"user_reports"`
	Saved                      bool     `json:"saved"`
	Id                         string   `json:"id"`
	BannedAtUtc                string   `json:"banned_at_utc"`
	ModReasonTitle             string   `json:"mod_reason_title"`
	Gilded                     float64  `json:"gilded"`
	Archived                   bool     `json:"archived"`
	NoFollow                   bool     `json:"no_follow"`
	Author                     string   `json:"author"`
	RteMode                    string   `json:"rte_mode"`
	CanModPost                 bool     `json:"can_mod_post"`
	CreatedUtc                 float64  `json:"created_utc"`
	SendReplies                bool     `json:"send_replies"`
	ParentId                   string   `json:"parent_id"`
	Score                      float64  `json:"score"`
	AuthorFullname             string   `json:"author_fullname"`
	ApprovedBy                 string   `json:"approved_by"`
	Mod_note                   string   `json:"mod_note"`
	AllAwardings               []string `json:"all_awardings"`
	SubredditId                string   `json:"subreddit_id"`
	Body                       string   `json:"body"`
	Edited                     bool     `json:"edited"`
	Gildings                   Gilding  `json:"gildings"`
	AuthorFlairCssClass        string   `json:"author_flair_css_class"`
	Name                       string   `json:"name"`
	AuthorPatreonFlair         bool     `json:"author_patreon_flair"`
	Downs                      float64  `json:"downs"`
	AuthorFlairRichtext        []string `json:"author_flair_richtext"`
	IsSubmitter                bool     `json:"is_submitter"`
	CollapsedReason            string   `json:"collapsed_reason"`
	BodyHtml                   string   `json:"body_html"`
	Stickied                   bool     `json:"stickied"`
	CanGild                    bool     `json:"can_gild"`
	Removed                    bool     `json:"removed"`
	Approved                   bool     `json:"approved"`
	AuthorFlairTextColor       string   `json:"author_flair_text_color"`
	ScoreHidden                bool     `json:"score_hidden"`
	Permalink                  string   `json:"permalink"`
	NumReports                 float64  `json:"num_reports"`
	Locked                     bool     `json:"locked"`
	ReportReasons              []string `json:"report_reasons"`
	Created                    float64  `json:"created"`
	Subreddit                  string   `json:"subreddit"`
	AuthorFlairText            string   `json:"author_flair_text"`
	Spam                       bool     `json:"spam"`
	Collapsed                  bool     `json:"collapsed"`
	SubredditNamePrefixed      string   `json:"subreddit_name_prefixed"`
	Controversiality           float64  `json:"controversiality"`
	IgnoreReports              bool     `json:"ignore_reports"`
	ModReports                 []string `json:"mod_reports"`
	SubredditType              string   `json:"subreddit_type"`
	Ups                        float64  `json:"ups"`
}

type CommentListing

type CommentListing struct {
	Kind string             `json:"kind"`
	Data CommentListingData `json:"data"`
}

func (*CommentListing) GetChildren

func (l *CommentListing) GetChildren() []Comment

type CommentListingData

type CommentListingData struct {
	Modhash  string    `json:"modhash"`
	Dist     float64   `json:"dist"`
	Children []Comment `json:"children"`
	After    string    `json:"after"`
	Before   string    `json:"before"`
}

type CommentListingDataChildrenData

type CommentListingDataChildrenData struct {
	FirstMessage          string   `json:"first_message"`
	FirstMessageName      string   `json:"first_message_name"`
	Subreddit             string   `json:"subreddit"`
	Likes                 string   `json:"likes"`
	Replies               string   `json:"replies"`
	Id                    string   `json:"id"`
	Subject               string   `json:"subject"`
	WasComment            bool     `json:"was_comment"`
	Score                 float64  `json:"score"`
	Author                string   `json:"author"`
	NumComments           float64  `json:"num_comments"`
	ParentId              string   `json:"parent_id"`
	SubredditNamePrefixed string   `json:"subreddit_name_prefixed"`
	New                   bool     `json:"new"`
	Body                  string   `json:"body"`
	LinkTitle             string   `json:"link_title"`
	Dest                  string   `json:"dest"`
	BodyHtml              string   `json:"body_html"`
	Name                  string   `json:"name"`
	Created               float64  `json:"created"`
	Created_utc           float64  `json:"created_utc"`
	Context               string   `json:"context"`
	Distinguished         string   `json:"distinguished"`
	Children              []string `json:"children"`
}

type CommentWrap

type CommentWrap struct {
	Json CommentJson `json:"json"`
}

func (CommentWrap) CreatedAt

func (c CommentWrap) CreatedAt() float64

Get the UNIX timestamp when the comment was created

func (CommentWrap) GetAuthor

func (c CommentWrap) GetAuthor() string

Get the name of the author. With no u/ preppended

func (CommentWrap) GetAuthorId

func (c CommentWrap) GetAuthorId() string

Get the name of the author. With no u/ preppended

func (CommentWrap) GetBody

func (c CommentWrap) GetBody() string

Get the body of the message

func (CommentWrap) GetDowns

func (c CommentWrap) GetDowns() float64

Get the number of downvotes

func (CommentWrap) GetId

func (c CommentWrap) GetId() string

Get ID of the comment. Should be something "t1_..."

func (CommentWrap) GetParentId

func (c CommentWrap) GetParentId() string

Get ID of the comment. Should be something "t1_..."

func (CommentWrap) GetScore

func (c CommentWrap) GetScore() float64

Get the score of the comment (Ups - Downs)

func (CommentWrap) GetSubreddit

func (c CommentWrap) GetSubreddit() string

Get the subreddit's name. With no r/ preppended

func (CommentWrap) GetSubredditId

func (c CommentWrap) GetSubredditId() string

func (CommentWrap) GetUps

func (c CommentWrap) GetUps() float64

Get the number of upvotes on the comment

func (CommentWrap) IsApproved

func (c CommentWrap) IsApproved() bool

Return true if the comment is approved, false otherwise

func (CommentWrap) IsAuthor

func (c CommentWrap) IsAuthor() bool

Return true if the author is submission's author, false otherwise

func (CommentWrap) IsRemoved

func (c CommentWrap) IsRemoved() bool

Return true if the comment is removed, false otherwise

func (CommentWrap) IsSticky

func (c CommentWrap) IsSticky() bool

Return true if the comment is stickied, false otherwise

type Credentials

type Credentials struct {
	ClientId     string
	ClientSecret string
	Username     string
	Password     string
	UserAgent    string
}

func ReadCredsFromEnv

func ReadCredsFromEnv() Credentials

Assuming that they all exist. Probably a bad idea. We can expand it later and do a more aggressive error handling.

func ReadCredsFromFile

func ReadCredsFromFile(file string) Credentials

type Gilding

type Gilding struct {
	Gid map[string]int `json:"gid"`
}

type Me

type Me struct {
	IsEmployee              bool        `json:"is_employee"`
	SeenLayoutSwitch        bool        `json:"seen_layout_switch"`
	HasVisitedNewProfile    bool        `json:"has_visited_new_profile"`
	PrefNoProfanity         bool        `json:"pref_no_profanity"`
	HasExternalAccount      bool        `json:"has_external_account"`
	PrefGeopopular          string      `json:"pref_geopopular"`
	SeenRedesignModal       bool        `json:"seen_redesign_modal"`
	PrefShowTrending        bool        `json:"pref_show_trending"`
	Subreddit               Subreddit_s `json:"subreddit"`
	IsSponsor               bool        `json:"is_sponsor"`
	GoldExpiration          float64     `json:"gold_expiration"`
	HasGoldSubscription     bool        `json:"has_gold_subscription"`
	NumFriends              float64     `json:"num_friends"`
	Features                MeFeatures  `json:"features"`
	HasAndroidSubscription  bool        `json:"has_android_subscription"`
	Verified                bool        `json:"verified"`
	NewModmailExists        bool        `json:"new_modmail_exists"`
	PrefAutoplay            bool        `json:"pref_autoplay"`
	Coins                   float64     `json:"coins"`
	HasPaypalSubscription   bool        `json:"has_paypal_subscription"`
	HasSubscribedToPremium  bool        `json:"has_subscribed_to_premium"`
	Id                      string      `json:"id"`
	HasStripeSubscription   bool        `json:"has_stripe_subscription"`
	SeenPremiumAdblockModal bool        `json:"seen_premium_adblock_modal"`
	CanCreateSubreddit      bool        `json:"can_create_subreddit"`
	Over18                  bool        `json:"over_18"`
	IsGold                  bool        `json:"is_gold"`
	IsMod                   bool        `json:"is_mod"`
	SuspensionExpirationUtc float64     `json:"suspension_expiration_utc"`
	HasVerifiedEmail        bool        `json:"has_verified_email"`
	IsSuspended             bool        `json:"is_suspended"`
	PrefVideoAutoplay       bool        `json:"pref_video_autoplay"`
	InChat                  bool        `json:"in_chat"`
	InRedesignBeta          bool        `json:"in_redesign_beta"`
	IconImg                 string      `json:"icon_img"`
	HasModMail              bool        `json:"has_mod_mail"`
	PrefNightmode           bool        `json:"pref_nightmode"`
	OauthClientId           bool        `json:"oauth_client_id"`
	HideFromRobots          bool        `json:"hide_from_robots"`
	LinkKarma               float64     `json:"link_karma"`
	ForcePasswordReset      bool        `json:"force_password_reset"`
	InboxCount              float64     `json:"inbox_count"`
	PrefTopKarmaSubreddits  bool        `json:"pref_top_karma_subreddits"`
	HasMail                 bool        `json:"has_mail"`
	PrefShowSnoovatar       bool        `json:"pref_show_snoovatar"`
	Name                    string      `json:"name"`
	PrefClickgadget         float64     `json:"pref_clickgadget"`
	Created                 float64     `json:"created"`
	GoldCreddits            float64     `json:"gold_creddits"`
	HasIosSubscription      bool        `json:"has_ios_subscription"`
	PrefShowTwitter         bool        `json:"pref_show_twitter"`
	InBeta                  bool        `json:"in_beta"`
	CommentKarma            float64     `json:"comment_karma"`
	HasSubscribed           bool        `json:"has_subscribed"`
	SeenSubredditChatFtux   bool        `json:"seen_subreddit_chat_ftux"`
}

type MeFeatures

type MeFeatures struct {
	RichtextPreviews                          bool         `json:"richtext_previews"`
	DoNotTrack                                bool         `json:"do_not_track"`
	ChatSubreddit                             bool         `json:"chat_subreddit"`
	Chat                                      bool         `json:"chat"`
	SeqRandomizeSort                          bool         `json:"seq_randomize_sort"`
	Sequence                                  bool         `json:"sequence"`
	MwebXpromoRevampV2                        MeSubFeature `json:"mweb_xpromo_revamp_v2"`
	MwebXpromoFloat64erstitialCommentsIos     bool         `json:"mweb_xpromo_float64erstitial_comments_ios"`
	ChatReddarReports                         bool         `json:"chat_reddar_reports"`
	ChatRollout                               bool         `json:"chat_rollout"`
	MwebXpromoFloat64erstitialCommentsAndroid bool         `json:"mwev_xpromo_float64erstitial_comments_android"`
	ChatGroutRollout                          bool         `json:"chat_group_rollout"`
	MwebLinkTab                               MeSubFeature `json:"mweb_link_tab"`
	SpezModal                                 bool         `json:"spez_modal"`
	CommunityAwards                           bool         `json:"community_awards"`
	DefaultSrsHoldout                         MeSubFeature `json:"default_srs_holdout"`
	ChatUserSettings                          bool         `json:"chat_user_settings"`
	DualWriteUserPrefs                        bool         `json:"dual_write_user_prefs"`

	MwebXpromoModalListingClickDailyDismissibleAndroid bool `json:"mweb_xpromo_modal_listing_click_daily_dismissible_ios"`
	MwebXpromoModalListingClickDailyDismisssibleIos    bool `json:"mweb_xpromo_modal_listing_click_daily_dismissible_android"`
}

type MeSubFeature

type MeSubFeature struct {
	Owner        string  `json:"owner"`
	Variant      string  `json:"variant"`
	ExperimentId float64 `json:"experiment_id"`
}

type PostAward

type PostAward struct {
	IsEnabled           bool            `json:"is_enabled"`
	Count               float64         `json:"count"`
	SubredditId         string          `json:"subreddit_id"`
	Description         string          `json:"description"`
	CoinReward          float64         `json:"coin_reward"`
	IconWidth           float64         `json:"icon_width"`
	IconUrl             string          `json:"icon_url"`
	DaysOfPremium       float64         `json:"days_of_premium"`
	IconHeight          float64         `json:"icon_height"`
	ResizedIcons        []PostAwardIcon `json:"resized_icons"`
	DaysOfDripExtension float64         `json:"days_of_drip_extension"`
	AwardType           string          `json:"award_type"`
	CoinPrice           float64         `json:"coin_price"`
	Id                  string          `json:"id"`
	Name                string          `json:"name"`
}

type PostAwardIcon

type PostAwardIcon struct {
	Url    string  `json:"url"`
	Width  float64 `json:"width"`
	Height float64 `json:"height"`
}

type PostListing

type PostListing struct {
	Kind string          `json:"kind"`
	Data PostListingData `json:"data"`
}

func (*PostListing) GetChildren

func (p *PostListing) GetChildren() []PostListingChild

type PostListingChild

type PostListingChild struct {
	Kind   string               `json:"kind"`
	Data   PostListingChildData `json:"data"`
	After  string               `json:"after"`
	Before string               `json:"before"`
}

func (*PostListingChild) GetAge

func (plc *PostListingChild) GetAge() float64

func (*PostListingChild) GetAuthor

func (plc *PostListingChild) GetAuthor() string

func (*PostListingChild) GetAuthorFlair

func (plc *PostListingChild) GetAuthorFlair() string

func (*PostListingChild) GetAuthorId

func (plc *PostListingChild) GetAuthorId() string

func (*PostListingChild) GetCommentCount

func (plc *PostListingChild) GetCommentCount() float64

func (*PostListingChild) GetCreated

func (plc *PostListingChild) GetCreated() float64

func (*PostListingChild) GetCrosspostCount

func (plc *PostListingChild) GetCrosspostCount() float64

func (*PostListingChild) GetDowns

func (plc *PostListingChild) GetDowns() float64

func (*PostListingChild) GetId

func (plc *PostListingChild) GetId() string
func (plc *PostListingChild) GetPermalink() string

func (*PostListingChild) GetScore

func (plc *PostListingChild) GetScore() float64

func (*PostListingChild) GetSubreddit

func (plc *PostListingChild) GetSubreddit() string

func (*PostListingChild) GetSubredditId

func (plc *PostListingChild) GetSubredditId() string

func (*PostListingChild) GetText

func (plc *PostListingChild) GetText() string

func (*PostListingChild) GetTimeCreated

func (plc *PostListingChild) GetTimeCreated() float64

func (*PostListingChild) GetTitle

func (plc *PostListingChild) GetTitle() string

func (*PostListingChild) GetUps

func (plc *PostListingChild) GetUps() float64

func (*PostListingChild) GetUrl

func (plc *PostListingChild) GetUrl() string

type PostListingChildData

type PostListingChildData struct {
	ApprovedAtUtc              float64            `json:"approved_at_utc"`
	Subreddit                  string             `json:"subreddit"`
	Selftext                   string             `json:"selftext"`
	AuthorFullname             string             `json:"author_fullname"`
	Saved                      bool               `json:"saved"`
	ModReasonTitle             string             `json:"mod_reason_title"`
	Gilded                     float64            `json:"gilded"`
	Clicked                    bool               `json:"clicked"`
	Title                      string             `json:"title"`
	LinkFlairRichtext          string             `json:"link_flair_richtext"`
	SubredditNamePrefixed      string             `json:"subreddit_name_prefixed"`
	Hidden                     bool               `json:"hidden"`
	Pwls                       float64            `json:"pwls"`
	LinkFlairCssClass          string             `json:"link_flair_css_class"`
	Downs                      float64            `json:"downs"`
	ThumbnailHeight            float64            `json:"thumbnail_height"`
	HideScore                  bool               `json:"hide_score"`
	Name                       string             `json:"name"`
	Quarantine                 bool               `json:"quarantine"`
	LinkFlairTextColor         string             `json:"link_flair_text_color"`
	AuthorFlairBackgroundColor string             `json:"author_flair_background_color"`
	SubredditType              string             `json:"subreddit_type"`
	Ups                        float64            `json:"ups"`
	TotalAwardsReceived        float64            `json:"total_awards_received"`
	MediaEmbed                 []string           `json:"media_embed"`
	ThumbnailWidth             float64            `json:"thumbnail_width"`
	AuthorFlairTemplateId      string             `json:"author_flair_template_id"`
	IsOriginalContent          bool               `json:"is_original_content"`
	UserReports                []string           `json:"user_reports"`
	SecureMedia                string             `json:"secure_media"`
	IsRedditMediaDomain        bool               `json:"is_reddit_media_domain"`
	IsMeta                     bool               `json:"is_meta"`
	Category                   string             `json:"category"`
	SecureMediaEmbed           []string           `json:"secure_media_embed"`
	LinkFlairText              string             `json:"link_flair_text"`
	CanModPost                 bool               `json:"can_mod_post"`
	Score                      float64            `json:"score"`
	ApprovedBy                 string             `json:"approved_by"`
	Thumbnail                  string             `json:"thumbnail"`
	Edited                     bool               `json:"edited"`
	AuthorFlairCssClass        string             `json:"author_flair_css_class"`
	AuthorFlairRichtext        []string           `json:"author_flair_richtext"`
	Gildings                   map[string]float64 `json:"gildings"`
	PostHint                   string             `json:"post_hint"`
	ContentCategories          []string           `json:"content_categories"`
	IsSelf                     bool               `json:"is_self"`
	ModNote                    string             `json:"mod_note"`
	Created                    float64            `json:"created"`
	LinkFlairType              string             `json:"link_flair_type"`
	Wls                        float64            `json:"wls"`
	BannedBy                   string             `json:"banned_by"`
	AuthorFlairType            string             `json:"author_flair_type"`
	Domain                     string             `json:"domain"`
	SelftextHtml               string             `json:"selftext_html"`
	Likes                      float64            `json:"likes"`
	SuggestedSort              string             `json:"suggested_sort"`
	BannedAtUtc                float64            `json:"banned_at_utc"`
	ViewCount                  float64            `json:"view_count"`
	Archived                   bool               `json:"archived"`
	NoFollow                   bool               `json:"no_follow"`
	IsCrosspostable            bool               `json:"is_crosspostable"`
	Pinned                     bool               `json:"pinned"`
	Over18                     bool               `json:"over_18"`
	Preview                    PostPreview        `json:"preview"`
	Awardings                  []PostAward        `json:"all_awardings"`
	MediaOnly                  bool               `json:"media_only"`
	CanGild                    bool               `json:"can_gild"`
	Spoiler                    bool               `json:"spoiler"`
	Locked                     bool               `json:"locked"`
	AuthorFlairText            string             `json:"author_flair_text"`
	Visited                    bool               `json:"visited"`
	NumReports                 float64            `json:"num_reports"`
	Distinguished              bool               `json:"distinguished"`
	SubredditId                string             `json:"subreddit_id"`
	ModReasonBy                string             `json:"mod_reason_by"`
	RemovalReason              string             `json:"removal_reason"`
	LinkFlairBackgroundColor   string             `json:"link_flair_background_color"`
	Id                         string             `json:"id"`
	IsRobotIndexable           bool               `json:"is_robot_indexable"`
	ReportReasons              string             `json:"report_reasons"`
	Author                     string             `json:"author"`
	NumCrossposts              float64            `json:"num_crossposts"`
	NumComments                float64            `json:"num_comments"`
	SendReplies                bool               `json:"send_replies"`
	WhitelistStatus            string             `json:"whitelist_status"`
	ContestMode                bool               `json:"contest_mode"`
	ModReports                 []string           `json:"mod_reports"`
	AuthorPatreonFlair         bool               `json:"author_patreon_flair"`
	AuthorFlairTextColor       string             `json:"author_flair_text_color"`
	Permalink                  string             `json:"permalink"`
	ParentWhitelistStatus      string             `json:"parent_whitelist_status"`
	Stickied                   bool               `json:"stickied"`
	Url                        string             `json:"url"`
	SubredditSubscribers       float64            `json:"subreddit_subscribers"`
	CreatedUtc                 float64            `json:"created_utc"`
	Media                      []string           `json:"media"`
	IsVideo                    bool               `json:"is_video"`
}

type PostListingData

type PostListingData struct {
	Modhash  string             `json:"modhash"`
	Dist     float64            `json:"dist"`
	Children []PostListingChild `json:"children"`
}

type PostPreview

type PostPreview struct {
	Images  []PostPreviewImage `json:"images"`
	Enabled bool               `json:"enabled"`
}

type PostPreviewImage

type PostPreviewImage struct {
	Source      PostPreviewImageSource      `json:"source"`
	Resolutions PostPreviewImageResolutions `json:"resolutions"`
	Variants    []string                    `json:"variants"`
	Id          string                      `json:"id"`
}

type PostPreviewImageResolutions

type PostPreviewImageResolutions struct {
	Url    string  `json:"url"`
	Width  float64 `json:"width"`
	Height float64 `json:"height"`
}

type PostPreviewImageSource

type PostPreviewImageSource struct {
	Url    string  `json:"url"`
	Width  float64 `json:"width"`
	Height float64 `json:"height"`
}

type Reddit

type Reddit struct {
	Token    string  `json:"access_token"`
	Duration float64 `json:"expires_in"`
	Creds    Credentials
	Stream   Streaming
	Values   RedditVals
	Client   *http.Client
}

func Authenticate

func Authenticate(c *Credentials) (*Reddit, error)

Returns an access_token acquired using the provided credentials

func Init

func Init(c Credentials) (*Reddit, error)

When we initialize the Reddit instance, automatically start a goroutine that will update the token every 45 minutes. The auto_refresh should not be accessible to the end user as it is an internal method

func (*Reddit) Approve

func (c *Reddit) Approve(comment_id string) error

func (*Reddit) Comment

func (c *Reddit) Comment(submission_id, text string) (*CommentWrap, error)

func (*Reddit) Compose

func (c *Reddit) Compose(to, subject, text string) error

func (*Reddit) DeleteComment

func (c *Reddit) DeleteComment(comment_id string) error

func (*Reddit) Distinguish

func (c *Reddit) Distinguish(comment_id string, how string, sticky bool) error

func (*Reddit) EditComment

func (c *Reddit) EditComment(comment_id, text string) (*CommentWrap, error)

func (*Reddit) GetComment

func (c *Reddit) GetComment(id string) (*Comment, error)

func (*Reddit) GetSubmission

func (c *Reddit) GetSubmission(id string) (*PostListing, error)

func (*Reddit) GetSubmissionComments

func (c *Reddit) GetSubmissionComments(sr string, post_id string, sort string, limit int) ([]Comment, []string, error)

func (*Reddit) GetSubmissionFromComment

func (c *Reddit) GetSubmissionFromComment(comment_id string) (string, error)

This function will return the submission id of a comment

Comment id has form of t1_... where submission is prefixed with t3_...

Comment structures in themselves do not have submission id included, they only have a parent_id field that points to a parent comment or a submission. If it does not point directly at the submission, we need to make iterative calls until we bump into an id that fits the submission prefix. It may take several calls.

For example:

- If comment is first-level, we make one call to get the object and extract the submission id. If you already have a Go struct at hand, please just invoke .GetParentId() to get the parent id

- If comment is second-level, it would take two calls to extact the submission id. If you want to save a call, you can pass a parent_id instead that would take 1 call instead of 2.

- If comment is N-level, it would take N calls. If you aleady have an object, just pass in its object, so it would take N-1 calls.

NOTE: If any error occurs, the method will return on error object. If it takes more than 12 calls, the function bails out.

func (*Reddit) GetSubreddit

func (c *Reddit) GetSubreddit(name string) (*Subreddit, error)

func (*Reddit) GetSubredditComments added in v1.1.0

func (c *Reddit) GetSubredditComments(sr string, sort string, tdur string, limit int) ([]Comment, error)

func (*Reddit) GetSubredditCommentsAfter added in v1.1.0

func (c *Reddit) GetSubredditCommentsAfter(sr string, sort string, last string, limit int) ([]Comment, error)

func (*Reddit) GetSubredditPosts

func (c *Reddit) GetSubredditPosts(sr string, sort string, tdur string, limit int) ([]PostListingChild, error)

Get submisssions from a subreddit up to a specified limit sorted by the given parameter

Sorting options: "hot", "new", "top", "rising", "controversial", "random"

Time options: "all", "year", "month", "week", "day", "hour"

Limit is any numerical value, so 0 <= limit <= 100

func (*Reddit) GetSubredditPostsAfter

func (c *Reddit) GetSubredditPostsAfter(sr string, last string, limit int) ([]PostListingChild, error)

Get submisssions from a subreddit up to a specified limit sorted by the given parameters and with specified anchor

Sorting options: "hot", "new", "top", "rising", "controversial", "random"

Limit is any numerical value, so 0 <= limit <= 100

Anchor options are submissions full thing, for example: t3_bqqwm3

func (*Reddit) GetUser

func (c *Reddit) GetUser(name string) (*Redditor, error)

func (*Reddit) ListUnreadMessages

func (c *Reddit) ListUnreadMessages() ([]Comment, error)

func (*Reddit) Me

func (c *Reddit) Me() (*Me, error)

func (*Reddit) MiraRequest added in v1.1.0

func (c *Reddit) MiraRequest(method string, target string, payload map[string]string) ([]byte, error)

func (*Reddit) ReadAllMessages

func (c *Reddit) ReadAllMessages() error

func (*Reddit) ReadMessage

func (c *Reddit) ReadMessage(message_id string) error

func (*Reddit) Reply

func (c *Reddit) Reply(comment_id string, text string) (*CommentWrap, error)

func (*Reddit) SetClient added in v1.1.0

func (c *Reddit) SetClient(client *http.Client)

func (*Reddit) SetDefault

func (c *Reddit) SetDefault()

func (*Reddit) StreamCommentReplies

func (r *Reddit) StreamCommentReplies() (<-chan Comment, chan bool)

c is the channel with all unread messages stop is the channel to stop the stream. Do stop <- true to stop the loop

func (*Reddit) StreamNewComments added in v1.1.0

func (r *Reddit) StreamNewComments(sr string) (<-chan Comment, chan bool)

c is the channel with all comments stop is the channel to stop the stream. Do stop <- true to stop the loop

func (*Reddit) StreamNewPosts

func (r *Reddit) StreamNewPosts(sr string) (<-chan PostListingChild, chan bool)

func (*Reddit) Submit

func (c *Reddit) Submit(sr string, title string, text string) (*Submission, error)

func (*Reddit) SubredditUpdateSidebar

func (c *Reddit) SubredditUpdateSidebar(sr, text string) ([]byte, error)

type RedditVals

type RedditVals struct {
	GetSubmissionFromCommentTries int
}

type Redditor

type Redditor struct {
	Kind string       `json:"kind"`
	Data RedditorData `json:"data"`
}

func (*Redditor) GetCommentKarma

func (r *Redditor) GetCommentKarma() float64

func (*Redditor) GetCreated

func (r *Redditor) GetCreated() float64

func (*Redditor) GetDescription

func (r *Redditor) GetDescription() string

func (*Redditor) GetId

func (r *Redditor) GetId() string

func (*Redditor) GetLinkKarma

func (r *Redditor) GetLinkKarma() float64

func (*Redditor) GetName

func (r *Redditor) GetName() string

func (*Redditor) IsEmployee

func (r *Redditor) IsEmployee() bool

type RedditorData

type RedditorData struct {
	IsEmployee        bool        `json:"is_employee"`
	IconImg           string      `json:"icon_img"`
	PrefShowSnoovatar bool        `json:"pref_show_snoovatar"`
	Name              string      `json:"name"`
	IsFriend          bool        `json:"is_friend"`
	Created           float64     `json:"created"`
	HasSubscribed     bool        `json:"has_subscribed"`
	HideFromRobots    bool        `json:"hide_from_robots"`
	CreatedUtc        float64     `json:"created_utc"`
	LinkKarma         float64     `json:"link_karma"`
	CommentKarma      float64     `json:"comment_karma"`
	IsGold            bool        `json:"is_gold"`
	IsMod             bool        `json:"is_mod"`
	Verified          bool        `json:"verified"`
	Subreddit         Subreddit_s `json:"subreddit"`
	HasVerifiedEmail  bool        `json:"has_verified_email"`
	Id                string      `json:"id"`
}

type Streaming

type Streaming struct {
	CommentListInterval time.Duration
	PostListInterval    time.Duration
	PostListSlice       int
}

type Submission

type Submission struct {
	Json SubmissionJson `json:"json"`
}

func (*Submission) GetDraftsCount

func (s *Submission) GetDraftsCount() float64

func (*Submission) GetId

func (s *Submission) GetId() string

Get the ID of the submission in form "t3_..."

func (*Submission) GetUrl

func (s *Submission) GetUrl() string

type SubmissionJson

type SubmissionJson struct {
	Errors []string           `json:"errors"`
	Data   SubmissionJsonData `json:"data"`
}

type SubmissionJsonData

type SubmissionJsonData struct {
	Url         string  `json:"url"`
	DraftsCount float64 `json:"drafts_count"`
	Id          string  `json:"id"`
	Name        string  `json:"name"`
}

type Subreddit

type Subreddit struct {
	Kind string        `json:"kind"`
	Data SubredditData `json:"data"`
}

func (Subreddit) GetCreated

func (s Subreddit) GetCreated() float64

func (Subreddit) GetDescription

func (s Subreddit) GetDescription() string

func (Subreddit) GetDisplayName

func (s Subreddit) GetDisplayName() string

func (Subreddit) GetId

func (s Subreddit) GetId() string

func (Subreddit) GetName

func (s Subreddit) GetName() string

func (Subreddit) GetPublicDescription

func (s Subreddit) GetPublicDescription() string

func (Subreddit) GetSubscribers

func (s Subreddit) GetSubscribers() float64

func (Subreddit) GetUrl

func (s Subreddit) GetUrl() string

func (Subreddit) IsOver18

func (s Subreddit) IsOver18() bool

type SubredditData

type SubredditData struct {
	UserFlairBackgroundColor   string    `json:"user_flair_background_color"`
	SubmitTextHtml             string    `json:"submit_text_html"`
	RestrictPosting            bool      `json:"restrict_posting"`
	UserIsBanned               bool      `json:"user_is_banned"`
	FreeFormReports            bool      `json:"free_form_reports"`
	WikiEnabled                string    `json:"wiki_enabled"`
	UserIsMuted                bool      `json:"user_is_muted"`
	UserCanFlairInSr           string    `json:"user_can_flair_in_sr"`
	DisplayName                string    `json:"display_name"`
	HeaderImg                  string    `json:"header_img"`
	Title                      string    `json:"title"`
	IconSize                   []float64 `json:"icon_size"`
	PrimaryColor               string    `json:"primary_color"`
	ActiveUserCount            float64   `json:"active_user_count"`
	IconImg                    string    `json:"icon_img"`
	AccountsActive             float64   `json:"accounts_active"`
	PublicTraffic              bool      `json:"public_traffic"`
	Subscribers                float64   `json:"subscribers"`
	UserFlairRichtext          string    `json:"user_flair_richtext"`
	VideostreamLinksCount      float64   `json:"videostream_links_count"`
	Name                       string    `json:"name"`
	Quarantine                 bool      `json:"quarantine"`
	HideAds                    bool      `json:"hide_ads"`
	EmojisEnabled              bool      `json:"emojis_enabled"`
	AdvertiserCategory         string    `json:"advertiser_category"`
	PublicDescription          string    `json:"public_description"`
	CommentScoreHideMins       float64   `json:"comment_score_hide_mins"`
	UserHasFavorited           bool      `json:"user_has_favorited"`
	UserFlairTemplateId        string    `json:"user_flair_template_id"`
	CommunityIcon              string    `json:"community_icon"`
	BannerBackgroundImage      string    `json:"banner_background_image"`
	OriginalContentTagEnabled  bool      `json:"original_content_tag_enabled"`
	SubmitText                 string    `json:"submit_text"`
	DescriptionHtml            string    `json:"description_html"`
	SpoilersEnabled            bool      `json:"spoilers_enabled"`
	HeaderTitle                string    `json:"header_title"`
	HeaderSize                 string    `json:"header_size"`
	UserFlairPosition          string    `json:"user_flair_position"`
	AllOriginalContent         bool      `json:"all_original_content"`
	HasMenuWidget              bool      `json:"has_menu_widget"`
	IsEnrolledInNewModmail     bool      `json:"is_enrolled_in_new_modmail"`
	KeyColor                   string    `json:"key_color"`
	EventPostsEnabled          bool      `json:"event_posts_enabled"`
	CanAssignUserFlair         bool      `json:"can_assign_user_flair"`
	Created                    float64   `json:"created"`
	Wls                        string    `json:"wls"`
	ShowMediaPreview           bool      `json:"show_media_preview"`
	SubmissionType             string    `json:"submission_type"`
	UserIsSubscriber           bool      `json:"user_is_subscriber"`
	DisableContributorRequests bool      `json:"disable_contributor_requests"`
	AllowVideogifs             bool      `json:"allow_videogifs"`
	UserFlairType              string    `json:"user_flair_type"`
	CollapseDeletedComments    bool      `json:"collapse_deleted_comments"`
	EmojisCustomSize           string    `json:"emojis_custom_size"`
	PublicDescriptionHtml      string    `json:"public_description_html"`
	AllowVideos                bool      `json:"allow_videos"`
	NotificationLevel          string    `json:"notification_level"`
	CanAssignLinkFlair         bool      `json:"can_assign_link_flair"`
	AccountsActiveIsFuzzed     bool      `json:"accounts_active_is_fuzzed"`
	SubmitTextLabel            string    `json:"submit_text_label"`
	LinkFlairPosition          string    `json:"link_flair_position"`
	UserSrFlairEnabled         bool      `json:"user_sr_flair_enabled"`
	UserFlairEnabledInSr       bool      `json:"user_flair_enabled_in_sr"`
	AllowDiscovery             bool      `json:"allow_discovery"`
	UserSrThemeEnabled         bool      `json:"user_sr_theme_enabled"`
	LinkFlairEnabled           bool      `json:"link_flair_enabled"`
	SubredditType              string    `json:"subreddit_type"`
	SuggestedCommentSort       string    `json:"suggested_comment_sort"`
	BannerImg                  string    `json:"banner_img"`
	UserFlairText              string    `json:"user_flair_text"`
	BannerBackgroundColor      string    `json:"banner_background_color"`
	ShowMedia                  bool      `json:"show_media"`
	Id                         string    `json:"id"`
	UserIsModerator            bool      `json:"user_is_moderator"`
	Over18                     bool      `json:"over18"`
	Description                string    `json:"description"`
	SubmitLinkLabel            string    `json:"submit_link_label"`
	UserFlairTextColor         string    `json:"user_flair_text_color"`
	RestrictCommenting         bool      `json:"restrict_commenting"`
	UserFlairCssClass          string    `json:"user_flair_css_class"`
	AllowImages                bool      `json:"allow_images"`
	Lang                       string    `json:"lang"`
	WhitelistStatus            string    `json:"whitelist_status"`
	Url                        string    `json:"url"`
	CreatedUtc                 float64   `json:"created_utc"`
	BannerSize                 []float64 `json:"banner_size"`
	MobileBannerImage          string    `json:"mobile_banner_image"`
	UserIsContributor          bool      `json:"user_is_contributor"`
}

type Subreddit_s

type Subreddit_s struct {
	DefaultSet                 bool      `json:"default_set"`
	UserIsContributor          bool      `json:"user_is_contributor"`
	BannerImg                  string    `json:"banner_img"`
	DisableContributorRequests bool      `json:"disable_contributor_requests"`
	UserIsBanned               bool      `json:"user_is_banned"`
	FreeFormReports            bool      `json:"free_form_reports"`
	CommunityIcon              string    `json:"community_icon"`
	ShowMedia                  bool      `json:"show_media"`
	IconColor                  string    `json:"icon_color"`
	UserIsMuted                bool      `json:"user_is_muted"`
	DisplayName                string    `json:"display_name"`
	HeaderImg                  string    `json:"header_img"` // *
	Title                      string    `json:"title"`
	Over18                     bool      `json:"over_18"`
	IconSize                   []float64 `json:"icon_size"`
	PrimaryColor               string    `json:"primary_color"`
	IconImg                    string    `json:"icon_img"`
	Description                string    `json:"description"`
	HeaderSize                 string    `json:"header_size"` // *
	RestrictPosting            bool      `json:"restrict_posting"`
	RestrictCommenting         bool      `json:"restrict_commenting"`
	Subscribers                float64   `json:"subscribers"`
	IsDefaultIcon              bool      `json:"is_default_icon"`
	LinkFlairPosition          string    `json:"link_flair_position"`
	DisplayNamePrefixed        string    `json:"display_name_prefixed"`
	KeyColor                   string    `json:"key_color"`
	Name                       string    `json:"name"`
	IsDefaultBanner            bool      `json:"is_default_banner"`
	Url                        string    `json:"url"`
	BannerSize                 []float64 `json:"banner_size"`
	UserIsModerator            bool      `json:"user_is_moderator"`
	PublicDescription          string    `json:"public_description"`
	LinkFlairEnabled           bool      `json:"link_flair_enabled"`
	SubredditType              string    `json:"subreddit_type"`
	UserIsSubscriber           bool      `json:"user_is_subscriber"`
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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