Module: Slack::Post
- Defined in:
- lib/slack/post.rb,
lib/slack/post/version.rb
Constant Summary collapse
- DefaultOpts =
{ channel: '#general' }.freeze
- NecessaryConfigParams =
[:subdomain,:token].freeze
- KnownConfigParams =
[:username,:channel,:subdomain,:token,:icon_url,:icon_emoji].freeze
- VERSION =
"0.1.0"
Class Method Summary collapse
- .config ⇒ Object
- .configure(opts) ⇒ Object
- .configured?(needs_channel = true) ⇒ Boolean
- .post(message, chan = nil, opts = {}) ⇒ Object
- .post_url ⇒ Object
- .prune(opts) ⇒ Object
Class Method Details
.config ⇒ Object
59 60 61 |
# File 'lib/slack/post.rb', line 59 def self.config @config ||= DefaultOpts end |
.configure(opts) ⇒ Object
63 64 65 |
# File 'lib/slack/post.rb', line 63 def self.configure(opts) @config = config.merge(prune(opts)) end |
.configured?(needs_channel = true) ⇒ Boolean
52 53 54 55 56 57 |
# File 'lib/slack/post.rb', line 52 def self.configured?(needs_channel=true) return false if needs_channel and !config[:channel] NecessaryConfigParams.all? do |parm| config[parm] end end |
.post(message, chan = nil, opts = {}) ⇒ Object
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/slack/post.rb', line 14 def self.post(,chan=nil,opts={}) raise "You need to call Slack::Post.configure before trying to send messages." unless configured?(chan.nil?) pkt = { channel: chan || config[:channel], text: , } if config[:username] pkt[:username] = config[:username] end if opts.has_key?(:icon_url) or config.has_key?(:icon_url) pkt[:icon_url] = opts[:icon_url] || config[:icon_url] end if opts.has_key?(:icon_emoji) or config.has_key?(:icon_emoji) pkt[:icon_emoji] = opts[:icon_emoji] || config[:icon_emoji] end uri = URI.parse(post_url) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.ssl_version = :TLSv1 http.verify_mode = OpenSSL::SSL::VERIFY_PEER req = Net::HTTP::Post.new(uri.request_uri) req.body = Yajl::Encoder.encode(pkt) req["Content-Type"] = 'application/json' resp = http.request(req) case resp when Net::HTTPSuccess return true else raise "There was an error while trying to post. Error was: #{resp.body}" end end |
.post_url ⇒ Object
46 47 48 |
# File 'lib/slack/post.rb', line 46 def self.post_url "https://#{config[:subdomain]}.slack.com/services/hooks/incoming-webhook?token=#{config[:token]}" end |
.prune(opts) ⇒ Object
69 70 71 72 73 74 75 76 77 |
# File 'lib/slack/post.rb', line 69 def self.prune(opts) opts.inject({}) do |acc,(k,v)| k = k.to_sym if KnownConfigParams.include?(k) acc[k] = v end acc end end |