我想在不使用Slack客户端的情况下通知Slack通道(不要问为什么):
#!/usr/bin/env ruby
#Notification Script Test
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
slack_url = "https://slack.com/api/chat.postMessage"
user = testuser
msg = 'This is a test message send'
data = {
"token" => slack_api_token,
"channel" => slack_rooms,
"text" => msg,
"username" => user
}
def send_slack_message(data)
puts %x{curl -k -X POST -d" #{data}" '#{slack_url}'}
end
send_slack_message(data)
但是我遇到了一些奇怪的错误:
./Cap2.rb:21: syntax error, unexpected end-of-input, expecting ')'
send_slack_message(data)
有人指出我错过了)
变量之后的结束slack_token_file
:
#!/usr/bin/env ruby
#Notification Script Test
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'
data = {
"token" => slack_api_token,
"channel" => slack_rooms,
"text" => msg,
}
def send_slack_message(data)
slack_url = "https://slack.com/api/chat.postMessage"
%x{curl -k -X POST -d" #{data}" '#{slack_url}'}
end
send_slack_message(data)
结果是:
% Total % Received % Xferd Average Speed Time Time Time
Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- 0:00:50 --:--:-- 0
当我现在运行脚本时,它会挂起Curl命令。有没有人有使用Slack API端点的经验?
答案 0 :(得分:0)
您创建发送数据的方式看起来并不正确。根据{{3}},它应该是JSON格式:
slack_rooms = ['#test_channel_notify']
slack_token_file = 'slack_token_file'
slack_api_token = 'slack_api_token'
msg = 'This is a test message send'
data = {
"token" => slack_api_token,
"channel" => slack_rooms,
"text" => msg,
}
slack_url = "https://slack.com/api/chat.postMessage"
%{curl -k -X POST -d" #{data}" '#{slack_url}'}
# => "curl -k -X POST -d\" {\"token\"=>\"slack_api_token\", \"channel\"=>[\"#test_channel_notify\"], \"text\"=>\"This is a test message send\"}\" 'https://slack.com/api/chat.postMessage'"
您的代码正在创建的内容。
require 'json'
%{curl -k -X POST -d" #{data.to_json}" '#{slack_url}'}
# => "curl -k -X POST -d\" {\"token\":\"slack_api_token\",\"channel\":[\"#test_channel_notify\"],\"text\":\"This is a test message send\"}\" 'https://slack.com/api/chat.postMessage'"
这是Slack的API所期望的。
我建议不要在子shell中使用curl,而是建议利用Ruby的the documentation之一。