Search Post
One script reply has been approved by the moderators Verified

Search posts by title. See the docs here

Created by hugo697 634 days ago Picked 11 times
Submitted by hugo697 Bun
Verified 226 days ago
1
import axios from 'axios'
2

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

11
export async function main(
12
	resource: Reddit,
13
	subreddit: string,
14
	searchQuery: string,
15
	limit: number
16
) {
17
	const endpoint = `/r/${subreddit}/search`
18
	const params = {
19
		q: searchQuery,
20
		limit: limit
21
	}
22
	return await makeRequest(resource, endpoint, { params })
23
}
24

25
async function makeRequest(resource: Reddit, endpoint: string, options = {}) {
26
	try {
27
		const access_token = await getAccessToken(resource)
28
		const headers = {
29
			Authorization: `Bearer ${access_token}`,
30
			'User-Agent': resource.userAgent
31
		}
32
		const baseUrl = 'https://oauth.reddit.com'
33
		const url = `${baseUrl}${endpoint}`
34
		const response = await axios(url, {
35
			headers,
36
			...options
37
		})
38
		return response.data
39
	} catch (error: Error | any) {
40
		console.error(error.message)
41
	}
42
}
43

44
async function getAccessToken(resource: Reddit) {
45
	try {
46
		const auth = {
47
			username: resource.clientId,
48
			password: resource.clientSecret
49
		}
50
		const response = await axios.post('https://www.reddit.com/api/v1/access_token', null, {
51
			params: { grant_type: 'password', username: resource.username, password: resource.password },
52
			auth
53
		})
54
		return response?.data?.access_token
55
	} catch (error) {
56
		throw new Error('Error getting access token')
57
	}
58
}
59