繁体   English   中英

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

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

我正在尝试为hubot制作一个函数,每隔5分钟向一个房间发送一条消息而没有任何命令,只需要他自己。

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

我需要改变什么?

使用node-cron。

$ npm install --save cron time

你的脚本应该是这样的:

# 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'

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

实际上, hubot文档显示了setInterval()setTimeout()的用法,而没有使用额外的模块。

您甚至可以通过绑定到msg对象来内联。 例如:

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")

真正的问题是你试图在没有消息对象的情况下使用msg.send 您应该使用robot.messageRoom命令替换该行(或者如果要发送私人消息,则替换一些等效命令)。

暂无
暂无

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

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