-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
121 lines (102 loc) · 4.19 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
require('dotenv').config();
const {retweet, search, getLatestRetweet, replyToTweet, findUserById} = require("./src/service/twitterService");
const {
upsertTimeEntry,
getNumbersFromTweet,
getLastEnteredTweetId,
upsertLatestEnteredTweetId, getTotalCampaignMinutes
} = require("./src/service/campaignService");
const {mongodb} = require("./src/service/mongodbService");
async function iterateOverInterval(interval, data, callback) {
return new Promise((resolve) => {
let index = 0;
const intervalId = setInterval(async () => {
if (data.length < 1 || index === data.length - 1) {
clearInterval(intervalId);
resolve();
}
if (!data[index]) {
//prevent continuation with empty data
return;
}
await callback(data[index])
index++;
}, interval);
});
}
async function startBot(req, res) {
console.log("Starting bot");
const response = await getLatestRetweet({
exclude: "replies",
"tweet.fields": "referenced_tweets",
expansions: "referenced_tweets.id"
});
if (!response) {
res.send("Failed to get latest retweet, not starting bot");
console.error("Failed to start bot. Couldn't fetch latest retweet");
return;
}
const latestId = response.tweets?.[0]?.referenced_tweets[0]?.id;
const sortedTweets = [];
const data = await search("#FitDevs -is:retweet", latestId);
for await (const result of data) {
sortedTweets.push(result);
}
//To ensure that the tweet we last RT'd is always the most recent
sortedTweets.reverse();
//15 mins / 50 requests = 1 request every 18 seconds
//+ 1 to avoid hitting rate limit
await iterateOverInterval(19000, sortedTweets, async function (tweet) {
console.info('Retweeting tweet ID', tweet?.id);
await retweet(tweet.id);
});
res.send("Bot Done");
console.log("Done")
}
async function runCampaign(req, res) {
console.log("Starting campaign updates...");
await mongodb.connect();
const tweets = [];
const lastEntered = await getLastEnteredTweetId();
//Most recent will be first in the array
const data = await search('#OneMillionMinutes -is:retweet', lastEntered?.tweetId, {
expansions: 'author_id'
});
for await (const result of data) {
const numbersFromTweet = getNumbersFromTweet(result);
if (numbersFromTweet) {
tweets.push(numbersFromTweet);
} else {
const response = await findUserById(result.author_id, {'user.fields': ['name']});
const username = response.data.username;
await replyToTweet(result.id, `@${username}, Your tweet was skipped because the bot couldn't parse your entry. @dev_nerd_2 will investigate and follow up.`);
}
}
if (tweets.length === 0) {
await mongodb.disconnect();
console.log("Done");
res.send("Bot Started but terminated early because there are no new tweets.");
return;
}
//15 mins / 200 requests = 1 request every 4.5 seconds
//+ 1 to avoid hitting rate limit
await iterateOverInterval(5500, tweets, async function (tweet) {
const response = await findUserById(tweet.twitterUserId, {'user.fields': ['name']});
const username = response.data.username;
//TODO: upsertTimeEntry was failing, claiming the Client must be connected before running operations.
// Need to have someone investigate what's going on
await mongodb.connect();
const {total} = await upsertTimeEntry(tweet.twitterUserId, tweet.number, username);
const communityTotal = await getTotalCampaignMinutes();
await replyToTweet(tweet.id, `Your entry has been logged. You have logged ${total} total minutes! The community has logged ${communityTotal} minutes toward our goal of one million.`);
});
//Update entry with the most recent tweetId so we know where to start our search next time
await upsertLatestEnteredTweetId(tweets[0].id);
await mongodb.disconnect();
res.send("Bot started");
console.log("Done");
}
module.exports = {
startBot,
runCampaign
}