Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
80731ea2e1 | ||
|
|
a905be10bc | ||
|
|
b4e712f3ac | ||
|
|
32c97d9173 | ||
|
|
a652900b9e | ||
|
|
556ac0ba21 | ||
|
|
c709e8d960 | ||
|
|
302f6f9f95 | ||
|
|
67f94fd2c0 | ||
|
|
9189c4f639 | ||
|
|
159182e6a1 | ||
|
|
d0f76b9978 | ||
|
|
b61feb4fef | ||
|
|
2825c2dbfd | ||
|
|
3ef6fc9409 | ||
|
|
ec2682d675 | ||
|
|
d90b7cdbf8 | ||
|
|
5a7a60d299 | ||
|
|
b3ed21eec2 | ||
|
|
b0a220e7a2 | ||
|
|
ae737c0bd0 | ||
|
|
d0b3fc6e18 | ||
|
|
5f66d1e1e0 | ||
|
|
8b7eac51c8 | ||
|
|
fb1387e6cc | ||
|
|
d972fdf145 | ||
|
|
753750530d | ||
|
|
f4f41abbe8 | ||
|
|
7fb3663097 | ||
|
|
530aeba667 | ||
|
|
10290fd28d | ||
|
|
b26a6a2d0a | ||
|
|
78ee9ac9da | ||
|
|
cef6886fd2 | ||
|
|
b3fe0fcf24 | ||
|
|
2484568e5f | ||
|
|
7f24145dc2 | ||
|
|
8f626a7737 | ||
|
|
4c57a3a310 | ||
|
|
407e27238f | ||
|
|
961c24a6c6 | ||
|
|
a16db7be01 | ||
|
|
92db785511 | ||
|
|
1f3db4dec8 | ||
|
|
1edaa2c71d | ||
|
|
004d227fd1 | ||
|
|
40d83cad12 |
No files matched your search
@@ -0,0 +1,118 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
schedule:
|
||||
# Saturday 05:00 UTC: 06:00 in Paris in winter, 07:00 in summer (Gitea runs cron in UTC).
|
||||
- cron: "0 5 * * 6"
|
||||
|
||||
jobs:
|
||||
build-and-scan:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
|
||||
- name: Get shared actions
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
repository: labeex/cicdeex
|
||||
ref: 1.1.0
|
||||
token: ${{ secrets.CICDEEX_TOKEN }}
|
||||
path: .cicdeex
|
||||
persist-credentials: false
|
||||
|
||||
- name: Scan for secrets
|
||||
uses: ./.cicdeex/secret-scan
|
||||
|
||||
- name: Lint Dockerfile with hadolint
|
||||
uses: ./.cicdeex/hadolint
|
||||
|
||||
- name: Build Docker image
|
||||
run: |
|
||||
docker build -t nvidia-stock-bot:ci . 2>&1 | tee build.log
|
||||
if grep -q "Building wheel for" build.log; then
|
||||
echo "::warning::A dependency was built from source — check Python/Alpine compatibility"
|
||||
fi
|
||||
|
||||
- name: Smoke test (syntax check)
|
||||
run: |
|
||||
docker run --rm --entrypoint python nvidia-stock-bot:ci -c "
|
||||
import ast, glob
|
||||
ok = True
|
||||
for f in glob.glob('/app/*.py'):
|
||||
with open(f) as fh:
|
||||
source = fh.read()
|
||||
try:
|
||||
ast.parse(source, filename=f)
|
||||
except SyntaxError as e:
|
||||
print(f'::error::Syntax error in {f}: {e}')
|
||||
ok = False
|
||||
if not ok:
|
||||
exit(1)
|
||||
print('OK: syntax is valid')
|
||||
"
|
||||
|
||||
- name: Run unit tests
|
||||
run: |
|
||||
docker build --target test -t nvidia-stock-bot:test .
|
||||
docker run --rm nvidia-stock-bot:test pytest -v --cov=. --cov-report=term-missing --cov-fail-under=75
|
||||
|
||||
- name: Lint with ruff
|
||||
run: docker build --target lint -t nvidia-stock-bot:lint .
|
||||
|
||||
- name: Check deprecation warnings
|
||||
run: |
|
||||
docker run --rm --entrypoint python \
|
||||
-e DISCORD_WEBHOOK_URL="https://discord.com/api/webhooks/123456789012345678/abcdef" \
|
||||
-e PRODUCT_NAMES="RTX 5090 Founders Edition" \
|
||||
-e TEST_MODE=True \
|
||||
nvidia-stock-bot:ci -W error::DeprecationWarning -c "import main" 2>&1 | tee deprecation.log || true
|
||||
if grep -qi "deprecat" deprecation.log; then
|
||||
echo "::warning::Deprecation warning detected, check logs"
|
||||
fi
|
||||
|
||||
- name: Scan with Trivy (critical - blocking)
|
||||
id: trivy_critical
|
||||
continue-on-error: true
|
||||
uses: ./.cicdeex/trivy
|
||||
with:
|
||||
image: nvidia-stock-bot:ci
|
||||
|
||||
- name: Handle CRITICAL findings
|
||||
if: steps.trivy_critical.outcome == 'failure'
|
||||
uses: ./.cicdeex/remediate
|
||||
with:
|
||||
push-token: ${{ secrets.CI_PUSH_TOKEN }}
|
||||
|
||||
- name: Scan with Trivy (high - informative)
|
||||
uses: ./.cicdeex/trivy
|
||||
with:
|
||||
image: nvidia-stock-bot:ci
|
||||
severity: HIGH
|
||||
exit-code: "0"
|
||||
|
||||
- name: Publish tagged image
|
||||
id: publish
|
||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||
uses: ./.cicdeex/publish
|
||||
with:
|
||||
image: nvidia-stock-bot:ci
|
||||
paths: '^(Dockerfile|VERSION)$|^app/'
|
||||
push-token: ${{ secrets.CI_PUSH_TOKEN }}
|
||||
registry-token: ${{ secrets.REGISTRY_TOKEN }}
|
||||
github-mirror: "true"
|
||||
github-token: ${{ secrets.GH_TOKEN }}
|
||||
|
||||
- name: Notify failures
|
||||
if: always()
|
||||
uses: ./.cicdeex/notify
|
||||
with:
|
||||
webhook-url: ${{ secrets.DISCORD_WEBHOOK_URL }}
|
||||
status: ${{ job.status }}
|
||||
@@ -0,0 +1,4 @@
|
||||
.venv
|
||||
__pycache__/
|
||||
.coverage
|
||||
.pytest_cache/
|
||||
+24
-1
@@ -1,11 +1,34 @@
|
||||
FROM python:3.11-alpine
|
||||
FROM python:3.15.2-alpine@sha256:0f9552bb28711333da16915ec146f5e6bb44a7fdac9ced15dc17c2e0206346dd AS base
|
||||
|
||||
RUN apk add --no-cache ca-certificates
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY VERSION /VERSION
|
||||
COPY /app/ /app/
|
||||
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
FROM base AS test
|
||||
|
||||
RUN pip install --no-cache-dir pytest==9.1.1 pytest-cov==7.1.0
|
||||
|
||||
COPY pytest.ini /app/pytest.ini
|
||||
COPY /tests/ /app/tests/
|
||||
|
||||
CMD ["pytest", "-v"]
|
||||
|
||||
FROM base AS lint
|
||||
|
||||
RUN pip install --no-cache-dir ruff==0.16.4
|
||||
COPY ruff.toml /app/ruff.toml
|
||||
COPY /tests/ /app/tests/
|
||||
RUN ruff check . && ruff format --check .
|
||||
|
||||
FROM base
|
||||
|
||||
RUN addgroup -g 911 nvbot && adduser -D -u 911 -G nvbot nvbot
|
||||
|
||||
USER nvbot
|
||||
|
||||
CMD ["python", "main.py"]
|
||||
@@ -11,9 +11,13 @@
|
||||
**🤖 Nvidia Stock Bot** - A bot that alerts you in real-time about **Nvidia RTX FE** GPU stock availability through Discord notifications.
|
||||
|
||||
> [!NOTE]
|
||||
>_The code was partially written and structured using a generative AI._
|
||||
>
|
||||
>_Github repo is a mirror of https://git.djeex.fr/Djeex/nvidia-stock-bot. You'll find full package, history and release note there._
|
||||
>_Github repo is a mirror of https://git.djeex.fr/Djeex/nvidia-stock-bot. You'll find full package, history and release note there. LLM used for bugs check and languages files generation._
|
||||
|
||||
## 🖼️ Screenshots
|
||||
|
||||
<div align="center" >
|
||||
<img src="https://git.djeex.fr/Djeex/nvidia-stock-bot/raw/branch/main/assets/img/nvidia-stock-bot-discord-screenshot.png" alt="Nvidia Stock Bot - screenshots">
|
||||
</div>
|
||||
|
||||
## 📌 Table of Contents
|
||||
|
||||
@@ -21,8 +25,8 @@
|
||||
- [🐳 Docker Installation without cloning the repo (quick)](#-docker-installation-without-the-repo-quick)
|
||||
- [🐙 Docker Installation with the repo (developer)](#-docker-installation-with-the-repo)
|
||||
- [🐍 Python Installation (developer)](#-python-installation)
|
||||
- [🖼️ Screenshots](#-screenshots)
|
||||
- [🐞 Common issues](#-common-issues)
|
||||
- [❓ How it works](#-how-it-works)
|
||||
- [🧑💻 Contributors](#-contributors)
|
||||
|
||||
## ✨ Features
|
||||
@@ -68,12 +72,11 @@ services:
|
||||
|---------------------|-------------------------------------------------|------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------|
|
||||
| `PRODUCT_NAMES` | The exact GPU names you're searching for | `RTX 5080, RTX 5090` | |
|
||||
| `DISCORD_WEBHOOK_URL` | Your Discord webhook URL | A valid URL | |
|
||||
| `COUNTRY` | Your country (only one). API localization, Discord notification currency and language will be set accordingly | `GB`, `US`, `CA`, `BE`, `NL`, `DK`, `DE`, `ES`, `FR`, `IT`, `NO`, `AT`, `PL`, `FI`, `SE`, `KR`, `JP`
|
||||
| `US` |
|
||||
| `COUNTRY` | Your country (only one). API localization, Discord notification currency and language will be set accordingly | `GB`, `US`, `CA`, `BE`, `NL`, `DK`, `DE`, `ES`, `FR`, `IT`, `NO`, `AT`, `PL`, `FI`, `SE`, `KR`, `JP` | `US` |
|
||||
| `DISCORD_SERVER_NAME` | The name of your server, displayed in notification's footer | A text | Shared for free |
|
||||
| `DISCORD_ROLES` | List of Discord roles ID in the same order than `PRODUCT_NAMES` values, found in your discord server settings (with user profile developer mode enabled) | `<@&12345><@&6789>` | @everyone |
|
||||
| `REFRESH_TIME` | Script refresh interval in seconds | `60`, `30`, etc. | `30` |
|
||||
| `API_URL_SKU` | API listing the product. Use it for development purpose. __Warning__ : it will override the locale set by `COUNTRY`. | An URL | https://api.nvidia.partners/edge/product/search?page=1&limit=100&locale={locale}&Manufacturer=Nvidia` |
|
||||
| `API_URL_SKU` | API listing the product. Use it for development purpose. __Warning__ : it will override the locale set by `COUNTRY`. | An URL | `https://api.nvidia.partners/edge/product/search?page=1&limit=100&locale={locale}&Manufacturer=Nvidia` |
|
||||
| `API_URL_STOCK` | API providing stock data. Use it for development purpose. __Warning__ : it will override the locale set by `COUNTRY`. | A URL | `https://api.store.nvidia.com/partner/v1/feinventory?locale={locale}&skus=` |
|
||||
| `PRODUCT_URL` | GPU purchase URL. Use it for development purpose. __Warning__ : it will override the locale set by `COUNTRY`. | A URL | `https://marketplace.nvidia.com/fr-fr/consumer/graphics-cards/?locale={locale}&page=1&limit=12&manufacturer=NVIDIA` |
|
||||
| `TEST_MODE` | For testing without sending notifications | `True`, `False` | `False` |
|
||||
@@ -151,7 +154,7 @@ git clone https://git.djeex.fr/Djeex/nvidia-stock-bot.git
|
||||
|
||||
```sh
|
||||
export DISCORD_WEBHOOK_URL="https://your_discord_url"
|
||||
export COUNTRY=€
|
||||
export COUNTRY=US
|
||||
export PRODUCT_NAMES=RTX 5080, RTX 5090
|
||||
export DISCORD_ROLES=<@&12345>, <@&6789>
|
||||
export REFRESH_TIME="60"
|
||||
@@ -165,19 +168,19 @@ export PYTHONUNBUFFERED=1
|
||||
python nvidia-stock-bot.py
|
||||
```
|
||||
|
||||
## 🖼️ Screenshots
|
||||
|
||||
<div align="center" >
|
||||
<img src="https://git.djeex.fr/Djeex/nvidia-stock-bot/raw/branch/main/assets/img/nvidia-stock-bot-discord.png" alt="Nvidia Stock Bot - screenshots">
|
||||
</div>
|
||||
|
||||
## 🐞 Common issues
|
||||
|
||||
Error when trying to reach product API url :
|
||||
- `API_SKU_URL` may be wrong
|
||||
- Custom `API_SKU_URL` may be wrong
|
||||
- Your IP may be blacklisted by nvidia. Try to use a VPN.
|
||||
- nvidia API may be down
|
||||
|
||||
## ❓ How it works
|
||||
|
||||
<div align="center" >
|
||||
<img src="https://git.djeex.fr/Djeex/nvidia-stock-bot/raw/branch/main/assets/img/nvidia-stock-bot-scheme.svg" alt="Nvidia Stock Bot - screenshots">
|
||||
</div>
|
||||
|
||||
## 🧑💻 Contributors
|
||||
|
||||
Thanks for their contributions:
|
||||
|
||||
+53
-41
@@ -1,10 +1,14 @@
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import logging
|
||||
import json
|
||||
import sys
|
||||
|
||||
VERSION = "4.0.0"
|
||||
# Read version from VERSION file
|
||||
with open(
|
||||
os.path.join(os.path.dirname(os.path.dirname(__file__)), "VERSION"), encoding="utf-8"
|
||||
) as f:
|
||||
VERSION = f.read().strip()
|
||||
|
||||
# Logger setup
|
||||
logging.basicConfig(
|
||||
@@ -21,13 +25,13 @@ logging.info("=" * 60)
|
||||
|
||||
# Env variables
|
||||
try:
|
||||
DISCORD_WEBHOOK_URL = os.environ['DISCORD_WEBHOOK_URL']
|
||||
DISCORD_SERVER_NAME = os.environ.get('DISCORD_SERVER_NAME', 'Shared for free')
|
||||
DISCORD_ROLES = os.environ.get('DISCORD_ROLES')
|
||||
COUNTRY = os.environ.get('COUNTRY') or 'US'
|
||||
REFRESH_TIME = int(os.environ.get('REFRESH_TIME') or 30)
|
||||
TEST_MODE = os.environ.get('TEST_MODE', 'False').lower() == 'true'
|
||||
PRODUCT_NAMES = os.environ['PRODUCT_NAMES']
|
||||
DISCORD_WEBHOOK_URL = os.environ["DISCORD_WEBHOOK_URL"]
|
||||
DISCORD_SERVER_NAME = os.environ.get("DISCORD_SERVER_NAME", "Shared for free")
|
||||
DISCORD_ROLES = os.environ.get("DISCORD_ROLES")
|
||||
COUNTRY = os.environ.get("COUNTRY") or "US"
|
||||
REFRESH_TIME = int(os.environ.get("REFRESH_TIME") or 30)
|
||||
TEST_MODE = os.environ.get("TEST_MODE", "False").lower() == "true"
|
||||
PRODUCT_NAMES = os.environ["PRODUCT_NAMES"]
|
||||
|
||||
# Errors and warning
|
||||
except KeyError as e:
|
||||
@@ -47,71 +51,74 @@ if not DISCORD_WEBHOOK_URL:
|
||||
logging.error("❌ DISCORD_WEBHOOK_URL is required but not defined.")
|
||||
sys.exit(1)
|
||||
|
||||
PRODUCT_NAMES = [name.strip() for name in PRODUCT_NAMES.split(',')]
|
||||
PRODUCT_NAMES = [name.strip() for name in PRODUCT_NAMES.split(",")]
|
||||
|
||||
# Role mapping
|
||||
DISCORD_ROLE_MAP = {}
|
||||
if not DISCORD_ROLES or not DISCORD_ROLES.strip():
|
||||
logging.warning("⚠️ DISCORD_ROLES not defined or empty. Defaulting all roles to @everyone.")
|
||||
for name in PRODUCT_NAMES:
|
||||
DISCORD_ROLE_MAP[name] = '@everyone'
|
||||
DISCORD_ROLE_MAP[name] = "@everyone"
|
||||
else:
|
||||
roles = [r.strip() if r.strip() else '@everyone' for r in DISCORD_ROLES.split(',')]
|
||||
roles = [r.strip() if r.strip() else "@everyone" for r in DISCORD_ROLES.split(",")]
|
||||
if len(roles) != len(PRODUCT_NAMES):
|
||||
logging.error("❌ The number of DISCORD_ROLES must match PRODUCT_NAMES.")
|
||||
sys.exit(1)
|
||||
for name, role in zip(PRODUCT_NAMES, roles):
|
||||
if role != '@everyone' and not re.match(r'^<@&\d{17,20}>$', role):
|
||||
if role != "@everyone" and not re.match(r"^<@&\d{17,20}>$", role):
|
||||
logging.error(f"❌ Invalid DISCORD_ROLE format for {name}: {role}")
|
||||
sys.exit(1)
|
||||
DISCORD_ROLE_MAP[name] = role
|
||||
|
||||
# Masked webhook in terminal
|
||||
match = re.search(r'/(\d+)/(.*)', DISCORD_WEBHOOK_URL)
|
||||
match = re.search(r"/(\d+)/(.*)", DISCORD_WEBHOOK_URL)
|
||||
if match:
|
||||
webhook_id = match.group(1)
|
||||
webhook_token = match.group(2)
|
||||
masked_webhook_id = webhook_id[:len(webhook_id) - 10] + '*' * 10
|
||||
masked_webhook_token = webhook_token[:len(webhook_token) - 120] + '*' * 10
|
||||
masked_webhook_id = webhook_id[: len(webhook_id) - 10] + "*" * 10
|
||||
masked_webhook_token = webhook_token[: len(webhook_token) - 120] + "*" * 10
|
||||
wh_masked_url = f"https://discord.com/api/webhooks/{masked_webhook_id}/{masked_webhook_token}"
|
||||
else:
|
||||
wh_masked_url = "[Invalid webhook URL]"
|
||||
|
||||
# HTTP headers
|
||||
HEADERS = {
|
||||
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
|
||||
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
||||
"Chrome/131.0.0.0 Safari/537.36",
|
||||
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,"
|
||||
"image/avif,image/webp,image/apng,*/*;q=0.8",
|
||||
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
"Accept-Language": "fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7",
|
||||
"Accept-Encoding": "gzip, deflate, br, zstd",
|
||||
"Accept-Language": "en-US,en;q=0.5",
|
||||
"Cache-Control": "max-age=0",
|
||||
"Referer": "https://partners.nvidia.com/",
|
||||
"Origin": "https://partners.nvidia.com",
|
||||
"Connection": "keep-alive",
|
||||
"Sec-Fetch-Dest": "document",
|
||||
"Sec-Fetch-Mode": "navigate",
|
||||
"Sec-Fetch-Site": "none",
|
||||
"Sec-Fetch-User": "?1",
|
||||
"Upgrade-Insecure-Requests": "1",
|
||||
"Sec-GPC": "1",
|
||||
"Sec-Fetch-Dest": "empty",
|
||||
"Sec-Fetch-Mode": "cors",
|
||||
"Sec-Ch-Ua": '"Google Chrome";v="131", "Chromium";v="131", "Not.A/Brand";v="24"',
|
||||
"Sec-Ch-Ua-Platform": '"macOS"',
|
||||
"Cache-Control": "no-cache, no-store, must-revalidate",
|
||||
"Pragma": "no-cache",
|
||||
"Expires": "0",
|
||||
}
|
||||
|
||||
# Load country setting and localization config
|
||||
country_code = os.environ.get("COUNTRY", "US").upper()
|
||||
|
||||
try:
|
||||
with open("localization.json", "r", encoding="utf-8") as f:
|
||||
with open("localization.json", encoding="utf-8") as f:
|
||||
localization_config = json.load(f)
|
||||
except FileNotFoundError:
|
||||
logging.error("❌ localization.json file not found.")
|
||||
sys.exit(1)
|
||||
|
||||
# Find country entry
|
||||
country_entry = next((entry for entry in localization_config if entry["country_code"].upper() == country_code), None)
|
||||
country_entry = next(
|
||||
(entry for entry in localization_config if entry["country_code"].upper() == country_code), None
|
||||
)
|
||||
|
||||
if not country_entry:
|
||||
logging.warning(f"⚠️ Country '{country_code}' not found in localization.json. Defaulting to US.")
|
||||
country_entry = next((entry for entry in localization_config if entry["country_code"].upper() == "US"), None)
|
||||
country_entry = next(
|
||||
(entry for entry in localization_config if entry["country_code"].upper() == "US"), None
|
||||
)
|
||||
if not country_entry:
|
||||
logging.error("❌ US fallback not found in localization.json.")
|
||||
sys.exit(1)
|
||||
@@ -123,7 +130,7 @@ currency = country_entry["currency"]
|
||||
|
||||
# Load language file
|
||||
try:
|
||||
with open("languages.json", "r", encoding="utf-8") as f:
|
||||
with open("languages.json", encoding="utf-8") as f:
|
||||
loc_lang = json.load(f)
|
||||
except FileNotFoundError:
|
||||
logging.error("❌ languages.json file not found.")
|
||||
@@ -140,9 +147,15 @@ if not loc:
|
||||
|
||||
# Ensure all required keys are present
|
||||
required_keys = [
|
||||
"in_stock_title", "out_of_stock_title", "sku_change_title",
|
||||
"buy_now", "price", "time", "footer",
|
||||
"sku_description", "imminent_drop"
|
||||
"in_stock_title",
|
||||
"out_of_stock_title",
|
||||
"sku_change_title",
|
||||
"buy_now",
|
||||
"price",
|
||||
"time",
|
||||
"footer",
|
||||
"sku_description",
|
||||
"imminent_drop",
|
||||
]
|
||||
missing_keys = [key for key in required_keys if key not in loc]
|
||||
fallback = loc_lang.get("en", {})
|
||||
@@ -158,17 +171,16 @@ for key in missing_keys:
|
||||
locale = full_lang_code.lower()
|
||||
API_URL_SKU = os.getenv(
|
||||
"API_URL_SKU",
|
||||
f"https://api.nvidia.partners/edge/product/search?page=1&limit=100&locale={locale}&Manufacturer=Nvidia"
|
||||
f"https://api.nvidia.partners/edge/product/search?page=1&limit=100&locale={locale}&Manufacturer=Nvidia",
|
||||
)
|
||||
|
||||
API_URL_STOCK = os.getenv(
|
||||
"API_URL_STOCK",
|
||||
f"https://api.store.nvidia.com/partner/v1/feinventory?locale={locale}&skus="
|
||||
"API_URL_STOCK", f"https://api.store.nvidia.com/partner/v1/feinventory?locale={locale}&skus="
|
||||
)
|
||||
|
||||
PRODUCT_URL = os.getenv(
|
||||
"PRODUCT_URL",
|
||||
f"https://marketplace.nvidia.com/{locale}/consumer/graphics-cards/?locale={locale}&page=1&limit=12&manufacturer=NVIDIA"
|
||||
f"https://marketplace.nvidia.com/{locale}/consumer/graphics-cards/?locale={locale}&page=1&limit=12&manufacturer=NVIDIA",
|
||||
)
|
||||
|
||||
# Public constants
|
||||
|
||||
+25
-12
@@ -1,26 +1,38 @@
|
||||
import requests
|
||||
import logging
|
||||
from env_config import HEADERS, PRODUCT_NAMES, API_URL_SKU, API_URL_STOCK, PRODUCT_URL
|
||||
from notifier import send_discord_notification, send_out_of_stock_notification, send_sku_change_notification
|
||||
import time
|
||||
|
||||
import requests
|
||||
from requests.adapters import HTTPAdapter, Retry
|
||||
|
||||
from env_config import API_URL_SKU, API_URL_STOCK, HEADERS, PRODUCT_NAMES, PRODUCT_URL
|
||||
from notifier import (
|
||||
send_discord_notification,
|
||||
send_out_of_stock_notification,
|
||||
send_sku_change_notification,
|
||||
)
|
||||
|
||||
# HTTP session
|
||||
session = requests.Session()
|
||||
retries = Retry(total=5, backoff_factor=1, status_forcelist=[500, 502, 503, 504])
|
||||
session.mount('https://', HTTPAdapter(max_retries=retries))
|
||||
session.mount("https://", HTTPAdapter(max_retries=retries))
|
||||
session.headers.update(HEADERS)
|
||||
|
||||
# Keeping memory of last run
|
||||
last_sku_dict = {}
|
||||
global_stock_status_dict = {}
|
||||
first_run_dict = {name: True for name in PRODUCT_NAMES}
|
||||
|
||||
|
||||
# Stock check function
|
||||
def check_rtx_50_founders():
|
||||
global last_sku_dict, global_stock_status_dict, first_run_dict
|
||||
|
||||
# Fetching nvidia API data
|
||||
try:
|
||||
response = session.get(API_URL_SKU, headers=HEADERS, timeout=10)
|
||||
cache_buster = int(time.time() * 1000)
|
||||
sku_url = f"{API_URL_SKU}&_t={cache_buster}"
|
||||
|
||||
response = session.get(sku_url, timeout=10)
|
||||
logging.info(f"SKU API response: {response.status_code}")
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
@@ -29,7 +41,7 @@ def check_rtx_50_founders():
|
||||
return
|
||||
|
||||
# Checking productSKU and productUPC for all GPU set in PRODUCT_NAME
|
||||
all_products = data['searchedProducts']['productDetails']
|
||||
all_products = data["searchedProducts"]["productDetails"]
|
||||
|
||||
for product_name in PRODUCT_NAMES:
|
||||
product_details = None
|
||||
@@ -42,8 +54,8 @@ def check_rtx_50_founders():
|
||||
logging.warning(f"⚠️ No product with GPU '{product_name}' found.")
|
||||
continue
|
||||
|
||||
product_sku = product_details['productSKU']
|
||||
product_upc = product_details.get('productUPC', "")
|
||||
product_sku = product_details["productSKU"]
|
||||
product_upc = product_details.get("productUPC", "")
|
||||
if not isinstance(product_upc, list):
|
||||
product_upc = [product_upc]
|
||||
|
||||
@@ -57,11 +69,12 @@ def check_rtx_50_founders():
|
||||
first_run_dict[product_name] = False
|
||||
|
||||
# Check product availability in API_URL_STOCK for each SKU
|
||||
api_stock_url = API_URL_STOCK + product_sku
|
||||
cache_buster = int(time.time() * 1000)
|
||||
api_stock_url = f"{API_URL_STOCK}{product_sku}&_t={cache_buster}"
|
||||
logging.info(f"[{product_name}] Checking stock: {api_stock_url}")
|
||||
|
||||
try:
|
||||
response = session.get(api_stock_url, headers=HEADERS, timeout=10)
|
||||
response = session.get(api_stock_url, timeout=10)
|
||||
logging.info(f"[{product_name}] Stock API response: {response.status_code}")
|
||||
response.raise_for_status()
|
||||
stock_data = response.json()
|
||||
@@ -74,8 +87,8 @@ def check_rtx_50_founders():
|
||||
products_price = "Price not available"
|
||||
if isinstance(products, list) and len(products) > 0:
|
||||
for p in products:
|
||||
price = p.get("price", 'Price not available')
|
||||
if price != 'Price not available':
|
||||
price = p.get("price", "Price not available")
|
||||
if price != "Price not available":
|
||||
products_price = price
|
||||
break
|
||||
else:
|
||||
|
||||
+6
-4
@@ -1,17 +1,20 @@
|
||||
import time
|
||||
import logging
|
||||
import signal
|
||||
import sys
|
||||
from gpu_checker import check_rtx_50_founders
|
||||
import time
|
||||
|
||||
from env_config import REFRESH_TIME
|
||||
from gpu_checker import check_rtx_50_founders
|
||||
|
||||
|
||||
# Signal handler function
|
||||
def handle_exit(signum, frame):
|
||||
logging.info(f"🛑 Received signal {signum}. Exiting gracefully...")
|
||||
sys.exit(0)
|
||||
|
||||
|
||||
# Register signal handlers
|
||||
signal.signal(signal.SIGINT, handle_exit) # Ctrl+C
|
||||
signal.signal(signal.SIGINT, handle_exit) # Ctrl+C
|
||||
signal.signal(signal.SIGTERM, handle_exit) # docker stop / kill -15
|
||||
|
||||
if __name__ == "__main__":
|
||||
@@ -24,4 +27,3 @@ if __name__ == "__main__":
|
||||
except KeyboardInterrupt:
|
||||
logging.info("🛑 Script interrupted by user (KeyboardInterrupt). Exiting gracefully.")
|
||||
sys.exit(0)
|
||||
|
||||
+43
-19
@@ -1,15 +1,29 @@
|
||||
import time
|
||||
import logging
|
||||
import time
|
||||
|
||||
import requests
|
||||
|
||||
from env_config import (
|
||||
DISCORD_WEBHOOK_URL, DISCORD_SERVER_NAME, DISCORD_ROLE_MAP, TEST_MODE, currency,
|
||||
in_stock_title, out_of_stock_title, sku_change_title,
|
||||
buy_now, price_label, time_label, footer, sku_description, imminent_drop
|
||||
DISCORD_ROLE_MAP,
|
||||
DISCORD_SERVER_NAME,
|
||||
DISCORD_WEBHOOK_URL,
|
||||
TEST_MODE,
|
||||
buy_now,
|
||||
currency,
|
||||
footer,
|
||||
imminent_drop,
|
||||
in_stock_title,
|
||||
out_of_stock_title,
|
||||
price_label,
|
||||
sku_change_title,
|
||||
sku_description,
|
||||
time_label,
|
||||
)
|
||||
|
||||
AVATAR = "https://git.djeex.fr/Djeex/nvidia-stock-bot/raw/branch/main/assets/img/ds_wh_pp.jpg"
|
||||
THUMBNAIL = "https://git.djeex.fr/Djeex/nvidia-stock-bot/raw/branch/main/assets/img/RTX5000.jpg"
|
||||
|
||||
|
||||
# In stock
|
||||
def send_discord_notification(gpu_name, product_link, products_price):
|
||||
timestamp = int(time.time())
|
||||
@@ -24,17 +38,20 @@ def send_discord_notification(gpu_name, product_link, products_price):
|
||||
"author": {"name": "Nvidia Founder Editions"},
|
||||
"fields": [
|
||||
{"name": price_label, "value": f"`{currency}{products_price}`", "inline": True},
|
||||
{"name": time_label, "value": f"<t:{timestamp}:d> <t:{timestamp}:T>", "inline": True}
|
||||
{"name": time_label, "value": f"<t:{timestamp}:d> <t:{timestamp}:T>", "inline": True},
|
||||
],
|
||||
"description": buy_now.format(product_link=product_link),
|
||||
"footer": {"text": footer.format(DISCORD_SERVER_NAME=DISCORD_SERVER_NAME), "icon_url": AVATAR}
|
||||
"footer": {
|
||||
"text": footer.format(DISCORD_SERVER_NAME=DISCORD_SERVER_NAME),
|
||||
"icon_url": AVATAR,
|
||||
},
|
||||
}
|
||||
|
||||
payload = {
|
||||
"content": DISCORD_ROLE_MAP.get(gpu_name, "@everyone"),
|
||||
"username": "NviBot",
|
||||
"avatar_url": AVATAR,
|
||||
"embeds": [embed]
|
||||
"embeds": [embed],
|
||||
}
|
||||
|
||||
try:
|
||||
@@ -46,6 +63,7 @@ def send_discord_notification(gpu_name, product_link, products_price):
|
||||
except Exception as e:
|
||||
logging.error(f"🚨 Error sending webhook: {e}")
|
||||
|
||||
|
||||
# Out of stock
|
||||
def send_out_of_stock_notification(gpu_name, product_link, products_price):
|
||||
timestamp = int(time.time())
|
||||
@@ -59,15 +77,16 @@ def send_out_of_stock_notification(gpu_name, product_link, products_price):
|
||||
"thumbnail": {"url": THUMBNAIL},
|
||||
"url": product_link,
|
||||
"author": {"name": "Nvidia Founder Editions"},
|
||||
"footer": {"text": footer.format(DISCORD_SERVER_NAME=DISCORD_SERVER_NAME), "icon_url": AVATAR},
|
||||
"fields": [{"name": time_label, "value": f"<t:{timestamp}:d> <t:{timestamp}:T>", "inline": True}]
|
||||
"footer": {
|
||||
"text": footer.format(DISCORD_SERVER_NAME=DISCORD_SERVER_NAME),
|
||||
"icon_url": AVATAR,
|
||||
},
|
||||
"fields": [
|
||||
{"name": time_label, "value": f"<t:{timestamp}:d> <t:{timestamp}:T>", "inline": True}
|
||||
],
|
||||
}
|
||||
|
||||
payload = {
|
||||
"username": "NviBot",
|
||||
"avatar_url": AVATAR,
|
||||
"embeds": [embed]
|
||||
}
|
||||
payload = {"username": "NviBot", "avatar_url": AVATAR, "embeds": [embed]}
|
||||
|
||||
try:
|
||||
response = requests.post(DISCORD_WEBHOOK_URL, json=payload)
|
||||
@@ -78,6 +97,7 @@ def send_out_of_stock_notification(gpu_name, product_link, products_price):
|
||||
except Exception as e:
|
||||
logging.error(f"🚨 Error sending webhook: {e}")
|
||||
|
||||
|
||||
# SKU change
|
||||
def send_sku_change_notification(gpu_name, old_sku, new_sku, product_link):
|
||||
timestamp = int(time.time())
|
||||
@@ -90,15 +110,20 @@ def send_sku_change_notification(gpu_name, old_sku, new_sku, product_link):
|
||||
"url": product_link,
|
||||
"description": sku_description.format(old_sku=old_sku, new_sku=new_sku),
|
||||
"color": 16776960,
|
||||
"footer": {"text": footer.format(DISCORD_SERVER_NAME=DISCORD_SERVER_NAME), "icon_url": AVATAR},
|
||||
"fields": [{"name": time_label, "value": f"<t:{timestamp}:d> <t:{timestamp}:T>", "inline": True}]
|
||||
"footer": {
|
||||
"text": footer.format(DISCORD_SERVER_NAME=DISCORD_SERVER_NAME),
|
||||
"icon_url": AVATAR,
|
||||
},
|
||||
"fields": [
|
||||
{"name": time_label, "value": f"<t:{timestamp}:d> <t:{timestamp}:T>", "inline": True}
|
||||
],
|
||||
}
|
||||
|
||||
payload = {
|
||||
"content": imminent_drop.format(DISCORD_ROLE=DISCORD_ROLE_MAP.get(gpu_name, '@everyone')),
|
||||
"content": imminent_drop.format(DISCORD_ROLE=DISCORD_ROLE_MAP.get(gpu_name, "@everyone")),
|
||||
"username": "NviBot",
|
||||
"avatar_url": AVATAR,
|
||||
"embeds": [embed]
|
||||
"embeds": [embed],
|
||||
}
|
||||
|
||||
try:
|
||||
@@ -109,4 +134,3 @@ def send_sku_change_notification(gpu_name, old_sku, new_sku, product_link):
|
||||
logging.error(f"❌ Webhook error: {response.status_code} - {response.text}")
|
||||
except Exception as e:
|
||||
logging.error(f"🚨 Error sending webhook: {e}")
|
||||
|
||||
@@ -1 +1 @@
|
||||
requests
|
||||
requests==2.34.2
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 257 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 95 KiB |
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" standalone="no"?>
|
||||
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
|
||||
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 4676.333384195949 3182.740093634052" width="14029.000152587847" height="9548.220280902155"><!-- svg-source:excalidraw --><metadata></metadata><defs><style class="style-fonts">
|
||||
@font-face { font-family: Virgil; src: url(data:font/woff2;base64,d09GMgABAAAAACCUAAsAAAAAM6gAACBHAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAABmAAgQQRCArcfMReC3AAATYCJAOBXAQgBYMcByAbWyYjA8HGAQhBeBXZXyRwAldhu01YGuvKOCguljAomgaN+jVZhMi4GJ7BhsWWP/DKCElmh+fn1vv/7/9lw4CxsRG1IEpYs5FjMKo3OizEKhQVo7HOpPSisOICo07PujPqMPKK5/+5/7bveTNj/UkSamVRf5RZ2Rc4w4B/WlRY539z2r+8lbZXkhMXBuJA2xlO2zd5ABA47+TBR1hsm21nazt2sGBKMslQCYZBtj78pdPeuuuk1vARSwAsDz39r5rddl9LAkcOCExxDkyhw8AR7EoW7fd7+V/94o6I7cyCh9BIjXaS+f/nflXcu5dELNu+3u+C+oaNNUxOp0RC0Q0d/pZ4kMTWoEHJhBgsNFLBtpAx9RV+jDR5AtoIkeuP6lZ+NgciLFQvXgrgYp4+KADfJRsAicpVBIAlV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m6TD9//iPSG5kKgrfvfLt7+6iQEeLmcG2v1aOqKlLVP32rZdYDDBZ8Bg3jrMpeKLine truncated
|
||||
@font-face { font-family: Excalifont; src: url(data:font/woff2;base64,d09GMgABAAAAACBsAA4AAAAAO4gAACAUAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGigbjwQcgjgGYACBTBEICtoIwkULbgABNgIkA4FYBCAFgxgHIBtmLrMREWwcQLMZXkr2Xx5wh4rJ34AlmsZaRqKsv7rKCmMMRsLIYR8W7GGhAZW/Sf9o458yM0KS2SGas2Zns5s4MQPiEMQSxBMnwYJroUIRregVqEOpiB961f+Kn1TtgZ5JTe5bHr6dr1+FFGBgeRIE625iA9Xtv87KedvZ5QWWuTpAyGwOsOq+W6mVvgwZZ8AQGg4MLPN925ZMV2xb3NrTkvzfMRTCGIwfU0LP1+0dnBw3k31JmCKo/T+d9i+1mvbOjMCwYFl2FshO8p4fABgeVP5YbVF9dOu0GpETlixD6GycOAvAI41uDEvtSz7kReH831pqMyFedzJAcoUMkDARKsbc/MN/P0A4F4LdU5lwFZNQebXIamWR3F5dXF2FaV1lq0RUX4WKs70IoSqMq7kRYz6/S4DYIXGFZMkYPvqfW+Qfm4F1vkh2Q+RVGzMBAgAaGIIIMPKXmkIIIRZkoaO3RUHK99UNCMOWlAnEu6NxcrOcxqpJllvWXMdPeDhbkmlPVWMdIBHqAUDAdhA+GUmQwNodUYf3ep+IdOjgUP8Z8JOiGC+Kq95u9119YOOHYWOwfsgqjxtL2prbb9yf3mqzco3kSPB6DPfzxvvY/yHNtqbxh/LxjUS3FcA1lPraqN9uctXGcB/nwuCW842DqzLnbtjIHzSx57dtTccN9udKiUBp0H9NSuvWspZl/cmDg9efd7aDVIrkesyu8lBulyCnAPfbJJGxMNvdkwfmWYaaUAQ4Kho6BiYWNg4uHj4BITEJdx48Kah48ablL0AgPQSk44bDVhLyGsWbcuY7AMFNqwQD9SwAoERwagmEMCJccGOUa+OIqHjYaPhMpRMAaiEEKoTwb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VW4MRat9siBQJvayWkQKfNyVXveL7lVBQV9eyO8ao+ZJalGRnh8p4TAdzEm0xLTdm1JLkA4WNu9cr27mW7tCd1g7C5OO8ZoQm4YMWCpHXQeCMSGECxEAD2FTJW5J4Cye/k+04Dingph3RR9S8/fb7+/i5vpA2/2KUfmArLhn11e6feKZE/8Fnm3X/na1q8udG7dqX9/o9SUFXgT6xR6XTQ6BNmNPYtz2boMAN/VLERzVCSyLMTFKNlvTonTHv70cPEVrSI2lKcuQWAYlqP5TEaCGrP4/ZEtyzJ2EI5OGtpJwbqn77/e6kPZnRl5aNIhnmAhIDTIh2AqJX6DvTLxuVQbWncYJPZA/j6mvjTLcbaYFKtT7PU6c4sgSQ1g2EpjBtzxwMB8++okkb+v2GETKpysg0NHJukGA9ELLIFX1cxlT20Rd97dWhNHeKI4bwRMlDHSoIkbAI9zIK2v9PsrMlaoBD+ndOF5Hgk8iwdP2BJde1XPf4/hBzs3r9HXfco2F+44SYjFoZTya/PYNLLRCIbrcBYSoPOB+sr+t73UB2A6fjZvrdhtiy/CwjGe/QRrhnXV8i88Nf8JLG2qnBXWHIBflQ3Ij2MkaM0KHyFObXJctyZaUVivz1pwIz282gsyGMDkLcU6k01/CvmxKPezvVX0jPdWmVFL2PmuS1/5++zc+SbXuqV5hJZe326I44cW4g6zrdm5DtfEjFZeiLine truncated
|
||||
|
After Width: | Height: | Size: 739 KiB |
+1
-3
@@ -1,5 +1,3 @@
|
||||
PRODUCT_NAMES= # Exact GPU name (e.g. "RTX 5080, RTX 5090")
|
||||
DISCORD_WEBHOOK_URL= # Your Discord webhook URL
|
||||
API_URL_SKU= # API listing the product for your country
|
||||
API_URL_STOCK= # API providing stock data for your country
|
||||
PRODUCT_URL= # GPU purchase URL for your country
|
||||
COUNTRY= # Set your country (e.g. 'US')
|
||||
+4
-7
@@ -7,10 +7,7 @@ services:
|
||||
- .env
|
||||
environment:
|
||||
# Minimal environment variables
|
||||
- PRODUCT_NAMES= # Exact GPU name (e.g. "RTX 5080, RTX 5090")
|
||||
- DISCORD_WEBHOOK_URL= # Your Discord webhook URL
|
||||
- DISCORD_NOTIFICATION_CURRENCY= # Set your country currency
|
||||
- API_URL_SKU= # API listing the product for your country
|
||||
- API_URL_STOCK= # API providing stock data for your country
|
||||
- PRODUCT_URL= # GPU purchase URL for your country
|
||||
- PYTHONUNBUFFERED=1 # Enables real-time log output
|
||||
- PRODUCT_NAMES=${PRODUCT_NAMES}
|
||||
- DISCORD_WEBHOOK_URL=${DISCORD_WEBHOOK_URL}
|
||||
- COUNTRY=${COUNTRY}
|
||||
- PYTHONUNBUFFERED=1
|
||||
@@ -0,0 +1 @@
|
||||
[pytest]
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
|
||||
"extends": ["local>labeex/renovateex"]
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
line-length = 100
|
||||
|
||||
[lint]
|
||||
select = ["E", "F", "I", "UP", "B"]
|
||||
# E501: handled by the formatter. B905: zip() without strict= in env_config.py —
|
||||
# app-logic change, left for the user to decide (see feedback-no-app-logic-changes).
|
||||
ignore = ["E501", "B905"]
|
||||
|
||||
[lint.isort]
|
||||
# Pinned explicitly: auto-detection of first-party modules differs between the
|
||||
# host (app/ subdir + .git present) and the Docker lint stage (flattened to /app,
|
||||
# no .git) — without this, import-sort results silently diverge between the two.
|
||||
known-first-party = ["env_config", "gpu_checker", "notifier", "main"]
|
||||
@@ -0,0 +1,17 @@
|
||||
import os
|
||||
import sys
|
||||
|
||||
_TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
_REPO_ROOT = os.path.dirname(_TESTS_DIR)
|
||||
|
||||
# app/*.py open their JSON config files with plain relative paths, so the
|
||||
# process cwd must be the directory the app modules live in — matches how
|
||||
# the Dockerfile runs them (WORKDIR /app).
|
||||
_APP_DIR = os.path.join(_REPO_ROOT, "app")
|
||||
if not os.path.isfile(os.path.join(_APP_DIR, "gpu_checker.py")):
|
||||
_APP_DIR = _REPO_ROOT # container test stage: code copied flat next to tests/
|
||||
|
||||
if _APP_DIR not in sys.path:
|
||||
sys.path.insert(0, _APP_DIR)
|
||||
|
||||
os.chdir(_APP_DIR)
|
||||
@@ -0,0 +1,120 @@
|
||||
import importlib
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
MODULE_NAME = "env_config"
|
||||
|
||||
VALID_WEBHOOK = "https://discord.com/api/webhooks/123456789012345678/abcdef"
|
||||
|
||||
ENV_KEYS = [
|
||||
"DISCORD_WEBHOOK_URL",
|
||||
"DISCORD_SERVER_NAME",
|
||||
"DISCORD_ROLES",
|
||||
"COUNTRY",
|
||||
"REFRESH_TIME",
|
||||
"TEST_MODE",
|
||||
"PRODUCT_NAMES",
|
||||
]
|
||||
|
||||
|
||||
def _reload_env_config(monkeypatch, env):
|
||||
for key in ENV_KEYS:
|
||||
monkeypatch.delenv(key, raising=False)
|
||||
for key, value in env.items():
|
||||
monkeypatch.setenv(key, value)
|
||||
sys.modules.pop(MODULE_NAME, None)
|
||||
return importlib.import_module(MODULE_NAME)
|
||||
|
||||
|
||||
def test_missing_webhook_exits(monkeypatch):
|
||||
with pytest.raises(SystemExit):
|
||||
_reload_env_config(monkeypatch, {"PRODUCT_NAMES": "RTX 5090"})
|
||||
|
||||
|
||||
def test_missing_product_names_exits(monkeypatch):
|
||||
with pytest.raises(SystemExit):
|
||||
_reload_env_config(monkeypatch, {"DISCORD_WEBHOOK_URL": VALID_WEBHOOK})
|
||||
|
||||
|
||||
def test_default_role_map_is_everyone(monkeypatch):
|
||||
cfg = _reload_env_config(
|
||||
monkeypatch,
|
||||
{
|
||||
"DISCORD_WEBHOOK_URL": VALID_WEBHOOK,
|
||||
"PRODUCT_NAMES": "RTX 5090, RTX 5080",
|
||||
},
|
||||
)
|
||||
assert cfg.DISCORD_ROLE_MAP == {"RTX 5090": "@everyone", "RTX 5080": "@everyone"}
|
||||
|
||||
|
||||
def test_role_count_mismatch_exits(monkeypatch):
|
||||
with pytest.raises(SystemExit):
|
||||
_reload_env_config(
|
||||
monkeypatch,
|
||||
{
|
||||
"DISCORD_WEBHOOK_URL": VALID_WEBHOOK,
|
||||
"PRODUCT_NAMES": "RTX 5090, RTX 5080",
|
||||
"DISCORD_ROLES": "<@&123456789012345678>",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def test_invalid_role_format_exits(monkeypatch):
|
||||
with pytest.raises(SystemExit):
|
||||
_reload_env_config(
|
||||
monkeypatch,
|
||||
{
|
||||
"DISCORD_WEBHOOK_URL": VALID_WEBHOOK,
|
||||
"PRODUCT_NAMES": "RTX 5090",
|
||||
"DISCORD_ROLES": "not-a-role",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def test_valid_role_format_accepted(monkeypatch):
|
||||
cfg = _reload_env_config(
|
||||
monkeypatch,
|
||||
{
|
||||
"DISCORD_WEBHOOK_URL": VALID_WEBHOOK,
|
||||
"PRODUCT_NAMES": "RTX 5090",
|
||||
"DISCORD_ROLES": "<@&123456789012345678>",
|
||||
},
|
||||
)
|
||||
assert cfg.DISCORD_ROLE_MAP["RTX 5090"] == "<@&123456789012345678>"
|
||||
|
||||
|
||||
def test_unknown_country_falls_back_to_us(monkeypatch):
|
||||
cfg = _reload_env_config(
|
||||
monkeypatch,
|
||||
{
|
||||
"DISCORD_WEBHOOK_URL": VALID_WEBHOOK,
|
||||
"PRODUCT_NAMES": "RTX 5090",
|
||||
"COUNTRY": "ZZ",
|
||||
},
|
||||
)
|
||||
assert cfg.currency == "$"
|
||||
|
||||
|
||||
def test_known_country_currency(monkeypatch):
|
||||
cfg = _reload_env_config(
|
||||
monkeypatch,
|
||||
{
|
||||
"DISCORD_WEBHOOK_URL": VALID_WEBHOOK,
|
||||
"PRODUCT_NAMES": "RTX 5090",
|
||||
"COUNTRY": "GB",
|
||||
},
|
||||
)
|
||||
assert cfg.currency == "£"
|
||||
|
||||
|
||||
def test_refresh_time_invalid_exits(monkeypatch):
|
||||
with pytest.raises(SystemExit):
|
||||
_reload_env_config(
|
||||
monkeypatch,
|
||||
{
|
||||
"DISCORD_WEBHOOK_URL": VALID_WEBHOOK,
|
||||
"PRODUCT_NAMES": "RTX 5090",
|
||||
"REFRESH_TIME": "not-a-number",
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,162 @@
|
||||
import importlib
|
||||
import sys
|
||||
|
||||
VALID_WEBHOOK = "https://discord.com/api/webhooks/123456789012345678/abcdef"
|
||||
PRODUCT_NAME = "RTX 5090 Founders Edition"
|
||||
|
||||
SKU_PAYLOAD = {
|
||||
"searchedProducts": {
|
||||
"productDetails": [{"gpu": PRODUCT_NAME, "productSKU": "SKU-1", "productUPC": "ABC123"}]
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class FakeResponse:
|
||||
def __init__(self, payload, status_code=200):
|
||||
self._payload = payload
|
||||
self.status_code = status_code
|
||||
|
||||
def raise_for_status(self):
|
||||
if self.status_code >= 400:
|
||||
raise Exception(f"HTTP {self.status_code}")
|
||||
|
||||
def json(self):
|
||||
return self._payload
|
||||
|
||||
|
||||
def _stock_payload(in_stock, price="1999"):
|
||||
return {
|
||||
"listMap": [
|
||||
{"fe_sku": "ABC123", "is_active": "true" if in_stock else "false", "price": price}
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def _import_gpu_checker(monkeypatch):
|
||||
monkeypatch.setenv("DISCORD_WEBHOOK_URL", VALID_WEBHOOK)
|
||||
monkeypatch.setenv("PRODUCT_NAMES", PRODUCT_NAME)
|
||||
monkeypatch.setenv("TEST_MODE", "True")
|
||||
monkeypatch.delenv("DISCORD_ROLES", raising=False)
|
||||
for mod in ("env_config", "notifier", "gpu_checker"):
|
||||
sys.modules.pop(mod, None)
|
||||
return importlib.import_module("gpu_checker")
|
||||
|
||||
|
||||
def _queue_responses(monkeypatch, checker, *payloads):
|
||||
responses = [FakeResponse(p) for p in payloads]
|
||||
monkeypatch.setattr(checker.session, "get", lambda *a, **k: responses.pop(0))
|
||||
|
||||
|
||||
def test_transition_to_in_stock_sends_notification(monkeypatch):
|
||||
checker = _import_gpu_checker(monkeypatch)
|
||||
calls = []
|
||||
monkeypatch.setattr(
|
||||
checker, "send_discord_notification", lambda *a: calls.append(("in_stock", a))
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
checker, "send_out_of_stock_notification", lambda *a: calls.append(("out_of_stock", a))
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
checker, "send_sku_change_notification", lambda *a: calls.append(("sku_change", a))
|
||||
)
|
||||
|
||||
_queue_responses(monkeypatch, checker, SKU_PAYLOAD, _stock_payload(True))
|
||||
checker.check_rtx_50_founders()
|
||||
|
||||
assert len(calls) == 1
|
||||
assert calls[0][0] == "in_stock"
|
||||
assert calls[0][1][0] == PRODUCT_NAME
|
||||
|
||||
|
||||
def test_transition_to_out_of_stock_sends_notification(monkeypatch):
|
||||
checker = _import_gpu_checker(monkeypatch)
|
||||
calls = []
|
||||
monkeypatch.setattr(
|
||||
checker, "send_discord_notification", lambda *a: calls.append(("in_stock", a))
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
checker, "send_out_of_stock_notification", lambda *a: calls.append(("out_of_stock", a))
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
checker, "send_sku_change_notification", lambda *a: calls.append(("sku_change", a))
|
||||
)
|
||||
|
||||
_queue_responses(monkeypatch, checker, SKU_PAYLOAD, _stock_payload(True))
|
||||
checker.check_rtx_50_founders()
|
||||
|
||||
_queue_responses(monkeypatch, checker, SKU_PAYLOAD, _stock_payload(False))
|
||||
checker.check_rtx_50_founders()
|
||||
|
||||
assert calls[-1][0] == "out_of_stock"
|
||||
assert calls[-1][1][0] == PRODUCT_NAME
|
||||
|
||||
|
||||
def test_no_duplicate_notification_while_still_in_stock(monkeypatch):
|
||||
checker = _import_gpu_checker(monkeypatch)
|
||||
calls = []
|
||||
monkeypatch.setattr(
|
||||
checker, "send_discord_notification", lambda *a: calls.append(("in_stock", a))
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
checker, "send_out_of_stock_notification", lambda *a: calls.append(("out_of_stock", a))
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
checker, "send_sku_change_notification", lambda *a: calls.append(("sku_change", a))
|
||||
)
|
||||
|
||||
_queue_responses(monkeypatch, checker, SKU_PAYLOAD, _stock_payload(True))
|
||||
checker.check_rtx_50_founders()
|
||||
_queue_responses(monkeypatch, checker, SKU_PAYLOAD, _stock_payload(True))
|
||||
checker.check_rtx_50_founders()
|
||||
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
def test_sku_change_triggers_notification_after_first_run(monkeypatch):
|
||||
checker = _import_gpu_checker(monkeypatch)
|
||||
sku_change_calls = []
|
||||
monkeypatch.setattr(checker, "send_discord_notification", lambda *a: None)
|
||||
monkeypatch.setattr(checker, "send_out_of_stock_notification", lambda *a: None)
|
||||
monkeypatch.setattr(
|
||||
checker, "send_sku_change_notification", lambda *a: sku_change_calls.append(a)
|
||||
)
|
||||
|
||||
_queue_responses(monkeypatch, checker, SKU_PAYLOAD, _stock_payload(False))
|
||||
checker.check_rtx_50_founders()
|
||||
assert sku_change_calls == [] # first run must never fire a "change" notification
|
||||
|
||||
changed_payload = {
|
||||
"searchedProducts": {
|
||||
"productDetails": [{"gpu": PRODUCT_NAME, "productSKU": "SKU-2", "productUPC": "ABC123"}]
|
||||
}
|
||||
}
|
||||
_queue_responses(monkeypatch, checker, changed_payload, _stock_payload(False))
|
||||
checker.check_rtx_50_founders()
|
||||
|
||||
assert len(sku_change_calls) == 1
|
||||
assert sku_change_calls[0][1] == "SKU-1"
|
||||
assert sku_change_calls[0][2] == "SKU-2"
|
||||
|
||||
|
||||
def test_missing_product_in_api_is_skipped_gracefully(monkeypatch):
|
||||
checker = _import_gpu_checker(monkeypatch)
|
||||
calls = []
|
||||
monkeypatch.setattr(checker, "send_discord_notification", lambda *a: calls.append(a))
|
||||
|
||||
empty_payload = {"searchedProducts": {"productDetails": []}}
|
||||
monkeypatch.setattr(checker.session, "get", lambda *a, **k: FakeResponse(empty_payload))
|
||||
|
||||
checker.check_rtx_50_founders() # must not raise, just log a warning and skip
|
||||
|
||||
assert calls == []
|
||||
|
||||
|
||||
def test_sku_api_error_is_handled_without_raising(monkeypatch):
|
||||
checker = _import_gpu_checker(monkeypatch)
|
||||
|
||||
def raise_error(*a, **k):
|
||||
raise checker.requests.exceptions.ConnectionError("boom")
|
||||
|
||||
monkeypatch.setattr(checker.session, "get", raise_error)
|
||||
|
||||
checker.check_rtx_50_founders() # must not propagate the network error
|
||||
@@ -0,0 +1,187 @@
|
||||
import importlib
|
||||
import sys
|
||||
|
||||
VALID_WEBHOOK = "https://discord.com/api/webhooks/123456789012345678/abcdef"
|
||||
|
||||
|
||||
def _import_notifier(monkeypatch, test_mode="False", discord_roles=None):
|
||||
monkeypatch.setenv("DISCORD_WEBHOOK_URL", VALID_WEBHOOK)
|
||||
monkeypatch.setenv("PRODUCT_NAMES", "RTX 5090 Founders Edition")
|
||||
monkeypatch.setenv("TEST_MODE", test_mode)
|
||||
if discord_roles is not None:
|
||||
monkeypatch.setenv("DISCORD_ROLES", discord_roles)
|
||||
else:
|
||||
monkeypatch.delenv("DISCORD_ROLES", raising=False)
|
||||
for mod in ("env_config", "notifier"):
|
||||
sys.modules.pop(mod, None)
|
||||
return importlib.import_module("notifier")
|
||||
|
||||
|
||||
class FakeResponse:
|
||||
def __init__(self, status_code=204, text=""):
|
||||
self.status_code = status_code
|
||||
self.text = text
|
||||
|
||||
|
||||
def test_test_mode_skips_network_call(monkeypatch):
|
||||
notifier = _import_notifier(monkeypatch, test_mode="True")
|
||||
calls = []
|
||||
monkeypatch.setattr(notifier.requests, "post", lambda *a, **k: calls.append((a, k)))
|
||||
|
||||
notifier.send_discord_notification("RTX 5090 Founders Edition", "https://example.com", "1999")
|
||||
|
||||
assert calls == []
|
||||
|
||||
|
||||
def test_in_stock_notification_posts_expected_payload(monkeypatch):
|
||||
notifier = _import_notifier(monkeypatch, test_mode="False")
|
||||
captured = {}
|
||||
|
||||
def fake_post(url, json=None, **kwargs):
|
||||
captured["url"] = url
|
||||
captured["json"] = json
|
||||
return FakeResponse()
|
||||
|
||||
monkeypatch.setattr(notifier.requests, "post", fake_post)
|
||||
|
||||
notifier.send_discord_notification(
|
||||
"RTX 5090 Founders Edition", "https://example.com/buy", "1999"
|
||||
)
|
||||
|
||||
assert captured["url"] == notifier.DISCORD_WEBHOOK_URL
|
||||
assert captured["json"]["content"] == "@everyone"
|
||||
embed = captured["json"]["embeds"][0]
|
||||
assert "RTX 5090 Founders Edition" in embed["title"]
|
||||
|
||||
|
||||
def test_discord_notification_survives_http_error(monkeypatch):
|
||||
notifier = _import_notifier(monkeypatch, test_mode="False")
|
||||
monkeypatch.setattr(
|
||||
notifier.requests, "post", lambda *a, **k: FakeResponse(status_code=500, text="boom")
|
||||
)
|
||||
|
||||
notifier.send_discord_notification("RTX 5090 Founders Edition", "https://example.com", "1999")
|
||||
|
||||
|
||||
def test_discord_notification_survives_connection_error(monkeypatch):
|
||||
notifier = _import_notifier(monkeypatch, test_mode="False")
|
||||
|
||||
def raise_error(*a, **k):
|
||||
raise notifier.requests.exceptions.ConnectionError("boom")
|
||||
|
||||
monkeypatch.setattr(notifier.requests, "post", raise_error)
|
||||
|
||||
# Should not raise even though the request itself blew up (network down, DNS, etc.)
|
||||
notifier.send_discord_notification("RTX 5090 Founders Edition", "https://example.com", "1999")
|
||||
|
||||
|
||||
def test_out_of_stock_test_mode_skips_network_call(monkeypatch):
|
||||
notifier = _import_notifier(monkeypatch, test_mode="True")
|
||||
calls = []
|
||||
monkeypatch.setattr(notifier.requests, "post", lambda *a, **k: calls.append((a, k)))
|
||||
|
||||
notifier.send_out_of_stock_notification(
|
||||
"RTX 5090 Founders Edition", "https://example.com", "1999"
|
||||
)
|
||||
|
||||
assert calls == []
|
||||
|
||||
|
||||
def test_out_of_stock_notification_posts_on_success(monkeypatch):
|
||||
notifier = _import_notifier(monkeypatch, test_mode="False")
|
||||
captured = {}
|
||||
|
||||
def fake_post(url, json=None, **kwargs):
|
||||
captured["json"] = json
|
||||
return FakeResponse(status_code=204)
|
||||
|
||||
monkeypatch.setattr(notifier.requests, "post", fake_post)
|
||||
|
||||
notifier.send_out_of_stock_notification(
|
||||
"RTX 5090 Founders Edition", "https://example.com/buy", "1999"
|
||||
)
|
||||
|
||||
assert captured["json"]["embeds"][0]["url"] == "https://example.com/buy"
|
||||
|
||||
|
||||
def test_out_of_stock_notification_survives_http_error(monkeypatch):
|
||||
notifier = _import_notifier(monkeypatch, test_mode="False")
|
||||
monkeypatch.setattr(
|
||||
notifier.requests, "post", lambda *a, **k: FakeResponse(status_code=500, text="boom")
|
||||
)
|
||||
|
||||
# Should not raise even though the webhook call "fails"
|
||||
notifier.send_out_of_stock_notification(
|
||||
"RTX 5090 Founders Edition", "https://example.com", "1999"
|
||||
)
|
||||
|
||||
|
||||
def test_out_of_stock_notification_survives_connection_error(monkeypatch):
|
||||
notifier = _import_notifier(monkeypatch, test_mode="False")
|
||||
|
||||
def raise_error(*a, **k):
|
||||
raise notifier.requests.exceptions.ConnectionError("boom")
|
||||
|
||||
monkeypatch.setattr(notifier.requests, "post", raise_error)
|
||||
|
||||
notifier.send_out_of_stock_notification(
|
||||
"RTX 5090 Founders Edition", "https://example.com", "1999"
|
||||
)
|
||||
|
||||
|
||||
def test_sku_change_test_mode_skips_network_call(monkeypatch):
|
||||
notifier = _import_notifier(monkeypatch, test_mode="True")
|
||||
calls = []
|
||||
monkeypatch.setattr(notifier.requests, "post", lambda *a, **k: calls.append((a, k)))
|
||||
|
||||
notifier.send_sku_change_notification(
|
||||
"RTX 5090 Founders Edition", "old-sku", "new-sku", "https://example.com"
|
||||
)
|
||||
|
||||
assert calls == []
|
||||
|
||||
|
||||
def test_sku_change_notification_survives_http_error(monkeypatch):
|
||||
notifier = _import_notifier(monkeypatch, test_mode="False")
|
||||
monkeypatch.setattr(
|
||||
notifier.requests, "post", lambda *a, **k: FakeResponse(status_code=500, text="boom")
|
||||
)
|
||||
|
||||
notifier.send_sku_change_notification(
|
||||
"RTX 5090 Founders Edition", "old-sku", "new-sku", "https://example.com"
|
||||
)
|
||||
|
||||
|
||||
def test_sku_change_notification_survives_connection_error(monkeypatch):
|
||||
notifier = _import_notifier(monkeypatch, test_mode="False")
|
||||
|
||||
def raise_error(*a, **k):
|
||||
raise notifier.requests.exceptions.ConnectionError("boom")
|
||||
|
||||
monkeypatch.setattr(notifier.requests, "post", raise_error)
|
||||
|
||||
notifier.send_sku_change_notification(
|
||||
"RTX 5090 Founders Edition", "old-sku", "new-sku", "https://example.com"
|
||||
)
|
||||
|
||||
|
||||
def test_sku_change_notification_mentions_role_and_skus(monkeypatch):
|
||||
notifier = _import_notifier(
|
||||
monkeypatch, test_mode="False", discord_roles="<@&123456789012345678>"
|
||||
)
|
||||
captured = {}
|
||||
|
||||
def fake_post(url, json=None, **kwargs):
|
||||
captured["json"] = json
|
||||
return FakeResponse()
|
||||
|
||||
monkeypatch.setattr(notifier.requests, "post", fake_post)
|
||||
|
||||
notifier.send_sku_change_notification(
|
||||
"RTX 5090 Founders Edition", "old-sku-123", "new-sku-456", "https://example.com"
|
||||
)
|
||||
|
||||
assert "<@&123456789012345678>" in captured["json"]["content"]
|
||||
description = captured["json"]["embeds"][0]["description"]
|
||||
assert "old-sku-123" in description
|
||||
assert "new-sku-456" in description
|
||||
Reference in new issue
Block a user