Search code examples
state-machinehubot

How to make Hubot understand chat context?


Is there any way to make Hubot understand the context of conversation between messages? Such that he could ask me clarifying questions?

For example:

me: hey, create a branch plz
Hubot: How should I name it?
me: super-duper
Hubot: Branch 'super-duper' created

Should I use some kind of state machine? Any advices on that?


Solution

  • You can use robot's brain to persist state.

    robot.respond /hey, create a branch plz/i, (res) ->
         res.reply "Ok, lets start"
         user = {stage: 1}
         name = res.message.user.name.toLowerCase()
         robot.brain.set name, user
    
    robot.hear /(\w+)\s(\w+)/i, (msg) ->
         name = msg.message.user.name.toLowerCase()
         user = robot.brain.get(name) or null
         if user != null
          answer = msg.match[2]
          switch user.stage
            when 1 
              msg.reply "How should I name it?"
            when 2 
              user.name = answer
              msg.reply "Are you sure (y/n) ?"
            when 3
              user.confimation=answer
    
          user.stage += 1
          robot.brain.set name, user
    
          if user.stage > 3 #End of process
            if /y/i.test(user.confimation) 
               msg.reply "Branch #{user.name} created." 
            else
               msg.reply "Branch creation aborted"
    
            robot.brain.remove name