1 | import qs from 'qs' |
2 | import axios from 'axios' |
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(resource: Reddit, parentId: string, comment: string) { |
13 | const endpoint = `/api/comment` |
14 | const data = { |
15 | api_type: 'json', |
16 | text: comment, |
17 | thing_id: parentId |
18 | } |
19 |
|
20 | return await makeRequest(resource, endpoint, { |
21 | data: qs.stringify(data), |
22 | method: 'POST' |
23 | }) |
24 | } |
25 |
|
26 | async function makeRequest(resource: Reddit, endpoint: string, options = {}) { |
27 | try { |
28 | const access_token = await getAccessToken(resource) |
29 | const headers = { |
30 | Authorization: `Bearer ${access_token}`, |
31 | 'User-Agent': resource.userAgent |
32 | } |
33 | const baseUrl = 'https://oauth.reddit.com' |
34 | const url = `${baseUrl}${endpoint}` |
35 | const response = await axios(url, { |
36 | headers, |
37 | ...options |
38 | }) |
39 | return response.data |
40 | } catch (error: Error | any) { |
41 | console.error(error.message) |
42 | } |
43 | } |
44 |
|
45 | async function getAccessToken(resource: Reddit) { |
46 | try { |
47 | const auth = { |
48 | username: resource.clientId, |
49 | password: resource.clientSecret |
50 | } |
51 | const response = await axios.post('https://www.reddit.com/api/v1/access_token', null, { |
52 | params: { grant_type: 'password', username: resource.username, password: resource.password }, |
53 | auth |
54 | }) |
55 | return response?.data?.access_token |
56 | } catch (error) { |
57 | throw new Error('Error getting access token') |
58 | } |
59 | } |
60 |
|