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: https://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.



49
50
51
52
53
54
55
# File 'lib/msteams_hermes/message.rb', line 49

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.



47
48
49
# File 'lib/msteams_hermes/message.rb', line 47

def content
  @content
end

#webhook_urlObject (readonly)

Returns the value of attribute webhook_url.



47
48
49
# File 'lib/msteams_hermes/message.rb', line 47

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



90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/msteams_hermes/message.rb', line 90

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



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/msteams_hermes/message.rb', line 65

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)

    return response if response_from_mst_workflow_webhook?(response) ||
                       response_from_mst_connector_webhook?(response)

    raise MessageBodyTooLargeError, body_json.bytesize if message_too_large?(response)

    raise UnknownError, response.body
  end
end