rveachkc / pymsteams

Format messages and post to Microsoft Teams.
https://pypi.org/project/pymsteams/
Apache License 2.0
428 stars 79 forks source link

0.2.1 issue with last_http_status #122

Closed mguyre closed 2 years ago

mguyre commented 2 years ago

I am using the following code to send teams messages def send_to_teams(webhook, title, message): if webhook == None: return False connector = pymsteams.connectorcard(webhook) connector.title(title + ' on ' + node_name) connector.text(message) section2 = pymsteams.cardsection() section2.text(datetime.now(timezone.utc).strftime(tm_fmt) + " UTC") connector.addSection(section2) connector.send() if connector.last_http_status.status_code != requests.codes.ok: nm.log_warning('Error posting to Teams ' + connector.last_http_status.status_code.reason) return False nm.log_info('Posted to Teams title: {}, message: {}'.format(title, message)) return True

With version 0.2.1, I get a runtime error File "./test.py", line 194, in send_to_teams if connector.last_http_status.status_code != requests.codes.ok: AttributeError: 'connectorcard' object has no attribute 'last_http_status'

rveachkc commented 2 years ago

Without being put in a code block, your code is difficult to read. I'm not sure why it's failing, but that's probably because it's executing in a way that connector.send() has not run, therefore, that class attribute has not been set yet.

You don't need to compare the status code, because pymsteams already does it for you: https://github.com/rveachkc/pymsteams/blob/b8d2d847df171911c4d2eb7d3fedaa52c9093cd8/pymsteams/__init__.py#L231-L246

It'll raise a TeamsWebhookException if it's not successful.

For your send call, you can do something like this:

try:
    connector.send()
except pymsteams.TeamsWebhookException:
    nm.log_warning('Error posting to Teams ' + connector.last_http_status.status_code.reason)
    return False
michaeladams commented 2 years ago

For anyone else finding this - it looks like last_http_status is now last_http_response in 2.x, and may be the issue in the code block in the original post.