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
- If you don't have Hubot installed, we'll be using the Slack adapter in this example so start with [https://github.com/slackhq/hubot-slack](the instructions on the slack-hubot adapter).
- If there is a Hubot you're already working with make sure that the https://github.com/hubot-scripts/hubot-redis-brain and https://github.com/slackhq/hubot-slack packages are installed.
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
- The Little Redis Book It's available for free on ePub. Kindle doesn't support ePub but you can easily import it into iBooks
- Redis Desktop Manager
- Hubot Scripting Guide and the section on Persistence](https://github.com/github/hubot/blob/master/docs/scripting.md#persistence)