Making the Bot - Part II

On the last page we fetched the newest threads from a chosen subreddit, parsed them for relevant data, and filtered for the threads that matched an arbitrary search term. Now it's time to do something with that data. Since our bot is supposed to alert users to new threads that match their interests, we should obviously do something to alert them. Since our bot is server-side we could just send the user an email or text, but we can also alert users without leaving Reddit. We can accomplish that by sending private messages (PMs) to our users.

We’ll use the “compose” API endpoint to accomplish this. Compose lets us write and send private messages to other users on Reddit. Unlike fetching threads, this endpoint requires us to POST instead of GET. Even though we’re POSTing, however, we will still send all our data as URI parameters, except for the authentication token which is still sent in the header as always. Compose has several parameters, some optional and some required:

api_type (optional): Set this to "json" if you want JSON data back.
from_sr (optional): Indicates which subreddit the PM is being sent from. Not relevant for our purposes.
g-recaptcha-response (optional): If the bot's account is new and doesn't have much karma, Reddit will force it to solve a CAPTCHA. This is where the response goes.
subject: The subject field of the message. Max length is 100 characters.
text: The body of the message which can be formatted in markdown. Note that although the API documentation doesn't say this, there is a max length for the text field as well. If you go above it, you'll get back an error when you try to POST to the API. to: The username of the recipient.
uh / X-Modhash-header (optional): This isn't required when using OAuth so don't worry about it.

Now let's see this call in action


function alertUser(token, threads) {
    var subject = "New threads matching your query have been posted";
    var to = "RECIPIENT_USER";
    // Construct message with markdown
    var message = "";
    for (thread in threads) {
        message += "* [" + threads[thread]['title']+ "](" + threads[thread]['link']+ ")\n";
    }

    var builtURL = "https://oauth.reddit.com/api/compose";
    builtURL += "?api_type=json&subject=" + subject + "&to=" + to + "&text=" + message;

    var options = {
                    url: builtURL,
                    method: 'POST',
                    contentType: 'application/json',
                    headers: {
                        'User-Agent': YOUR_USER_AGENT,
                        'Authorization': 'bearer ' + token
                    },
                    body: "" 
                 };

    console.log("Trying to send request...");
    request(options, function(err, res, body) {
        // You can check for errors and success here
    });
}

Walking through this code, we first set our subject to a standard subject line and set our recipient. Then we construct the message body using the array of processed thread data we created earlier along with a little markdown for prettier formatting. Next, we create the URL using the above pieces. Finally, we POST our request to send the message.

That's it! The message has been sent and our user is now aware of new threads they're interested in without having to constantly check their favorite subreddit!