Jokes Script

The jokes script (scripts/jokes.js) contains a single handler for responding to the phrase:

hubot tell me a joke

The script fetches a list of jokes from a remote website and chooses a joke at random. All of the jokes take the form of a question followed by an answer [1]. The Hubot first replies to the user by asking the question. After a three second delay, it replies with the answer.

The robot does not pay any attention to the user’s attempt to answer the question part of the joke. It simply replies with the question, waits 3 seconds, and replies with the answer.

The joke data is available on the course website. All valid joke data is JSON-encoded. The data is stored as an Array that contains objects. Each object has a question property and an answer property. Both the question and answer are strings.

Here’s an example JSON-encoded array of jokes:

    "question": "What do goblins and ghosts drink when they're hot and thirsty on Halloween?",
    "answer": "Ghoul-aid!!!"
    "question": "What is a Mummie's favorite type of music?",
    "answer": "Wrap!!!!!"
    "question": "Why do demons and ghouls hang out together?",
    "answer": "Because demons are a ghouls best friend!"

How it Works

Your callback for tell me a joke should do the following:

  1. Check process.env.JOKE_URL to see if the user set a new joke url using the JOKE_URL environment variable.
  1. Use the request library (which is already installed via NPM) to send a GET request to the joke url. When a response is received, the provided callback will receive three parameters: error, response, and body.
  • If error has value or if response.statusCode is not 200, then an error occurred. In that case, the Hubot should reply with:

    I couldn't retrieve any jokes...

    and return immediately.

  • Otherwise, the request must have succeeded.

  1. Assuming the request was successful, the Hubot should choose a random joke to send to the user.
  • Use JSON.parse() to parse the body.

    • If parsing the body raises an exception [2], the Hubot should reply with:

      I couldn't parse any jokes...

      and return immediately.

  • If the parsed JSON returns an empty array (no jokes), the Hubot should reply with:

    The joke list was empty!
  • Otherwise, a random joke object should be chosen from the parsed array.

  1. The Hubot should then reply with the question and answer.
  • The Hubot should immediately reply to the user with the question.
  • The Hubot should then delay replying with the answer for a set amount of time (THINKING_TIME [3]).
[1]a.k.a the punchline.
[2]You’ll want to use a try catch to handle the exception.
[3]It’s set to 3 seconds by default, but we can always change it.