Class: Slackwebhook

Inherits:
Object
  • Object
show all
Defined in:
lib/slackwebhook.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(webhook) ⇒ Slackwebhook

Returns a new instance of Slackwebhook.



13
14
15
16
17
18
19
20
21
22
23
# File 'lib/slackwebhook.rb', line 13

def initialize(webhook)
  #Output Variable to see th output of the scan
  @output = ""
  #Check the url and assign it
  @webhook = check_url(webhook)
  #Headers to set for the slack post request
  @headers = {'Content-Type': 'text/json'}
  #Type of request to send to the hook
  @type = "normal"

end

Instance Attribute Details

#headersObject

Returns the value of attribute headers.



9
10
11
# File 'lib/slackwebhook.rb', line 9

def headers
  @headers
end

#outputObject (readonly)

Returns the value of attribute output.



10
11
12
# File 'lib/slackwebhook.rb', line 10

def output
  @output
end

#typeObject

Returns the value of attribute type.



9
10
11
# File 'lib/slackwebhook.rb', line 9

def type
  @type
end

#webhookObject

Returns the value of attribute webhook.



9
10
11
# File 'lib/slackwebhook.rb', line 9

def webhook
  @webhook
end

Instance Method Details

#check_url(webhook) ⇒ Object



57
58
59
60
61
62
# File 'lib/slackwebhook.rb', line 57

def check_url(webhook)
  #Parse url
  uri = URI.parse(webhook)
  # If parsing of url and host of the url matches the hooks.slack.com then return url
  (webhook =~ URI::regexp && uri.host == "hooks.slack.com") ? uri : error("Invalid URL")
end

#data_format(data) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/slackwebhook.rb', line 39

def data_format(data)
  #format the message depend upon the type field
  @body = {}   
  case @type.downcase
  when 'info'
    @body[:attachments] = [{color: "#0FF612",text: data}]
  when 'warning'
    @body[:attachments] = [{color: "#F2F60F",text: data}]
  when 'alert'
    @body[:attachments] = [{color: "#e33d3b",text: data}]
  else
    @body[:text] = data
  end
  puts @body
  @body

end

#error(text) ⇒ Object



64
65
66
67
68
69
# File 'lib/slackwebhook.rb', line 64

def error(text)
  #Display the error
  puts "[-] #{text}. Check the url documentation: https://api.slack.com/incoming-webhooks"
  #assing to output variable
  @output = text
end

#send=(data) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/slackwebhook.rb', line 25

def send=(data)
  #Set the https request
  https = Net::HTTP.new(@webhook.host, @webhook.port)
  https.use_ssl = true
  #Set the hearders and path for the request
  request = Net::HTTP::Post.new(@webhook.request_uri, @header)
  #set the output message
  request.body = data_format(data).to_json
  #send the request and assing the response to output variable
  @output = https.request(request)
  puts @output.code
end