Skip to content

Commit

Permalink
Merge pull request #85 from citricsquid/adds-refresh-requests
Browse files Browse the repository at this point in the history
Adds conversion comment refresh requests via Private Messages
  • Loading branch information
cannawen authored Oct 10, 2017
2 parents 39cd06c + 3a9ce41 commit 61c762f
Show file tree
Hide file tree
Showing 6 changed files with 237 additions and 39 deletions.
5 changes: 5 additions & 0 deletions src/analytics.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ function trackConversion(data) {
track("conversion", data);
}

function trackEdit(data) {
track("edit", data);
}

function trackUnsubscribe(data) {
track("unsubscribe", data);
}
Expand All @@ -39,6 +43,7 @@ function track(category, data) {
module.exports = {
"trackPersonality" : trackPersonality,
"trackConversion" : trackConversion,
"trackEdit" : trackEdit,
"trackUnsubscribe" : trackUnsubscribe,
"trackError" : trackError
}
65 changes: 51 additions & 14 deletions src/bot.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const personality = require('./personality');
const environment = helper.environment();
let replyMetadata = {};
let excludedSubreddits = [];
try {
try {
excludedSubreddits = yaml
.safeLoad(fs.readFileSync('./private/excluded_subreddits.yaml', 'utf8'))
.map(subreddit => subreddit.toLowerCase());
Expand Down Expand Up @@ -63,15 +63,15 @@ function replyToMessages() {
}
});
}

function messageIsShort(message) {
return message['body'].length < 30;
}

const now = helper.now();

network.refreshToken();

