Coffeescript 在hubot coffescript中同时调用2个https请求

Coffeescript 在hubot coffescript中同时调用2个https请求,coffeescript,hubot,Coffeescript,Hubot,我正在尝试自动确认pagerduty中触发的事件。第一个http请求生效。但是第二个http请求(代码的最后一行)从未生效。我试过varipus组合。但这没有帮助。我不熟悉coffeescript,只在hubot中使用它。有人能帮我吗?首先,您不需要指定您正在执行的HTTP操作: module.exports = (robot) -> robot.respond /log (.*)/i, (msg) -> group = "test" incident_messa

我正在尝试自动确认pagerduty中触发的事件。第一个http请求生效。但是第二个http请求(代码的最后一行)从未生效。我试过varipus组合。但这没有帮助。我不熟悉coffeescript,只在hubot中使用它。有人能帮我吗?

首先,您不需要指定您正在执行的HTTP操作:

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")
应该以
.get()
.post()
结尾

另外,可能是由于粘贴不好,如果缩进在中间有点脱落:

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

  .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."
另一件事,由于NodeJ的性质,这些HTTP调用是异步进行的,并且很有可能第二个调用在第一个调用之前完成。要避免这种情况,请从第一个请求的回调运行第二个请求:

  .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."
您可以找到一些Hubot 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."