Cookbook · Python 3.9+
Tour alerts under budget
You name the countries, a budget per person in lei and the nights. Three times a day the script searches the offers of Moldova's travel agencies and tells you only about offers that are new or got cheaper.
- Runs on
- Python 3.9+
- One run
- 7 credits
- A month
- 630 credits
- Set up in
- 10 min
$ COUNTRIES=Egipt,Turcia BUDGET=9000 NIGHTS_MIN=7 python3 tours_alert.py14 offers under 9000 lei, 7 creditsHow it works
- Read each country's lowest price per person from
/v1/tours/countries. A country over budget costs no search. - For each country left, search
/v1/tourssorted by price, with the nights, dates and board filters. - Stop at the first offer over budget: the rest cost more.
- Compare with the last run in
tours-state.jsonand alert only new or cheaper offers.
What it costs: 1 credit for the countries, 3 for each search: 7 credits with two countries. Three times a day: 630 credits a month. Fits in the Start plan.
How to run it
export SATELIT_KEY=sat_live_...
COUNTRIES=Egipt,Turcia BUDGET=9000 NIGHTS_MIN=7 python3 tours_alert.pyWhat it outputs
14 offers under 9000 lei, 7 creditsThe full script
#!/usr/bin/env python3
"""Tours under budget: package tours from Moldova's agencies, an alert when one fits your price.
SATELIT_KEY=sat_live_... COUNTRIES=Egipt,Turcia BUDGET=9000 python3 tours_alert.py
BUDGET is lei per person. Optional: NIGHTS_MIN, NIGHTS_MAX, FROM and TO (YYYY-MM-DD, the departure window),
BOARD (AI, BB...), ALERT_URL (a Slack-style incoming webhook; empty prints the alerts).
Standard library only. Put it in cron: 0 8,14,20 * * * python3 /path/tours_alert.py
"""
import json
import os
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
sys.stdout.reconfigure(encoding="utf-8") # names hold ă, ș, ț whatever the console's code page
BASE = os.environ.get("SATELIT_BASE", "https://api.satelit.md/v1")
KEY = os.environ["SATELIT_KEY"]
COUNTRIES = [c.strip() for c in os.environ.get("COUNTRIES", "Egipt,Turcia").split(",") if c.strip()]
BUDGET = float(os.environ.get("BUDGET", "9000"))
FILTERS = {k.lower(): os.environ[k] for k in ("NIGHTS_MIN", "NIGHTS_MAX", "FROM", "TO", "BOARD") if os.environ.get(k)}
ALERT_URL = os.environ.get("ALERT_URL", "")
STATE = Path(os.environ.get("STATE_FILE", "tours-state.json"))
credits_used = 0
def api(path, **params):
global credits_used
query = urllib.parse.urlencode({"lang": "ro", **params})
req = urllib.request.Request(f"{BASE}{path}?{query}", headers={"Authorization": f"Bearer {KEY}"})
for attempt in range(3):
try:
with urllib.request.urlopen(req, timeout=20) as res:
body = json.load(res)
credits_used += body["meta"].get("credits", 0)
return body["data"]
except urllib.error.HTTPError as err:
retry = err.headers.get("Retry-After")
if err.code in (429, 503) and retry and attempt < 2:
time.sleep(int(retry))
continue
raise SystemExit(f"{path}: {err.code} {err.read().decode()}")
def alert(text):
print(text)
if ALERT_URL:
req = urllib.request.Request(ALERT_URL, json.dumps({"text": text}).encode(), {"Content-Type": "application/json"})
urllib.request.urlopen(req, timeout=10).close()
def main():
# the cheapest price per country first: a country whose floor is over budget costs no search
floors = {c["country"]: c["min_price_pp_mdl"] for c in api("/tours/countries")}
last = json.loads(STATE.read_text("utf-8")) if STATE.exists() else {}
now, found = {}, 0
for country in COUNTRIES:
if floors.get(country, 0) > BUDGET:
print(f"{country}: from {floors[country]:.0f} lei, over budget")
continue
for t in api("/tours", country=country, sort="price", **FILTERS):
price = t["price_pp_mdl"]
if price > BUDGET:
break # sorted by price: the rest cost more
key = str(t["id"])
now[key] = price
found += 1
before = last.get(key)
if before is None or price < before - 1:
stars = "*" * (t["stars"] or 0)
was = f" (was {before:.0f})" if before else ""
alert(f"{country}, {t['resort']}: {t['hotel']} {stars} {t['board']}, {t['nights']} nights from {t['date_from']}, "
f"{price:.0f} lei/person{was}, {t['agency']}: {t['url']}")
STATE.write_text(json.dumps(now), "utf-8")
print(f"{found} offers under {BUDGET:.0f} lei, {credits_used} credits")
if __name__ == "__main__":
main()
Routes used
Questions about this cookbook
Which agencies do the offers come from?
From the public offers of the Moldovan travel agencies that Satelit reads. Each offer carries the agency and a link to its page; you book with the agency.
Is the price per person or per room?
price_per says how the agency gave the price; price_pp_mdl is always per person, in lei. The script compares the budget with it.
Can I search only all inclusive or only some dates?
Yes: BOARD=AI for the board, FROM and TO for the departure date, NIGHTS_MIN and NIGHTS_MAX for the nights.