Class: MsTeamsHermes::Message

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

Overview

Defined Under Namespace

Classes: MessageBodyTooLargeError, UnknownError

Constant Summary collapse

MSTEAMS_MESSAGE_SIZE_LIMIT =

Docu says: ‘The message size limit is 28 KB’, but testing aligned with 21KB. See: learn.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/add-incoming-webhook

21_000
MSTEAMS_MESSAGE_413_ERROR_TOKEN =
"returned HTTP error 413"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(content:, webhook_url: ENV["WEBHOOK_URL"]) ⇒ Message

Returns a new instance of Message.



40
41
42
43
44
45
46
# File 'lib/msteams_hermes/message.rb', line 40

def initialize(content:, webhook_url: ENV["WEBHOOK_URL"])
  @webhook_url = webhook_url
  @content = content

  raise "Message `webhook_url` cannot be empty" if @webhook_url.nil?
  raise "Message `content` must be an AdaptiveCard" unless @content.is_a? Components::AdaptiveCard
end

Instance Attribute Details

#contentObject (readonly)

Returns the value of attribute content.



38
39
40
# File 'lib/msteams_hermes/message.rb', line 38

def content
  @content
end

#webhook_urlObject (readonly)

Returns the value of attribute webhook_url.



38
39
40
# File 'lib/msteams_hermes/message.rb', line 38

def webhook_url
  @webhook_url
end

Instance Method Details

#body_jsonObject

Formats the JSON object to be set on the HTTP request

Returns:

  • a JSON object



84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/msteams_hermes/message.rb', line 84

def body_json
  {
    type: "message",
    attachments: [
      {
        contentType: "application/vnd.microsoft.card.adaptive",
        contentUrl: nil,
        content: content.to_hash
      }
    ]
  }.to_json
end

#deliverObject

rubocop:disable Metrics/AbcSize rubocop:disable Metrics/MethodLength

Sends a HTTP request to the webhook URL specified via either environment variable or when initializing the class

Returns:

  • a Net::HTTP response object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/msteams_hermes/message.rb', line 56

def deliver
  uri = URI.parse(webhook_url)
  Net::HTTP.start(uri.host, uri.port, use_ssl: true, verify_mode: OpenSSL::SSL::VERIFY_NONE) do |http|
    req = Net::HTTP::Post.new(uri)
    req.body = body_json
    req["Content-Type"] = "application/json"

    response = http.request(req)

    # For details see:
    # https://learn.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/connectors-using?tabs=cURL%2Ctext1#send-messages-using-curl-and-powershell
    if response.body != "1"
      raise MessageBodyTooLargeError, body_json.bytesize if response.body.include? MSTEAMS_MESSAGE_413_ERROR_TOKEN

      raise UnknownError, response.body
    end

    response
  end
end