简体   繁体   English

Hubot如何在没有任何命令的情况下定期运行功能?

[英]How can Hubot run function regularly, without any command?

I'm trying to make a function for hubot send a message every 5 minutes to a room without any command, just by himself. 我正在尝试为hubot制作一个函数,每隔5分钟向一个房间发送一条消息而没有任何命令,只需要他自己。

module.exports = (robot, scripts) ->
  setTimeout () ->
    setInterval () ->
      msg.send "foo"
    , 5 * 60 * 1000
  , 5 * 60 * 1000

What do I need to change? 我需要改变什么?

Use node-cron. 使用node-cron。

$ npm install --save cron time

And your script should look like this: 你的脚本应该是这样的:

# Description:
#   Defines periodic executions

module.exports = (robot) ->
  cronJob = require('cron').CronJob
  tz = 'America/Los_Angeles'
  new cronJob('0 0 9 * * 1-5', workdaysNineAm, null, true, tz)
  new cronJob('0 */5 * * * *', everyFiveMinutes, null, true, tz)

  room = 12345678

  workdaysNineAm = ->
    robot.emit 'slave:command', 'wake everyone up', room

  everyFiveMinutes = ->
    robot.messageRoom room, 'I will nag you every 5 minutes'

More details: https://leanpub.com/automation-and-monitoring-with-hubot/read#leanpub-auto-periodic-task-execution 更多细节: https//leanpub.com/automation-and-monitoring-with-hubot/read#leanpub-auto-periodic-task-execution

Actually the hubot documentation shows the usage of setInterval() and setTimeout() without the use of extra modules. 实际上, hubot文档显示了setInterval()setTimeout()的用法,而没有使用额外的模块。

You could even do it inline by binding onto the msg object. 您甚至可以通过绑定到msg对象来内联。 For example this: 例如:

module.exports = (robot) ->
  updateId = null

  robot.respond /start/i, (msg) ->
      msg.update = () ->                        # this is your update
          console.log "updating"                # function

      if not this.updateId                      # and here it
          this.updateId = setInterval () ->     # gets
             msg.update()                       # periodically
          , 60*1000                             # triggered minutely
          msg.send("starting")

The real issue is that you are trying to use msg.send without a message object. 真正的问题是你试图在没有消息对象的情况下使用msg.send You should instead replace that line with a robot.messageRoom command (or some equivalent command if you want to send a private message). 您应该使用robot.messageRoom命令替换该行(或者如果要发送私人消息,则替换一些等效命令)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM