Skip to content

Instantly share code, notes, and snippets.

@michikono
Last active March 24, 2017 21:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michikono/634c2371e93576f4417c to your computer and use it in GitHub Desktop.
Save michikono/634c2371e93576f4417c to your computer and use it in GitHub Desktop.
# demo of brain functionality (persisting data)
# https://github.com/github/hubot/blob/master/docs/scripting.md#persistence
# counts every time somebody says "up"
# prints out the count when somebody says "are we up?"
# /STUFF/ means match things between the slashes. the stuff between the slashes =
# regular expression.
# \b is a word boundary, and basically putting it on each side of a phrase ensures
# we are matching against the word "up" instead of a partial text match such as in "sup"
robot.hear /\bup\b/, (msg) ->
# note that this variable is *GLOBAL TO ALL SCRIPTS* so choose a unique name
robot.brain.set('everything_uppity_count',
(robot.brain.get('everything_uppity_count') || 0) + 1
)
# ? is a special character in regex so it needs to be escaped with a \
# the i on the end means "case *insensitive*"
robot.hear /are we up<b>\?</b>/i, (msg) ->
msg.send "Up-ness: " + (robot.brain.get('everything_uppity_count') || "0")
###
# Demonstration of how to parse private messages
###
# responds to all private messages with a mean remark
robot.hear /./i, (msg) ->
# you can chain if clauses on the end of a statement in
# coffeescript to make things look cleaner
# in a direct message, the channel name and author are the same
msg.send 'shoo!' if get_channel(msg) == get_username(msg)
# replies to any message containing an "!" with an exact replica of that message
# .* = matches anything; we access the entire matching string using match[0]
# for using regex, use this tool: http://regexpal.com/
robot.hear /.*!.*/, (msg) ->
# send back the same message
# reply prefixes the user's name in front of the text
msg.reply msg.match[0]
# responds to "[botname] sleep it off"
# note that if you direct message this command to the bot,
# you don't need to prefix it with the name of the bot</em>
robot.respond /sleep it off/i, (msg) ->
# responds in the current channel
msg.send 'zzz...'
# helper method to get sender of the message
get_username = (response) ->
"@#{response.message.user.name}"
# helper method to get channel of originating message
get_channel = (response) ->
if response.message.room == response.message.user.name
"@#{response.message.room}"
else
"##{response.message.room}"
try
robot.messageRoom "bob", "Hello, this is a private message!"
catch error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment