Ghid · Node.js 18+
Bot de reduceri pe Telegram
De două ori pe zi, cele mai mari reduceri din magazinele din Moldova ajung pe canalul tău de Telegram: prețul, cât era, cât economisești și linkul spre magazin. O reducere se postează o singură dată.
- Rulează pe
- Node.js 18+
- O rulare
- 5 credite
- Pe lună
- 300 de credite
- Pornit în
- 10 min
$ MIN_DISCOUNT=30 TOP=10 node deals_bot.mjs8 new deals of at least 30%, 5 creditsCum funcționează
- Ia reducerile zilei din
/v1/deals, pe toate categoriile sau doar pe cele dinCATEGORIES. - Păstrează reducerile de cel puțin
MIN_DISCOUNTprocente, cele mai mari primele. - Scoate ce a postat deja: magazinul, numele și prețul stau în
deals-seen.json. - Trimite postarea pe Telegram, cu rândul de atribuire din
meta.attribution. Fără token, o afișează.
Cât costă: 5 credite la o rulare pentru toate categoriile, 5 pentru fiecare categorie aleasă. De două ori pe zi: 300 de credite pe lună. Încape în planul Start.
Cum îl rulezi
export SATELIT_KEY=sat_live_...
export TELEGRAM_TOKEN=... TELEGRAM_CHAT=@canalul_tau
MIN_DISCOUNT=30 TOP=10 node deals_bot.mjsCe scoate
8 new deals of at least 30%, 5 creditsScriptul complet
#!/usr/bin/env node
// Deals bot: the deepest discounts in Moldova's shops, posted once each to a Telegram channel.
// SATELIT_KEY=sat_live_... node deals_bot.mjs
// Optional: MIN_DISCOUNT (percent, 30), CATEGORIES (keys, comma separated), STORE (one shop's key), TOP (10),
// TELEGRAM_TOKEN and TELEGRAM_CHAT to post. Without them it prints the post.
// No dependencies, Node 18 or newer. Put it in cron: 0 9,18 * * * node /path/deals_bot.mjs
import { existsSync, readFileSync, writeFileSync } from "node:fs";
const BASE = process.env.SATELIT_BASE ?? "https://api.satelit.md/v1";
const KEY = process.env.SATELIT_KEY;
const LANG = process.env.POST_LANG ?? "ro";
const MIN_DISCOUNT = Number(process.env.MIN_DISCOUNT ?? 30);
const CATEGORIES = (process.env.CATEGORIES ?? "").split(",").filter(Boolean);
const STORE = process.env.STORE ?? "";
const TOP = Number(process.env.TOP ?? 10);
const STATE = process.env.STATE_FILE ?? "deals-seen.json";
if (!KEY) throw new Error("Set SATELIT_KEY");
const WORDS = {
ro: { title: "Reducerile zilei", was: "era", save: "economisești" },
ru: { title: "Скидки дня", was: "было", save: "экономия" },
en: { title: "Today's deals", was: "was", save: "you save" },
uk: { title: "Знижки дня", was: "було", save: "економія" },
};
const w = WORDS[LANG];
let credits = 0;
async function api(path, params = {}) {
const url = new URL(BASE + path);
for (const [k, v] of Object.entries({ lang: LANG, ...params })) if (v) url.searchParams.set(k, v);
for (let attempt = 0; ; attempt++) {
const res = await fetch(url, { headers: { Authorization: `Bearer ${KEY}` } });
const retry = Number(res.headers.get("retry-after"));
if ((res.status === 429 || res.status === 503) && retry && attempt < 2) {
await new Promise((ok) => setTimeout(ok, retry * 1000));
continue;
}
const body = await res.json();
if (!res.ok) throw new Error(`${path}: ${body.error.code}: ${body.error.message}`);
credits += body.meta.credits ?? 0;
return body;
}
}
// one call per category, or one for all of them
const answers = await Promise.all((CATEGORIES.length ? CATEGORIES : [""]).map((category) => api("/deals", { category, store: STORE })));
const attribution = answers[0].meta.attribution;
const lei = (n) => `${n.toFixed(2)} lei`;
const idOf = (d) => `${d.store.key}|${d.name}|${d.price}`;
// a deal is posted once: the same shop, name and price never twice
const seen = new Set(existsSync(STATE) ? JSON.parse(readFileSync(STATE, "utf8")) : []);
const fresh = answers.flatMap((a) => a.data)
.filter((d) => d.discount_pct >= MIN_DISCOUNT && !seen.has(idOf(d)))
.sort((a, b) => b.discount_pct - a.discount_pct)
.slice(0, TOP);
const esc = (s) => String(s).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
const lines = fresh.map((d) => `−${d.discount_pct}% <a href="${esc(d.url)}">${esc(d.name)}</a>\n${esc(d.store.name)}: <b>${lei(d.price)}</b> (${w.was} ${lei(d.old_price)}, ${w.save} ${lei(d.save)})`);
const post = `<b>${w.title}</b>\n\n${lines.join("\n\n")}\n\n<i>${esc(attribution)}</i>`;
if (fresh.length && process.env.TELEGRAM_TOKEN && process.env.TELEGRAM_CHAT) {
const res = await fetch(`https://api.telegram.org/bot${process.env.TELEGRAM_TOKEN}/sendMessage`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ chat_id: process.env.TELEGRAM_CHAT, text: post, parse_mode: "HTML", disable_web_page_preview: true }),
});
if (!res.ok) throw new Error(`Telegram: ${res.status} ${await res.text()}`);
} else if (fresh.length) {
console.log(post);
}
for (const d of fresh) seen.add(idOf(d));
writeFileSync(STATE, JSON.stringify([...seen].slice(-2000)));
console.log(`${fresh.length} new deals of at least ${MIN_DISCOUNT}%, ${credits} credits`);
Rutele folosite
Întrebări despre acest ghid
Cât de des se schimbă reducerile?
Câmpul meta.updated_at din fiecare răspuns spune când au fost citite ultima dată. Două rulări pe zi, la 9 și la 18, prind schimbările zilei.
Pot posta doar o categorie sau un magazin?
Da. CATEGORIES=alcohol,sweets_snacks ia doar acele categorii, STORE=nr1 doar un magazin. Cheile sunt în referința API.
Botul postează aceeași reducere de două ori?
Nu. Fiecare reducere postată rămâne în deals-seen.json după magazin, nume și preț. Dacă prețul scade din nou, e o reducere nouă și se postează.