forked from cannawen/metric_units_reddit_bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.js
executable file
·252 lines (214 loc) · 7.54 KB
/
bot.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
const deasync = require('deasync');
const fs = require('fs');
const https = require('https');
const path = require('path');
const request = require('request');
const yaml = require('js-yaml');
const analytics = require('./analytics');
const converter = require('./converter');
const helper = require('./helper');
const network = require('./network');
const replier = require('./reply_maker');
const personality = require('./personality');
const environment = helper.environment();
let replyMetadata = {};
let excludedSubreddits = [];
try {
excludedSubreddits = yaml
.safeLoad(fs.readFileSync('./private/excluded_subreddits.yaml', 'utf8'))
.map(subreddit => subreddit.toLowerCase());
} catch (e) {
// helper.logError(e);
}
process.on('uncaughtException', function (err) {
helper.logError(err);
});
network.refreshToken();
helper.setIntervalSafely(postConversions, 2);
helper.setIntervalSafely(replyToMessages, 60);
function replyToMessages() {
function filterCommentReplies(messages) {
return messages
.filter(raw => raw['kind'] === 't1')
.map(raw => raw['data'])
.map(data => {
return {
'body': data['body'],
'id': data['name'],
'postTitle': data['link_title'],
'link': 'https://www.reddit.com' + data['context'],
'timestamp' : data['created_utc'],
'subreddit' : data['subreddit'],
'username' : data['author']
}
});
}
function filterPrivateMessages(messages) {
return messages
.filter(raw => raw['kind'] === 't4')
.map(raw => raw['data'])
.map(data => {
return {
'body' : data['body'],
'subject' : data['subject'],
'id' : data['name'],
'username' : data['author'],
'timestamp' : data['created_utc']
}
});
}
function messageIsShort(message) {
return message['body'].length < 30;
}
const now = helper.now();
network.refreshToken();
const messages = network.getUnreadMessages();
network.markAllMessagesAsRead();
if (!messages) {
return;
}
filterCommentReplies(messages)
.filter(messageIsShort)
.forEach(message => {
const reply = personality.robotReply(message);
if (reply === undefined) {
return;
}
if (message['subreddit'].match(/^totallynotrobots$/i)) {
const humanReply = personality.humanReply(message);
if (humanReply) {
analytics.trackPersonality([message['timestamp'], message['link'], message['body'], reply, true]);
network.postComment(message['id'], humanReply);
}
return;
}
const postTitle = message['postTitle'];
// Always replies if no personality in post within the last 24h
// Replies are 50% less likely for each reply within 24 hours
// Possible refactor candidate, story #150342011
let shouldReply = false;
if (replyMetadata[postTitle] === undefined) {
shouldReply = true;
replyMetadata[postTitle] = {
'timestamp' : now,
'personalityReplyChance' : 0.5
};
} else if (helper.random() < replyMetadata[postTitle]['personalityReplyChance']) {
shouldReply = true;
Object.assign(replyMetadata[postTitle], {
'timestamp' : now,
'personalityReplyChance': replyMetadata[postTitle]['personalityReplyChance'] / 2
});
}
analytics.trackPersonality([message['timestamp'], message['link'], message['body'], reply, shouldReply]);
if (shouldReply) {
network.postComment(message['id'], reply);
}
});
filterPrivateMessages(messages)
.filter(message => message['subject'].match(/stop/i))
.forEach(message => {
analytics.trackUnsubscribe([message['timestamp'], message['username']]);
network.postComment(message['id'], replier.stopMessage);
network.blockAuthorOfMessageWithId(message['id']);
});
//cleanup old replyMetadata
replyMetadata = Object
.keys(replyMetadata)
.reduce((memo, key) => {
const lessThan24hAgo = replyMetadata[key]['timestamp'] > now - 24*60*60*1000;
if (lessThan24hAgo) {
memo[key] = replyMetadata[key];
}
return memo;
}, {});
};
function postConversions() {
function allowedToPostInSubreddit(comment) {
return excludedSubreddits.indexOf(comment['subreddit'].toLowerCase()) === -1;
}
function commentIsntFromABot(comment) {
const noBotInCommentBody = comment['body'].match(/\bbot\b/gi) === null;
const noBotInAuthorName = comment['author'].match(/bot/gi) === null;
const thisBotDidntWriteComment = comment['author'].toLowerCase() !== environment['reddit-username'].toLowerCase();
return noBotInCommentBody && noBotInAuthorName && thisBotDidntWriteComment;
}
function postIsShort(comment) {
return comment['body'].length < 300;
}
function isNotSarcastic(comment) {
return comment['body'].match(new RegExp("(^|[ \\n])/s($|[ \\n])", 'i')) === null;
}
function hasNumber(comment) {
return comment['body'].match(/\d/) !== null;
}
function filterIfAlreadyReplied(map) {
const postTitle = map['comment']['postTitle'];
const conversions = map['conversions'];
const newConversions = new Set(Object.keys(conversions));
//If we have not seen this post within 24 hours
if (replyMetadata[postTitle] === undefined) {
replyMetadata[postTitle] = {
'timestamp' : helper.now(),
'personalityReplyChance' : 1,
'conversions' : newConversions
}
//We should perform conversions
return map;
//If we have seen this post within 24 hours
} else {
const alreadyConverted = replyMetadata[postTitle]['conversions'];
//If we have done personality but not converted
if (alreadyConverted === undefined) {
replyMetadata[postTitle] = Object.assign(replyMetadata[postTitle], {
'conversions' : newConversions
});
//We should perform the conversion
return map;
//If we have converted something
} else {
const unconverted = [...newConversions].filter(x => !alreadyConverted.has(x));
//If all conversions in the current comment have already been converted
if (unconverted.length === 0) {
//Do not convert anything for this comment
return Object.assign(map, {'conversions' : {}});
//If one or more of the conversions in this comment have not been converted
} else {
replyMetadata[postTitle] = Object.assign(replyMetadata[postTitle], {
'conversions' : new Set([...alreadyConverted, ...newConversions])
});
//Convert all conversions in this comment
return map;
}
}
}
}
function hasConversions(map) {
return Object.keys(map['conversions']).length > 0;
}
const comments = network.getRedditComments("all");
if (!comments) {
return;
}
comments
.filter(commentIsntFromABot)
.filter(allowedToPostInSubreddit)
.filter(postIsShort)
.filter(hasNumber)
.filter(isNotSarcastic)
.map(comment => {
return {
"comment" : comment,
"conversions" : converter.conversions(comment)
}
})
.map(filterIfAlreadyReplied)
.filter(hasConversions)
.forEach(map => {
const comment = map['comment'];
const conversions = map['conversions'];
const reply = replier.formatReply(comment, conversions);
analytics.trackConversion([comment['timestamp'], comment['link'], comment['body'], conversions]);
network.postComment(comment['id'], reply);
})
};