-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
69 lines (63 loc) · 2.06 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
"use strict";
const { keyword, query, interjections, locations } = require("./config.js");
const { createStatus, filterStatus, isFromAz } = require("./utils.js");
// Init Firebase
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
// Init Realtime Database
const db = admin.database();
const ref = db.ref("/");
// Init Twit
const Twit = require("twit");
const T = new Twit({
consumer_key: functions.config().twitter.consumer_key,
consumer_secret: functions.config().twitter.consumer_secret,
access_token: functions.config().twitter.access_token,
access_token_secret: functions.config().twitter.access_token_secret
});
exports.scheduledFunction = functions.pubsub
.schedule("every 15 minutes")
.onRun(context =>
ref
.once("value")
.then(snapshot =>
// Retrieve since_id and array of ignored keywords from db
snapshot.val()
)
.then(({ ignore = [], since_id }) =>
// Fetch recent tweets matching query after since_id
T.get("search/tweets", {
q: `${keyword.incorrect} ${ignore
.map(i => `-${i}`)
.join(" ")} ${query}`,
result_type: "recent",
tweet_mode: "extended",
since_id
})
)
.then(({ data }) => {
data.statuses.length > 0 &&
functions.logger.info(JSON.stringify(data, null, 2));
// Filter tweets not containing keyword in status.text and reverse order
return data.statuses.filter(filterStatus);
})
.then(
filtered =>
filtered.length &&
Promise.all(
filtered.map(status =>
// Post new tweet
T.post("statuses/update", {
status: createStatus(status)
})
)
)
.then(() =>
// Record id of most recent tweet in db
ref.child("since_id").set(filtered[0].id_str)
)
.catch(err => functions.logger.error(err))
)
.catch(err => functions.logger.error(err))
);