-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
96 lines (77 loc) · 2.38 KB
/
index.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
88
89
90
91
92
93
94
95
96
const fs = require("fs");
const axios = require("axios");
const cheerio = require("cheerio");
const cloudscraper = require("cloudscraper");
const { TwitterApi } = require("twitter-api-v2");
const express = require("express");
require("dotenv").config();
const app = express();
const PORT = process.env.PORT || 3000;
app.head("/ping", (req, res) => {});
app.head("/tweet", async (req, res) => {
await main();
});
app.listen(PORT, () => {
console.log(`Listening at http://localhost:${PORT}`);
});
const QUOTE_URL = "https://api.quotable.io/random";
const CHARACTER_URL = "https://bestrandoms.com/random-character";
const main = async () => {
const quote = await getQuote();
const [character, pictureUrl] = await getCharacter();
await dowloadPicture(pictureUrl);
await tweet(quote, character, pictureUrl);
};
const tweet = async (quote, character, pictureUrl) => {
const userClient = new TwitterApi({
appKey: process.env.TWITTER_API_KEY,
appSecret: process.env.TWITTER_API_SECRET,
accessToken: process.env.TWITTER_ACCESS_TOKEN,
accessSecret: process.env.TWITTER_ACCESS_SECRET,
});
const mediaId = await userClient.v1.uploadMedia("image.jpeg");
console.log("Media Id:", mediaId);
await userClient.v2.tweet(`${quote}\n\n- ${character}`, {
media: {
media_ids: [mediaId],
},
});
console.log("Tweeted!");
};
const getQuote = async () => {
const quoteApiRes = await axios.get(QUOTE_URL);
const quote = quoteApiRes.data.content;
console.log(`${quote}`);
return quote;
};
const getCharacter = async () => {
var options = {
uri: CHARACTER_URL,
formData: { quantity: 1, rank: 1000 },
headers: {
"User-Agent": "Safari/537.36",
},
};
const characterPageHtml = await cloudscraper.post(options);
const $ = cheerio.load(characterPageHtml);
let character = $("p.text-center:nth-child(2)").text().trim();
const pictureUrl = $(".center-block").attr("src");
console.log(`${character}\n${pictureUrl}`);
return [character, pictureUrl];
};
const dowloadPicture = async (url) => {
const pictureRes = await axios.get(url, {
headers: {
"Accept-Encoding": "gzip,deflate,compress",
"User-Agent": "Axios 0.21.1",
},
responseType: "stream",
});
return new Promise((resolve, reject) => {
pictureRes.data
.pipe(fs.createWriteStream("image.jpeg"))
.on("finish", () => {
resolve();
});
});
};