Посібник · Node.js 18+
Сповіщення про землетрус до хвилі
Satelit сам виявляє глибокі землетруси Вранчі в перші секунди. Хвилі, яка трясе, потрібна близько хвилини до Кишинева. У цьому проміжку вебхук earthquake.early надходить на ваш сервер. Перевірено на 84 реальних землетрусах від 2014 року: усі з магнітудою 5 і більше отримали сповіщення через 17–24 секунди після початку, тобто за 35–44 секунди до хвилі S у Кишиневі.
- Працює на
- Node.js 18+
- Один запуск
- 0 кредитів
- На місяць
- 0 кредитів
- Налаштування
- 15 хв
$ CITY=chisinau MIN_INTENSITY=3 PORT=8080 node quake_alert.mjsEARTHQUAKE ALERT: Vrancea, M 5.5 (estimate, +-0.28). S wave in chisinau in 44 s, estimated intensity IV.Як це працює
- Додайте адресу свого сервера в панелі з подіями
earthquake.earlyіearthquake. Для першої потрібен план Pro або вищий. - Скрипт перевіряє підпис із
Satelit-Signatureі відповідає 200 раніше за все інше. - Бере ваше місто з
data.moldovaі рахує секунди, що лишилися, заs_wave_at, а не за моментом надсилання. - Одразу повідомляє в канал, потім ще раз за
stage: 2, з кращою оцінкою. Локалізований землетрус надходить якearthquake.
Скільки коштує: Вебхуки не витрачають кредитів. earthquake.early доступний на планах Pro, Business та Enterprise; earthquake, після локалізації, на будь-якому плані з вебхуками. На плані Start вебхуків немає.
Як запустити
export SATELIT_WEBHOOK_SECRET=whsec_...
export TELEGRAM_TOKEN=... TELEGRAM_CHAT=@canalul_tau
CITY=chisinau MIN_INTENSITY=3 PORT=8080 node quake_alert.mjsЩо виводить
EARTHQUAKE ALERT: Vrancea, M 5.5 (estimate, +-0.28). S wave in chisinau in 44 s, estimated intensity IV.Повний скрипт
#!/usr/bin/env node
// Receives earthquake.early from Satelit (Pro, Business, Enterprise): a deep Vrancea earthquake seen about 20 seconds
// after it starts, tens of seconds before its S wave reaches Moldova. Checks the signature, works out the seconds left
// for your town and tells your channel at once. The located earthquake follows as `earthquake`.
// SATELIT_WEBHOOK_SECRET=... CITY=chisinau MIN_INTENSITY=3 PORT=8080 node quake_alert.mjs
// TELEGRAM_TOKEN=... TELEGRAM_CHAT=@your_channel (without them the alert is printed)
// Put it behind HTTPS and add the address in the dashboard with the events earthquake.early and earthquake.
import { createHmac, timingSafeEqual } from "node:crypto";
import { createServer } from "node:http";
const SECRET = process.env.SATELIT_WEBHOOK_SECRET;
if (!SECRET) throw new Error("Set SATELIT_WEBHOOK_SECRET");
const CITY = process.env.CITY ?? "chisinau";
const MIN_INTENSITY = Number(process.env.MIN_INTENSITY ?? 3);
const { TELEGRAM_TOKEN, TELEGRAM_CHAT } = process.env;
const seen = new Set();
function verified(rawBody, header = "") {
const parts = Object.fromEntries(header.split(",").map((p) => p.split("=")));
const t = Number(parts.t);
if (!t || Math.abs(Date.now() / 1000 - t) > 300) return false;
const expected = Buffer.from(createHmac("sha256", SECRET).update(`${t}.${rawBody}`).digest("hex"));
const given = Buffer.from(parts.v1 ?? "");
return expected.length === given.length && timingSafeEqual(expected, given);
}
async function tell(text) {
console.log(text);
if (!TELEGRAM_TOKEN || !TELEGRAM_CHAT) return;
// no waiting on Telegram's answer: every second counts, and a failed post must not stop the next alert
fetch(`https://api.telegram.org/bot${TELEGRAM_TOKEN}/sendMessage`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ chat_id: TELEGRAM_CHAT, text }),
}).catch((e) => console.error(`telegram: ${e.message}`));
}
function early(data) {
const town = data.moldova.find((t) => t.key === CITY) ?? data.strongest;
if (town.intensity_estimate < MIN_INTENSITY) return;
// the seconds left now, from the wave's own arrival time: the event took a moment to reach us
const left = Math.max(0, Math.round((new Date(town.s_wave_at) - Date.now()) / 1000));
const head = data.stage === 1 ? "EARTHQUAKE ALERT" : "Earthquake alert, updated";
tell(`${head}: Vrancea, M ${data.magnitude_estimate} (estimate, +-${data.magnitude_sd}). ` +
`S wave in ${town.key} in ${left} s, estimated intensity ${town.intensity_roman}. Preliminary. ${data.attribution}`);
}
function located(data) {
tell(`Earthquake located: M ${data.magnitude} ${data.region}, depth ${data.depth_km} km. ` +
`Estimated in ${data.moldova.strongest_in_name}: ${data.moldova.intensity_roman}. ${data.url}`);
}
const server = createServer((req, res) => {
const chunks = [];
req.on("data", (c) => chunks.push(c));
req.on("end", () => {
const raw = Buffer.concat(chunks).toString("utf8");
if (!verified(raw, req.headers["satelit-signature"])) {
res.writeHead(401).end();
return;
}
const event = JSON.parse(raw);
res.writeHead(200).end(); // answer first: Satelit does not wait for your work
if (seen.has(event.id)) return; // a retry of what we already handled
seen.add(event.id);
if (event.type === "earthquake.early") early(event.data);
else if (event.type === "earthquake") located(event.data);
});
});
server.listen(Number(process.env.PORT ?? 8080), () => console.log(`listening on ${server.address().port}`));
Використані маршрути
Питання про цей посібник
Наскільки рано надходить сповіщення?
Приблизно через 20 секунд після початку глибокого землетрусу у Вранчі. Хвиля S доходить до Кагула приблизно за 46 секунд, до Кишинева за 57–66, тож лишається близько 24 і 35–44 секунд.
Наскільки точна магнітуда у сповіщенні?
Це оцінка за першими секундами землетрусу зі стандартним відхиленням 0,24–0,28. Вище магнітуди 6 це нижня межа: перші секунди сильного землетрусу не показують усієї його величини. Поле preliminary завжди true.
Про які землетруси раннього сповіщення немає?
Про ті, що не глибокі й не з Вранчі: коровий землетрус чи поштовх з іншої зони надходить лише як earthquake, після локалізації. Це не офіційна система попередження.