1
module.exports = (robot) ->
  robot.respond /log (.*)/i, (msg) ->
    group = "test"
    incident_message = msg.match[0]
    service_key = keys[group]
    curtime = new Date().getTime()
    incident_key = "hubot/#{curtime}"
    reporter = msg.message.user.name
    query = {
      "service_key": service_key,
      "incident_key": incident_key,
      "event_type": "trigger",
      "description": "Change Log #{reporter}",
      "details": "#{incident_message}"
    }
    string_query = JSON.stringify(query)
    content_length = string_query.length
    msg
      .http("https://events.pagerduty.com/generic/2010-04-15/create_event.json")
      .headers
      "Content-type": "application/json",
      "Content-length": content_length
      .post(string_query) (err, res, body) ->
      result = JSON.parse(body)
      if result.status == "success"
        msg.send "Your log has been sent"
      else
        msg.send "There was an error sending your log."
    msg
      .http("https://xyz.pagerduty.com/api/v1/incidents/#{incident_key}/acknowledge")

我正在尝试自动确认在 pagerduty 中触发的事件。第一个http请求生效。但是第二个 http 请求(代码的最后一行)永远不会生效。我尝试过 varipus 组合。但这无济于事。我是coffeescript的新手,只将它用于hubot。有人可以帮助我吗?

4

1 回答 1

2

首先,您没有指定您正在执行的 HTTP 操作:

msg.http("https://xyz.pagerduty.com/api/v1/incidents/#{incident_key}/acknowledge")

应该以.get()or结尾.post()

此外,可能是由于粘贴不良,如果在中间有点偏离,您的缩进:

  .post(string_query) (err, res, body) ->
  result = JSON.parse(body)
  if result.status == "success"
    msg.send "Your log has been sent"
  else
    msg.send "There was an error sending your log."

应该:

  .post(string_query) (err, res, body) ->
    result = JSON.parse(body)
    if result.status == "success"
      msg.send "Your log has been sent"
    else
      msg.send "There was an error sending your log."

另一件事,由于 NodeJS 的性质,这些 HTTP 调用是异步进行的,并且很有可能第二次调用在第一次调用之前完成。为避免这种情况,请从第一个回调中运行第二个请求:

msg
  .http("https://events.pagerduty.com/generic/2010-04-15/create_event.json")
  .headers
  "Content-type": "application/json",
  "Content-length": content_length
  .post(string_query) (err, res, body) ->
    result = JSON.parse(body)
    if result.status == "success"
      msg.send "Your log has been sent"
      msg
        .http("https://xyz.pagerduty.com/api/v1/incidents/#{incident_key}/acknowledge")
        .get()
    else
      msg.send "There was an error sending your log."

您可以在此处找到一些 Hubot HTTP 请求和其他脚本技巧的示例。

于 2014-03-07T10:48:47.780 回答