### Fetching with Pagination Example Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/listing-class.md An example demonstrating fetching an initial set of posts and then fetching more, appending them to the existing list. ```javascript // Get 25 hot posts r.getHot({limit: 25}).then(posts => { console.log(`Got ${posts.length} posts`); // Fetch 10 more and append return posts.fetchMore({amount: 10, append: true}); }).then(posts => { console.log(`Now have ${posts.length} posts`); }); ``` -------------------------------- ### Working with Listings in Loops Example Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/listing-class.md An example of asynchronously processing a listing in a loop, fetching more items until the listing is finished. ```javascript async function processAllPosts() { let listing = await r.getHot({limit: 10}); while (!listing.isFinished) { listing.forEach(post => { console.log(post.title); }); listing = await listing.fetchMore({amount: 10}); } } ``` -------------------------------- ### Basic Reply Example Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/comment-class.md A straightforward example of replying to a comment. ```javascript r.getComment('c0b6xx0').reply('Thanks for the comment!'); ``` -------------------------------- ### Listing Options Example Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/listing-class.md Shows how to use listing options such as limit, time, and sort when fetching content. Also includes an example of pagination using fetchMore. ```javascript r.getHot('AskReddit', { limit: 50, time: 'week' }).then(posts => { console.log(posts); }); // Pagination r.getNew({limit: 10}).then(posts => { return posts.fetchMore({amount: 10, append: true}); }); ``` -------------------------------- ### Example Usage Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/private-message-class.md Practical examples of using PrivateMessage methods. ```APIDOC ### Reply to a Message ```javascript async function replyToMessage(messageId, replyText) { const msg = r.getMessage(messageId); const reply = await msg.reply(replyText); console.log('Reply sent!'); return reply; } ``` ``` ```APIDOC ### Mark Message as Read and Delete ```javascript async function processMessage(messageId) { const msg = r.getMessage(messageId); await msg.markAsRead(); await msg.delete(); } ``` ``` ```APIDOC ### Process Inbox ```javascript async function processUnreadMessages() { const unread = await r.getUnreadMessages({limit: 50}); for (const message of unread) { if (message instanceof snoowrap.objects.PrivateMessage) { console.log(`From: ${message.author.name}`); console.log(`Subject: ${message.subject}`); // Mark as read await message.markAsRead(); // Reply to certain messages if (message.subject.includes('help')) { await message.reply('Help text goes here'); } } } } ``` ``` ```APIDOC ### Mute/Unmute Users ```javascript async function muteUser(messageId) { const msg = await r.getMessage(messageId).fetch(); console.log(`Muting ${msg.author.name}`); await msg.mute(); } async function unmuteUser(messageId) { const msg = await r.getMessage(messageId).fetch(); console.log(`Unmuting ${msg.author.name}`); await msg.unmute(); } ``` ``` -------------------------------- ### Clone Snoowrap and Install Dependencies Source: https://github.com/not-an-aardvark/snoowrap/blob/master/src/README.md Clone the Snoowrap repository and install the necessary npm packages to begin development. ```bash git clone https://github.com/not-an-aardvark/snoowrap.git cd snoowrap/ npm install ``` -------------------------------- ### getSettings() Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/subreddit-class.md Gets the current settings for this subreddit. ```APIDOC ## getSettings() ### Description Gets this subreddit's settings. ### Returns Promise - Settings object ``` -------------------------------- ### Install Snoowrap with npm Source: https://github.com/not-an-aardvark/snoowrap/blob/master/README.md Use this command to install the Snoowrap package for Node.js projects. ```bash npm install snoowrap --save ``` -------------------------------- ### Create Snoowrap Instance with Application-Only Auth (Installed Client) Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/snoowrap-class.md Initialize a Snoowrap instance for installed applications using application-only authentication. This method does not require user context and is suitable for bots or scripts. ```javascript // For installed apps (public clients) snoowrap.fromApplicationOnlyAuth({ userAgent: 'MyBot/1.0.0 by MyUsername', clientId: 'your_client_id', deviceId: 'unique_device_identifier_20_to_30_chars', grantType: snoowrap.grantType.INSTALLED_CLIENT }).then(r => { return r.getHot().then(posts => console.log(posts)); }); ``` -------------------------------- ### Submit a Link Post Source: https://github.com/not-an-aardvark/snoowrap/blob/master/README.md Example of submitting a link post to a specified subreddit. ```javascript r.getSubreddit('gifs').submitLink({ title: 'Mt. Cameramanjaro', url: 'https://i.imgur.com/n5iOc72.gifv' }); ``` -------------------------------- ### Expanding Comment Threads Example Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/listing-class.md Shows how to fetch all comments and their replies for a given submission using `fetchAll`. ```javascript // Get all comments and replies r.getSubmission('2np694').comments.fetchAll().then(allComments => { console.log(`Total comments: ${allComments.length}`); }); ``` -------------------------------- ### Saving Comments Example Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/comment-class.md Illustrates saving a comment both with and without a category. ```javascript // Save without category await r.getComment('c0b6xx0').save(); // Save with category (Reddit Gold required) await r.getComment('c0b6xx0').save('interesting-discussions'); ``` -------------------------------- ### Filtering Comments Example Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/listing-class.md Demonstrates fetching comments for a submission and using `fetchMore` with `skipReplies: true` to get top-level comments only. ```javascript // Get top-level comments without replies r.getSubmission('2np694').comments.fetchMore({ amount: 50, skipReplies: true }).then(comments => { console.log(comments); }); ``` -------------------------------- ### Get Specific Wiki Page Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/wiki-page-class.md Fetches a specific wiki page by its name and then retrieves its markdown content. ```javascript const page = r.getSubreddit('snoowrap').getWikiPage('index').fetch(); console.log(page.content_md); ``` -------------------------------- ### Edit and Delete Comment Example Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/comment-class.md Demonstrates the sequence of editing a comment and then deleting it. ```javascript const comment = r.getComment('c0b6xx0'); await comment.edit('Updated: Thanks for the comment!'); // ... later ... await comment.delete(); ``` -------------------------------- ### Get User's Overview (Posts and Comments) Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/reddit-user-class.md Retrieves a listing of all content, including submissions and comments, made by a user with `getOverview`. You can specify listing options like limit and sort. ```javascript r.getUser('spez').getOverview({limit: 50}).then(content => { content.forEach(item => { if (item instanceof snoowrap.objects.Submission) { console.log('Post:', item.title); } else { console.log('Comment:', item.body); } }); }); ``` -------------------------------- ### Manage Users Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/common-patterns.md Provides examples for managing users within a subreddit, including banning, unbanning, muting, and unmuting. ```APIDOC ## Manage Users ### Description Provides methods to manage users within a subreddit, such as banning, unbanning, muting, and unmuting. ### Methods - `getSubreddit(name).banUser(options)` - `getSubreddit(name).unbanUser(options)` - `getSubreddit(name).muteUser(options)` - `getSubreddit(name).unmuteUser(options)` ### Parameters #### Ban User Options - **name** (string) - Required - The username of the user to ban. - **banReason** (string) - Optional - The reason for the ban. - **banMessage** (string) - Optional - The message to send to the user. - **numDays** (number) - Optional - The number of days to ban the user for (0 for permanent). #### Unban User Options - **name** (string) - Required - The username of the user to unban. #### Mute User Options - **name** (string) - Required - The username of the user to mute. #### Unmute User Options - **name** (string) - Required - The username of the user to unmute. ### Request Example ```javascript const sub = r.getSubreddit('snoowrap'); // Ban user await sub.banUser({ name: 'username', banReason: 'Spam', banMessage: 'You have been banned', numDays: 0 // Permanent }); // Unban user await sub.unbanUser({name: 'username'}); // Mute user await sub.muteUser({name: 'username'}); // Unmute user await sub.unmuteUser({name: 'username'}); ``` ``` -------------------------------- ### Get Specific User Information Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/quick-reference.md Fetches the profile details for a given Reddit username. ```javascript r.getUser('spez') ``` -------------------------------- ### Get Authenticated User Preferences Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/quick-reference.md Use `getPreferences()` to fetch the current preferences of the authenticated user. ```javascript r.getPreferences() ``` -------------------------------- ### Getting Objects Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/quick-reference.md Methods for retrieving specific Reddit objects like users, submissions, comments, and subreddits. ```APIDOC ## Getting Objects Retrieve individual Reddit objects. | Method | Returns | Example | |--------|---------|---------| | `getMe()` | RedditUser | `r.getMe()` | | `getUser(name)` | RedditUser | `r.getUser('spez')` | | `getSubmission(id)` | Submission | `r.getSubmission('abc123')` | | `getComment(id)` | Comment | `r.getComment('xyz789')` | | `getSubreddit(name)` | Subreddit | `r.getSubreddit('AskReddit')` | | `getMessage(id)` | PrivateMessage | `r.getMessage('msg123')` | | `getLivethread(id)` | LiveThread | `r.getLivethread('thread_id')` | ``` -------------------------------- ### Get User Flair Templates Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/subreddit-class.md Retrieves available user flair templates for the current subreddit. ```javascript r.getSubreddit('snoowrap').getUserFlairTemplates().then(templates => { console.log(templates); }); ``` -------------------------------- ### Instantiate Listing (Constructor) Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/listing-class.md Demonstrates the constructor for the Listing class. It's typically created via API methods, not directly instantiated. ```javascript new Listing(options, requester) ``` -------------------------------- ### Instantiate WikiPage Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/wiki-page-class.md Demonstrates the constructor for the WikiPage class. It's usually created indirectly via a Subreddit object. ```javascript new WikiPage(data, requester, hasFetched) ``` -------------------------------- ### Get Rate Limit Expiration Timestamp Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/configuration.md Access the `ratelimitExpiration` property to get the UNIX timestamp when the current rate limit window will reset. ```javascript await r.getMe(); const msUntilReset = (r.ratelimitExpiration * 1000) - Date.now(); console.log(`Rate limit resets in ${msUntilReset}ms`); ``` -------------------------------- ### Get User Content Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/common-patterns.md Retrieve submissions, comments, or an overview of a user's activity. Supports sorting by time. ```javascript const user = r.getUser('spez'); // Get submissions const posts = await user.getSubmissions({limit: 50}); // Get comments const comments = await user.getComments({limit: 50}); // Get all content (posts and comments) const allContent = await user.getOverview({limit: 100}); // Get content sorted by time const recent = await user.getComments({ limit: 25, sort: 'new', time: 'month' }); ``` -------------------------------- ### Base Requester GET Request Source: https://github.com/not-an-aardvark/snoowrap/blob/master/src/README.md Sends a GET request to a specified Reddit API endpoint using the base requester instance. This is useful for fetching data from Reddit. ```javascript // `r` is an instance of the snoowrap class // --> send a GET request to reddit.com/r/snoowrap/about/moderators, // return a Promise for the populated response r._get({uri: 'r/snoowrap/about/moderators'}) ``` -------------------------------- ### Initialization Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/quick-reference.md Demonstrates how to initialize the snoowrap client using different authentication methods: refresh token, username/password, and access token. ```APIDOC ## Initialization Initialize snoowrap with your Reddit API credentials. ### Refresh Token ```javascript const snoowrap = require('snoowrap'); const r = new snoowrap({ userAgent: 'MyBot/1.0 by username', clientId: 'client_id', clientSecret: 'secret', refreshToken: 'token' }); ``` ### Username/Password ```javascript const snoowrap = require('snoowrap'); const r = new snoowrap({ userAgent: 'MyBot/1.0 by username', clientId: 'client_id', clientSecret: 'secret', username: 'user', password: 'pass' }); ``` ### Access Token ```javascript const snoowrap = require('snoowrap'); const r = new snoowrap({ userAgent: 'MyBot/1.0', accessToken: 'token' }); ``` ``` -------------------------------- ### Using Native Array Methods with Listings Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/listing-class.md Demonstrates how to use native Array methods like map, filter, forEach, and reduce on a Listing object, as it extends the Array prototype. ```javascript r.getHot({limit: 10}).then(posts => { // Map const titles = posts.map(post => post.title); // Filter const longPosts = posts.filter(post => post.selftext.length > 100); // ForEach posts.forEach(post => console.log(post.title)); // Reduce const totalScore = posts.reduce((sum, post) => sum + post.score, 0); }); ``` -------------------------------- ### Get Private Message by ID Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/snoowrap-class.md Retrieve a `PrivateMessage` object using its Base36 message ID. The returned object is unfetched, and you need to access its properties, such as `subject`, to get the message content. ```javascript const msg = r.getMessage('51shnw'); msg.subject.then(subject => console.log(subject)); ``` -------------------------------- ### Get Related Submissions (Deprecated) Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/submission-class.md Deprecated: Attempts to get submissions related to the current one. The Reddit API no longer properly supports this endpoint. Accepts an optional 'options' object for listing parameters. Returns a Promise. ```javascript r.getSubmission('2np694').getRelated(); ``` -------------------------------- ### Fetch All Items from a Listing Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/quick-reference.md Use `fetchAll(opts)` to retrieve all available items from a listing. This method returns the listing containing all items. ```javascript listing.fetchAll() ``` -------------------------------- ### Get Specific Subreddit Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/quick-reference.md Retrieves a subreddit object by its name. ```javascript r.getSubreddit('AskReddit') ``` -------------------------------- ### config(options) Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/snoowrap-class.md Gets or sets configuration options for the current snoowrap instance. This method allows fine-grained control over API request behavior, including delays, timeouts, retries, and logging. ```APIDOC ## config(options) ### Description Gets or sets configuration options for this snoowrap instance. ### Signature ```javascript config(options = {}) ``` ### Parameters #### Query Parameters - **endpointDomain** (string) - Optional - Domain for API requests. Defaults to 'reddit.com'. - **requestDelay** (number) - Optional - Minimum milliseconds between API calls; >1000 prevents rate limiting. Defaults to 0. - **requestTimeout** (number) - Optional - Timeout in milliseconds for OAuth requests. Defaults to 30000. - **continueAfterRatelimitError** (boolean) - Optional - If true, queues requests when rate limited instead of throwing. Defaults to false. - **retryErrorCodes** (number[]) - Optional - HTTP status codes that trigger automatic retry. Defaults to [502,503,504,522]. - **maxRetryAttempts** (number) - Optional - Maximum number of retry attempts for failed requests. Defaults to 3. - **warnings** (boolean) - Optional - If true, logs deprecation warnings to console. Defaults to true. - **debug** (boolean) - Optional - If true, logs debug information. Defaults to false. - **logger** (object) - Optional - Logger object with warn, info, debug, trace methods. Defaults to console. - **proxies** (boolean) - Optional - If true, enables method chaining via Proxy; must be set before any requests. Defaults to true. ### Returns object - Updated configuration object ### Example ```javascript r.config({ requestDelay: 1000, // 1 second between requests requestTimeout: 60000, // 60 second timeout continueAfterRatelimitError: true, warnings: false }); // Get current config const config = r.config(); console.log(config.requestDelay); // 1000 ``` ``` -------------------------------- ### getUserFlair Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/subreddit-class.md Gets the flair information for a specific user on this subreddit. ```APIDOC ## getUserFlair(name) ### Description Gets the flair for a specific user on this subreddit. ### Parameters #### Query Parameters - **name** (string) - Required - Username ### Response #### Success Response - **object** - Flair information ``` -------------------------------- ### getUserFlairTemplates Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/subreddit-class.md Gets available user flair templates for this subreddit. ```APIDOC ## getUserFlairTemplates() ### Description Gets available user flair templates for this subreddit. ### Response #### Success Response - **object[]** - Array of flair template objects ``` -------------------------------- ### Configuration Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/quick-reference.md Shows how to configure snoowrap's behavior, including network settings, rate limiting, and logging. ```APIDOC ## Configuration Configure snoowrap's global settings. ```javascript r.config({ endpointDomain: 'reddit.com', requestDelay: 0, requestTimeout: 30000, continueAfterRatelimitError: false, retryErrorCodes: [502, 503, 504, 522], maxRetryAttempts: 3, warnings: true, debug: false, logger: console, proxies: true }); ``` ``` -------------------------------- ### Fetch Wiki Page Content Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/wiki-page-class.md Fetches the complete content of a wiki page. Use this to get the latest markdown content before displaying or processing it. ```javascript const page = r.getSubreddit('snoowrap').getWikiPage('index'); await page.fetch(); console.log(page.content_md); ``` -------------------------------- ### Get Live Thread Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/quick-reference.md Retrieves a live thread object by its ID. ```javascript r.getLivethread('thread_id') ``` -------------------------------- ### fetchAll(options) Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/listing-class.md Fetches all remaining items in the listing. It accepts an options object to control fetching behavior. ```APIDOC ## fetchAll(options) ### Description Fetches all remaining items in the listing. It accepts an options object to control fetching behavior. ### Method Signature ```javascript fetchAll({ skipReplies = false, amount = 100 }) ``` ### Parameters #### Options Object - **skipReplies** (boolean) - Optional - Default: `false` - For comment listings, skip fetching replies - **amount** (number) - Optional - Default: `100` - Items per request (higher = fewer requests but more memory) ### Returns Promise ### Example ```javascript r.getHot().then(posts => { return posts.fetchAll(); }).then(allPosts => { console.log(`Fetched ${allPosts.length} hot posts`); }); ``` ``` -------------------------------- ### Useful NPM Commands for Snoowrap Development Source: https://github.com/not-an-aardvark/snoowrap/blob/master/src/README.md A collection of npm commands for linting, testing, compiling, and building documentation for the Snoowrap project. ```bash npm run lint ``` ```bash npm run test:browser ``` ```bash npm run smoketest ``` ```bash npm run compile ``` ```bash npm run build-docs ``` -------------------------------- ### Get Specific Comment Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/quick-reference.md Fetches a comment using its unique ID. ```javascript r.getComment('xyz789') ``` -------------------------------- ### Get Specific Submission Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/quick-reference.md Retrieves a submission using its unique ID. ```javascript r.getSubmission('abc123') ``` -------------------------------- ### Create Snoowrap Instance Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/INDEX.md Instantiate the Snoowrap class with different authentication methods. Ensure you provide the necessary credentials for each method. ```javascript new snoowrap({userAgent, clientId, clientSecret, refreshToken}) ``` ```javascript new snoowrap({userAgent, clientId, clientSecret, username, password}) ``` ```javascript new snoowrap({userAgent, accessToken}) ``` ```javascript snoowrap.fromAuthCode({code, userAgent, clientId, redirectUri}) ``` ```javascript snoowrap.fromApplicationOnlyAuth({userAgent, clientId, deviceId}) ``` -------------------------------- ### Manage Posts Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/common-patterns.md Demonstrates how to manage individual posts, including approving, removing, spamming, sticking, unsticking, locking, and unlocking. ```APIDOC ## Manage Posts ### Description Provides methods to manage individual posts, such as approving, removing, spamming, sticking, unsticking, locking, and unlocking. ### Methods - `getSubmission(id).approve()` - `getSubmission(id).remove(options)` - `getSubmission(id).sticky(options)` - `getSubmission(id).unsticky()` - `getSubmission(id).lock()` - `getSubmission(id).unlock()` ### Parameters #### Remove Options - **spam** (boolean) - Optional - Whether to mark the post as spam. #### Sticky Options - **num** (number) - Required - The stickied position (1 or 2). ### Request Example ```javascript const post = r.getSubmission('2np694'); // Approve post await post.approve(); // Remove post await post.remove({spam: false}); // Spam it await post.remove({spam: true}); // Sticky await post.sticky({num: 1}); // Unsticky await post.unsticky(); // Lock await post.lock(); // Unlock await post.unlock(); ``` ``` -------------------------------- ### Instantiate Comment Object Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/comment-class.md Demonstrates the constructor for the Comment class. Typically, comments are obtained via API calls rather than direct instantiation. ```javascript new Comment(data, requester, hasFetched) ``` -------------------------------- ### Create and Configure a Sticky Thread Source: https://github.com/not-an-aardvark/snoowrap/blob/master/README.md Submits a selfpost, makes it sticky, distinguishes it, approves it, assigns a flair, and adds a reply. ```javascript r.getSubreddit('some_subreddit_name') .submitSelfpost({title: 'Daily thread', text: 'Discuss things here'}) .sticky() .distinguish() .approve() .assignFlair({text: 'Daily Thread flair text', css_class: 'daily-thread'}) .reply('This is a comment that appears on that daily thread'); // etc. etc. ``` -------------------------------- ### Require Snoowrap in Node.js Source: https://github.com/not-an-aardvark/snoowrap/blob/master/README.md Include the Snoowrap library in your Node.js project after installation. ```js var snoowrap = require('snoowrap'); ``` -------------------------------- ### Get Submission Duplicates Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/quick-reference.md Use `getDuplicates` to retrieve a list of duplicate submissions. ```javascript submission.getDuplicates() ``` -------------------------------- ### Access Token Authentication Options Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/types.md Use this structure for authenticating directly with an access token. Only the user agent and access token are needed. ```javascript { userAgent: string, accessToken: string } ``` -------------------------------- ### Get User Flair Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/subreddit-class.md Retrieves the flair information for a specific user on this subreddit. ```javascript r.getSubreddit('snoowrap').getUserFlair('username').then(flair => { console.log(flair); }); ``` -------------------------------- ### Submit Options for Creating Submissions Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/types.md Parameters required for creating new posts. Specify the target subreddit, title, and content (text, URL). ```javascript { subredditName: string, title: string, text?: string, url?: string, sendReplies?: boolean, resubmit?: boolean, captchaIden?: string, captchaResponse?: string } ``` -------------------------------- ### Get Random Submission from Subreddit Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/subreddit-class.md Retrieves a single random submission from the subreddit. ```javascript r.getSubreddit('AskReddit').getRandomSubmission().then(post => { console.log(post.title); }); ``` -------------------------------- ### Username/Password Authentication Options Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/types.md Use this structure for username and password authentication. All fields are required. ```javascript { userAgent: string, clientId: string, clientSecret: string, username: string, password: string } ``` -------------------------------- ### Get New Comments Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/quick-reference.md Fetches a listing of the newest comments from a subreddit, with optional limits. ```javascript r.getNewComments() ``` -------------------------------- ### Configure Custom Logger Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/configuration.md Set a custom logger object for warnings and debug output. The logger must implement warn, info, debug, and trace methods. This example shows integration with Winston and a simple custom logger. ```javascript const winston = require('winston'); r.config({logger: winston}); ``` ```javascript const myLogger = { warn(...args) { console.warn('[warn]', ...args); }, info(...args) { console.info('[info]', ...args); }, debug(...args) { console.debug('[debug]', ...args); }, trace(...args) { console.trace('[trace]', ...args); } }; r.config({logger: myLogger}); ``` -------------------------------- ### Get Best Submissions Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/quick-reference.md Retrieves a listing of the best posts from a subreddit, with optional limits. ```javascript r.getBest({limit: 50}) ``` -------------------------------- ### Get Hot Submissions Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/quick-reference.md Fetches a listing of hot posts from a subreddit, with optional limits. ```javascript r.getHot('AskReddit', {limit: 10}) ``` -------------------------------- ### Initialize Snoowrap with OAuth Credentials Source: https://github.com/not-an-aardvark/snoowrap/blob/master/README.md Use this to create a snoowrap requester with OAuth credentials. It's recommended to use environment variables or a config file instead of hardcoding credentials. ```javascript 'use strict'; const snoowrap = require('snoowrap'); // NOTE: The following examples illustrate how to use snoowrap. However, hardcoding // credentials directly into your source code is generally a bad idea in practice (especially // if you're also making your source code public). Instead, it's better to either (a) use a separate // config file that isn't committed into version control, or (b) use environment variables. // Create a new snoowrap requester with OAuth credentials. // For more information on getting credentials, see here: https://github.com/not-an-aardvark/reddit-oauth-helper const r = new snoowrap({ userAgent: 'put your user-agent string here', clientId: 'put your client id here', clientSecret: 'put your client secret here', refreshToken: 'put your refresh token here' }); // Alternatively, just pass in a username and password for script-type apps. const otherRequester = new snoowrap({ userAgent: 'put your user-agent string here', clientId: 'put your client id here', clientSecret: 'put your client secret here', username: 'put your username here', password: 'put your password here' }); // That's the entire setup process, now you can just make requests. ``` -------------------------------- ### Get Specific Private Message Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/quick-reference.md Fetches a private message using its unique ID. ```javascript r.getMessage('msg123') ``` -------------------------------- ### Manage Flair Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/common-patterns.md Shows how to manage flair for posts and users within a subreddit, including fetching flair templates and assigning flair. ```APIDOC ## Manage Flair ### Description Provides methods for managing flair for posts and users within a subreddit, including fetching flair templates and assigning flair. ### Methods - `getSubreddit(name).getLinkFlairTemplates()` - `getSubmission(id).assignFlair(options)` - `getSubreddit(name).setUserFlair(options)` ### Parameters #### Assign Flair to Post Options - **text** (string) - Required - The flair text to assign. - **cssClass** (string) - Optional - The CSS class for the flair. #### Set User Flair Options - **name** (string) - Required - The username of the user. - **text** (string) - Required - The flair text to assign. - **cssClass** (string) - Optional - The CSS class for the flair. ### Request Example ```javascript const sub = r.getSubreddit('snoowrap'); // Get flair templates const templates = await sub.getLinkFlairTemplates(); // Assign flair to post await r.getSubmission('2np694').assignFlair({ text: 'Breaking News', cssClass: 'breaking' }); // Assign flair to user await sub.setUserFlair({ name: 'username', text: 'Expert', cssClass: 'expert-flair' }); ``` ``` -------------------------------- ### Get User Content Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/common-patterns.md Retrieve submissions, comments, or an overview of a user's activity. ```APIDOC ## Get User Content ### Description Retrieve a user's submissions, comments, or a combined overview of their activity, with options for limiting results and sorting. ### Method `getUser(username).getSubmissions(options)` `getUser(username).getComments(options)` `getUser(username).getOverview(options)` ### Parameters #### Path Parameters - `username` (string) - Required - The username of the user whose content to fetch. #### Query Parameters - `limit` (number) - Optional - The maximum number of items to retrieve. - `sort` (string) - Optional - The sorting order (e.g., 'new'). - `time` (string) - Optional - The time period for sorting (e.g., 'month'). ### Request Example ```javascript const user = r.getUser('spez'); // Get submissions const posts = await user.getSubmissions({limit: 50}); // Get comments const comments = await user.getComments({limit: 50}); // Get all content (posts and comments) const allContent = await user.getOverview({limit: 100}); // Get content sorted by time const recent = await user.getComments({ limit: 25, sort: 'new', time: 'month' }); ``` ``` -------------------------------- ### Paginate Through a Listing Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/INDEX.md Demonstrates how to paginate through a Reddit listing (e.g., hot posts) by repeatedly fetching more items until the listing is finished. This is useful for retrieving large amounts of data. ```javascript let listing = await r.getHot({limit: 10}); while (!listing.isFinished) { listing = await listing.fetchMore({amount: 10}); console.log(`Got ${listing.length} items`); } ``` -------------------------------- ### Get User Profile Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/common-patterns.md Fetch details for a specific user or the currently authenticated user. ```APIDOC ## Get User Profile ### Description Fetch user details by username or get the profile of the currently logged-in user. ### Method `getUser(username).fetch()` `getMe()` ### Parameters #### Path Parameters - `username` (string) - Required - The username of the user to fetch. ### Request Example ```javascript // Fetch user details const user = await r.getUser('spez').fetch(); console.log(`${user.name} - ${user.link_karma} link karma`); // Get your own profile const me = await r.getMe(); console.log(`Logged in as: ${me.name}`); ``` ``` -------------------------------- ### Fetch More Items from a Listing Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/quick-reference.md Use `fetchMore(opts)` to load additional items into a listing. The `opts` object can specify the `amount` of items to fetch. This method returns the updated listing. ```javascript listing.fetchMore({amount: 10}) ``` -------------------------------- ### User Methods Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/quick-reference.md Methods available for User objects. ```APIDOC ## User Methods ### fetch() Fetches the latest data for the user. ### getOverview(opts) Retrieves the user's overview content. ### getSubmissions(opts) Retrieves the user's submissions. ### getComments(opts) Retrieves the user's comments. ### getUpvotedContent(opts) Retrieves the content upvoted by the user. ### getDownvotedContent(opts) Retrieves the content downvoted by the user. ### getSavedContent(opts) Retrieves the content saved by the user. ### getHiddenContent(opts) Retrieves the content hidden by the user. ### getTrophies() Retrieves the user's trophies. ### giveGold(months) Gives the user gold for the specified number of months. ### friend(opts) Friends the user with an optional note. ### unfriend() Unfriends the user. ``` -------------------------------- ### Get Authenticated User Friends Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/quick-reference.md Use `getFriends()` to list all users that the authenticated user has friended. ```javascript r.getFriends() ``` -------------------------------- ### Listing Options for API Queries Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/types.md These query parameters can be used with methods that return listings, such as getHot(), getNew(), etc. Note the limit is capped at 100 items per page. ```javascript { limit?: number, // Items per page (max 100) after?: string, // Pagination cursor (base36 ID) before?: string, // Pagination cursor (base36 ID) count?: number, // Offset count show?: string, // 'all' to include removed/deleted time?: string, // 'all', 'year', 'month', 'week', 'day', 'hour' sort?: string // 'hot', 'new', 'top', 'controversial' } ``` -------------------------------- ### Get Authenticated User Trophies Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/quick-reference.md Use `getMyTrophies()` to retrieve all trophies associated with the authenticated user. ```javascript r.getMyTrophies() ``` -------------------------------- ### getMe() Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/snoowrap-class.md Fetches the profile information of the currently authenticated user. This is useful for verifying authentication and retrieving user-specific details. ```APIDOC ## getMe() ### Description Gets the authenticated user's profile. ### Returns Promise ### Example ```javascript r.getMe().then(user => { console.log(user.name); // e.g., 'my_username' console.log(user.link_karma); // e.g., 1000 console.log(user.comment_karma); // e.g., 5000 }); ``` ``` -------------------------------- ### Listing Methods Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/quick-reference.md Methods available for Listing objects. ```APIDOC ## Listing Methods ### fetchMore(opts) Fetches more items for the listing. ### fetchAll(opts) Fetches all remaining items for the listing. ### .isFinished A boolean indicating if the listing has finished fetching all items. ``` -------------------------------- ### Get Authenticated User Karma Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/quick-reference.md Use `getKarma()` to retrieve the karma details for the authenticated user. ```javascript r.getKarma() ``` -------------------------------- ### Get Banned Users from Subreddit Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/quick-reference.md Use `getBannedUsers` to retrieve a list of users banned from a subreddit. ```javascript sub.getBannedUsers() ``` -------------------------------- ### getWikiPages() Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/subreddit-class.md Fetches a list of all available wiki pages for this subreddit. ```APIDOC ## getWikiPages() ### Description Gets a list of wiki pages for this subreddit. ### Returns Promise - Array of page names ``` -------------------------------- ### Get Subreddit New Listings Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/quick-reference.md Use `getNew` to retrieve a list of the newest posts in a subreddit. ```javascript sub.getNew() ``` -------------------------------- ### Creating Content Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/quick-reference.md Methods for creating new posts, including selfposts, link posts, and crossposts, either globally or within a specific subreddit. ```APIDOC ## submitSelfpost(opts) ### Description Submits a new selfpost to a specified subreddit. ### Method `submitSelfpost(opts)` ### Parameters #### Request Body - **opts** (object) - Required - Options for the selfpost. - **subredditName** (string) - Required - The name of the subreddit to post to. - **title** (string) - Required - The title of the selfpost. - **text** (string) - Required - The body text of the selfpost. ### Returns Submission ``` ```APIDOC ## submitLink(opts) ### Description Submits a new link post to a specified subreddit. ### Method `submitLink(opts)` ### Parameters #### Request Body - **opts** (object) - Required - Options for the link post. - **subredditName** (string) - Required - The name of the subreddit to post to. - **title** (string) - Required - The title of the link post. - **url** (string) - Required - The URL for the link post. ### Returns Submission ``` ```APIDOC ## submitCrosspost(opts) ### Description Submits a new crosspost to a specified subreddit. ### Method `submitCrosspost(opts)` ### Parameters #### Request Body - **opts** (object) - Required - Options for the crosspost. - **subredditName** (string) - Required - The name of the subreddit to post to. - **title** (string) - Required - The title of the crosspost. - **originalPost** (string) - Required - The ID of the original post to crosspost. ### Returns Submission ``` ```APIDOC ## sub.submitSelfpost(opts) ### Description Submits a new selfpost to the subreddit represented by the `sub` object. ### Method `sub.submitSelfpost(opts)` ### Parameters #### Request Body - **opts** (object) - Required - Options for the selfpost. - **title** (string) - Required - The title of the selfpost. - **text** (string) - Required - The body text of the selfpost. ### Returns Submission ``` ```APIDOC ## sub.submitLink(opts) ### Description Submits a new link post to the subreddit represented by the `sub` object. ### Method `sub.submitLink(opts)` ### Parameters #### Request Body - **opts** (object) - Required - Options for the link post. - **title** (string) - Required - The title of the link post. - **url** (string) - Required - The URL for the link post. ### Returns Submission ``` -------------------------------- ### Basic Try/Catch for User Fetch Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/errors.md Use a basic try/catch block to handle potential errors when fetching user data. ```javascript const snoowrap = require('snoowrap'); try { const user = await r.getUser('valid_username').fetch(); console.log(user.name); } catch (error) { console.error('Error fetching user:', error.message); } ``` -------------------------------- ### Get Current User Information Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/quick-reference.md Retrieves the currently authenticated user's profile information. ```javascript r.getMe() ``` -------------------------------- ### Instantiate Subreddit Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/subreddit-class.md Subreddits are typically created via the r.getSubreddit(name) method, not directly instantiated. ```javascript new Subreddit(data, requester, hasFetched) ``` -------------------------------- ### Get Submission Body with Snoowrap Source: https://github.com/not-an-aardvark/snoowrap/blob/master/README.md Retrieve the body of a Reddit submission. This method returns a Promise. ```javascript r.getSubmission('2np694').body ``` -------------------------------- ### Create a Selfpost Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/INDEX.md Submits a new selfpost to a specified subreddit with a given title and content. Ensure the subreddit exists and you have posting permissions. ```javascript await r.getSubreddit('test').submitSelfpost({ title: 'My Title', text: 'Post content' }); ``` -------------------------------- ### Create Snoowrap Instance with Application-Only Auth (Web App) Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/snoowrap-class.md Initialize a Snoowrap instance for web applications using application-only authentication with client credentials. This method is for confidential clients and requires a client secret. ```javascript // For web apps (confidential clients) snoowrap.fromApplicationOnlyAuth({ userAgent: 'MyBot/1.0.0 by MyUsername', clientId: 'your_client_id', clientSecret: 'your_client_secret', grantType: snoowrap.grantType.CLIENT_CREDENTIALS }).then(r => { return r.getHot().then(posts => console.log(posts)); }); ``` -------------------------------- ### Get Authenticated User Messages Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/quick-reference.md Use `getMessages()` to retrieve all messages from the authenticated user's inbox. ```javascript r.getMessages() ``` -------------------------------- ### sticky(options) Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/submission-class.md Makes the current submission sticky. Optionally, you can specify a sticky slot. Returns a Promise. ```APIDOC ## sticky(options) ### Description Stickies this submission. ### Parameters #### Path Parameters - **num** (number) - Optional - Sticky slot (1 or 2) ### Returns Promise ### Example ```javascript r.getSubmission('2np694').sticky({num: 2}); ``` ``` -------------------------------- ### Review Modqueue Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/common-patterns.md This snippet demonstrates how to fetch items from a subreddit's moderation queue and perform actions like approving, removing, or marking items as spam. ```APIDOC ## Review Modqueue ### Description Fetches items from the moderation queue of a subreddit and allows for actions on each item. ### Method `getSubreddit(name).getModqueue(options)` ### Parameters #### Query Parameters - **limit** (number) - Optional - The maximum number of items to retrieve. ### Request Example ```javascript const sub = r.getSubreddit('snoowrap'); const queue = await sub.getModqueue({limit: 50}); queue.forEach(async item => { console.log(`${item.author}: ${item.body || item.title}`); // Approve // await item.approve(); // Or remove // await item.remove(); // Or spam // await item.spam(); }); ``` ``` -------------------------------- ### Get Subreddit Moderators Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/subreddit-class.md Fetches a list of moderators for a given subreddit. Useful for checking who moderates a community. ```javascript r.getSubreddit('AskReddit').getModerators().then(mods => { mods.forEach(mod => console.log(mod.name)); }); ``` -------------------------------- ### Listing Options Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/types.md Specifies query parameters for methods that return listings, including options for limiting items, pagination, and sorting. ```APIDOC ## Listing Options Query parameters for methods that return listings. ```javascript { limit?: number, // Items per page (max 100) after?: string, // Pagination cursor (base36 ID) before?: string, // Pagination cursor (base36 ID) count?: number, // Offset count show?: string, // 'all' to include removed/deleted time?: string, // 'all', 'year', 'month', 'week', 'day', 'hour' sort?: string // 'hot', 'new', 'top', 'controversial' } ``` ``` -------------------------------- ### Fetch Submission Details Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/quick-reference.md Use `fetch` to retrieve the full details of a submission. ```javascript submission.fetch() ``` -------------------------------- ### Instantiate RedditUser Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/reddit-user-class.md Demonstrates the constructor for the RedditUser class. This is typically not called directly but rather through Snoowrap's requester methods like `r.getUser(name)` or `r.getMe()`. ```javascript new RedditUser(data, requester, hasFetched) ``` -------------------------------- ### Comment Object Transformation Example Source: https://github.com/not-an-aardvark/snoowrap/blob/master/src/README.md Shows how the JSON response is transformed into a Snoowrap Comment object with Snoowrap-specific properties. ```javascript Comment { author: RedditUser {name: 'not_an_aardvark'}, approved_by: RedditUser {name: 'not_an_aardvark'}, subreddit: Subreddit {display_name: 'AskReddit'} } ``` -------------------------------- ### Get Authenticated User Saved Categories Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/quick-reference.md Use `getSavedCategories()` to retrieve the categories used for saving posts and comments. ```javascript r.getSavedCategories() ``` -------------------------------- ### fetchMore(options) Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/listing-class.md Fetches additional items from the listing. It can be called with an options object or a number representing the amount to fetch. ```APIDOC ## fetchMore(options) ### Description Fetches additional items from the listing. It can be called with an options object or a number representing the amount to fetch. ### Method Signature ```javascript fetchMore({ amount, skipReplies = false, append = true }) ``` Or pass a number directly: `fetchMore(10)` ### Parameters #### Options Object - **amount** (number) - Required - Number of items to fetch - **skipReplies** (boolean) - Optional - Default: `false` - For comment listings, skip fetching comment replies (fetches 100 per call instead of 20) - **append** (boolean) - Optional - Default: `true` - If true, append to existing items; if false, return only new items ### Returns Promise ### Example ```javascript r.getHot({limit: 25}).then(myListing => { console.log(myListing.length); // 25 return myListing.fetchMore({amount: 10}); }).then(extendedListing => { console.log(extendedListing.length); // 35 }); // Shorthand r.getHot({limit: 10}).then(posts => posts.fetchMore(5)); ``` ``` -------------------------------- ### Fetching Messages Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/private-message-class.md Demonstrates how to fetch individual messages and collections of messages from the inbox. ```APIDOC ### Get a Single Message ```javascript const msg = r.getMessage('51shnw'); await msg.fetch(); console.log(msg.subject); console.log(msg.body); ``` ``` ```APIDOC ### Get All Messages ```javascript // Get inbox (includes messages and notifications) r.getInbox().then(messages => { messages.forEach(msg => { console.log(`From: ${msg.author.name}`); console.log(`Subject: ${msg.subject}`); }); }); // Get only private messages r.getMessages().then(messages => { messages.forEach(msg => { console.log(`Message: ${msg.body}`); }); }); // Get unread messages r.getUnreadMessages().then(unread => { console.log(`${unread.length} unread messages`); }); ``` ``` -------------------------------- ### Get Authenticated User Blocked Users Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/quick-reference.md Use `getBlockedUsers()` to retrieve a list of users that the authenticated user has blocked. ```javascript r.getBlockedUsers() ``` -------------------------------- ### Get User Trophies Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/quick-reference.md Use `getTrophies()` to fetch a list of trophies awarded to a user. This method returns a Promise. ```javascript user.getTrophies() ``` -------------------------------- ### Instantiate snoowrap with Username and Password Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/snoowrap-class.md This method is suitable for script-type applications. It requires a user agent, client ID, client secret, username, and password for authentication. ```javascript const snoowrap = require('snoowrap'); // Using username/password (for script-type apps) const r = new snoowrap({ userAgent: 'MyBot/1.0.0 by MyUsername', clientId: 'your_client_id', clientSecret: 'your_client_secret', username: 'your_username', password: 'your_password' }); ``` -------------------------------- ### getRising(options) Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/api-reference/subreddit-class.md Retrieves the rising posts from a subreddit. Accepts an options object for customization. ```APIDOC ## getRising(options) ### Description Gets rising posts from this subreddit. ### Parameters #### Query Parameters - **options** (object) - Optional - Listing options ### Returns Promise> ``` -------------------------------- ### Get Top Submissions Source: https://github.com/not-an-aardvark/snoowrap/blob/master/_autodocs/quick-reference.md Fetches a listing of top posts from a subreddit, allowing filtering by time (e.g., 'month'). ```javascript r.getTop('funny', {time: 'month'}) ```