const messages = network.getUnreadMessages();
network.markAllMessagesAsRead();
if (!messages) {
Expand All @@ -85,15 +85,15 @@ function replyToMessages() {
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'];

Expand All @@ -104,21 +104,21 @@ function replyToMessages() {

if (replyMetadata[postTitle] === undefined) {
shouldReply = true;
replyMetadata[postTitle] = {
'timestamp' : now,
replyMetadata[postTitle] = {
'timestamp' : now,
'personalityReplyChance' : 0.5
};

} else if (helper.random() < replyMetadata[postTitle]['personalityReplyChance']) {
shouldReply = true;
Object.assign(replyMetadata[postTitle], {
'timestamp' : now,
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);
}
Expand All @@ -132,6 +132,42 @@ function replyToMessages() {
network.blockAuthorOfMessageWithId(message['id']);
});

filterPrivateMessages(messages)
.filter(message => message['subject'].match(/refresh (\w+)/i))
.forEach(message => {
const commentId = message['subject'].match(/refresh (\w+)/i)[1];
const comment = network.getComment('t1_' + commentId);

if (! comment) {
return;
}

const commentReplies = network.getCommentReplies(comment['link_id'], commentId);

const botReply = commentReplies.find(reply => {
return reply['data']['author'].toLowerCase() == environment['reddit-username'].toLowerCase();
});

if (! botReply) {
return;
}

const conversions = converter.conversions(comment);
const reply = replier.formatReply(comment, conversions);

if (Object.keys(conversions).length === 0) {
return;
}

network.editComment('t1_' + botReply['data']['id'], reply);

if (! comment['link_id']) {
comment['link_id'] = 't3_value';
}

analytics.trackEdit([message['timestamp'], 'https://reddit.com/comments/' + comment['link_id'].replace(/t3_/g, '') + '//' + commentId, comment['body'], conversions]);
});

//cleanup old replyMetadata
replyMetadata = Object
.keys(replyMetadata)
Expand Down Expand Up @@ -177,7 +213,7 @@ function postConversions() {
//If we have not seen this post within 24 hours
if (replyMetadata[postTitle] === undefined) {
replyMetadata[postTitle] = {
'timestamp' : helper.now(),
'timestamp' : helper.now(),
'personalityReplyChance' : 1,
'conversions' : newConversions
}
Expand Down Expand Up @@ -219,12 +255,12 @@ function postConversions() {
function hasConversions(map) {
return Object.keys(map['conversions']).length > 0;
}

const comments = network.getRedditComments("all");
if (!comments) {
return;
}

comments
.filter(commentIsntFromABot)
.filter(allowedToPostInSubreddit)
Expand All @@ -248,4 +284,5 @@ function postConversions() {
analytics.trackConversion([comment['timestamp'], comment['link'], comment['body'], conversions]);
network.postComment(comment['id'], reply);
})
};

};
43 changes: 40 additions & 3 deletions src/network.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ var oauthTokenValidUntil = undefined;
var lastProcessedCommentId = undefined;

function get(url) {
let content;
let content;

if (url.startsWith('http')) {
content = networkRequest({ url: url }, false);
Expand Down Expand Up @@ -41,7 +41,7 @@ function post(urlPath, form) {

function networkRequest(options, oauthRequest) {
function redditOauthHeader() {
const userAgent =
const userAgent =
"script:" + environment['reddit-username'] + ":" + environment['version']
+ " (by: /u/" + environment['reddit-username'] + ")";

Expand Down Expand Up @@ -129,7 +129,7 @@ function printBannedSubreddits() {
.filter(match => match !== null)
.map(match => match[1])
.forEach(subreddit => helper.log("- " + subreddit));

const lastMessageId = messages[messages.length - 1]['data']['name'];

messages = get("/message/inbox?limit=100&after=" + lastMessageId)
Expand Down Expand Up @@ -171,6 +171,40 @@ function postComment(parentId, markdownBody) {
post('/api/comment', { 'parent' : parentId, 'text' : markdownBody });
}

function getComment(commentId) {
const comment = get('https://www.reddit.com/api/info.json?id=' + commentId);

if (comment.length == 0) {
return;
}

const data = comment[0]['data'];

return {
'body': data['body'],
'author': data['author'],
'id': data['name'],
'link_id' : data['link_id'],
'postTitle': '', // api/info does not return a value for postTitle but this property is required by shouldConvertComment
'subreddit': data['subreddit'],
'timestamp' : data['created_utc']
}
}

function editComment(commentId, markdownBody) {
post('/api/editusertext', { 'thing_id' : commentId, 'text' : markdownBody });
}

function getCommentReplies(linkId, commentId) {
const replies = get('https://www.reddit.com/api/morechildren.json?api_type=json&link_id=' + linkId + '&children=' + commentId);

if (! replies.length === 0) {
return null;
}

return replies['json']['data']['things'];
}

function getUnreadMessages() {
return get("/message/unread?limit=100");
}
Expand All @@ -186,7 +220,10 @@ function blockAuthorOfMessageWithId(id) {
module.exports = {
"refreshToken" : refreshToken,
"getRedditComments" : getRedditComments,
"getComment" : getComment,
"postComment" : postComment,
"editComment" : editComment,
"getCommentReplies" : getCommentReplies,
"getUnreadMessages" : getUnreadMessages,
"markAllMessagesAsRead" : markAllMessagesAsRead,
"blockAuthorOfMessageWithId" : blockAuthorOfMessageWithId
Expand Down
40 changes: 27 additions & 13 deletions src/reply_maker.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ function formatReply(comment, conversions) {
let source = "source"
let version = environment['version'];
let subreddit = comment['subreddit'];
let commentId = comment['id'];
let transform = (x) => x;

if (comment['subreddit'].match(/^totallynotrobots$/i)) {
Expand All @@ -17,22 +18,35 @@ function formatReply(comment, conversions) {
transform = (x) => x.toUpperCase();
}

const items = [
{"value" : "metric units " + species },
{"type" : "link", "value" : "feedback", "href" : "https://redd.it/73edn2" },
{"type" : "link", "value" : "source", "href" : "https://github.com/cannawen/metric_units_reddit_bot" },
{"type" : "link", "value" : "hacktoberfest", "href" : "https://redd.it/73ef7e" },
{"type" : "link", "value" : "block", "href" : formatRedditComposeLink(environment['reddit-username'], 'block', stopMessage) },
{"type" : "link", "value" : "refresh conversion", "href" : formatRedditComposeLink(environment['reddit-username'], 'refresh ' + commentId, "Please click 'send' below and I will update my comment to convert any new or updated values in your comment.") },
{"value" : version }
];

const footer = items.map(item => {
item.value = transform(item.value);
item.value = '^' + item.value.replace(/ /g, ' ^');

if (item.type == 'link') {
item.value = `[${item.value}](${item.href})`;
}

return item.value;
}).join(' ^| ');

return Object.keys(conversions)
.map(nonMetricValue => nonMetricValue + " ≈ " + conversions[nonMetricValue])
.map(transform)
.join(" \n")
+ "\n\n"
+ transform("^metric ^units ^" + species)
+ " ^|"
+ " ^[" + transform("feedback") + "](https://www.reddit.com/r/metric_units/comments/73edn2/constructive_feedback_thread/)"
+ " ^|"
+ " ^[" + source + "](https://github.com/cannawen/metric_units_reddit_bot)"
+ " ^|"
+ " ^[" + transform("hacktoberfest") + "](https://www.reddit.com/r/metric_units/comments/73ef7e/contribute_to_metric_units/)"
+ " ^|"
+ " ^[" + transform("block") + "](https://www.reddit.com/message/compose?to=metric_units&subject=stop&message=If%20you%20would%20like%20to%20stop%20seeing%20this%20bot%27s%20comments%2C%20please%20send%20this%20private%20message%20with%20the%20subject%20%27stop%27.%20If%20you%20are%20a%20moderator%2C%20please%20go%20to%20https%3A%2F%2Fwww.reddit.com%2Fr%2F" + subreddit + "%2Fabout%2Fbanned%2F)"
+ " ^|"
+ " ^" + version;
.join(" \n") + '\n\n' + footer;
}

function formatRedditComposeLink(to, subject, message) {
return 'https://www.reddit.com/message/compose?to=' + to + '&subject=' + encodeURIComponent(subject) + '&message=' + encodeURIComponent(message);
}

module.exports = {
Expand Down
Loading

0 comments on commit 61c762f

Please sign in to comment.