Alerta diário de câmbio

A daily rate alert via cron or GitHub Actions

Um script Node curto, sem dependências, que roda uma vez por dia: busca /rate/USD/BRL, compara com um limite definido em variável de ambiente e, se a taxa cruzar esse limite, dispara uma notificação por webhook (compatível com Slack/Discord).

A short, dependency-free Node script that runs once a day: it fetches /rate/USD/BRL, compares it against a threshold from an environment variable, and if the rate crosses that threshold, fires a webhook notification (Slack/Discord compatible).

Base: https://moneta.api.insyde.one — aberta, sem autenticação / open, no auth.

1. O script / The script

Salve como alert.mjs. Node 18+ já traz fetch embutido. / Save as alert.mjs. Node 18+ ships fetch built in.

// alert.mjs — sem dependências / no dependencies
const PAIR = process.env.PAIR || "USD/BRL";
const THRESHOLD = Number(process.env.THRESHOLD);     // ex.: 5.10
const WEBHOOK = process.env.WEBHOOK_URL;            // incoming webhook

const [base, quote] = PAIR.split("/");
const res = await fetch(`https://moneta.api.insyde.one/rate/${base}/${quote}`);
if (!res.ok) {
  console.error(`fetch failed: ${res.status}`);
  process.exit(1);
}

const { date, rate } = await res.json();
console.log(`${date} ${PAIR} = ${rate}`);

if (rate >= THRESHOLD) {
  const text = `⚠️ ${PAIR} hit ${rate} on ${date} (threshold ${THRESHOLD})`;
  await fetch(WEBHOOK, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({ text }),           // Slack-compatible payload
  });
  console.log("alert sent");
}

2. Variáveis de ambiente / Environment variables

VarExemplo / ExampleDescrição / Description
PAIRUSD/BRLPar a monitorar. / Pair to watch.
THRESHOLD5.10Dispara quando rate >= THRESHOLD. / Fires when rate >= THRESHOLD.
WEBHOOK_URLhttps://hooks…/…Incoming webhook (Slack/Discord). Nunca hardcode. / Never hardcode.

3. Rodar via cron / Run via cron

Os bancos centrais publicam pela manhã; agende para depois disso (ex.: 11h, dias úteis). Mantenha os segredos fora do crontab — carregue de um arquivo de ambiente.

Central banks publish in the morning; schedule for after that (e.g. 11:00, weekdays). Keep secrets out of the crontab — load them from an env file.

# minuto hora * * dia-da-semana  comando
0 11 * * 1-5  cd /opt/fx && set -a && . ./.env && set +a && node alert.mjs >> fx.log 2>&1

4. Rodar via GitHub Actions / Run via GitHub Actions

Mesma lógica, agendada na nuvem. Os segredos ficam em Settings → Secrets. / Same logic, scheduled in the cloud. Secrets live in Settings → Secrets.

# .github/workflows/fx-alert.yml
name: fx-alert
on:
  schedule:
    - cron: "0 14 * * 1-5"      # 14:00 UTC, seg-sex (cron em UTC)
  workflow_dispatch: {}        # permite rodar à mão
jobs:
  check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: "20" }
      - run: node alert.mjs
        env:
          PAIR: USD/BRL
          THRESHOLD: "5.10"
          WEBHOOK_URL: ${{ secrets.WEBHOOK_URL }}
Idempotência: rode uma vez por dia útil, após a publicação. As taxas são valores oficiais de bancos centrais e não mudam ao longo do dia — chamar de novo no mesmo dia retorna o mesmo número.
Idempotency: run once per business day, after publication. Rates are official central-bank values and do not change intraday — calling again the same day returns the same number.
Fuso/cron: o cron do GitHub Actions usa UTC; ajuste a hora ao seu fuso. Em finais de semana e feriados não há publicação nova — o script só repete o último valor.
Timezone/cron: GitHub Actions cron is UTC; adjust the hour to your timezone. On weekends and holidays there is no new publication — the script just repeats the last value.

Moneta docs · Live demo · Back to Insyde APIs