0
Submit a Post
One script reply has been approved by the moderators Verified

Create a post to a subreddit. See the docs here

Created by hugo697 272 days ago Viewed 7263 times
0
Submitted by hugo697 Bun
Verified 272 days ago
1
import axios from 'axios'
2
import qs from 'qs'
3

4
type Reddit = {
5
	clientId: string
6
	clientSecret: string
7
	username: string
8
	password: string
9
	userAgent?: string
10
}
11

12
export async function main(
13
	resource: Reddit,
14
	subreddit: string,
15
	title: string,
16
	text: string,
17
	kind: string
18
) {
19
	const endpoint = `/api/submit`
20
	const data = {
21
		sr: subreddit,
22
		title,
23
		text,
24
		kind,
25
		api_type: 'json'
26
	}
27

28
	return await makeRequest(resource, endpoint, {
29
		data: qs.stringify(data),
30
		method: 'POST'
31
	})
32
}
33

34
async function makeRequest(resource: Reddit, endpoint: string, options = {}) {
35
	try {
36
		const access_token = await getAccessToken(resource)
37
		const headers = {
38
			Authorization: `Bearer ${access_token}`,
39
			'User-Agent': resource.userAgent
40
		}
41
		const baseUrl = 'https://oauth.reddit.com'
42
		const url = `${baseUrl}${endpoint}`
43
		const response = await axios(url, {
44
			headers,
45
			...options
46
		})
47
		return response.data
48
	} catch (error: Error | any) {
49
		console.error(error.message)
50
	}
51
}
52

53
async function getAccessToken(resource: Reddit) {
54
	try {
55
		const auth = {
56
			username: resource.clientId,
57
			password: resource.clientSecret
58
		}
59
		const response = await axios.post('https://www.reddit.com/api/v1/access_token', null, {
60
			params: { grant_type: 'password', username: resource.username, password: resource.password },
61
			auth
62
		})
63
		return response?.data?.access_token
64
	} catch (error) {
65
		throw new Error('Error getting access token')
66
	}
67
}
68