lib/dingbot/client.rb in dingbot-0.2.3 vs lib/dingbot/client.rb in dingbot-0.2.5

- old
+ new

@@ -1,6 +1,7 @@ require 'httparty' +require 'json' require 'dingbot/configuration' require 'dingbot/message/base' require 'dingbot/message/text' require 'dingbot/message/markdown' @@ -10,11 +11,12 @@ include HTTParty format :json headers "Content-Type" => "application/json" - attr_accessor :access_token + # attr_accessor :access_token + # attr_accessor :secret # @private attr_accessor(*Configuration::VALID_OPTIONS_KEYS) # Creates a new API. @@ -41,11 +43,24 @@ rescue JSON::ParserError raise Error::Parsing.new "The response is not a valid JSON" end def send_msg(message) - validate self.class.post(@endpoint, {query: {access_token: @access_token}, body: message.to_json}) + query = { + access_token: @access_token, + } + + if !@secret.nil? and !@secret.empty? + timestamp = (Time.now.to_f * 1000).to_i + + query.merge!({ + timestamp: timestamp, + sign: Base64.encode64(OpenSSL::HMAC.digest(OpenSSL::Digest.new('sha256'), @secret, "#{timestamp}\n#{@secret}")).strip + }) + end + + validate self.class.post(@endpoint, { query: query, body: message.to_json }) end def send_text(content) message = DingBot::Message::Text.new(content) send_msg(message) @@ -81,11 +96,15 @@ when 503 then Error::ServiceUnavailable end fail error_klass.new(response) if error_klass - parsed = response.parsed_response + + body = JSON.parse(response.body) + errcode = body["errcode"] + fail body["errmsg"] if errcode != 0 + parsed.client = self if parsed.respond_to?(:client=) parsed.parse_headers!(response.headers) if parsed.respond_to?(:parse_headers!) parsed end