tsumiki-reddit.js v2.7.0
tsumiki-reddit.js
A simple wrapper NPM package for fetching information from reddit posts. Excellent for Discord Bots! \
Mainly recoded for Tsumiki, a Discord Bot written in Javascript. \
Perfect for Pagination, since you can adjust how many results you get back with amount
property! \
It also supports discord friendly images for discord embeds that will guarantee a fetchable image URL.
[NEW] Retry on failed attempts!
With the newest release, it will automatically retry any attempts that failed to produce a outcome. \
This is all made possible with the async-retry
NPM module. \
This feature is most useful if you want to fetch a request that you're unsure exists or is available.
Table of contents
Dependencies
Options
FIELD | TYPE | DESCRIPTION | DEFAULT |
---|---|---|---|
subreddit | string | The reddit community name or reddit link (e.g https://reddit.com/r/discordjs) | |
type | string? | A valid reddit type option (hot, top, new, rising) | 'top' |
sort | string? | A valid reddit sorting option | 'all' |
allowNSFW | boolean? | Whether or not the returned post can be marked as NSFW | False |
allowModPost | boolean? | Whether or not the returned post can be distinguished as a mod post | False |
allowCrossPost | boolean? | Whether or not the returned post can be a crosspost | False |
onlyImage | boolean? | Whether or not the returned post is an image. | False |
allowAllDomains | boolean? | Whether or not the returned post can be from another domain than "i.redd.it" | False |
amount | number? | The amount of objects to fetch (max: 100) | 1 |
retryResult | bolean? | Whether or not to retry the result | True |
retries | number? | The amount of times to retry a request | 5 |
Read more about the Reddit API documentation here: \ Reddit API Documentation
All the returned object responses
All responses are returned in lowercase. \ Showcase:
const redditFetch = require('tsumiki-reddit.js');
redditFetch({
subreddit: 'ThisSubredditDontExist',
type: `top`,
sort: 'all',
allowNSFW: false,
allowModPost: true,
allowCrossPost: true,
onlyImage: true,
allowAllDomains: false,
amount: 1,
}).then(post => {
if(post == "invalid") {
console.log(`The subreddit you tried to retrive from does not exist!`)
}
})
The returned object
If the subreddit was found and fufilled all the passed requirements. \
The returned object will be available in a .then()
(i.e .then(post => {post.id})
) call.
Pastebin Example 1: pastebin - This is a example output for all possible posts, if onlyImage
is set to true
. \
This does not include the property post_hint
property, which means its automaticly sorted out if onlyImage
is set to false
\
I personally just want images, so I usually have it set to false
, since I want to be certain I get images that supports Discord embeds.
Pastebin Example 2: pastebin - This is a example output if onlyImage
is set to true
. \
This is the prefered way, since it only fetches posts with images that is part of i.redd.it
domain and is fetchable for Discord Embeds.
null
If the subreddit don't exist or for whatever reason it could not retrieve anything.
private
If the subreddit you tried to access returns a "private" code, this will fire.
Invalid
If the subreddit was misspelled or the actual subreddit don't exists.
0 (the number 0)
If the subreddit don't contain any posts that fufilled the passed requirements. \
Usually only if you pass in several requirements like (onlyImages: true
and allowAllDomains: true
in the same request)
All output types & domain types.
If you want all output types (videos, GIFs, external URLs etc) and allow it from all types of domains. \
Then set onlyImage
to false
and allowAllDomains
to true
.
Usage and Example
const redditFetch = require('tsumiki-reddit.js');
redditFetch({
subreddit: 'Pokemon',
type: `top`,
sort: 'all',
allowNSFW: false,
allowModPost: true,
allowCrossPost: true,
onlyImage: true,
allowAllDomains: false,
amount: 1,
}).then(post => {
// Do something with post (i.e post.id - gets the reddit post ID)
});
Returns a promise that resolves to a JSON object (Promise<object>
).
All output types & domain types example
const redditFetch = require('tsumiki-reddit.js');
redditFetch({
subreddit: 'Pokemon',
type: `top`,
sort: 'all',
allowNSFW: false,
allowModPost: true,
allowCrossPost: true,
onlyImage: false,
allowAllDomains: true,
amount: 1,
retryResult: true,
retries: 7,
}).then(post => {
// Returns null if the body is missing (Server unreachable)
if(post == null) {
return message.channel.send(`Seems like the Reddit server is unreachable right now.\nTry again later!`)
// replace <message> with what you called the message property
}
// Returns "private" (in lowercase) if the subreddit mentioned is "private".
if(post == "private") {
return message.channel.send(`The subreddit mentioned is a private subreddit!\nPlease use a public subreddit that I can access!`)
// replace <message> with what you called the message property
}
// Returns "invalid" (in lowercase) if the subreddit mentioned is not a name of any existing subreddit (even if its private).
if(post == "invalid") {
return message.channel.send(`Check your subreddit name input again. Because no subreddits exists with your input!`)
// replace <message> with what you called the message property
}
// Returns 0 if there were no posts found in the subreddit (but it exists and isn't private)
if(post == 0) {
return message.channel.send(`There were no posts to be found in that subreddit!\nTry another one!`)
// replace <message> with what you called the message property
}
/* Console logs the object */
console.log(post);
});
Returns a promise that resolves to a JSON object (Promise<object>
).
Example on Pagination / Return more then 1 object
const redditFetch = require('tsumiki-reddit.js');
redditFetch({
subreddit: 'Ecchi',
type: `top`,
sort: 'all',
allowNSFW: true, // If you're a degenerate uwu
allowModPost: true,
allowCrossPost: true,
onlyImage: true,
allowAllDomains: false,
amount: 10,
retryResult: true,
retries: 2,
}).then(post => {
// Access each post's individual post objects.
console.log(post[0].data); // Index always starts at 0
console.log(post[1].data);
console.log(post[2].data);
// . . . etc
});
.catch() // ... I reccomend to catch it, in case of any errors along the road.
Returns a promise that resolves to a JSON object (Promise<object>
).
Return a image/GIF that is supported by Discord embeds
Be sure to set onlyImage
to true
and allowAllDomains
to false
for a 100% chance of recieving a discord supported image/GIF format. \
If you don't do this, you will ocassionally get GIFs from Imgur that is of GIFV format, or get External URLs to images that isn't fetchable.
Example for a Discord bot
/* This example follows Discord.js v12 and may differ in v13 and above or below.
The code may or may not work in versions above or below Discord.js v12. */
// Require reddit module
const redditFetch = require('tsumiki-reddit.js');
redditFetch({
subreddit: 'Anime',
type: `new`,
sort: 'all',
allowNSFW: false,
allowModPost: true,
allowCrossPost: true,
onlyImage: true,
allowAllDomains: false,
amount: 1,
retryResult: true, // Turn this to false if you don't expect a failed request call
retries: 4,
})
.catch((err) => {
// Catch any errors that might have lurked its way around the system
console.log(err)
})
.then(post => {
/* post will be null if an option is invalid. */
/* This can be because you entered a subreddit that wasn't correct/closed. */
/* Or you messed up something in the options, check NPM page or Github for help. */
/* This is where you can catch before the promise, if the subreddit entred is incorrect or closed */
if(post == null) {
return message.channel.send(`Check your options!\nAnd check if you spelled the subreddit correctly.`) // replace <message> with what you called the message property
}
// Returns null if the body is missing (Server unreachable)
if(post == null) {
return message.channel.send(`Seems like the Reddit server is unreachable right now.\nTry again later!`)
// replace <message> with what you called the message property
}
// Returns "private" (in lowercase) if the subreddit mentioned is "private".
if(post == "private") {
return message.channel.send(`The subreddit mentioned is a private subreddit!\nPlease use a public subreddit that I can access!`)
// replace <message> with what you called the message property
}
// Returns "invalid" (in lowercase) if the subreddit mentioned is not a name of any existing subreddit (even if its private).
if(post == "invalid") {
return message.channel.send(`Check your subreddit name input again. Because no subreddits exists with your input!`)
// replace <message> with what you called the message property
}
// Returns 0 if there were no posts found in the subreddit (but it exists and isn't private)
if(post == 0) {
return message.channel.send(`There were no posts to be found in that subreddit!\nTry another one!`)
// replace <message> with what you called the message property
}
/* Defines a embed to send in chat */
let embed = new Discord.MessageEmbed() /* for discord.js V.11 or below, use let embed = new Discord.RichEmbed() */
.setTitle(post.title)
.setURL(`https://www.reddit.com${post.permalink}`)
.setColor("RANDOM")
.setDesciption(`Here is a random picture from **${post.subreddit_name_prefixed}**`)
.setImage(`${post.url}`)
/* Send the embed in chat */
return message.channel.send(embed) // replace <message> with what you called the message property
/* Console log the JSON object */
console.log(post)
});
.catch() // Do something with the catch (e.g console.log() the error)
Returns a promise that resolves to a JSON object (Promise<object>
).
Convert reddit date to a normal date format
<post>.created_utc
is displayed in Epoch time. You want to use <post>.created_utc
over <post>.created
. \
While you can still use <post>.created
, it is preferred to use the one converted to UTC to get the correct time. \
I highly reccomend using moment NPM package to convert it. \
Replace <post>
with whatever you named the output on .then()
function.
Example converting Epoch time with moment for a Discord Bot
const moment = require("moment");
const redditFetch = require('tsumiki-reddit.js');
redditFetch({
/* Insert your options here, you can find all options on the NPM or Github repo */
subreddit: 'Pokemon',
type: `top`,
sort: 'all',
allowNSFW: false,
allowModPost: true,
allowCrossPost: true,
onlyImage: true,
allowAllDomains: false,
amount: 1,
}).then(post => {
// Returns null if the body is missing (Server unreachable)
if(post == null) {
return message.channel.send(`Seems like the Reddit server is unreachable right now.\nTry again later!`)
// replace <message> with what you called the message property
}
// Returns "private" (in lowercase) if the subreddit mentioned is "private".
if(post == "private") {
return message.channel.send(`The subreddit mentioned is a private subreddit!\nPlease use a public subreddit that I can access!`)
// replace <message> with what you called the message property
}
// Returns "invalid" (in lowercase) if the subreddit mentioned is not a name of any existing subreddit (even if its private).
if(post == "invalid") {
return message.channel.send(`Check your subreddit name input again. Because no subreddits exists with your input!`)
// replace <message> with what you called the message property
}
// Returns 0 if there were no posts found in the subreddit (but it exists and isn't private)
if(post == 0) {
return message.channel.send(`There were no posts to be found in that subreddit!\nTry another one!`)
// replace <message> with what you called the message property
}
// Define the Date variable to use later on
var Date = moment.unix(post.created_utc).format('DD.MM.YYYY')
/* Defines a embed to send in chat */
let embed = new Discord.MessageEmbed() // for discord.js V.11 or below, use let embed = new Discord.RichEmbed()
.setTitle(post.title)
.setURL(`https://www.reddit.com${post.permalink}`)
.setColor("RANDOM")
.setDesciption(`Here is a random picture from **${post.subreddit_name_prefixed}**
This was created on: ${Date}`)
.setImage(`${post.url}`)
/* Send the embed in chat */
return message.channel.send(embed) // replace <message> with what you called the message property
});
.catch() // Do something with the catch (e.g console.log() the error)
Returns a promise that resolves to a JSON object (Promise<object>
).
Hint and Tips
- If you just want supported images for a Discord Embed, set
onlyImage
totrue
. Its set to false by default. - If you want Pagination for Discord bots, make sure to use
post[x].data
to access the data property of each object. (x = index number) - Want to display all top posts in a subreddit? set
type
totop
andsort
toall
. subreddit
accepts both the subreddit name or the subreddit url \ Examples: https://reddit.com/r/discordjs or r/discordjs or even reddit.com/discord.js (which is just a simplified version) \ It has an advanced filter to find the community name in most scenarios.post
has 4 different properties:null
(subreddit unavailable),invalid
(Subreddit does not exist),private
(Subreddit is private),0
(No posts were found in the subreddit)