-
Notifications
You must be signed in to change notification settings - Fork 0
/
reddit.js
87 lines (77 loc) · 1.99 KB
/
reddit.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
"use strict";
const snoowrap = require("snoowrap");
const dotenv = require("dotenv");
dotenv.config();
const r = new snoowrap({
userAgent: "Reddit Bot by u/" + process.env.REDDIT_USERNAME,
clientId: process.env.REDDIT_PERSONAL_USE_SCRIPT,
clientSecret: process.env.REDDIT_SECRET,
refreshToken: process.env.REDDIT_REFRESH_TOKEN,
accessToken: process.env.REDDIT_ACCESS_TOKEN,
});
let getTopPost = async (subreddit) => {
let postsFunc = (posts) => {
let rndPost = Math.floor(Math.random() * posts.length);
let post = posts[rndPost];
let obj = {};
if (post.over_18) {
obj.over_18 = true;
}
if (post.thumbnail) {
obj.thumbnail = post.thumbnail;
}
// if post is image
if (
post.url.endsWith(".png") ||
post.url.endsWith(".jpg") ||
post.url.endsWith(".jpeg") ||
post.url.includes("imgur")
) {
obj.image = post.url;
}
// if post is reddit video
else if (post.is_video) {
if (post.url.includes("v.redd.it")) {
obj.redditVideo =
"https://reddit.com" +
post.permalink +
"?utm_source=share&utm_medium=web2x&context=3";
}
}
// if post is video
else if (
post.url.endsWith(".mp4") ||
post.url.endsWith(".gifv") ||
post.url.endsWith(".gif") ||
post.url.includes("gfycat") ||
post.url.includes("youtu.be")
) {
obj.video = post.url;
}
obj.text = post.selftext + "\n" + post.url;
obj.title = post.title;
obj.sub = post.subreddit_name_prefixed;
obj.link = "https://reddit.com" + post.permalink;
return obj;
};
try {
let x = await r.getTop(subreddit, { limit: 50, time: "week" });
let obj = postsFunc(x);
log(obj);
return obj;
} catch {
let obj = {
error: true,
};
return obj;
}
};
let log = (obj) => {
console.log(obj);
};
// test module
// (async () => {
// let obj = await getTopPost("python");
// console.log(obj);
// })();
module.exports.getPost = getTopPost;