> ## Documentation Index
> Fetch the complete documentation index at: https://avala.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Alertas e notificações

> Roteamento de alertas para Slack, e-mail e webhooks

Receba notificações quando as condições da frota mudarem. Configure canais de alerta, defina regras de roteamento e gerencie o ciclo de vida do alerta -- da detecção ao reconhecimento e à resolução -- para que os problemas cheguem às pessoas certas no momento certo.

> [!NOTE]
>
> O Fleet Management está em versão prévia. As APIs e os recursos descritos nesta página podem mudar.

## Canais de alerta

Um canal de alerta é um destino configurado para notificações. Crie canais para cada via de comunicação que sua equipe usa e, em seguida, referencie-os em [regras de gravação](https://avala.ai/docs/pt/visualization/fleet/recording-rules.md) e políticas de alerta.

| Canal | Configuração | Caso de uso |
| - | - | - |
| **Slack** | URL do webhook + nome do canal | Notificações para toda a equipe, canais de plantão |
| **E-mail** | Endereços de e-mail dos destinatários | Alertas individuais, resumos gerenciais |
| **Webhook** | URL do endpoint + segredo de assinatura | Integrações personalizadas, PagerDuty, Opsgenie |
| **No aplicativo** | Automático (sem configuração) | Notificações no painel para todos os membros da organização |

> [!TIP]
>
> As notificações no aplicativo estão sempre ativadas. Todo alerta disparado aparece no sino de notificações em Mission Control, independentemente das configurações dos outros canais.

### Criar um canal do Slack

```python Python theme={null}
from avala import Client

client = Client()

channel = client.fleet.alerts.channels.create(
    type="slack",
    name="Robotics Alerts",
    config={
        "webhook_url": "https://hooks.slack.com/services/T00/B00/xxxx",
        "channel": "#robotics-alerts",
        "username": "Avala Fleet Bot",
        "icon_emoji": ":robot_face:"
    }
)

print(f"Channel created: {channel.name} ({channel.uid})")
```

```typescript TypeScript theme={null}
import Avala from "@avala-ai/sdk";

const avala = new Avala();

const channel = await avala.fleet.alerts.channels.create({
  type: "slack",
  name: "Robotics Alerts",
  config: {
    webhook_url: "https://hooks.slack.com/services/T00/B00/xxxx",
    channel: "#robotics-alerts",
    username: "Avala Fleet Bot",
    icon_emoji: ":robot_face:",
  },
});

console.log(`Channel created: ${channel.name} (${channel.uid})`);
```

```bash CLI theme={null}
avala fleet alerts channels create \
  --type slack \
  --name "Robotics Alerts" \
  --config '{"webhook_url": "https://hooks.slack.com/services/T00/B00/xxxx", "channel": "#robotics-alerts"}'
```

### Criar um canal de e-mail

```python Python theme={null}
channel = client.fleet.alerts.channels.create(
    type="email",
    name="Engineering Leads",
    config={
        "recipients": ["lead@example.com", "oncall@example.com"],
        "subject_prefix": "[Fleet Alert]"
    }
)
```

```typescript TypeScript theme={null}
const channel = await avala.fleet.alerts.channels.create({
  type: "email",
  name: "Engineering Leads",
  config: {
    recipients: ["lead@example.com", "oncall@example.com"],
    subject_prefix: "[Fleet Alert]",
  },
});
```

```bash CLI theme={null}
avala fleet alerts channels create \
  --type email \
  --name "Engineering Leads" \
  --config '{"recipients": ["lead@example.com", "oncall@example.com"]}'
```

### Criar um canal de webhook

Os canais de webhook enviam uma requisição HTTP POST ao seu endpoint com a carga do alerta. Use um segredo de assinatura para verificar se as requisições se originam da Avala.

```python Python theme={null}
channel = client.fleet.alerts.channels.create(
    type="webhook",
    name="PagerDuty Integration",
    config={
        "url": "https://events.pagerduty.com/v2/enqueue",
        "signing_secret": "whsec_your_signing_secret",
        "headers": {
            "Content-Type": "application/json"
        }
    }
)
```

```typescript TypeScript theme={null}
const channel = await avala.fleet.alerts.channels.create({
  type: "webhook",
  name: "PagerDuty Integration",
  config: {
    url: "https://events.pagerduty.com/v2/enqueue",
    signing_secret: "whsec_your_signing_secret",
    headers: {
      "Content-Type": "application/json",
    },
  },
});
```

### Carga do webhook

Os canais de webhook entregam uma carga JSON com a seguinte estrutura:

```json theme={null}
{
  "uid": "alt_abc123",
  "rule_id": "rul_def456",
  "rule_name": "High Latency Alert",
  "severity": "warning",
  "status": "open",
  "device": {
    "uid": "dev_ghi789",
    "name": "robot-arm-01"
  },
  "recording": {
    "uid": "rec_jkl012",
    "url": "https://avala.ai/recordings/rec_jkl012"
  },
  "message": "High latency detected: 142ms (threshold: 100ms)",
  "metadata": {
    "latency_ms": 142,
    "threshold_ms": 100,
    "topic": "/diagnostics/latency"
  },
  "triggered_at": "2026-01-15T10:30:00Z"
}
```

> [!TIP]
>
> Para verificar a autenticidade do webhook, calcule um HMAC-SHA256 do corpo da requisição usando seu segredo de assinatura e compare-o com o cabeçalho `X-Avala-Signature`. Consulte o [guia de integração de webhooks](https://avala.ai/docs/pt/integrations/webhooks.md) para ver exemplos de implementação.

### Testar um canal

Envie uma notificação de teste para verificar a configuração do canal antes de associá-lo às regras.

```python Python theme={null}
result = client.fleet.alerts.channels.test(channel_id="ch_abc123")

if result.success:
    print("Test notification sent successfully")
else:
    print(f"Test failed: {result.error}")
```

```typescript TypeScript theme={null}
const result = await avala.fleet.alerts.channels.test({ channelId: "ch_abc123" });

if (result.success) {
  console.log("Test notification sent successfully");
} else {
  console.log(`Test failed: ${result.error}`);
}
```

```bash CLI theme={null}
avala fleet alerts channels test ch_abc123
```

### Listar e gerenciar canais

```python Python theme={null}
# List all channels
channels = client.fleet.alerts.channels.list()
for ch in channels:
    print(f"{ch.name} ({ch.type}) -- {ch.uid}")

# Update a channel
client.fleet.alerts.channels.update(
    channel_id="ch_abc123",
    name="Robotics Alerts (Updated)",
    config={"channel": "#robotics-alerts-v2"}
)

# Delete a channel
client.fleet.alerts.channels.delete(channel_id="ch_abc123")
```

```typescript TypeScript theme={null}
const channels = await avala.fleet.alerts.channels.list();
for (const ch of channels.items) {
  console.log(`${ch.name} (${ch.type}) -- ${ch.uid}`);
}

await avala.fleet.alerts.channels.update({
  channelId: "ch_abc123",
  name: "Robotics Alerts (Updated)",
  config: { channel: "#robotics-alerts-v2" },
});

await avala.fleet.alerts.channels.delete({ channelId: "ch_abc123" });
```

```bash CLI theme={null}
avala fleet alerts channels list
avala fleet alerts channels update ch_abc123 --name "Robotics Alerts (Updated)"
avala fleet alerts channels delete ch_abc123
```

> [!WARNING]
>
> Excluir um canal o remove de todas as regras e políticas de alerta que o referenciam. Essas regras continuarão sendo avaliadas, mas a ação `notify` direcionada ao canal excluído será ignorada. Atualize suas regras para referenciar outro canal antes de excluir.

## Regras de alerta

Os alertas são vinculados às [regras de gravação](https://avala.ai/docs/pt/visualization/fleet/recording-rules.md) por meio da ação `notify`. Quando a condição de uma regra de gravação é atendida, sua ação notify dispara um alerta para o canal especificado.

### Níveis de severidade

Configure a severidade na ação notify da regra de gravação para controlar como os alertas são exibidos e roteados.

| Severidade | Descrição | Comportamento padrão |
| - | - | - |
| `critical` | Requer atenção imediata | Todos os canais são notificados, com repetição a cada 5 minutos até o reconhecimento |
| `warning` | Precisa de investigação | Canais configurados são notificados uma vez |
| `info` | Informativo, nenhuma ação necessária | Somente notificação no aplicativo (a menos que seja roteado explicitamente para outros canais) |

```python Python theme={null}
# Recording rule with severity-based alert routing
rule = client.fleet.rules.create(
    name="Motor Overheat Critical",
    condition={
        "type": "threshold",
        "topic": "/sensors/temperature",
        "field": "temp_c",
        "operator": "gt",
        "value": 90
    },
    actions=[
        {"type": "create_event", "event_type": "error", "label": "Motor overheat"},
        {
            "type": "notify",
            "channel_id": "ch_slack_oncall",
            "severity": "critical",
            "message": "Motor temperature exceeded 90C -- immediate shutdown may be required"
        }
    ]
)
```

```typescript TypeScript theme={null}
const rule = await avala.fleet.rules.create({
  name: "Motor Overheat Critical",
  condition: {
    type: "threshold",
    topic: "/sensors/temperature",
    field: "temp_c",
    operator: "gt",
    value: 90,
  },
  actions: [
    { type: "create_event", eventType: "error", label: "Motor overheat" },
    {
      type: "notify",
      channelId: "ch_slack_oncall",
      severity: "critical",
      message: "Motor temperature exceeded 90C -- immediate shutdown may be required",
    },
  ],
});
```

### Políticas de escalonamento

Para alertas críticos, defina uma política de escalonamento que notifique canais adicionais se o alerta não for reconhecido dentro de um período especificado.

```python Python theme={null}
policy = client.fleet.alerts.policies.create(
    name="Critical Escalation",
    steps=[
        {
            "channel_id": "ch_slack_oncall",
            "wait": "5m"
        },
        {
            "channel_id": "ch_email_leads",
            "wait": "15m"
        },
        {
            "channel_id": "ch_webhook_pagerduty",
            "wait": None  # Final step, no further escalation
        }
    ]
)

# Attach policy to a rule's notify action
rule = client.fleet.rules.create(
    name="Critical System Failure",
    condition={
        "type": "absence",
        "topic": "/system/heartbeat",
        "timeout": "60s"
    },
    actions=[
        {
            "type": "notify",
            "policy_id": policy.uid,
            "severity": "critical"
        }
    ]
)
```

```typescript TypeScript theme={null}
const policy = await avala.fleet.alerts.policies.create({
  name: "Critical Escalation",
  steps: [
    { channelId: "ch_slack_oncall", wait: "5m" },
    { channelId: "ch_email_leads", wait: "15m" },
    { channelId: "ch_webhook_pagerduty", wait: null },
  ],
});

const rule = await avala.fleet.rules.create({
  name: "Critical System Failure",
  condition: {
    type: "absence",
    topic: "/system/heartbeat",
    timeout: "60s",
  },
  actions: [
    {
      type: "notify",
      policyId: policy.uid,
      severity: "critical",
    },
  ],
});
```

## Ciclo de vida do alerta

Todo alerta passa por um conjunto definido de estados. Você pode fazer a transição dos alertas manualmente por meio de SDK, CLI ou do painel.

```
open  -->  acknowledged  -->  resolved
  |                              ^
  +------------------------------+
          (auto-resolve)
```

| Estado | Descrição |
| - | - |
| `open` | A condição foi atendida e as notificações foram enviadas. O alerta está ativo e pode ser escalonado. |
| `acknowledged` | Um membro da equipe viu o alerta e está investigando. O escalonamento é pausado. |
| `resolved` | O problema foi tratado. O alerta está encerrado. |

### Reconhecer um alerta

Reconhecer um alerta interrompe o escalonamento e sinaliza para a equipe que alguém está investigando.

```python Python theme={null}
client.fleet.alerts.acknowledge(
    alert_id="alt_abc123",
    note="Investigating -- checking motor temperature logs"
)
```

```typescript TypeScript theme={null}
await avala.fleet.alerts.acknowledge({
  alertId: "alt_abc123",
  note: "Investigating -- checking motor temperature logs",
});
```

```bash CLI theme={null}
avala fleet alerts acknowledge alt_abc123 --note "Investigating -- checking motor temperature logs"
```

### Resolver um alerta

Marque um alerta como resolvido quando o problema subjacente tiver sido corrigido.

```python Python theme={null}
client.fleet.alerts.resolve(
    alert_id="alt_abc123",
    note="Fixed: firmware update applied to motor controller, temperature nominal"
)
```

```typescript TypeScript theme={null}
await avala.fleet.alerts.resolve({
  alertId: "alt_abc123",
  note: "Fixed: firmware update applied to motor controller, temperature nominal",
});
```

```bash CLI theme={null}
avala fleet alerts resolve alt_abc123 --note "Fixed: firmware update applied to motor controller"
```

### Resolução automática

Os alertas podem ser resolvidos automaticamente quando a condição que os acionou deixa de existir. Ative a resolução automática na ação de notificação da regra de gravação:

```python Python theme={null}
rule = client.fleet.rules.create(
    name="High CPU Usage",
    condition={
        "type": "threshold",
        "topic": "/system/diagnostics",
        "field": "cpu_percent",
        "operator": "gt",
        "value": 90,
        "window": "5m"
    },
    actions=[
        {
            "type": "notify",
            "channel_id": "ch_abc123",
            "severity": "warning",
            "auto_resolve": True,
            "resolve_after": "10m"
        }
    ]
)
```

```typescript TypeScript theme={null}
const rule = await avala.fleet.rules.create({
  name: "High CPU Usage",
  condition: {
    type: "threshold",
    topic: "/system/diagnostics",
    field: "cpu_percent",
    operator: "gt",
    value: 90,
    window: "5m",
  },
  actions: [
    {
      type: "notify",
      channelId: "ch_abc123",
      severity: "warning",
      autoResolve: true,
      resolveAfter: "10m",
    },
  ],
});
```

> [!TIP]
>
> Quando `auto_resolve` está ativado, o alerta passa para `resolved` após a duração `resolve_after` se a condição não corresponder mais. Se a condição for acionada novamente durante a janela de resolução, o alerta permanece no estado atual.

## Histórico de alertas

Veja alertas anteriores com seu ciclo de vida completo: quando foram disparados, quem os reconheceu e como foram resolvidos.

```python Python theme={null}
# List recent alerts
alerts = client.fleet.alerts.list(
    status="resolved",
    since="2026-01-01T00:00:00Z",
    until="2026-02-01T00:00:00Z"
)

for alert in alerts:
    print(f"[{alert.severity}] {alert.rule_name}")
    print(f"  Triggered: {alert.triggered_at}")
    print(f"  Acknowledged: {alert.acknowledged_at} by {alert.acknowledged_by}")
    print(f"  Resolved: {alert.resolved_at}")
    print(f"  Duration: {alert.duration}")
    print()

# Filter by severity
critical_alerts = client.fleet.alerts.list(severity="critical")

# Filter by device
device_alerts = client.fleet.alerts.list(device_id="dev_abc123")

# Filter by channel
slack_alerts = client.fleet.alerts.list(channel_id="ch_abc123")
```

```typescript TypeScript theme={null}
const alerts = await avala.fleet.alerts.list({
  status: "resolved",
  since: "2026-01-01T00:00:00Z",
  until: "2026-02-01T00:00:00Z",
});

for (const alert of alerts.items) {
  console.log(`[${alert.severity}] ${alert.ruleName}`);
  console.log(`  Triggered: ${alert.triggeredAt}`);
  console.log(`  Acknowledged: ${alert.acknowledgedAt} by ${alert.acknowledgedBy}`);
  console.log(`  Resolved: ${alert.resolvedAt}`);
  console.log(`  Duration: ${alert.duration}`);
}

const criticalAlerts = await avala.fleet.alerts.list({ severity: "critical" });
const deviceAlerts = await avala.fleet.alerts.list({ deviceId: "dev_abc123" });
```

```bash CLI theme={null}
avala fleet alerts list --status resolved --since 2026-01-01 --until 2026-02-01
avala fleet alerts list --severity critical
avala fleet alerts list --device dev_abc123
```

### Métricas de alertas

Estatísticas agregadas de alertas para relatórios e acompanhamento de SLA.

```python Python theme={null}
metrics = client.fleet.alerts.metrics(
    since="2026-01-01T00:00:00Z",
    until="2026-02-01T00:00:00Z"
)

print(f"Total alerts: {metrics.total}")
print(f"  Critical: {metrics.by_severity['critical']}")
print(f"  Warning: {metrics.by_severity['warning']}")
print(f"  Info: {metrics.by_severity['info']}")
print(f"Mean time to acknowledge: {metrics.mean_time_to_acknowledge}")
print(f"Mean time to resolve: {metrics.mean_time_to_resolve}")
```

```typescript TypeScript theme={null}
const metrics = await avala.fleet.alerts.metrics({
  since: "2026-01-01T00:00:00Z",
  until: "2026-02-01T00:00:00Z",
});

console.log(`Total alerts: ${metrics.total}`);
console.log(`  Critical: ${metrics.bySeverity.critical}`);
console.log(`  Warning: ${metrics.bySeverity.warning}`);
console.log(`  Info: ${metrics.bySeverity.info}`);
console.log(`Mean time to acknowledge: ${metrics.meanTimeToAcknowledge}`);
console.log(`Mean time to resolve: ${metrics.meanTimeToResolve}`);
```

## Silenciamento e adiamento

Silencie temporariamente os alertas durante manutenções planejadas, interrupções conhecidas ou períodos de teste. Os alertas silenciados continuam sendo avaliados e registrados, mas as notificações são suprimidas.

### Silenciar uma regra

Suprima todas as notificações de uma regra específica por um período definido.

```python Python theme={null}
client.fleet.alerts.mute(
    rule_id="rul_abc123",
    duration="2h",
    reason="Scheduled maintenance on warehouse B robots"
)
```

```typescript TypeScript theme={null}
await avala.fleet.alerts.mute({
  ruleId: "rul_abc123",
  duration: "2h",
  reason: "Scheduled maintenance on warehouse B robots",
});
```

```bash CLI theme={null}
avala fleet alerts mute rul_abc123 --duration 2h --reason "Scheduled maintenance"
```

### Silenciar um dispositivo

Suprima todos os alertas de um dispositivo específico. Útil ao tirar um dispositivo de operação para manutenção.

```python Python theme={null}
client.fleet.alerts.mute_device(
    device_id="dev_abc123",
    duration="4h",
    reason="Firmware upgrade in progress"
)
```

```typescript TypeScript theme={null}
await avala.fleet.alerts.muteDevice({
  deviceId: "dev_abc123",
  duration: "4h",
  reason: "Firmware upgrade in progress",
});
```

```bash CLI theme={null}
avala fleet alerts mute-device dev_abc123 --duration 4h --reason "Firmware upgrade"
```

### Adiar um alerta

Adie um alerta aberto específico para suprimir temporariamente suas notificações. O alerta retorna ao estado `open` quando o adiamento expira.

```python Python theme={null}
client.fleet.alerts.snooze(
    alert_id="alt_abc123",
    duration="30m",
    reason="Known issue, fix deploying in next release"
)
```

```typescript TypeScript theme={null}
await avala.fleet.alerts.snooze({
  alertId: "alt_abc123",
  duration: "30m",
  reason: "Known issue, fix deploying in next release",
});
```

```bash CLI theme={null}
avala fleet alerts snooze alt_abc123 --duration 30m --reason "Known issue, fix deploying"
```

### Ver silenciamentos ativos

```python Python theme={null}
mutes = client.fleet.alerts.mutes.list()
for mute in mutes:
    print(f"{mute.target_type}: {mute.target_id}")
    print(f"  Reason: {mute.reason}")
    print(f"  Expires: {mute.expires_at}")

# Unmute early
client.fleet.alerts.unmute(mute_id="mute_abc123")
```

```typescript TypeScript theme={null}
const mutes = await avala.fleet.alerts.mutes.list();
for (const mute of mutes.items) {
  console.log(`${mute.targetType}: ${mute.targetId}`);
  console.log(`  Reason: ${mute.reason}`);
  console.log(`  Expires: ${mute.expiresAt}`);
}

await avala.fleet.alerts.unmute({ muteId: "mute_abc123" });
```

```bash CLI theme={null}
avala fleet alerts mutes list
avala fleet alerts unmute mute_abc123
```

> [!TIP]
>
> Agende silenciamentos com antecedência para janelas de manutenção recorrentes. Use o parâmetro `starts_at` para criar silenciamentos que são ativados em um momento futuro:
>
> ```python theme={null}
> client.fleet.alerts.mute(
>     rule_id="rul_abc123",
>     starts_at="2026-02-01T02:00:00Z",
>     duration="2h",
>     reason="Weekly maintenance window"
> )
> ```

## Próximos passos

> [card]
>
> Regras de gravaçãoDefina as condições que acionam alertas em toda a sua frota.
>
> [Open](https://avala.ai/docs/pt/visualization/fleet/recording-rules.md)

> [card]
>
> Painel da frotaMonitore dispositivos, gravações e a integridade da frota a partir do painel central.
>
> [Open](https://avala.ai/docs/pt/visualization/fleet/fleet-dashboard.md)

> [card]
>
> Eventos e marcadoresAnote gravações com eventos com carimbo de data/hora para uma análise detalhada.
>
> [Open](https://avala.ai/docs/pt/visualization/fleet/events-and-markers.md)

> [card]
>
> WebhooksReceba notificações em tempo real sobre eventos de conjuntos de dados, exportações e tarefas.
>
> [Open](https://avala.ai/docs/pt/integrations/webhooks.md)
