记录一下, 直接上代码:
相关API文档:https://api.slack.com/
def self.add_ann(group, user, title, url, desc, slack_info_id= nil, color= '#ffba01')
team_url= $HOST + "/team/#{group.g_name}"
title= title.gsub('"', "\\\"")
desc= desc.gsub('"', "\\\"")
desc= "\\\"" + desc + "\\\""
content = PlainText.plain_text(desc)
format= "{
\"text\": \"*#{user.name}* made a highlight on <#{url}|#{title}> \",
\"attachments\": [{
\"fallback\": \"*#{user.name}* <#{url}|#{title}>\",
\"text\": \"#{content}\",
\"color\": \"#{color}\"
}]
}"
msg= {:payload=> format}
send_ann_slack_message(group.id, user.id, slack_info_id, msg)
end
def self.send_ann_slack_message(group_id, user_id, slack_info_id, msg)
api_urls= []
if !slack_info_id.blank?
slack_info= get_group_slack_info_by_id(slack_info_id)
api_urls << slack_info.slack_incoming_webhook_url if !slack_info.blank?
else
slack_info= get_group_slack_info_by_status(group_id, [STATUS_SEND_ANN, STATUS_SEND_POST_AND_ANN])
slack_info.each do |v|
api_urls << v.slack_incoming_webhook_url
end
end
api_urls.each do |slack_incoming_webhook_url|
slack_ret= http_request(slack_incoming_webhook_url, msg)
end
end
private
def self.http_request(url, params, json= false)
Timeout::timeout($REQUEST_TIME) {
agent = Mechanize.new
uri = url
page = agent.post(uri, params)
if json== true
r = page.body ? JSON.parse(page.body): nil
return r
end
return page.body
}
rescue Timeout::Error
#p "http_request timeout."
Rails.logger.error "http request timeout. "
nil
rescue => e
#p "http_request error.", e
Rails.logger.error "http request error. #{e.inspect}"
nil
end