Charca / bootbot

Facebook Messenger Bot Framework for Node.js
MIT License
974 stars 254 forks source link

How to handle async data flow (show a message when a cron job runs)? #80

Closed dragGH102 closed 6 years ago

dragGH102 commented 7 years ago

As per the title,

I've looked into the documentation thoroughly but I am having a hard time understanding how to have the bot available (without starting and stopping it each time) when the bot runs after waiting for new data fetched periodically (like, a news feed)?

Thanks in advance

mraaroncruz commented 7 years ago

Bootbot is essentially an express.js server and a Facebook Messenger HTTP client with a lot of wonderful sugar on top.

So you can do anything you would do in a normal node app.

You could either loop in another thread (setTimeout recursion) but I always run into memory leak problems, probably because I am not a JS developer. Or what I do to be on the safe side is to listen to a unix signal like USR2 and then do some action. Then I wire up sending that signal to my app in a cron task.

Here's an example from my Ruby News Bot

const listen = (botName) => {
  process.on('SIGUSR2', function() {   // IMPORTANT PART
    logger.info(`Starting ${botName} workers...`)
    logger.info("SCHEDULE::", schedule)
    switch(botName) {
      case "ruby":
        async.parallel([
          startRubyflowWorker,
          startTwitterWorkers,
          startRubyWeeklyWorker,
          startArticleSenderWorker
        ])
        break
    }
  })
}

And the shell script that sets it off

#!/bin/bash

CWD=`dirname "${BASH_SOURCE[0]}"`
cat $CWD/tmp/pids/newsbot.pid | xargs kill -USR2

And the crontab

 */5  *   *   *   *    bash -l -c "/bin/bash /path/to/cron.sh"

You could get by by adding some endpoints to the express.js app too. You can find it via bot.app and add something like bot.app.get("/check_feeds") then handle the feed checking when you hit that endpoint, which you could do with cron and curl.

And I'm sure there are a lot of other really nice ways to handle this.

mraaroncruz commented 6 years ago

Closing due to no response