34
loading...
This website collects cookies to deliver better user experience
This post is for day 2 of my #100DaysOfCode. In this post I'll be discussing how to programmatically post to Reddit using NodeJS and Typescript.
package.json
file and run yarn install
to install the dependencies.{
"name": "reddit-post",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"dev": "ts-node index.ts"
},
"devDependencies": {
"ts-node": "^10.1.0",
"typescript": "^4.3.5"
},
"dependencies": {
"dotenv": "^10.0.0",
"snoowrap": "^1.23.0"
}
}
.gitignore
file and add .env
to it..env
file should look like this:username = '<REDDIT USERNAME>'
password = '<REDDIT PASSWORD>'
clientId = 'CLIENT_ID'
clientSecret = 'CLIENT SECRET'
<>
text with the tokens Twitter provided you.const snoowrap = require('snoowrap')
require('dotenv').config()
const config = {
username: process.env.username,
password: process.env.password,
clientId: process.env.clientId,
clientSecret: process.env.clientSecret,
}
/api/submit
with the title, link, and subreddit parameters.
function postLink(title: string, link: string, subreddit: string) {
const r = new snoowrap({
userAgent: 'Whatever',
clientId: config.clientId,
clientSecret: config.clientSecret,
username: config.username,
password: config.password,
})
r.getSubreddit(subreddit).submitLink({
title: title,
url: link,
sendReplies: true,
})
}
const r = new snoowrap({
userAgent: 'Whatever',
clientId: config.clientId,
clientSecret: config.clientSecret,
username: config.username,
password: config.password,
})
snoowrap
instance that connects to the Reddit service.r.getSubreddit(subreddit).submitLink({
title: title,
url: link,
sendReplies: true,
})
submitLink
: Creates a new link submission on this subreddit with the title provided, url of the link, and any other options that the snoowrap api allows, such as the sendReplies
option that allows replies to the post to send replies to the authenticated user's inbox.postLink(
'Post to Reddit with NodeJS and Typescript',
'https://codybontecou.com/post-to-reddit-with-nodejs-and-typescript.html',
'webdev'
)
index.ts
.yarn dev
into your projects terminal. If all is good, you should be able to see your post is now on Reddit!const url =
'https://codybontecou.com/post-to-reddit-with-nodejs-and-typescript.html'
const title = 'Post to Reddit using its API'
const subreddits = ['webdev', 'learnjavascript', 'typescript', 'programming']
subreddits.forEach(subreddit => postLink(title, url, subreddit))
34