new snoowrap(options)
Constructs a new requester.
You should use the snoowrap constructor if you are able to authorize a reddit account in advance (e.g. for a Node.js
script that always uses the same account). If you aren't able to authorize in advance (e.g. acting through an arbitrary user's
account while running snoowrap in a browser), then you should use snoowrap.getAuthUrl
and
snoowrap.fromAuthCode
instead.
To edit snoowrap specific settings, see snoowrap#config
.
snoowrap supports several different options for pre-existing authentication:
- Refresh token: To authenticate with a refresh token, pass an object with the properties
userAgent
,clientId
,clientSecret
, andrefreshToken
to the snoowrap constructor. You will need to get the refresh token from reddit beforehand. A script to automatically generate refresh tokens for you can be found here. - Username/password: To authenticate with a username and password, pass an object with the properties
userAgent
,clientId
,clientSecret
,username
, andpassword
to the snoowrap constructor. Note that username/password authentication is only possible forscript
-type apps. - Access token: To authenticate with an access token, pass an object with the properties
userAgent
andaccessToken
to the snoowrap constructor. Note that all access tokens expire one hour after being generated, so this method is not recommended for long-term use.
Parameters:
Name | Type | Description | ||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
object | An object containing authentication options. This should always have the property Properties
|
Members
-
<static> grantType
Returns the grant types available for app-only authentication
-
Per the Reddit API OAuth docs, there are two different grant types depending on whether the app is an installed client or a confidential client such as a web app or string. This getter returns the possible values for the "grant_type" field in application-only auth.
Methods
-
<static> getAuthUrl(options)
Gets an authorization URL, which allows a user to authorize access to their account
-
This create a URL where a user can authorize an app to act through their account. If the user visits the returned URL in a web browser, they will see a page that looks like this. If the user clicks "Allow", they will be redirected to your
redirectUri
, with acode
querystring parameter containing an authorization code. If this code is passed tosnoowrap.fromAuthCode
, you can create a requester to make requests on behalf of the user.The main use-case here is for running snoowrap in a browser. You can generate a URL, send the user there, and then continue after the user authenticates on reddit and is redirected back.
Parameters:
Name Type Description options
object Properties
Name Type Argument Default Description clientId
string The client ID of your app (assigned by reddit). If your code is running clientside in a browser, using an "Installed" app type is recommended.
scope
Array.<string> An array of scopes (permissions on the user's account) to request on the authentication page. A list of possible scopes can be found here. You can also get them on-the-fly with
snoowrap#getOauthScopeList
.redirectUri
string The URL where the user should be redirected after authenticating. This must be the same as the redirect URI that is configured for the reddit app. (If there is a mismatch, the returned URL will display an error page instead of an authentication form.)
permanent
boolean <optional>
true If
true
, the app will have indefinite access to the user's account. Iffalse
, access to the user's account will expire after 1 hour.state
string <optional>
A string that can be used to verify a user after they are redirected back to the site. When the user is redirected from reddit, to the redirect URI after authenticating, the resulting URI will have this same
state
value in the querystring. (See here for more information on how to use thestate
value.)endpointDomain
string <optional>
'reddit.com' The endpoint domain for the URL. If the user is authenticating on reddit.com (as opposed to some other site with a reddit-like API), you can omit this value.
Returns:
A URL where the user can authenticate with the given options
- Type
- string
Example
var authenticationUrl = snoowrap.getAuthUrl({ clientId: 'foobarbazquuux', scope: ['identity', 'wikiread', 'wikiedit'], redirectUri: 'https://example.com/reddit_callback', permanent: false, state: 'fe211bebc52eb3da9bef8db6e63104d3' // a random string, this could be validated when the user is redirected back }); // --> 'https://www.reddit.com/api/v1/authorize?client_id=foobarbaz&response_type=code&state= ...' window.location.href = authenticationUrl; // send the user to the authentication url
-
<static> fromAuthCode(options)
Creates a snoowrap requester from an authorization code.
-
An authorization code is the
code
value that appears in the querystring after a user authenticates with reddit and is redirected. For more information, seesnoowrap.getAuthUrl
.The main use-case for this function is for running snoowrap in a browser. You can generate a URL with
snoowrap.getAuthUrl
and send the user to that URL, and then use this function to create a requester when the user is redirected back with an authorization code.Parameters:
Name Type Description options
object Properties
Name Type Argument Default Description code
string The authorization code
userAgent
string A unique description of what your app does. This argument is not necessary when snoowrap is running in a browser.
clientId
string The client ID of your app (assigned by reddit). If your code is running clientside in a browser, using an "Installed" app type is recommended.
clientSecret
string <optional>
The client secret of your app. If your app has the "Installed" app type, omit this parameter.
redirectUri
string The redirect URI that is configured for the reddit app.
endpointDomain
string <optional>
'reddit.com' The endpoint domain that the returned requester should be configured to use. If the user is authenticating on reddit.com (as opposed to some other site with a reddit-like API), you can omit this value.
Returns:
A Promise that fulfills with a
snoowrap
instance- Type
- Promise.<snoowrap>
Example
// Get the `code` querystring param (assuming the user was redirected from reddit) var code = new URL(window.location.href).searchParams.get('code'); snoowrap.fromAuthCode({ code: code, userAgent: 'My app', clientId: 'foobarbazquuux', redirectUri: 'example.com' }).then(r => { // Now we have a requester that can access reddit through the user's account return r.getHot().then(posts => { // do something with posts from the front page }); })
-
<static> fromApplicationOnlyAuth(options)
Creates a snoowrap requester from a "user-less" Authorization token
-
In some cases, 3rd party app clients may wish to make API requests without a user context. App clients can request a "user-less" Authorization token via either the standard client_credentials grant, or the reddit specific extension to this grant, https://oauth.reddit.com/grants/installed_client. Which grant type an app uses depends on the app-type and its use case.
Parameters:
Name Type Description options
object Properties
Name Type Argument Default Description userAgent
string A unique description of what your app does. This argument is not necessary when snoowrap is running in a browser.
clientId
string The client ID of your app (assigned by reddit). If your code is running clientside in a browser, using an "Installed" app type is recommended.
clientSecret
string <optional>
The client secret of your app. Only required for "client_credentials" grant type.
deviceId
string <optional>
A unique, per-device ID generated by your client. Only required for "Installed" grant type, needs to be between 20-30 characters long. From the reddit docs: "reddit may choose to use this ID to generate aggregate data about user counts. Clients that wish to remain anonymous should use the value DO_NOT_TRACK_THIS_DEVICE."
grantType
string <optional>
snoowrap.grantType.INSTALLED_CLIENT The type of "user-less" token to use
snoowrap.grantType
permanent
boolean <optional>
true If
true
, the app will have indefinite access. Iffalse
, access will expire after 1 hour.endpointDomain
string <optional>
'reddit.com' The endpoint domain that the returned requester should be configured to use. If the user is authenticating on reddit.com (as opposed to some other site with a reddit-like API), you can omit this value.
Returns:
A Promise that fulfills with a
snoowrap
instance- Type
- Promise.<snoowrap>
Example
snoowrap.fromApplicationOnlyAuth({ userAgent: 'My app', clientId: 'foobarbazquuux', deviceId: 'unique id between 20-30 chars', grantType: snoowrap.grantType.INSTALLED_CLIENT }).then(r => { // Now we have a requester that can access reddit through a "user-less" Auth token return r.getHot().then(posts => { // do something with posts from the front page }); }) snoowrap.fromApplicationOnlyAuth({ userAgent: 'My app', clientId: 'foobarbazquuux', clientSecret: 'your web app secret', grantType: snoowrap.grantType.CLIENT_CREDENTIALS }).then(r => { // Now we have a requester that can access reddit through a "user-less" Auth token return r.getHot().then(posts => { // do something with posts from the front page }); })
-
config( [options])
Retrieves or modifies the configuration options for this snoowrap instance.
-
Parameters:
Name Type Argument Description options
object <optional>
A map of
{[config property name]: value}
. Note that any omitted config properties will simply retain whatever value they had previously. (In other words, if you only want to change one property, you only need to put that one property in this parameter. To get the current configuration without modifying anything, simply omit this parameter.)Properties
Name Type Argument Default Description endpointDomain
string <optional>
'reddit.com' The endpoint where requests should be sent
requestDelay
Number <optional>
0 A minimum delay, in milliseconds, to enforce between API calls. If multiple api calls are requested during this timespan, they will be queued and sent one at a time. Setting this to more than 1000 will ensure that reddit's ratelimit is never reached, but it will make things run slower than necessary if only a few requests are being sent. If this is set to zero, snoowrap will not enforce any delay between individual requests. However, it will still refuse to continue if reddit's enforced ratelimit (600 requests per 10 minutes) is exceeded.
requestTimeout
Number <optional>
30000 A timeout for all OAuth requests, in milliseconds. If the reddit server fails to return a response within this amount of time, the Promise will be rejected with a timeout error.
continueAfterRatelimitError
boolean <optional>
false Determines whether snoowrap should queue API calls if reddit's ratelimit is exceeded. If set to
true
when the ratelimit is exceeded, snoowrap will queue all further requests, and will attempt to send them again after the current ratelimit period expires (which happens every 10 minutes). If set tofalse
, snoowrap will simply throw an error when reddit's ratelimit is exceeded.retryErrorCodes
Array.<Number> <optional>
[502, 503, 504, 522] If reddit responds to an idempotent request with one of these error codes, snoowrap will retry the request, up to a maximum of
max_retry_attempts
requests in total. (These errors usually indicate that there was an temporary issue on reddit's end, and retrying the request has a decent chance of success.) This behavior can be disabled by simply setting this property to an empty array.maxRetryAttempts
Number <optional>
3 See
retryErrorCodes
.warnings
boolean <optional>
true snoowrap may occasionally log warnings, such as deprecation notices, to the console. These can be disabled by setting this to
false
.debug
boolean <optional>
false If set to true, snoowrap will print out potentially-useful information for debugging purposes as it runs.
logger
object <optional>
console By default, snoowrap will log any warnings and debug output to the console. A custom logger object may be supplied via this option; it must expose
warn
,info
,debug
, andtrace
functions.proxies
boolean <optional>
true Setting this to
false
disables snoowrap's method-chaining feature. This causes the syntax for using snoowrap to become a bit heavier, but allows for consistency between environments that support the ES6Proxy
object and environments that don't. This option is a no-op in environments that don't support theProxy
object, since method chaining is always disabled in those environments. Note, changing this setting must be done before making any requests.Returns:
An updated Object containing all of the configuration values
- Type
- object
Example
r.config({requestDelay: 1000, warnings: false}); // sets the request delay to 1000 milliseconds, and suppresses warnings.
-
getUser(name)
Gets information on a reddit user with a given name.
-
Parameters:
Name Type Description name
string The user's username
Returns:
An unfetched RedditUser object for the requested user
- Type
- RedditUser
Example
r.getUser('not_an_aardvark') // => RedditUser { name: 'not_an_aardvark' } r.getUser('not_an_aardvark').link_karma.then(console.log) // => 6
-
getComment(commentId)
Gets information on a comment with a given id.
-
Parameters:
Name Type Description commentId
string The base36 id of the comment
Returns:
An unfetched Comment object for the requested comment
- Type
- Comment
Example
r.getComment('c0b6xx0') // => Comment { name: 't1_c0b6xx0' } r.getComment('c0b6xx0').author.name.then(console.log) // => 'Kharos'
-
getSubreddit(displayName)
Gets information on a given subreddit.
-
Parameters:
Name Type Description displayName
string The name of the subreddit (e.g. 'AskReddit')
Returns:
An unfetched Subreddit object for the requested subreddit
- Type
- Subreddit
Example
r.getSubreddit('AskReddit') // => Subreddit { display_name: 'AskReddit' } r.getSubreddit('AskReddit').created_utc.then(console.log) // => 1201233135
-
getSubmission(submissionId)
Gets information on a given submission.
-
Parameters:
Name Type Description submissionId
string The base36 id of the submission
Returns:
An unfetched Submission object for the requested submission
- Type
- Submission
Example
r.getSubmission('2np694') // => Submission { name: 't3_2np694' } r.getSubmission('2np694').title.then(console.log) // => 'What tasty food would be distusting if eaten over rice?'
-
getMessage(messageId)
Gets a private message by ID.
-
Parameters:
Name Type Description messageId
string The base36 ID of the message
Returns:
An unfetched PrivateMessage object for the requested message
- Type
- PrivateMessage
Example
r.getMessage('51shnw') // => PrivateMessage { name: 't4_51shnw' } r.getMessage('51shnw').subject.then(console.log) // => 'Example' // See here for a screenshot of the PM in question https://i.gyazo.com/24f3b97e55b6ff8e3a74cb026a58b167.png
-
getLivethread(threadId)
-
Gets a livethread by ID.
Parameters:
Name Type Description threadId
string The base36 ID of the livethread
Returns:
An unfetched LiveThread object
- Type
- LiveThread
Example
r.getLivethread('whrdxo8dg9n0') // => LiveThread { id: 'whrdxo8dg9n0' } r.getLivethread('whrdxo8dg9n0').nsfw.then(console.log) // => false
-
getMe()
Gets information on the requester's own user profile.
-
Returns:
A RedditUser object corresponding to the requester's profile
- Type
- RedditUser
Example
r.getMe().then(console.log); // => RedditUser { is_employee: false, has_mail: false, name: 'snoowrap_testing', ... }
-
getKarma()
Gets a distribution of the requester's own karma distribution by subreddit.
-
Returns:
A Promise for an object with karma information
- Type
- Promise
Example
r.getKarma().then(console.log) // => [ // { sr: Subreddit { display_name: 'redditdev' }, comment_karma: 16, link_karma: 1 }, // { sr: Subreddit { display_name: 'programming' }, comment_karma: 2, link_karma: 1 }, // ... // ]
-
getPreferences()
Gets information on the user's current preferences.
-
Returns:
A promise for an object containing the user's current preferences
- Type
- Promise
Example
r.getPreferences().then(console.log) // => { default_theme_sr: null, threaded_messages: true, hide_downs: false, ... }
-
updatePreferences(updatedPreferences)
Updates the user's current preferences.
-
Parameters:
Name Type Description updatedPreferences
object An object of the form {[some preference name]: 'some value', ...}. Any preference not included in this object will simply retain its current value.
Returns:
A Promise that fulfills when the request is complete
- Type
- Promise
Example
r.updatePreferences({threaded_messages: false, hide_downs: true}) // => { default_theme_sr: null, threaded_messages: false,hide_downs: true, ... } // (preferences updated on reddit)
-
getMyTrophies()
Gets the currently-authenticated user's trophies.
-
Returns:
A TrophyList containing the user's trophies
- Type
- Promise
Example
r.getMyTrophies().then(console.log) // => TrophyList { trophies: [ // Trophy { icon_70: 'https://s3.amazonaws.com/redditstatic/award/verified_email-70.png', // description: null, // url: null, // icon_40: 'https://s3.amazonaws.com/redditstatic/award/verified_email-40.png', // award_id: 'o', // id: '16fn29', // name: 'Verified Email' // } // ] }
-
getFriends()
Gets the list of the currently-authenticated user's friends.
-
Returns:
A Promise that resolves with a list of friends
- Type
- Promise
Example
r.getFriends().then(console.log) // => [ [ RedditUser { date: 1457927963, name: 'not_an_aardvark', id: 't2_k83md' } ], [] ]
-
getBlockedUsers()
Gets the list of people that the currently-authenticated user has blocked.
-
Returns:
A Promise that resolves with a list of blocked users
- Type
- Promise
Example
r.getBlockedUsers().then(console.log) // => [ RedditUser { date: 1457928120, name: 'actually_an_aardvark', id: 't2_q3519' } ]
-
checkCaptchaRequirement()
Determines whether the currently-authenticated user needs to fill out a captcha in order to submit content.
-
Returns:
A Promise that resolves with a boolean value
- Type
- Promise
Example
r.checkCaptchaRequirement().then(console.log) // => false
-
getNewCaptchaIdentifier()
Gets the identifier (a hex string) for a new captcha image.
-
Returns:
A Promise that resolves with a string
- Type
- Promise
Example
r.getNewCaptchaIdentifier().then(console.log) // => 'o5M18uy4mk0IW4hs0fu2GNPdXb1Dxe9d'
-
getCaptchaImage(identifier)
Gets an image for a given captcha identifier.
-
Parameters:
Name Type Description identifier
string The captcha identifier.
Returns:
A string containing raw image data in PNG format
- Type
- Promise
Example
r.getCaptchaImage('o5M18uy4mk0IW4hs0fu2GNPdXb1Dxe9d').then(console.log) // => (A long, incoherent string representing the image in PNG format)
-
getSavedCategories()
Gets an array of categories that items can be saved in. (Requires reddit gold)
-
Returns:
An array of categories
- Type
- Promise
Example
r.getSavedCategories().then(console.log) // => [ { category: 'cute cat pictures' }, { category: 'interesting articles' } ]
-
markAsVisited(links)
Marks a list of submissions as 'visited'.
-
Note: This endpoint only works if the authenticated user is subscribed to reddit gold.
Parameters:
Name Type Description links
Array.<Submission> A list of Submission objects to mark
Returns:
A Promise that fulfills when the request is complete
- Type
- Promise
Example
var submissions = [r.getSubmission('4a9u54'), r.getSubmission('4a95nb')] r.markAsVisited(submissions) // (the links will now appear purple on reddit)
-
submitSelfpost(options)
Creates a new selfpost on the given subreddit.
-
Parameters:
Name Type Description options
object An object containing details about the submission
Properties
Name Type Argument Default Description subredditName
string The name of the subreddit that the post should be submitted to
title
string The title of the submission
text
string <optional>
The selftext of the submission
sendReplies
boolean <optional>
true Determines whether inbox replies should be enabled for this submission
captchaIden
string <optional>
A captcha identifier. This is only necessary if the authenticated account requires a captcha to submit posts and comments.
captchaResponse
string <optional>
The response to the captcha with the given identifier
Returns:
The newly-created Submission object
- Type
- Promise
Example
r.submitSelfpost({ subredditName: 'snoowrap_testing', title: 'This is a selfpost', text: 'This is the text body of the selfpost' }).then(console.log) // => Submission { name: 't3_4abmsz' } // (new selfpost created on reddit)
-
submitLink(options)
Creates a new link submission on the given subreddit.
-
Parameters:
Name Type Description options
object An object containing details about the submission
Properties
Name Type Argument Default Description subredditName
string The name of the subreddit that the post should be submitted to
title
string The title of the submission
url
string The url that the link submission should point to
sendReplies
boolean <optional>
true Determines whether inbox replies should be enabled for this submission
resubmit
boolean <optional>
true If this is false and same link has already been submitted to this subreddit in the past, reddit will return an error. This could be used to avoid accidental reposts.
captchaIden
string <optional>
A captcha identifier. This is only necessary if the authenticated account requires a captcha to submit posts and comments.
captchaResponse
string <optional>
The response to the captcha with the given identifier
Returns:
The newly-created Submission object
- Type
- Promise
Example
r.submitLink({ subredditName: 'snoowrap_testing', title: 'I found a cool website!', url: 'https://google.com' }).then(console.log) // => Submission { name: 't3_4abnfe' } // (new linkpost created on reddit)
-
submitCrosspost(options)
Creates a new crosspost submission on the given subreddit
-
NOTE: To create a crosspost, the authenticated account must be subscribed to the subreddit where the crosspost is being submitted, and that subreddit be configured to allow crossposts.
Parameters:
Name Type Description options
object An object containing details about the submission
Properties
Name Type Argument Default Description subredditName
string The name of the subreddit that the crosspost should be submitted to
title
string The title of the crosspost
originalPost
string | Submission A Submission object or a post ID for the original post which is being crossposted
sendReplies
boolean <optional>
true Determines whether inbox replies should be enabled for this submission
resubmit
boolean <optional>
true If this is false and same link has already been submitted to this subreddit in the past, reddit will return an error. This could be used to avoid accidental reposts.
Returns:
The newly-created Submission object
- Type
- Promise
Example
await r.submitCrosspost({ title: 'I found an interesting post', originalPost: '6vths0', subredditName: 'snoowrap' })
-
getHot( [subredditName] [, options])
Gets a Listing of hot posts.
-
Parameters:
Name Type Argument Default Description subredditName
string <optional>
The subreddit to get posts from. If not provided, posts are fetched from the front page of reddit.
options
object <optional>
{} Options for the resulting Listing
Returns:
A Listing containing the retrieved submissions
- Type
- Promise
Example
r.getHot().then(console.log) // => Listing [ // Submission { domain: 'imgur.com', banned_by: null, subreddit: Subreddit { display_name: 'pics' }, ... }, // Submission { domain: 'i.imgur.com', banned_by: null, subreddit: Subreddit { display_name: 'funny' }, ... }, // ... // ] r.getHot('gifs').then(console.log) // => Listing [ // Submission { domain: 'i.imgur.com', banned_by: null, subreddit: Subreddit { display_name: 'gifs' }, ... }, // Submission { domain: 'i.imgur.com', banned_by: null, subreddit: Subreddit { display_name: 'gifs' }, ... }, // ... // ] r.getHot('redditdev', {limit: 1}).then(console.log) // => Listing [ // Submission { domain: 'self.redditdev', banned_by: null, subreddit: Subreddit { display_name: 'redditdev' }, ...} // ]
-
getBest( [options])
Gets a Listing of best posts.
-
Parameters:
Name Type Argument Default Description options
object <optional>
{} Options for the resulting Listing
Returns:
A Listing containing the retrieved submissions
- Type
- Promise.<Listing>
Example
r.getBest().then(console.log) // => Listing [ // Submission { domain: 'imgur.com', banned_by: null, subreddit: Subreddit { display_name: 'pics' }, ... }, // Submission { domain: 'i.imgur.com', banned_by: null, subreddit: Subreddit { display_name: 'funny' }, ... }, // ... // ] r.getBest({limit: 1}).then(console.log) // => Listing [ // Submission { domain: 'self.redditdev', banned_by: null, subreddit: Subreddit { display_name: 'redditdev' }, ...} // ]
-
getNew( [subredditName] [, options])
Gets a Listing of new posts.
-
Parameters:
Name Type Argument Default Description subredditName
string <optional>
The subreddit to get posts from. If not provided, posts are fetched from the front page of reddit.
options
object <optional>
{} Options for the resulting Listing
Returns:
A Listing containing the retrieved submissions
- Type
- Promise
Example
r.getNew().then(console.log) // => Listing [ // Submission { domain: 'self.Jokes', banned_by: null, subreddit: Subreddit { display_name: 'Jokes' }, ... }, // Submission { domain: 'self.AskReddit', banned_by: null, subreddit: Subreddit { display_name: 'AskReddit' }, ... }, // ... // ]
-
getNewComments( [subredditName] [, options])
Gets a Listing of new comments.
-
Parameters:
Name Type Argument Default Description subredditName
string <optional>
The subreddit to get comments from. If not provided, posts are fetched from the front page of reddit.
options
object <optional>
{} Options for the resulting Listing
Returns:
A Listing containing the retrieved comments
- Type
- Promise
Example
r.getNewComments().then(console.log) // => Listing [ // Comment { link_title: 'What amazing book should be made into a movie, but hasn\'t been yet?', ... } // Comment { link_title: 'How far back in time could you go and still understand English?', ... } // ]
-
getContentByIds(ids)
Get list of content by IDs. Returns a listing of the requested content.
-
Parameters:
Name Type Description ids
Array.<(string|Submission|Comment)> An array of content IDs. Can include the id itself, or a Submission or Comment object. can get a post and a comment * @returns {Promise<Listing<Submission|Comment>>} A listing of content requested, can be any class fetchable by API. e.g. Comment, Submission
Example
r.getContentByIds(['t3_9l9vof','t3_9la341']).then(console.log); // => Listing [ // Submission { approved_at_utc: null, ... } // Submission { approved_at_utc: null, ... } // ] r.getContentByIds([r.getSubmission('9l9vof'), r.getSubmission('9la341')]).then(console.log); // => Listing [ // Submission { approved_at_utc: null, ... } // Submission { approved_at_utc: null, ... } // ]
-
getRandomSubmission( [subredditName])
Gets a single random Submission.
-
Note: This function will not work when snoowrap is running in a browser, because the reddit server sends a redirect which cannot be followed by a CORS request.
Parameters:
Name Type Argument Description subredditName
string <optional>
The subreddit to get the random submission. If not provided, the post is fetched from the front page of reddit.
Returns:
The retrieved Submission object
- Type
- Promise
Example
r.getRandomSubmission('aww').then(console.log) // => Submission { domain: 'i.imgur.com', banned_by: null, subreddit: Subreddit { display_name: 'aww' }, ... }
-
getTop( [subredditName] [, options])
Gets a Listing of top posts.
-
Parameters:
Name Type Argument Default Description subredditName
string <optional>
The subreddit to get posts from. If not provided, posts are fetched from the front page of reddit.
options
object <optional>
{} Options for the resulting Listing
Properties
Name Type Argument Description time
string <optional>
Describes the timespan that posts should be retrieved from. Should be one of
hour, day, week, month, year, all
Returns:
A Listing containing the retrieved submissions
- Type
- Promise
Example
r.getTop({time: 'all', limit: 2}).then(console.log) // => Listing [ // Submission { domain: 'self.AskReddit', banned_by: null, subreddit: Subreddit { display_name: 'AskReddit' }, ... }, // Submission { domain: 'imgur.com', banned_by: null, subreddit: Subreddit { display_name: 'funny' }, ... } // ] r.getTop('AskReddit').then(console.log) // => Listing [ // Submission { domain: 'self.AskReddit', banned_by: null, subreddit: Subreddit { display_name: 'AskReddit' }, ... }, // Submission { domain: 'self.AskReddit', banned_by: null, subreddit: Subreddit { display_name: 'AskReddit' }, ... }, // Submission { domain: 'self.AskReddit', banned_by: null, subreddit: Subreddit { display_name: 'AskReddit' }, ... }, // ... // ]
-
getControversial( [subredditName] [, options])
Gets a Listing of controversial posts.
-
Parameters:
Name Type Argument Default Description subredditName
string <optional>
The subreddit to get posts from. If not provided, posts are fetched from the front page of reddit.
options
object <optional>
{} Options for the resulting Listing
Properties
Name Type Argument Description time
string <optional>
Describes the timespan that posts should be retrieved from. Should be one of
hour, day, week, month, year, all
Returns:
A Listing containing the retrieved submissions
- Type
- Promise
Example
r.getControversial('technology').then(console.log) // => Listing [ // Submission { domain: 'thenextweb.com', banned_by: null, subreddit: Subreddit { display_name: 'technology' }, ... }, // Submission { domain: 'pcmag.com', banned_by: null, subreddit: Subreddit { display_name: 'technology' }, ... } // ]
-
getRising( [subredditName] [, options])
Gets a Listing of controversial posts.
-
Parameters:
Name Type Argument Description subredditName
string <optional>
The subreddit to get posts from. If not provided, posts are fetched from the front page of reddit.
options
object <optional>
Options for the resulting Listing
Returns:
A Listing containing the retrieved submissions
- Type
- Promise
Example
r.getRising('technology').then(console.log) // => Listing [ // Submission { domain: 'thenextweb.com', banned_by: null, subreddit: Subreddit { display_name: 'technology' }, ... }, // Submission { domain: 'pcmag.com', banned_by: null, subreddit: Subreddit { display_name: 'technology' }, ... } // ]
-
getUnreadMessages( [options])
Gets the authenticated user's unread messages.
-
Parameters:
Name Type Argument Default Description options
object <optional>
{} Options for the resulting Listing
Returns:
A Listing containing unread items in the user's inbox
- Type
- Promise
Example
r.getUnreadMessages().then(console.log) // => Listing [ // PrivateMessage { body: 'hi!', was_comment: false, first_message: null, ... }, // Comment { body: 'this is a reply', link_title: 'Yay, a selfpost!', was_comment: true, ... } // ]
-
getInbox( [options])
Gets the items in the authenticated user's inbox.
-
Parameters:
Name Type Argument Default Description options
object <optional>
{} Filter options. Can also contain options for the resulting Listing.
Properties
Name Type Argument Description filter
string <optional>
A filter for the inbox items. If provided, it should be one of
unread
, (unread items),messages
(i.e. PMs),comments
(comment replies),selfreply
(selfpost replies), ormentions
(username mentions).Returns:
A Listing containing items in the user's inbox
- Type
- Promise
Example
r.getInbox().then(console.log) // => Listing [ // PrivateMessage { body: 'hi!', was_comment: false, first_message: null, ... }, // Comment { body: 'this is a reply', link_title: 'Yay, a selfpost!', was_comment: true, ... } // ]
-
getModmail( [options])
Gets the authenticated user's modmail.
-
Parameters:
Name Type Argument Default Description options
object <optional>
{} Options for the resulting Listing
Returns:
A Listing of the user's modmail
- Type
- Promise
Example
r.getModmail({limit: 2}).then(console.log) // => Listing [ // PrivateMessage { body: '/u/not_an_aardvark has accepted an invitation to become moderator ... ', ... }, // PrivateMessage { body: '/u/not_an_aardvark has been invited by /u/actually_an_aardvark to ...', ... } // ]
-
getNewModmailConversations( [options])
Gets a list of ModmailConversations from the authenticated user's subreddits.
-
Parameters:
Name Type Argument Description options
object <optional>
Options for the resulting Listing
Returns:
A Listing containing Subreddits
- Type
- Promise.<Listing.<ModmailConversation>>
Example
r.getNewModmailConversations({limit: 2}).then(console.log) // => Listing [ // ModmailConversation { messages: [...], objIds: [...], subject: 'test subject', ... }, // ModmailConversation { messages: [...], objIds: [...], subject: 'test subject', ... } // ]
-
createModmailDiscussion(options)
Create a new modmail discussion between moderators
-
Parameters:
Name Type Description options
object Properties
Name Type Description body
string Body of the discussion
subject
string Title or subject
srName
string Subreddit name without fullname
Returns:
the created ModmailConversation
- Type
- Promise.<ModmailConversation>
Example
r.createModeratorDiscussion({ body: 'test body', subject: 'test subject', srName: 'AskReddit' }).then(console.log) // ModmailConversation { messages: [...], objIds: [...], subject: 'test subject', ... }
-
getNewModmailConversation(id)
Get a ModmailConversation by its id
-
Parameters:
Name Type Description id
string of the ModmailConversation
Returns:
the requested ModmailConversation
- Type
- Promise.<ModmailConversation>
Example
r.getNewModmailConversation('75hxt').then(console.log) // ModmailConversation { messages: [...], objIds: [...], ... }
-
markNewModmailConversationsAsRead(conversations)
Marks all conversations in array as read.
-
Parameters:
Name Type Description conversations
Array.<ModmailConversation> to mark as read
Example
r.markNewModmailConversationsAsRead(['pics', 'sweden'])
-
markNewModmailConversationsAsUnread(conversations)
Marks all conversations in array as unread.
-
Parameters:
Name Type Description conversations
Array.<ModmailConversation> to mark as unread
Example
r.markNewModmailConversationsAsUnread(['pics', 'sweden'])
-
getNewModmailSubreddits()
Gets all moderated subreddits that have new Modmail activated
-
Returns:
a Listing of ModmailConversations marked as read
Example
r.getNewModmailSubreddits().then(console.log) // => Listing [ // Subreddit { display_name: 'tipofmytongue', ... }, // Subreddit { display_name: 'EarthPorn', ... }, // ]
-
getUnreadNewModmailConversationsCount()
Retrieves an object of unread Modmail conversations for each state.
-
Returns:
unreadCount
- Type
- UnreadCount
Example
r.getUnreadNewModmailConversationsCount().then(console.log) // => { // archived: 1, // appeals: 1, // highlighted: 0, // notifications: 0, // join_requests: 0, // new: 2, // inprogress: 5, // mod: 1, // }
-
bulkReadNewModmail(subreddits, state)
Mark Modmail conversations as read given the subreddit(s) and state.
-
Parameters:
Name Type Description subreddits
Array.<Subreddit> | Array.<String> state
'archived' | 'appeals' | 'highlighted' | 'notifications' | 'join_requests' | 'new' | 'inprogress' | 'mod' | 'all' selected state to mark as read
Returns:
a Listing of ModmailConversations marked as read
- Type
- Promise.<Listing.<ModmailConversation>>
Example
r.bulkReadNewModmail(['AskReddit'], 'all').then(console.log) // => Listing [ // ModmailConversation { id: '75hxt' }, // ModmailConversation { id: '75hxg' } // ] r.bulkReadNewModmail([r.getSubreddit('AskReddit')], 'all').then(console.log) // => Listing [ // ModmailConversation { id: '75hxt' }, // ModmailConversation { id: '75hxg' } // ]
-
getSentMessages( [options])
Gets the user's sent messages.
-
Parameters:
Name Type Argument Default Description options
object <optional>
{} options for the resulting Listing
Returns:
A Listing of the user's sent messages
- Type
- Promise
Example
r.getSentMessages().then(console.log) // => Listing [ // PrivateMessage { body: 'you have been added as an approved submitter to ...', ... }, // PrivateMessage { body: 'you have been banned from posting to ...' ... } // ]
-
markMessagesAsRead(messages)
Marks all of the given messages as read.
-
Parameters:
Name Type Description messages
Array.<PrivateMessage> | Array.<String> An Array of PrivateMessage or Comment objects. Can also contain strings representing message or comment IDs. If strings are provided, they are assumed to represent PrivateMessages unless a fullname prefix such as
t1_
is specified.Returns:
A Promise that fulfills when the request is complete
- Type
- Promise
Example
r.markMessagesAsRead(['51shsd', '51shxv']) // To reference a comment by ID, be sure to use the `t1_` prefix, otherwise snoowrap will be unable to distinguish the // comment ID from a PrivateMessage ID. r.markMessagesAsRead(['t5_51shsd', 't1_d3zhb5k']) // Alternatively, just pass in a comment object directly. r.markMessagesAsRead([r.getMessage('51shsd'), r.getComment('d3zhb5k')])
-
markMessagesAsUnread(messages)
Marks all of the given messages as unread.
-
Parameters:
Name Type Description messages
Array.<PrivateMessage> | Array.<String> An Array of PrivateMessage or Comment objects. Can also contain strings representing message IDs. If strings are provided, they are assumed to represent PrivateMessages unless a fullname prefix such as
t1_
is included.Returns:
A Promise that fulfills when the request is complete
- Type
- Promise
Example
r.markMessagesAsUnread(['51shsd', '51shxv']) // To reference a comment by ID, be sure to use the `t1_` prefix, otherwise snoowrap will be unable to distinguish the // comment ID from a PrivateMessage ID. r.markMessagesAsUnread(['t5_51shsd', 't1_d3zhb5k']) // Alternatively, just pass in a comment object directly. r.markMessagesAsRead([r.getMessage('51shsd'), r.getComment('d3zhb5k')])
-
readAllMessages()
Marks all of the user's messages as read.
-
Note: The reddit.com site imposes a ratelimit of approximately 1 request every 10 minutes on this endpoint. Further requests will cause the API to return a 429 error.
Returns:
A Promise that resolves when the request is complete
- Type
- Promise
Example
r.readAllMessages().then(function () { r.getUnreadMessages().then(console.log) }) // => Listing [] // (messages marked as 'read' on reddit)
-
composeMessage(options)
Composes a new private message.
-
Parameters:
Name Type Description options
object Properties
Name Type Argument Description to
RedditUser | Subreddit | string The recipient of the message.
subject
string The message subject (100 characters max)
text
string The body of the message, in raw markdown text
fromSubreddit
Subreddit | string <optional>
If provided, the message is sent as a modmail from the specified subreddit.
captchaIden
string <optional>
A captcha identifier. This is only necessary if the authenticated account requires a captcha to submit posts and comments.
captchaResponse
string <optional>
The response to the captcha with the given identifier
Returns:
A Promise that fulfills when the request is complete
- Type
- Promise
Example
r.composeMessage({ to: 'actually_an_aardvark', subject: "Hi, how's it going?", text: 'Long time no see' }) // (message created on reddit)
-
getOauthScopeList()
Gets a list of all oauth scopes supported by the reddit API.
-
Note: This lists every single oauth scope. To get the scope of this requester, use the
scope
property instead.Returns:
An object containing oauth scopes.
- Type
- Promise
Example
r.getOauthScopeList().then(console.log) // => { // creddits: { // description: 'Spend my reddit gold creddits on giving gold to other users.', // id: 'creddits', // name: 'Spend reddit gold creddits' // }, // modcontributors: { // description: 'Add/remove users to approved submitter lists and ban/unban or mute/unmute users from ...', // id: 'modcontributors', // name: 'Approve submitters and ban users' // }, // ... // }
-
search(options)
Conducts a search of reddit submissions.
-
Parameters:
Name Type Description options
object Search options. Can also contain options for the resulting Listing.
Properties
Name Type Argument Default Description query
string The search query
time
string <optional>
Describes the timespan that posts should be retrieved from. One of
hour, day, week, month, year, all
subreddit
Subreddit | string <optional>
The subreddit to conduct the search on.
restrictSr
boolean <optional>
true Restricts search results to the given subreddit
sort
string <optional>
Determines how the results should be sorted. One of
relevance, hot, top, new, comments
syntax
string <optional>
'plain' Specifies a syntax for the search. One of
cloudsearch, lucene, plain
Returns:
A Listing containing the search results.
- Type
- Promise
Example
r.search({ query: 'Cute kittens', subreddit: 'aww', sort: 'top' }).then(console.log) // => Listing [ // Submission { domain: 'i.imgur.com', banned_by: null, ... }, // Submission { domain: 'imgur.com', banned_by: null, ... }, // ... // ]
-
searchSubredditNames(options)
Searches for subreddits given a query.
-
Parameters:
Name Type Description options
object Properties
Name Type Argument Default Description query
string A search query (50 characters max)
exact
boolean <optional>
false Determines whether the results shouldbe limited to exact matches.
includeNsfw
boolean <optional>
true Determines whether the results should include NSFW subreddits.
Returns:
An Array containing subreddit names
- Type
- Promise
Example
r.searchSubredditNames({query: 'programming'}).then(console.log) // => [ // 'programming', // 'programmingcirclejerk', // 'programminghorror', // ... // ]
-
createSubreddit(options)
Creates a new subreddit.
-
Parameters:
Name Type Description options
object Properties
Name Type Argument Default Description name
string The name of the new subreddit
title
string The text that should appear in the header of the subreddit
public_description
string The text that appears with this subreddit on the search page, or on the blocked-access page if this subreddit is private. (500 characters max)
description
string The sidebar text for the subreddit. (5120 characters max)
submit_text
string <optional>
'' The text to show below the submission page (1024 characters max)
hide_ads
boolean <optional>
false Determines whether ads should be hidden on this subreddit. (This is only allowed for gold-only subreddits.)
lang
string <optional>
'en' The language of the subreddit (represented as an IETF language tag)
type
string <optional>
'public' Determines who should be able to access the subreddit. This should be one of
public, private, restricted, gold_restricted, gold_only, archived, employees_only
.link_type
string <optional>
'any' Determines what types of submissions are allowed on the subreddit. This should be one of
any, link, self
.submit_link_label
string <optional>
Custom text to display on the button that submits a link. If this is omitted, the default text will be displayed.
submit_text_label
string <optional>
Custom text to display on the button that submits a selfpost. If this is omitted, the default text will be displayed.
wikimode
string <optional>
'modonly' Determines who can edit wiki pages on the subreddit. This should be one of
modonly, anyone, disabled
.wiki_edit_karma
number <optional>
0 The minimum amount of subreddit karma needed for someone to edit this subreddit's wiki. (This is only relevant if
options.wikimode
is set toanyone
.)wiki_edit_age
number <optional>
0 The minimum account age (in days) needed for someone to edit this subreddit's wiki. (This is only relevant if
options.wikimode
is set toanyone
.)spam_links
string <optional>
'high' The spam filter strength for links on this subreddit. This should be one of
low, high, all
.spam_selfposts
string <optional>
'high' The spam filter strength for selfposts on this subreddit. This should be one of
low, high, all
.spam_comments
string <optional>
'high' The spam filter strength for comments on this subreddit. This should be one of
low, high, all
.over_18
boolean <optional>
false Determines whether this subreddit should be classified as NSFW
allow_top
boolean <optional>
true Determines whether the new subreddit should be able to appear in /r/all and trending subreddits
show_media
boolean <optional>
false Determines whether image thumbnails should be enabled on this subreddit
show_media_preview
boolean <optional>
true Determines whether media previews should be expanded by default on this subreddit
allow_images
boolean <optional>
true Determines whether image uploads and links to image hosting sites should be enabled on this subreddit
exclude_banned_modqueue
boolean <optional>
false Determines whether posts by site-wide banned users should be excluded from the modqueue.
public_traffic
boolean <optional>
false Determines whether the /about/traffic page for this subreddit should be viewable by anyone.
collapse_deleted_comments
boolean <optional>
false Determines whether deleted and removed comments should be collapsed by default
suggested_comment_sort
string <optional>
The suggested comment sort for the subreddit. This should be one of
confidence, top, new, controversial, old, random, qa
.If left blank, there will be no suggested sort, which means that users will see the sort method that is set in their own preferences (usuallyconfidence
.)spoilers_enabled
boolean <optional>
false Determines whether users can mark their posts as spoilers
Returns:
A Promise for the newly-created subreddit object.
- Type
- Promise
Example
r.createSubreddit({ name: 'snoowrap_testing2', title: 'snoowrap testing: the sequel', public_description: 'thanks for reading the snoowrap docs!', description: 'This text will go on the sidebar', type: 'private' }).then(console.log) // => Subreddit { display_name: 'snoowrap_testing2' } // (/r/snoowrap_testing2 created on reddit)
-
searchSubredditTopics(options)
Searches subreddits by topic.
-
Parameters:
Name Type Description options
object Properties
Name Type Description query
string The search query. (50 characters max)
- Deprecated:
-
- Reddit no longer provides the corresponding API endpoint.
Returns:
An Array of subreddit objects corresponding to the search results
- Type
- Promise
Example
r.searchSubredditTopics({query: 'movies'}).then(console.log) // => [ // Subreddit { display_name: 'tipofmytongue' }, // Subreddit { display_name: 'remove' }, // Subreddit { display_name: 'horror' }, // ... // ]
-
getSubscriptions( [options])
Gets a list of subreddits that the currently-authenticated user is subscribed to.
-
Parameters:
Name Type Argument Description options
object <optional>
Options for the resulting Listing
Returns:
A Listing containing Subreddits
- Type
- Promise
Example
r.getSubscriptions({limit: 2}).then(console.log) // => Listing [ // Subreddit { // display_name: 'gadgets', // title: 'reddit gadget guide', // ... // }, // Subreddit { // display_name: 'sports', // title: 'the sportspage of the Internet', // ... // } // ]
-
getContributorSubreddits( [options])
Gets a list of subreddits in which the currently-authenticated user is an approved submitter.
-
Parameters:
Name Type Argument Description options
object <optional>
Options for the resulting Listing
Returns:
A Listing containing Subreddits
- Type
- Promise
Example
r.getContributorSubreddits().then(console.log) // => Listing [ // Subreddit { // display_name: 'snoowrap_testing', // title: 'snoowrap', // ... // } // ]
-
getModeratedSubreddits( [options])
Gets a list of subreddits in which the currently-authenticated user is a moderator.
-
Parameters:
Name Type Argument Description options
object <optional>
Options for the resulting Listing
Returns:
A Listing containing Subreddits
- Type
- Promise
Example
r.getModeratedSubreddits().then(console.log) // => Listing [ // Subreddit { // display_name: 'snoowrap_testing', // title: 'snoowrap', // ... // } // ]
-
searchSubreddits(options)
Searches subreddits by title and description.
-
Parameters:
Name Type Description options
object Options for the search. May also contain Listing parameters.
Properties
Name Type Description query
string The search query
Returns:
A Listing containing Subreddits
- Type
- Promise
Example
r.searchSubreddits({query: 'cookies'}).then(console.log) // => Listing [ Subreddit { ... }, Subreddit { ... }, ...]
-
getPopularSubreddits( [options])
Gets a list of subreddits, arranged by popularity.
-
Parameters:
Name Type Argument Description options
object <optional>
Options for the resulting Listing
Returns:
A Listing containing Subreddits
- Type
- Promise
Example
r.getPopularSubreddits().then(console.log) // => Listing [ Subreddit { ... }, Subreddit { ... }, ...]
-
getNewSubreddits( [options])
Gets a list of subreddits, arranged by age.
-
Parameters:
Name Type Argument Description options
object <optional>
Options for the resulting Listing
Returns:
A Listing containing Subreddits
- Type
- Promise
Example
r.getNewSubreddits().then(console.log) // => Listing [ Subreddit { ... }, Subreddit { ... }, ...]
-
getGoldSubreddits( [options])
Gets a list of gold-exclusive subreddits.
-
Parameters:
Name Type Argument Description options
object <optional>
Options for the resulting Listing
Returns:
A Listing containing Subreddits
- Type
- Promise
Example
r.getGoldSubreddits().then(console.log) // => Listing [ Subreddit { ... }, Subreddit { ... }, ...]
-
getDefaultSubreddits( [options])
Gets a list of default subreddits.
-
Parameters:
Name Type Argument Description options
object <optional>
Options for the resulting Listing
Returns:
A Listing containing Subreddits
- Type
- Promise
Example
r.getDefaultSubreddits().then(console.log) // => Listing [ Subreddit { ... }, Subreddit { ... }, ...]
-
checkUsernameAvailability(name)
Checks whether a given username is available for registration
-
Note: This function will not work when snoowrap is running in a browser, due to an issue with reddit's CORS settings.
Parameters:
Name Type Description name
string The username in question
Returns:
A Promise that fulfills with a Boolean (
true
orfalse
)- Type
- Promise
Example
r.checkUsernameAvailability('not_an_aardvark').then(console.log) // => false r.checkUsernameAvailability('eqwZAr9qunx7IHqzWVeF').then(console.log) // => true
-
createLivethread(options)
Creates a new LiveThread.
-
Parameters:
Name Type Description options
object Properties
Name Type Argument Default Description title
string The title of the livethread (100 characters max)
description
string <optional>
A descriptions of the thread. 120 characters max
resources
string <optional>
Information and useful links related to the thread. 120 characters max
nsfw
boolean <optional>
false Determines whether the thread is Not Safe For Work
Returns:
A Promise that fulfills with the new LiveThread when the request is complete
- Type
- Promise
Example
r.createLivethread({title: 'My livethread'}).then(console.log) // => LiveThread { id: 'wpimncm1f01j' }
-
getStickiedLivethread()
Gets the "happening now" LiveThread, if it exists
-
This is the LiveThread that is occasionally linked at the top of reddit.com, relating to current events.
Returns:
A Promise that fulfills with the "happening now" LiveThread if it exists, or rejects with a 404 error otherwise.
- Type
- Promise
Example
r.getCurrentEventsLivethread().then(thread => thread.stream.on('update', console.log))
-
getMyMultireddits()
Gets the user's own multireddits.
-
Returns:
A Promise for an Array containing the requester's MultiReddits.
- Type
- Promise
Example
r.getMyMultireddits().then(console.log) => [ MultiReddit { ... }, MultiReddit { ... }, ... ]
-
createMultireddit(options)
Creates a new multireddit.
-
Parameters:
Name Type Description options
object Properties
Name Type Argument Default Description name
string The name of the new multireddit. 50 characters max
description
string A description for the new multireddit, in markdown.
subreddits
Array An Array of Subreddit objects (or subreddit names) that this multireddit should compose of
visibility
string <optional>
'private' The multireddit's visibility setting. One of
private
,public
,hidden
.icon_name
string <optional>
'' One of
art and design
,ask
,books
,business
,cars
,comics
,cute animals
,diy
,entertainment
,food and drink
,funny
,games
,grooming
,health
,life advice
,military
,models pinup
,music
,news
,philosophy
,pictures and gifs
,science
,shopping
,sports
,style
,tech
,travel
,unusual stories
,video
,None
key_color
string <optional>
'#000000' A six-digit RGB hex color, preceded by '#'
weighting_scheme
string <optional>
'classic' One of
classic
,fresh
Returns:
A Promise for the newly-created MultiReddit object
- Type
- Promise
Example
r.createMultireddit({ name: 'myMulti', description: 'An example multireddit', subreddits: ['snoowrap', 'snoowrap_testing'] }).then(console.log) => MultiReddit { display_name: 'myMulti', ... }
-
revokeAccessToken()
Invalidates the current access token.
-
Note: This can only be used if the current requester was supplied with a
client_id
andclient_secret
. If the current requester was supplied with a refresh token, it will automatically create a new access token if any more requests are made after this one.Returns:
A Promise that fulfills when this request is complete
- Type
- Promise
Example
r.revokeAccessToken();
-
revokeRefreshToken()
Invalidates the current refresh token.
-
Note: This can only be used if the current requester was supplied with a
client_id
andclient_secret
. All access tokens generated by this refresh token will also be invalidated. This effectively de-authenticates the requester and prevents it from making any more valid requests. This should only be used in a few cases, e.g. if this token has been accidentally leaked to a third party.Returns:
A Promise that fulfills when this request is complete
- Type
- Promise
Example
r.revokeRefreshToken();
-
<static> noConflict()
In browsers, restores the
window.snoowrap
property to whatever it was before this instance of snoowrap was loaded. This is a no-op in Node. -
Returns:
This instance of the snoowrap constructor
Example
var snoowrap = window.snoowrap.noConflict();
-
oauthRequest(options)
Sends an oauth-authenticated request to the reddit server, and returns the server's response.
-
Note: While this function primarily exists for internal use, it is exposed and considered a stable feature. However, keep in mind that there are usually better alternatives to using this function. For instance, this function can be used to send a POST request to the 'api/vote' endpoint in order to upvote a comment, but it's generally easier to just use snoowrap's
upvote function
.If you're using this function to access an API feature/endpoint that is unsupported by snoowrap, please consider creating an issue for it so that the functionality can be added to snoowrap more directly.
Parameters:
Name Type Description options
object Options for the request. For documentation on these options, see the Request API. Supported options include
uri
,qs
,form
,headers
,method
,auth
, andbody
. A defaultbaseUrl
parameter ofthis.config().endpoint_domain
is internally included by default, so it is recommended that auri
parameter be used, rather than aurl
parameter with a domain name.Returns:
A Promise that fulfills with reddit's response.
- Type
- Promise
Example
r.oauthRequest({uri: '/user/spez/about', method: 'get'}).then(console.log) // => RedditUser { name: 'spez', link_karma: 9567, ... } // Note that this is equivalent to: r.getUser('spez').fetch().then(console.log) // ###### r.oauthRequest({uri: '/api/vote', method: 'post', form: {dir: 1, id: 't3_4fzg2k'}}) // equivalent to: r.getSubmission('4fzg2k').upvote() // ###### r.oauthRequest({uri: '/top', method: 'get', qs: {t: 'all'}}) // equivalent to: r.getTop({time: 'all'})
-
credentialedClientRequest(options)
Sends a request to the reddit server, authenticated with the user's client ID and client secret.
-
Note: This is used internally as part of the authentication process, but it cannot be used to actually fetch content from reddit. To do that, use
snoowrap#oauthRequest
or another of snoowrap's helper functions.This function can work with alternate
this
-bindings, provided that the binding has theclientId
,clientSecret
, anduserAgent
properties. This allows it be used if no snoowrap requester has been created yet.Parameters:
Name Type Description options
object | string Options for the request; these are passed directly to the Request API.
Returns:
The response from the reddit server
- Type
- Promise
Example
// example: this function could be used to exchange a one-time authentication code for a refresh token. snoowrap.prototype.credentialedClientRequest.call({ clientId: 'client id goes here', clientSecret: 'client secret goes here', userAgent: 'user agent goes here' }, { method: 'post', baseUrl: 'https://www.reddit.com', uri: 'api/v1/access_token', form: {grant_type: 'authorization_code', code: 'code goes here', redirect_uri: 'redirect uri goes here'} }).then(response => { //handle response here })
-
unauthenticatedRequest(options)
Sends a request to the reddit server without authentication.
-
Parameters:
Name Type Description options
object | string Options for the request; these are passed directly to the Request API.
Returns:
The response from the reddit server
- Type
- Promise
-
updateAccessToken()
Updates this requester's access token if the current one is absent or expired.
-
Note: This function is automatically called internally when making a request. While the function is exposed as a stable feature, using it is rarely necessary unless an access token is needed for some external purpose.
Returns:
A Promise that fulfills with the access token when this request is complete
- Type
- Promise
Example
r.updateAccessToken()
-
rawRequest(options)
Sends an HTTP request
-
Note: This function is called internally whenever snoowrap makes a request. You generally should not call this function directly; use
snoowrap#oauthRequest
or another snoowrap function instead.This method allows snoowrap's request behavior to be customized via subclassing. If you create a snoowrap subclass and shadow this method, all requests from snoowrap will pass through it.
To ensure that all other snoowrap methods work correctly, the API for a shadowed version of this method must match the API for the original
makeRequest
method. This method is based on the API of the request-promise library, so if you do create a subclass, it might be helpful to userequest-promise
internally. This will ensure that the API works correctly, so that you don't have to reimplement this function's API from scratch.Parameters:
Name Type Description options
object Options for the request
Properties
Name Type Argument Default Description json
boolean If
true
, theContent-Type: application/json
header is added, and the response body will be parsed as JSON automatically.baseUrl
string The base URL that a request should be sent to
uri
string The uri that a request should be sent to, using the provided
baseUrl
.method
string 'GET' Method for the request
headers
object Headers for the request
qs
object <optional>
Querystring parameters for the request
form
object <optional>
Form data for the request. If provided, the
Content-Type: application/x-www-form-urlencoded
header is set, and the provided object is serialized into URL-encoded form data in the request body.formData
object <optional>
Multipart form data for the request. If provided, the
Content-Type: multipart/form-data
header is set, and the provided object is serialized as multipart form data.body
object <optional>
The body of the request. Should be converted to a string with JSON.stringify(). This is ignored for GET requests, or of
options.form
oroptions.formData
are provided.transform
function <optional>
A function that is called before the response Promise fulfills. Accepts two parameters:
response.body
andresponse
. This function should be called regardless of the status code of the response, and the returned Promise frommakeRequest
should fulfill with its return value.resolveWithFullResponse
boolean <optional>
false If
true
, a Promise for the entire response is returned. Iffalse
, a Promise for only the response body is returned. This is ignored if anoptions.transform
function is provided.Returns:
A Promise for a response object. Depending on
options.transform
andoptions.resolveWithFullResponse
, the Promise should settle with either the response object itself, the body of the response, or the value returned byoptions.transform
. The Promise should be fulfilled if the status code is between 200 and 299, inclusive, and reject otherwise. (If a redirect is returned from the server, the function should follow the redirect if possible, otherwise reject with an error.) A response object has 4 properties:statusCode
(number) the status code of the response,body
(object) the body of the response,headers
(object) the parsed response headers, andrequest
(object) an object of the form{method: 'GET', uri: {href: 'https://oauth.reddit.com/full/url'}}
representing information about the original request.- Type
- Promise
Example
const snoowrap = require('snoowrap'); class SnoowrapSubclass extends snoowrap { rawRequest(options) { // do custom behavior with `options` if you want, then call the regular rawRequest function console.log(`made a request with options:`); console.log(options); return super.rawRequest(options) } } const request = require('request-promise'); class AnotherSnoowrapSubclass extends snoowrap { rawRequest(options) { // send all requests through a proxy return request(Object.assign(options, {proxy: 'https://example.com'})) } }