---
# System prepended metadata

title: Untitled

---

```
import json
import traceback
from datetime import datetime

import requests

from lifeguard import NORMAL
from lifeguard import WARNING
from lifeguard import CRITICAL
from lifeguard import PROBLEM
from lifeguard.infrastructure.mongodb import (
    read_last_notification,
    read_settings,
    update_notification,
)
from lifeguard.json import converter
from lifeguard.logger import lifeguard_logger as logger
from lifeguard.settings import (
    EXTERNAL_PROXY,
    LIFEGUARD_ENV,
    SKIP_PROXY,
    TEAMS_CHAT_URL,
    status_link,
)

PROXIES = {"https": EXTERNAL_PROXY}
TEXT_WHEN_HEALTH_IS_NORMAL = "Parece que a situação da validação: <b>{}</b> foi normalizada.<br>Detalhes: {} </a><br><div style=\"border-radius: 25px;width:70px; text-align: center; border: 1px solid #5cb85c;float:right;margin-top: -40px\"><p style=\"color:#b32d00;\">{}</p></div>"
TEXT_WHEN_HEALTH_IS_WARNING = "Parece que a validação: <b>{}</b> encontrou um problema.<br>Detalhes: {}</a><br><div style='border-radius: 25px;width:70px; text-align: center; border: 1px solid #b32d00;float:right;margin-top: -40px'><p style='color:#f0ad4e;'>{}</p></div>"
TEXT_WHEN_HEALTH_IS_PROBLEM = "<div>Parece que a validação: <b>{}</b> encontrou um problema.<br>Detalhes: {}</a><br><div style='border-radius: 25px;width:70px; text-align: center; border: 1px solid #b32d00;float:right;margin-top: -40px'><p style='color:#b32d00;'>{}</p></div>"
TEXT_WHEN_HEALTH_IS_CRITICAL = "<div>Parece que a validação: <b>{}</b> encontrou um problema.<br>Detalhes: {}</a><br><div style='border-radius: 25px;width:70px; text-align: center; border: 1px solid #b32d00;float:right;margin-top: -40px'><p style='color:#b32d00;'>{}</p></div>"
problem = "<div> Parece que a validação <b>check_etcd_connection</b> encontrou um problema. <br>Detalhes: </a><br> <div style=\"border-radius: 25px;width:70px; text-align: center; border: 1px solid #b32d00;float:right;margin-top: -40px\"> <p style=\"color:#b32d00;\">Crítico</p> </div> </div>"

def notify(notification_settings, bot_message, health_response):
    headers = {"Content-Type": "text/html; charset=UTF-8"}

    group_url = TEAMS_CHAT_URL
    if notification_settings["staging"]:
        return

    request_args = {
        "url": group_url,
        "headers": headers,
        "data": bot_message,
    }

    if not SKIP_PROXY:
        request_args["proxies"] = PROXIES

    response = requests.post(**request_args)
    content = response.content.decode("utf-8")

    update_notification(health_response.health, "notify_teams", health_response.status)
    logger.info("teams notification response %s: %s", response.status_code, content)


def notify_teams(health_response):
    if LIFEGUARD_ENV != "production":
        return

    try:
        logger.info("notify teams in production")
        notification_settings = read_settings(health_response.health)["notification"]
        last_notification = read_last_notification(
            health_response.health, "notify_teams"
        )

        bot_message = None
        current_status = NORMAL
        delta = datetime.now() - datetime.min

        if last_notification:
            delta = datetime.now() - last_notification["sent_at"]
            current_status = last_notification["status"]

        # when normal
        if health_response.status == NORMAL and current_status != NORMAL:
            logger.info("teams: closing notification")
            bot_message = TEXT_WHEN_HEALTH_IS_NORMAL.format(
                health_response.health, status_link(health_response.health), NORMAL
                )

        # when warning
        if (
            notification_settings["when"] == health_response.status
            and notification_settings["interval"] <= delta.seconds
        ):
            logger.info("teams: opening notification")
            prefix = TEXT_WHEN_HEALTH_IS_WARNING.format(
                health_response.health
            )

            text = "{}<br>Detalhes: <a>{}</a><br>".format(
                prefix, status_link(status_link(health_response.health), status_link(health_response.health), WARNING)
            )

        # when problem
        if health_response.status == PROBLEM:
            logger.info("teams: opening PROBLEM notification")
            text =  TEXT_WHEN_HEALTH_IS_PROBLEM.format(
                health_response.health, status_link(health_response.health), PROBLEM
                )
            bot_message = text

        # when critical
        if health_response.status == CRITICAL:
            text = TEXT_WHEN_HEALTH_IS_CRITICAL.format(
                status_link(health_response.health), status_link(health_response.health), CRITICAL
                )
            bot_message = text

        if bot_message:
            notify(notification_settings, bot_message, health_response)

    except Exception as exception:
        logger.error(
            "error on execute notify_group action",
            extra={"traceback": traceback.format_exc()},
        )
```