Saving user data in the Hubot Redis brain

This is a quick tutorial about saving user data in the Hubot Redis brain using the Slack adapter.

There is documentation out there about the hubot-redis-brain, about redis commands, and the Hubot slack adapter, but very little mention of how to use them all together.

I'm writing a couple hubot scripts that need to save data about a user but want to know if there is already built to handle this. Does hubot have built in commands to access and save data? If so how is the data stored? How does this work with the Slack adapter? What is the unique identifier? In looking for answers to these questions I learned a little about Hubot, redis, and Slack.

Before starting

You'll also need to configure the Hubot integration in Slack. In Slack Click the team name > Configure Integrations > Hubot. After configuring it you'll be given an API token which you'll need for Heroku and for local testing.

Troubleshooting notes

robot.brain

Hubot has an " in-memory key-value store exposed as robot.brain that can be used to store and retrieve data by scripts." Since it is only in-memory it really isn't persistent. When hubot restarts, all that data will be gone. That's where hubot-redis-brain comes in. Because robot-brain it's just a Redis instance, you can use all of the Redis commands for getting setting, etc.

robot.brain.users

The brain has  users object with a key of users and a key value pair for each user. At a minimum hubot sets an ID. Other adapters and scripts may set additional key value pairs.

The hubot methods for looking up users are userForName, userForId, userForFuzzyName, and usersForFuzzyName.

robot.brain.users & slack

This is a sample of the users object when using the slack adapter:

{
    "users": {
        "1": {
            "id": 1,
            "name": "Shell",
            "room": "Shell"
        },
        "A12B3CDE4": {
            "email_address": "example@zack.io",
            "id": "A12B3CDE4",
            "name": "jane",
            "real_name": "Jane Smith",
            "room": "general"
        },
        "A12H7OYG4": {
            "id": "A12H7OYG4",
            "name": "hubot",
            "real_name": ""
        },
        "USLACKBOT": {
            "email_address": null,
            "id": "USLACKBOT",
            "name": "slackbot",
            "real_name": "slackbot"
        }
    }
}

You can see there are 2 Hubots, and one real person in the room. Now we know that the ID is set based on the Slack user id so we can use this to save additional information.

Resources

Scripts that helped by example

Source code