发布请求松弛端点失败

时间:2017-04-28 13:31:02

标签: ruby curl slack

我已经在Ruby中发布了一个关于松散端点的帖子请求并且它失败了,这是我的请求,不知道我缺少什么:

#!/usr/bin/env ruby
#Notification Script Test

def send_slack_message
    slack_rooms = [ '#test_channel_notify' ]
    slack_token_file = (File.join(ENV['HOME'], '.slack_api_token'))
    slack_api_token = (File.open(@slack_token_file).readlines)[0].chomp
    msg = 'This is a test message send'
    slack_url = "https://slack.com/api/chat.postMessage"
    %x{curl -k -X POST -d"token=#{slack_api_token}\&channel=#{slack_rooms}\&text=#{msg}" '#{slack_url}'} 
end

send_slack_message

我收到以下错误,不确定我错过了什么:

./cap2.rb:7:in `initialize': no implicit conversion of nil into String (TypeError)
from ./cap2.rb:7:in `open'
from ./cap2.rb:7:in `send_slack_message'
from ./cap2.rb:13:in `<main>'

我是一个红宝石新手所以我可能会错过一切都会喜欢一些帮助!

3 个答案:

答案 0 :(得分:2)

错误表示您无法将nil提交给File.open。确保@slack_token_file存在且不是零。

答案 1 :(得分:1)

松弛的API希望以这种格式接收有效载荷:'payload = {“json”:“data”}' 使用Net :: HTTP,您可以发出如下的POST请求:

require 'net/http'
require 'uri'

def payload(message, channel)
  { channel: channel, username: 'your-username', text: message, icon_emoji: ':robot_face:' }
end

msg = 'This is a test message send'
body = payload(msg, '#test_channel_notify').to_json

url = URI("https://slack.com/api/chat.postMessage")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Post.new(url)
request.body = "payload=#{body}"
http.request(request)

答案 2 :(得分:0)

虽然您的原始问题已经解决,但我将提供替代解决方案,该解决方案遵循更常见的存储秘密凭据as environment variables, not as files的做法(例如,可以更容易地通过事故,致力于源头控制,pasted to a presentation等。

在您的环境中设置SLACK_TOKEN,然后使用:

#!/usr/bin/env ruby
#Notification Script Test

def send_slack_message
    slack_rooms = [ '#test_channel_notify' ]
    slack_api_token = ENV['SLACK_TOKEN']
    msg = 'This is a test message send'
    slack_url = "https://slack.com/api/chat.postMessage"
    %x{curl -k -X POST -d"token=#{slack_api_token}\&channel=#{slack_rooms}\&text=#{msg}" '#{slack_url}'} 
end

send_slack_message