-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
224 lines (184 loc) · 7.13 KB
/
Copy pathmain.py
File metadata and controls
224 lines (184 loc) · 7.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
"""
Price Monitor — main entry point.
Periodically scrapes a product page, logs the price, and sends alerts
when the price drops below a configured threshold or hits a new low.
"""
from __future__ import annotations
import logging
import os
import sys
import time
from datetime import datetime, timezone
# ---------------------------------------------------------------------------
# Bootstrap: allow `python main.py` to work from the project root
# ---------------------------------------------------------------------------
_here = os.path.dirname(os.path.abspath(__file__))
if _here not in sys.path:
sys.path.insert(0, _here)
# ---------------------------------------------------------------------------
# Optional .env support — load before reading config
# ---------------------------------------------------------------------------
try:
from dotenv import load_dotenv
load_dotenv(os.path.join(_here, ".env"))
except ImportError:
pass
# ---------------------------------------------------------------------------
# Project modules
# ---------------------------------------------------------------------------
from scraper import get_current_price
from storage import PriceRecord, save_record, price_dropped, get_lowest_price
from notifier import notify, NOTIFIERS
# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------
def _load_config() -> dict:
"""Load configuration from ``config.py``, falling back to env vars.
``config.py`` is the preferred source; any key that is also set as an
environment variable will be overridden by the env var.
"""
config: dict = {}
# 1. Try to import config.py
try:
import config as cfg_mod
for key in dir(cfg_mod):
if key.isupper():
config[key] = getattr(cfg_mod, key)
logging.debug("Loaded %d keys from config.py", len(config))
except ImportError:
logging.warning("config.py not found — using environment variables only")
# 2. Overlay environment variables (higher priority)
for key in (
"TARGET_URL",
"CSS_SELECTOR",
"PRICE_REGEX",
"CHECK_INTERVAL",
"PRICE_THRESHOLD",
"EMAIL_RECIPIENT",
"SMTP_SERVER",
"SMTP_PORT",
"SMTP_USER",
"SMTP_PASSWORD",
"TELEGRAM_BOT_TOKEN",
"TELEGRAM_CHAT_ID",
):
env_val = os.getenv(key)
if env_val is not None:
config[key] = env_val
return config
def _validate_config(config: dict) -> None:
"""Exit early if required keys are missing."""
required = ["TARGET_URL", "CSS_SELECTOR"]
missing = [k for k in required if not config.get(k)]
if missing:
logging.error(
"Missing required config key(s): %s\n"
"Copy config.example.py → config.py and fill in the values.",
", ".join(missing),
)
sys.exit(1)
# Normalise numeric config
config.setdefault("CHECK_INTERVAL", 3600)
config.setdefault("PRICE_THRESHOLD", float("inf"))
try:
config["CHECK_INTERVAL"] = int(config["CHECK_INTERVAL"])
config["PRICE_THRESHOLD"] = float(config["PRICE_THRESHOLD"])
except (TypeError, ValueError) as exc:
logging.error("Invalid numeric config value: %s", exc)
sys.exit(1)
# ---------------------------------------------------------------------------
# Core logic
# ---------------------------------------------------------------------------
def _build_alert_body(price: float, threshold: float, lowest: float | None) -> str:
lines = [
f"当前价格: ¥{price:.2f}",
f"设定阈值: ¥{threshold:.2f}",
]
if lowest is not None:
lines.append(f"历史最低: ¥{lowest:.2f}")
return "\n".join(lines)
def check_once(config: dict) -> PriceRecord | None:
"""Run one scrape→save→alert cycle. Returns the new record, or None on failure."""
url = config["TARGET_URL"]
selector = config["CSS_SELECTOR"]
regex = config.get("PRICE_REGEX")
threshold = config["PRICE_THRESHOLD"]
history_file = config.get("HISTORY_FILE", "price_history.jsonl")
# 1. Scrape
price = get_current_price(url, selector, regex=regex)
if price is None:
logging.warning("Could not extract price — skipping this cycle")
return None
# 2. Persist
record = PriceRecord(
timestamp=datetime.now(timezone.utc).isoformat(),
url=url,
price=price,
)
save_record(record, filepath=history_file)
# 3. Decide whether to alert
should_alert = False
reason = ""
if price <= threshold:
should_alert = True
reason = f"价格 ¥{price:.2f} 低于阈值 ¥{threshold:.2f}"
elif price_dropped(price, filepath=history_file):
should_alert = True
reason = f"价格 ¥{price:.2f} 较上次记录下降"
if should_alert:
lowest = get_lowest_price(filepath=history_file)
lowest_price = lowest.price if lowest else None
subject = f"🔔 价格提醒: ¥{price:.2f}"
body = reason + "\n\n" + _build_alert_body(price, threshold, lowest_price)
notify(config, subject, body)
return record
# ---------------------------------------------------------------------------
# Main loop
# ---------------------------------------------------------------------------
def main() -> None:
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
config = _load_config()
_validate_config(config)
interval = config["CHECK_INTERVAL"]
logging.info(
"🚀 Price Monitor started — checking %s every %ds",
config["TARGET_URL"], interval,
)
logging.info(
" Notifiers enabled: %s",
", ".join(NOTIFIERS.keys()) or "(none)",
)
consecutive_errors = 0
MAX_CONSECUTIVE_ERRORS = 5
try:
while True:
try:
check_once(config)
consecutive_errors = 0 # 成功后重置
except Exception as exc:
# ---- 全局兜底:即使 check_once 内部崩溃也不退出 ----
logging.error(
"未预期的异常 (%s): %s — 跳过本次检查,继续运行",
type(exc).__name__, exc,
)
logging.debug("详细堆栈:", exc_info=True)
consecutive_errors += 1
if consecutive_errors >= MAX_CONSECUTIVE_ERRORS:
logging.critical(
"连续异常 %d 次,自动退出。请检查:\n"
" 1) 网络是否正常\n"
" 2) 目标页面 URL 是否仍然有效\n"
" 3) CSS_SELECTOR 是否需要更新",
MAX_CONSECUTIVE_ERRORS,
)
break
logging.info("Next check in %ds ...", interval)
time.sleep(interval)
except KeyboardInterrupt:
logging.info("👋 Shutting down. Goodbye!")
if __name__ == "__main__":
main()