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, andrefreshTokento 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, andpasswordto 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
userAgentandaccessTokento 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 acodequerystring 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 optionsobject Properties
Name Type Argument Default Description clientIdstring 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.
scopeArray.<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.redirectUristring 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.)
permanentboolean <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.statestring <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
statevalue in the querystring. (See here for more information on how to use thestatevalue.)endpointDomainstring <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
codevalue 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.getAuthUrland 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 optionsobject Properties
Name Type Argument Default Description codestring The authorization code
userAgentstring A unique description of what your app does. This argument is not necessary when snoowrap is running in a browser.
clientIdstring 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.
clientSecretstring <optional>
The client secret of your app. If your app has the "Installed" app type, omit this parameter.
redirectUristring The redirect URI that is configured for the reddit app.
endpointDomainstring <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
snoowrapinstance- 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 optionsobject Properties
Name Type Argument Default Description userAgentstring A unique description of what your app does. This argument is not necessary when snoowrap is running in a browser.
clientIdstring 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.
clientSecretstring <optional>
The client secret of your app. Only required for "client_credentials" grant type.
deviceIdstring <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."
grantTypestring <optional>
snoowrap.grantType.INSTALLED_CLIENT The type of "user-less" token to use
snoowrap.grantTypepermanentboolean <optional>
true If
true, the app will have indefinite access. Iffalse, access will expire after 1 hour.endpointDomainstring <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
snoowrapinstance- 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 optionsobject <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 endpointDomainstring <optional>
'reddit.com' The endpoint where requests should be sent
requestDelayNumber <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.
requestTimeoutNumber <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.
continueAfterRatelimitErrorboolean <optional>
false Determines whether snoowrap should queue API calls if reddit's ratelimit is exceeded. If set to
truewhen 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.retryErrorCodesArray.<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_attemptsrequests 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.maxRetryAttemptsNumber <optional>
3 See
retryErrorCodes.warningsboolean <optional>
true snoowrap may occasionally log warnings, such as deprecation notices, to the console. These can be disabled by setting this to
false.debugboolean <optional>
false If set to true, snoowrap will print out potentially-useful information for debugging purposes as it runs.
loggerobject <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, andtracefunctions.proxiesboolean <optional>
true Setting this to
falsedisables 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 ES6Proxyobject and environments that don't. This option is a no-op in environments that don't support theProxyobject, 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 namestring 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 commentIdstring 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 displayNamestring 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 submissionIdstring 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 messageIdstring 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 threadIdstring 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 updatedPreferencesobject 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 identifierstring 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 linksArray.<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 optionsobject An object containing details about the submission
Properties
Name Type Argument Default Description subredditNamestring The name of the subreddit that the post should be submitted to
titlestring The title of the submission
textstring <optional>
The selftext of the submission
sendRepliesboolean <optional>
true Determines whether inbox replies should be enabled for this submission
captchaIdenstring <optional>
A captcha identifier. This is only necessary if the authenticated account requires a captcha to submit posts and comments.
captchaResponsestring <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 optionsobject An object containing details about the submission
Properties
Name Type Argument Default Description subredditNamestring The name of the subreddit that the post should be submitted to
titlestring The title of the submission
urlstring The url that the link submission should point to
sendRepliesboolean <optional>
true Determines whether inbox replies should be enabled for this submission
resubmitboolean <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.
captchaIdenstring <optional>
A captcha identifier. This is only necessary if the authenticated account requires a captcha to submit posts and comments.
captchaResponsestring <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 optionsobject An object containing details about the submission
Properties
Name Type Argument Default Description subredditNamestring The name of the subreddit that the crosspost should be submitted to
titlestring The title of the crosspost
originalPoststring | Submission A Submission object or a post ID for the original post which is being crossposted
sendRepliesboolean <optional>
true Determines whether inbox replies should be enabled for this submission
resubmitboolean <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 subredditNamestring <optional>
The subreddit to get posts from. If not provided, posts are fetched from the front page of reddit.
optionsobject <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 optionsobject <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 subredditNamestring <optional>
The subreddit to get posts from. If not provided, posts are fetched from the front page of reddit.
optionsobject <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 subredditNamestring <optional>
The subreddit to get comments from. If not provided, posts are fetched from the front page of reddit.
optionsobject <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 idsArray.<(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 subredditNamestring <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 subredditNamestring <optional>
The subreddit to get posts from. If not provided, posts are fetched from the front page of reddit.
optionsobject <optional>
{} Options for the resulting Listing
Properties
Name Type Argument Description timestring <optional>
Describes the timespan that posts should be retrieved from. Should be one of
hour, day, week, month, year, allReturns:
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 subredditNamestring <optional>
The subreddit to get posts from. If not provided, posts are fetched from the front page of reddit.
optionsobject <optional>
{} Options for the resulting Listing
Properties
Name Type Argument Description timestring <optional>
Describes the timespan that posts should be retrieved from. Should be one of
hour, day, week, month, year, allReturns:
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 subredditNamestring <optional>
The subreddit to get posts from. If not provided, posts are fetched from the front page of reddit.
optionsobject <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 optionsobject <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 optionsobject <optional>
{} Filter options. Can also contain options for the resulting Listing.
Properties
Name Type Argument Description filterstring <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 optionsobject <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 optionsobject <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 optionsobject Properties
Name Type Description bodystring Body of the discussion
subjectstring Title or subject
srNamestring 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 idstring 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 conversationsArray.<ModmailConversation> to mark as read
Example
r.markNewModmailConversationsAsRead(['pics', 'sweden'])
-
markNewModmailConversationsAsUnread(conversations)
Marks all conversations in array as unread.
-
Parameters:
Name Type Description conversationsArray.<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 subredditsArray.<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 optionsobject <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 messagesArray.<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 messagesArray.<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 optionsobject Properties
Name Type Argument Description toRedditUser | Subreddit | string The recipient of the message.
subjectstring The message subject (100 characters max)
textstring The body of the message, in raw markdown text
fromSubredditSubreddit | string <optional>
If provided, the message is sent as a modmail from the specified subreddit.
captchaIdenstring <optional>
A captcha identifier. This is only necessary if the authenticated account requires a captcha to submit posts and comments.
captchaResponsestring <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
scopeproperty 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 optionsobject Search options. Can also contain options for the resulting Listing.
Properties
Name Type Argument Default Description querystring The search query
timestring <optional>
Describes the timespan that posts should be retrieved from. One of
hour, day, week, month, year, allsubredditSubreddit | string <optional>
The subreddit to conduct the search on.
restrictSrboolean <optional>
true Restricts search results to the given subreddit
sortstring <optional>
Determines how the results should be sorted. One of
relevance, hot, top, new, commentssyntaxstring <optional>
'plain' Specifies a syntax for the search. One of
cloudsearch, lucene, plainReturns:
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 optionsobject Properties
Name Type Argument Default Description querystring A search query (50 characters max)
exactboolean <optional>
false Determines whether the results shouldbe limited to exact matches.
includeNsfwboolean <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 optionsobject Properties
Name Type Argument Default Description namestring The name of the new subreddit
titlestring The text that should appear in the header of the subreddit
public_descriptionstring 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)
descriptionstring The sidebar text for the subreddit. (5120 characters max)
submit_textstring <optional>
'' The text to show below the submission page (1024 characters max)
hide_adsboolean <optional>
false Determines whether ads should be hidden on this subreddit. (This is only allowed for gold-only subreddits.)
langstring <optional>
'en' The language of the subreddit (represented as an IETF language tag)
typestring <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_typestring <optional>
'any' Determines what types of submissions are allowed on the subreddit. This should be one of
any, link, self.submit_link_labelstring <optional>
Custom text to display on the button that submits a link. If this is omitted, the default text will be displayed.
submit_text_labelstring <optional>
Custom text to display on the button that submits a selfpost. If this is omitted, the default text will be displayed.
wikimodestring <optional>
'modonly' Determines who can edit wiki pages on the subreddit. This should be one of
modonly, anyone, disabled.wiki_edit_karmanumber <optional>
0 The minimum amount of subreddit karma needed for someone to edit this subreddit's wiki. (This is only relevant if
options.wikimodeis set toanyone.)wiki_edit_agenumber <optional>
0 The minimum account age (in days) needed for someone to edit this subreddit's wiki. (This is only relevant if
options.wikimodeis set toanyone.)spam_linksstring <optional>
'high' The spam filter strength for links on this subreddit. This should be one of
low, high, all.spam_selfpostsstring <optional>
'high' The spam filter strength for selfposts on this subreddit. This should be one of
low, high, all.spam_commentsstring <optional>
'high' The spam filter strength for comments on this subreddit. This should be one of
low, high, all.over_18boolean <optional>
false Determines whether this subreddit should be classified as NSFW
allow_topboolean <optional>
true Determines whether the new subreddit should be able to appear in /r/all and trending subreddits
show_mediaboolean <optional>
false Determines whether image thumbnails should be enabled on this subreddit
show_media_previewboolean <optional>
true Determines whether media previews should be expanded by default on this subreddit
allow_imagesboolean <optional>
true Determines whether image uploads and links to image hosting sites should be enabled on this subreddit
exclude_banned_modqueueboolean <optional>
false Determines whether posts by site-wide banned users should be excluded from the modqueue.
public_trafficboolean <optional>
false Determines whether the /about/traffic page for this subreddit should be viewable by anyone.
collapse_deleted_commentsboolean <optional>
false Determines whether deleted and removed comments should be collapsed by default
suggested_comment_sortstring <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_enabledboolean <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 optionsobject Properties
Name Type Description querystring 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 optionsobject <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 optionsobject <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 optionsobject <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 optionsobject Options for the search. May also contain Listing parameters.
Properties
Name Type Description querystring 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 optionsobject <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 optionsobject <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 optionsobject <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 optionsobject <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 namestring The username in question
Returns:
A Promise that fulfills with a Boolean (
trueorfalse)- 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 optionsobject Properties
Name Type Argument Default Description titlestring The title of the livethread (100 characters max)
descriptionstring <optional>
A descriptions of the thread. 120 characters max
resourcesstring <optional>
Information and useful links related to the thread. 120 characters max
nsfwboolean <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 optionsobject Properties
Name Type Argument Default Description namestring The name of the new multireddit. 50 characters max
descriptionstring A description for the new multireddit, in markdown.
subredditsArray An Array of Subreddit objects (or subreddit names) that this multireddit should compose of
visibilitystring <optional>
'private' The multireddit's visibility setting. One of
private,public,hidden.icon_namestring <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,Nonekey_colorstring <optional>
'#000000' A six-digit RGB hex color, preceded by '#'
weighting_schemestring <optional>
'classic' One of
classic,freshReturns:
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_idandclient_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_idandclient_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.snoowrapproperty 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 optionsobject Options for the request. For documentation on these options, see the Request API. Supported options include
uri,qs,form,headers,method,auth, andbody. A defaultbaseUrlparameter ofthis.config().endpoint_domainis internally included by default, so it is recommended that auriparameter be used, rather than aurlparameter 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#oauthRequestor another of snoowrap's helper functions.This function can work with alternate
this-bindings, provided that the binding has theclientId,clientSecret, anduserAgentproperties. This allows it be used if no snoowrap requester has been created yet.Parameters:
Name Type Description optionsobject | 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 optionsobject | 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#oauthRequestor 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
makeRequestmethod. 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-promiseinternally. 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 optionsobject Options for the request
Properties
Name Type Argument Default Description jsonboolean If
true, theContent-Type: application/jsonheader is added, and the response body will be parsed as JSON automatically.baseUrlstring The base URL that a request should be sent to
uristring The uri that a request should be sent to, using the provided
baseUrl.methodstring 'GET' Method for the request
headersobject Headers for the request
qsobject <optional>
Querystring parameters for the request
formobject <optional>
Form data for the request. If provided, the
Content-Type: application/x-www-form-urlencodedheader is set, and the provided object is serialized into URL-encoded form data in the request body.formDataobject <optional>
Multipart form data for the request. If provided, the
Content-Type: multipart/form-dataheader is set, and the provided object is serialized as multipart form data.bodyobject <optional>
The body of the request. Should be converted to a string with JSON.stringify(). This is ignored for GET requests, or of
options.formoroptions.formDataare provided.transformfunction <optional>
A function that is called before the response Promise fulfills. Accepts two parameters:
response.bodyandresponse. This function should be called regardless of the status code of the response, and the returned Promise frommakeRequestshould fulfill with its return value.resolveWithFullResponseboolean <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.transformfunction is provided.Returns:
A Promise for a response object. Depending on
options.transformandoptions.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'})) } }