Developer

Language: English
Appearance

Theme

Accent colour

Your theme and colour carry over to satelit.md and the app.

Sign in

Where should the theme change?

Choose where the new theme applies.

You can change it any time from the header.

Cookbook · Node.js 18+

Telegram deals bot

Twice a day, the deepest discounts in Moldova's shops reach your Telegram channel: the price, what it was, what you save and the link to the shop. A deal is posted only once.

Runs on
Node.js 18+
One run
5 credits
A month
300 credits
Set up in
10 min
$ MIN_DISCOUNT=30 TOP=10 node deals_bot.mjs8 new deals of at least 30%, 5 credits

How it works

  1. Get the day's deals from /v1/deals, in every category or only those in CATEGORIES.
  2. Keep deals of at least MIN_DISCOUNT percent, the deepest first.
  3. Drop what it posted before: shop, name and price are kept in deals-seen.json.
  4. Send the post to Telegram with the attribution line from meta.attribution. Without a token, it prints it.

What it costs: 5 credits a run for all categories, 5 for each category you pick. Twice a day: 300 credits a month. Fits in the Start plan.

How to run it

bash
export SATELIT_KEY=sat_live_...
export TELEGRAM_TOKEN=... TELEGRAM_CHAT=@canalul_tau
MIN_DISCOUNT=30 TOP=10 node deals_bot.mjs

What it outputs

stdout
8 new deals of at least 30%, 5 credits

The full script

deals_bot.mjs
#!/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, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
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`);

Routes used

Data in this cookbook

Updated:

Questions about this cookbook

How often do the deals change?

Every answer's meta.updated_at says when they were last read. Two runs a day, at 9 and 18, catch the day's changes.

Can it post only one category or one shop?

Yes. CATEGORIES=alcohol,sweets_snacks takes only those categories, STORE=nr1 only one shop. The keys are in the API reference.

Does the bot post the same deal twice?

No. Every posted deal stays in deals-seen.json by shop, name and price. If the price drops again, it is a new deal and gets posted.