Thursday 1 June 2017

How to "wait" on a user's reply without holding up the server?

I'm trying to build a bot using the remixz/messenger-bot module. So how the bot works is that it waits for a POST request made from Facebook

app.post('/', (req, res, next) => {

  let hmac = forge.hmac.create()
  hmac.start('sha1', config.APP_SECRET)
  hmac.update(req.rawBody)
  if (req.get('x-hub-signature') !== `sha1=${hmac.digest().toHex()}`) {
    // throw error
    console.log('Error?')
    return res.send(JSON.stringify({status: 'not ok', error: 'Message integrity check failed'}))
  }
  bot._handleMessage(req.body)
  res.send(JSON.stringify({status: 'ok'}))
})

It then uses the _handleMessage(req.body) method that checks for the type of message that is being sent by the user, e.g a postback button or a picture etc, and then it emits an event depending on the message.

  _handleMessage (json) {
    let entries = json.entry

    entries.forEach((entry) => {
      let events = entry.messaging
      events.forEach((event) => {
        if (event.message) {
          if (event.message.is_echo) {
            // message is echo
          } else {
            // message received
            this._handleEvent('message', event)
          }
        } 
        ....

(and the _handleEvent method that emits the event)

_handleEvent (type, event) {
    this.emit(type, event, this.sendMessage.bind(this, event.sender.id), this._getActionsObject(event))
  }

So my question is this: Given that multiple users could be interacting with the bot at any given time and nodejs is single threaded..

  1. What is the best way to manage different conversation states by different users?

  2. How do i "wait" on users reply, such that after an extended period of time (say 30 mins?) the conversation with the bot can still be picked-off where it was last left at?



via cookiedookie

No comments:

Post a Comment