-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnft_floor_tracker.py
More file actions
681 lines (608 loc) Β· 29.1 KB
/
Copy pathnft_floor_tracker.py
File metadata and controls
681 lines (608 loc) Β· 29.1 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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
"""
nft_floor_tracker.py - NFT Floor Price Tracker
By Rizal | github.com/rizalcodes
Track NFT collection floor prices, volume & sales on Ethereum
Source: OpenSea API v2 (free tier)
Output: Real-time alerts + Telegram bot
"""
import os
import time
import logging
import requests
from datetime import datetime
from collections import defaultdict
# βββββββββββββββββββββββββββββββββββββββββββββ
# LOGGING
# βββββββββββββββββββββββββββββββββββββββββββββ
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
datefmt="%Y-%m-%d %H:%M:%S"
)
log = logging.getLogger(__name__)
# βββββββββββββββββββββββββββββββββββββββββββββ
# CONFIG
# βββββββββββββββββββββββββββββββββββββββββββββ
OPENSEA_API_KEY = os.getenv("OPENSEA_API_KEY", "Your_OpenSea_Api_Key_Here")
TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN", "Your_Bot_Token_Here")
TELEGRAM_CHAT_ID = os.getenv("TELEGRAM_CHAT_ID", "Your_Chat_ID_Here")
# Thresholds
FLOOR_DROP_ALERT = 10.0 # alert kalau floor drop > 10%
FLOOR_PUMP_ALERT = 20.0 # alert kalau floor pump > 20%
VOLUME_SPIKE_ALERT = 50.0 # alert kalau volume spike > 50%
POLL_INTERVAL = 300 # cek setiap 5 menit
# Known collections (slug β display name)
KNOWN_COLLECTIONS = {
"boredapeyachtclub" : "Bored Ape Yacht Club",
"cryptopunks" : "CryptoPunks",
"mutant-ape-yacht-club" : "Mutant Ape Yacht Club",
"azuki" : "Azuki",
"doodles-official" : "Doodles",
"clonex" : "Clone X",
"pudgypenguins" : "Pudgy Penguins",
"milady" : "Milady Maker",
"degods" : "DeGods",
}
# βββββββββββββββββββββββββββββββββββββββββββββ
# 1. OPENSEA CLIENT
# βββββββββββββββββββββββββββββββββββββββββββββ
class OpenSeaClient:
"""
OpenSea API v2 β official NFT data API.
Free tier: 4 req/sec
Docs: https://docs.opensea.io/reference/api-overview
"""
BASE = "https://api.opensea.io/api/v2"
def __init__(self, api_key: str):
self.session = requests.Session()
self.session.headers.update({
"accept" : "application/json",
"x-api-key": api_key,
})
def _get(self, endpoint: str, params: dict = None) -> dict:
try:
r = self.session.get(
f"{self.BASE}{endpoint}",
params=params,
timeout=15
)
if r.status_code == 429:
log.warning("Rate limited β sleeping 2s")
time.sleep(2)
r = self.session.get(f"{self.BASE}{endpoint}", params=params, timeout=15)
return r.json()
except Exception as e:
log.error(f"OpenSea API error: {e}")
return {}
def get_collection(self, slug: str) -> dict:
"""Ambil info & stats collection."""
# Get collection info
info = self._get(f"/collections/{slug}")
if not info or info.get("detail"):
return {}
# Get collection stats
stats = self._get(f"/collections/{slug}/stats")
total = stats.get("total", {})
inter = stats.get("intervals", [])
# Get 1day interval stats
day1 = {}
for iv in inter:
if iv.get("interval") == "one_day":
day1 = iv
break
# Get ETH price for USD conversion
eth_price = self._get_eth_price()
floor_eth = float(total.get("floor_price", 0) or 0)
vol_24h = float(day1.get("volume", 0) or 0)
vol_7d = sum(
float(iv.get("volume", 0) or 0)
for iv in inter if iv.get("interval") == "one_week"
)
sales_24h = int(day1.get("sales", 0) or 0)
return {
"name" : info.get("name", "Unknown"),
"slug" : slug,
"contract" : info.get("contracts", [{}])[0].get("address", "") if info.get("contracts") else "",
"description" : info.get("description", "")[:100],
"floor_eth" : floor_eth,
"floor_usd" : round(floor_eth * eth_price, 2),
"volume_24h_eth" : vol_24h,
"volume_7d_eth" : vol_7d,
"sales_24h" : sales_24h,
"supply" : int(total.get("supply", 0) or 0),
"owners" : int(total.get("num_owners", 0) or 0),
"market_cap_eth" : float(total.get("market_cap", 0) or 0),
"avg_price_eth" : float(total.get("average_price", 0) or 0),
"timestamp" : datetime.now().isoformat(),
}
def get_recent_sales(self, slug: str, limit: int = 5) -> list:
"""Ambil recent sales untuk collection."""
data = self._get(f"/events/collection/{slug}", params={"event_type": "sale", "limit": limit})
sales = data.get("asset_events", [])
result = []
for s in sales:
payment = s.get("payment", {})
qty = int(s.get("quantity", 1) or 1)
price = int(payment.get("quantity", 0) or 0)
decs = int(payment.get("decimals", 18) or 18)
price_eth = price / (10 ** decs) if price else 0
eth_price = self._get_eth_price()
nft = s.get("nft", {})
result.append({
"token_id" : nft.get("identifier", ""),
"name" : nft.get("name", f"#{nft.get('identifier','')}"),
"price_eth" : round(price_eth, 4),
"price_usd" : round(price_eth * eth_price, 2),
"buyer" : s.get("buyer", ""),
"seller" : s.get("seller", ""),
"tx_hash" : s.get("transaction", ""),
"timestamp" : s.get("closing_date", ""),
"marketplace": "OpenSea",
})
return result
def get_top_collections(self, limit: int = 10) -> list:
"""Ambil top collections by volume."""
data = self._get("/collections", params={"order_by": "one_day_volume", "limit": limit})
collections = data.get("collections", [])
result = []
eth_price = self._get_eth_price()
for c in collections:
floor_eth = float(c.get("stats", {}).get("floor_price", 0) or 0)
result.append({
"name" : c.get("name", "Unknown"),
"slug" : c.get("collection", ""),
"floor_eth" : floor_eth,
"floor_usd" : round(floor_eth * eth_price, 2),
"volume_24h_eth": float(c.get("stats", {}).get("one_day_volume", 0) or 0),
"sales_24h" : int(c.get("stats", {}).get("one_day_sales", 0) or 0),
})
return result
def search_collection(self, query: str) -> list:
"""Search collection by name via OpenSea."""
try:
r = self.session.get(
f"{self.BASE}/collections",
params={
"order_by": "one_day_volume",
"limit" : 100, # ambil lebih banyak buat filter
},
timeout=15
)
collections = r.json().get("collections", [])
query_lower = query.lower()
results = []
for c in collections:
name = c.get("name", "")
slug = c.get("collection", "")
if query_lower in name.lower() or query_lower in slug.lower():
results.append({
"name" : name,
"slug" : slug,
"contract": c.get("contracts", [{}])[0].get("address", "") if c.get("contracts") else "",
})
return results[:5]
except Exception as e:
log.error(f"Search error: {e}")
return []
def _get_eth_price(self) -> float:
"""Ambil ETH price dari CoinGecko."""
try:
r = requests.get(
"https://api.coingecko.com/api/v3/simple/price",
params={"ids": "ethereum", "vs_currencies": "usd"},
timeout=10
)
return float(r.json().get("ethereum", {}).get("usd", 3000))
except Exception:
return 3000
# βββββββββββββββββββββββββββββββββββββββββββββ
# 2. NFT FLOOR TRACKER
# βββββββββββββββββββββββββββββββββββββββββββββ
class NFTFloorTracker:
"""Core engine untuk track NFT floor prices."""
def __init__(self, api_key: str):
self.opensea = OpenSeaClient(api_key)
self.watchlist = {}
self.price_history = defaultdict(list)
def add_collection(self, slug: str) -> dict:
log.info(f"πΌοΈ Adding collection: {slug}")
data = self.opensea.get_collection(slug)
if not data:
return {"error": f"Collection '{slug}' not found"}
self.watchlist[slug] = data
self.price_history[slug].append({
"floor_eth" : data["floor_eth"],
"floor_usd" : data["floor_usd"],
"timestamp" : data["timestamp"],
})
log.info(f"β
Added: {data['name']} β Floor: {data['floor_eth']} ETH")
return data
def remove_collection(self, slug: str):
self.watchlist.pop(slug, None)
self.price_history.pop(slug, None)
def get_collections(self) -> list:
return list(self.watchlist.values())
def refresh(self, slug: str) -> dict:
old_data = self.watchlist.get(slug, {})
new_data = self.opensea.get_collection(slug)
if not new_data:
return {}
alerts = []
if old_data and old_data.get("floor_eth", 0) > 0:
old_floor = old_data["floor_eth"]
new_floor = new_data["floor_eth"]
change_pct = ((new_floor - old_floor) / old_floor) * 100
if change_pct <= -FLOOR_DROP_ALERT:
alerts.append({
"type" : "FLOOR_DROP",
"change_pct": round(change_pct, 2),
"old_floor" : old_floor,
"new_floor" : new_floor,
"severity" : "HIGH" if change_pct <= -20 else "MEDIUM",
})
elif change_pct >= FLOOR_PUMP_ALERT:
alerts.append({
"type" : "FLOOR_PUMP",
"change_pct": round(change_pct, 2),
"old_floor" : old_floor,
"new_floor" : new_floor,
"severity" : "HIGH" if change_pct >= 50 else "MEDIUM",
})
old_vol = old_data.get("volume_24h_eth", 0)
new_vol = new_data.get("volume_24h_eth", 0)
if old_vol > 0:
vol_change = ((new_vol - old_vol) / old_vol) * 100
if vol_change >= VOLUME_SPIKE_ALERT:
alerts.append({
"type" : "VOLUME_SPIKE",
"change_pct": round(vol_change, 2),
"old_vol" : old_vol,
"new_vol" : new_vol,
"severity" : "MEDIUM",
})
self.watchlist[slug] = new_data
self.price_history[slug].append({
"floor_eth" : new_data["floor_eth"],
"floor_usd" : new_data["floor_usd"],
"timestamp" : new_data["timestamp"],
})
if len(self.price_history[slug]) > 100:
self.price_history[slug] = self.price_history[slug][-100:]
new_data["alerts"] = alerts
return new_data
def refresh_all(self) -> list:
all_alerts = []
for slug in list(self.watchlist.keys()):
data = self.refresh(slug)
if data.get("alerts"):
for alert in data["alerts"]:
alert["collection"] = data["name"]
alert["slug"] = slug
alert["floor_eth"] = data["floor_eth"]
all_alerts.extend(data["alerts"])
time.sleep(0.5)
return all_alerts
def get_price_change(self, slug: str) -> dict:
history = self.price_history.get(slug, [])
if len(history) < 2:
return {"change_pct": 0, "change_eth": 0, "direction": "β‘οΈ"}
first = history[0]["floor_eth"]
last = history[-1]["floor_eth"]
if first == 0:
return {"change_pct": 0, "change_eth": 0, "direction": "β‘οΈ"}
change_eth = last - first
change_pct = (change_eth / first) * 100
return {
"change_pct": round(change_pct, 2),
"change_eth": round(change_eth, 4),
"direction" : "π" if change_pct > 0 else "π" if change_pct < 0 else "β‘οΈ",
}
# βββββββββββββββββββββββββββββββββββββββββββββ
# 3. TELEGRAM BOT
# βββββββββββββββββββββββββββββββββββββββββββββ
class NFTFloorBot:
def __init__(self):
self.token = TELEGRAM_TOKEN
self.chat_id = TELEGRAM_CHAT_ID
self.base = f"https://api.telegram.org/bot{self.token}"
self.tracker = NFTFloorTracker(OPENSEA_API_KEY)
self.offset = 0
self.running = True
self.monitoring = False
log.info("π€ NFTFloorBot initialized")
def send(self, chat_id: str, text: str):
for attempt in range(3): # retry 3x
try:
requests.post(
f"{self.base}/sendMessage",
json={"chat_id": chat_id, "text": text, "parse_mode": "Markdown"},
timeout=15 # naikin dari 10 β 15
)
return
except Exception as e:
log.error(f"Send error (attempt {attempt+1}): {e}")
time.sleep(2)
def get_updates(self) -> list:
try:
r = requests.get(
f"{self.base}/getUpdates",
params={"offset": self.offset, "timeout": 10},
timeout=15
)
return r.json().get("result", [])
except Exception:
return []
def _format_collection(self, data: dict, show_history: bool = False) -> str:
name = data.get("name", "Unknown")
slug = data.get("slug", "")
floor_eth = data.get("floor_eth", 0)
floor_usd = data.get("floor_usd", 0)
vol_24h = data.get("volume_24h_eth", 0)
vol_7d = data.get("volume_7d_eth", 0)
sales_24h = data.get("sales_24h", 0)
supply = data.get("supply", 0)
owners = data.get("owners", 0)
mktcap = data.get("market_cap_eth", 0)
avg_price = data.get("avg_price_eth", 0)
unique_pct = round((owners / supply * 100), 1) if supply > 0 else 0
msg = f"""
πΌοΈ *{name}*
ββββββββββββββββββββββ
π Floor : `{floor_eth:.4f} ETH` (~`${floor_usd:,.2f}`)
π Vol 24h : `{vol_24h:.2f} ETH`
π
Vol 7d : `{vol_7d:.2f} ETH`
π Sales 24h : `{sales_24h}`
π° Avg Price : `{avg_price:.4f} ETH`
π¦ Market Cap : `{mktcap:.1f} ETH`
π₯ Owners : `{owners:,}` / `{supply:,}` ({unique_pct}% unique)
""".strip()
if show_history:
change = self.tracker.get_price_change(slug)
msg += f"\n\n{change['direction']} Session Change: `{change['change_pct']:+.2f}%` (`{change['change_eth']:+.4f} ETH`)"
msg += f"\n\nβ° `{data.get('timestamp', '')[:19]}`"
return msg
def _format_alert(self, alert: dict) -> str:
if alert["type"] == "FLOOR_DROP":
sev, emoji, title = ("π΄" if alert["severity"] == "HIGH" else "π‘"), "π", "FLOOR DROP ALERT"
elif alert["type"] == "FLOOR_PUMP":
sev, emoji, title = "π’", "π", "FLOOR PUMP ALERT"
else:
sev, emoji, title = "π‘", "π", "VOLUME SPIKE ALERT"
msg = f"{sev} *{title}* {emoji}\nββββββββββββββββββββββ\nπΌοΈ *{alert.get('collection', 'Unknown')}*"
if alert["type"] in ("FLOOR_DROP", "FLOOR_PUMP"):
msg += f"\n\nπ Old Floor : `{alert['old_floor']:.4f} ETH`\nπ New Floor : `{alert['new_floor']:.4f} ETH`\nπ Change : `{alert['change_pct']:+.2f}%`"
else:
msg += f"\n\nπ Old Vol : `{alert['old_vol']:.2f} ETH`\nπ New Vol : `{alert['new_vol']:.2f} ETH`\nπ Change : `{alert['change_pct']:+.2f}%`"
msg += f"\n\nβ° `{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}`"
return msg
# ββ Commands ββββββββββββββββββββββββββββββ
def cmd_start(self, chat_id: str):
self.send(chat_id, """
πΌοΈ *NFT Floor Price Tracker*
ββββββββββββββββββββββ
Track NFT floor prices & get alerts on pumps/dumps!
π *Commands:*
/floor `<slug>` β Get floor price
/add `<slug>` β Add to watchlist
/remove `<slug>` β Remove from watchlist
/list β Show tracked collections
/sales `<slug>` β Recent sales
/top β Top collections by volume
/search `<name>` β Search collection
/monitor on/off β Auto monitor
/known β Show known collections
/help β Show commands
*Example:*
`/floor pudgypenguins`
`/add boredapeyachtclub`
`/search azuki`
""".strip())
def cmd_floor(self, chat_id: str, args: list):
if not args:
self.send(chat_id, "β οΈ Usage: `/floor <slug>`\nExample: `/floor pudgypenguins`")
return
slug = args[0].strip().lower()
self.send(chat_id, f"π Fetching floor price for `{slug}`...\nβ³ Please wait...")
try:
data = self.tracker.opensea.get_collection(slug)
if not data:
self.send(chat_id, f"β Collection `{slug}` not found.\nTry `/search {slug}` or `/known` for valid slugs.")
return
self.send(chat_id, self._format_collection(data))
except Exception as e:
self.send(chat_id, f"β Error: `{str(e)[:200]}`")
def cmd_add(self, chat_id: str, args: list):
if not args:
self.send(chat_id, "β οΈ Usage: `/add <slug>`")
return
slug = args[0].strip().lower()
self.send(chat_id, f"π Adding `{slug}`...\nβ³ Please wait...")
try:
data = self.tracker.add_collection(slug)
if data.get("error"):
self.send(chat_id, f"β {data['error']}\nTry `/search {slug}` or `/known` for valid slugs.")
return
self.send(chat_id, f"β
*Added to watchlist!*\n\n" + self._format_collection(data))
except Exception as e:
self.send(chat_id, f"β Error: `{str(e)[:200]}`")
def cmd_remove(self, chat_id: str, args: list):
if not args:
self.send(chat_id, "β οΈ Usage: `/remove <slug>`")
return
slug = args[0].strip().lower()
if slug in self.tracker.watchlist:
name = self.tracker.watchlist[slug]["name"]
self.tracker.remove_collection(slug)
self.send(chat_id, f"β
*{name}* removed from watchlist.")
else:
self.send(chat_id, f"β `{slug}` not in watchlist.")
def cmd_list(self, chat_id: str):
collections = self.tracker.get_collections()
if not collections:
self.send(chat_id, "π Watchlist empty.\nUse `/add <slug>` to track collections.")
return
lines = [f"π *Tracked Collections ({len(collections)})*\nββββββββββββββββββββββ"]
for i, c in enumerate(collections, 1):
change = self.tracker.get_price_change(c["slug"])
lines.append(
f"{i}. *{c['name']}*\n"
f" π `{c['floor_eth']:.4f} ETH` {change['direction']} `{change['change_pct']:+.2f}%`"
)
self.send(chat_id, "\n\n".join(lines))
def cmd_sales(self, chat_id: str, args: list):
if not args:
self.send(chat_id, "β οΈ Usage: `/sales <slug>`")
return
slug = args[0].strip().lower()
self.send(chat_id, f"π Fetching recent sales for `{slug}`...")
try:
sales = self.tracker.opensea.get_recent_sales(slug, limit=5)
if not sales:
self.send(chat_id, "π No recent sales found.")
return
msg = f"π *Recent Sales β {slug}*\nββββββββββββββββββββββ\n"
for s in sales:
msg += f"\nβ’ *{s['name']}* β `{s['price_eth']:.4f} ETH` (~`${s['price_usd']:,.2f}`)\n"
msg += f" β° {s['timestamp'][:19] if s['timestamp'] else 'N/A'}\n"
self.send(chat_id, msg)
except Exception as e:
self.send(chat_id, f"β Error: `{str(e)[:200]}`")
def cmd_top(self, chat_id: str):
self.send(chat_id, "π Fetching top collections...\nβ³ Please wait...")
try:
collections = self.tracker.opensea.get_top_collections(10)
if not collections:
self.send(chat_id, "β No data available.")
return
msg = "π *TOP NFT COLLECTIONS β 24h Volume*\nββββββββββββββββββββββ\n\n"
for i, c in enumerate(collections, 1):
msg += (
f"{i}. *{c['name']}*\n"
f" π Floor: `{c['floor_eth']:.4f} ETH`\n"
f" π Vol 24h: `{c['volume_24h_eth']:.2f} ETH` | Sales: `{c['sales_24h']}`\n\n"
)
msg += f"β° {datetime.now().strftime('%Y-%m-%d %H:%M')}"
self.send(chat_id, msg)
except Exception as e:
self.send(chat_id, f"β Error: `{str(e)[:200]}`")
def cmd_search(self, chat_id: str, args: list):
if not args:
self.send(chat_id, "β οΈ Usage: `/search <name>`")
return
query = " ".join(args).strip().lower().replace(" ", "-")
self.send(chat_id, f"π Searching `{query}`...")
slug_variants = [
query,
query.replace("-", ""),
query.replace(" ", ""),
query + "official",
query + "-official",
]
found = False
for slug in slug_variants:
data = self.tracker.opensea.get_collection(slug)
if data and data.get("name"):
self.send(chat_id, f"π *Found!*\nββββββββββββββββββββββ\nβ’ *{data['name']}*\n Slug: `{slug}`\n π Floor: `{data['floor_eth']:.4f} ETH`\n Use: `/add {slug}`")
found = True
break
if not found:
self.send(chat_id, "β *Not found!*\n\nTry:\n`/add cryptopunks`\n`/add boredapeyachtclub`\n`/add pudgypenguins`\n`/add azuki`\n`/add clonex`\n`/add milady`\n`/add degods`\n\nOr use `/known` for full list!")
def cmd_monitor(self, chat_id: str, args: list):
if not args:
status = "ON β
" if self.monitoring else "OFF β"
self.send(chat_id, f"π‘ Auto Monitor: *{status}*\nUse `/monitor on` or `/monitor off`")
return
if args[0].lower() == "on":
if not self.tracker.get_collections():
self.send(chat_id, "β οΈ No collections tracked. Add one first with `/add <slug>`")
return
self.monitoring = True
self.send(chat_id, f"β
*Monitor ON* β Checking every {POLL_INTERVAL//60} mins.")
elif args[0].lower() == "off":
self.monitoring = False
self.send(chat_id, "β *Monitor OFF*")
def cmd_known(self, chat_id: str):
lines = ["π *Known Collections*\nββββββββββββββββββββββ"]
for slug, name in KNOWN_COLLECTIONS.items():
lines.append(f"β’ *{name}*\n `/add {slug}`")
self.send(chat_id, "\n\n".join(lines))
# ββ Message Router ββββββββββββββββββββββββ
def handle(self, message: dict):
text = message.get("text", "").strip()
chat_id = str(message.get("chat", {}).get("id", ""))
if not text or not chat_id:
return
parts = text.split()
command = parts[0].lower()
args = parts[1:]
log.info(f"π¨ {command} from {chat_id}")
if command in ("/start", "/help"): self.cmd_start(chat_id)
elif command == "/floor": self.cmd_floor(chat_id, args)
elif command == "/add": self.cmd_add(chat_id, args)
elif command == "/remove": self.cmd_remove(chat_id, args)
elif command == "/list": self.cmd_list(chat_id)
elif command == "/sales": self.cmd_sales(chat_id, args)
elif command == "/top": self.cmd_top(chat_id)
elif command == "/search": self.cmd_search(chat_id, args)
elif command == "/monitor": self.cmd_monitor(chat_id, args)
elif command == "/known": self.cmd_known(chat_id)
else:
self.send(chat_id, "β Unknown command. Type /help for commands.")
# ββ Background Monitor ββββββββββββββββββββ
def _monitor_loop(self):
log.info("π‘ NFT monitor loop started")
while self.running:
if self.monitoring and self.tracker.get_collections():
try:
alerts = self.tracker.refresh_all()
for alert in alerts:
self.send(self.chat_id, self._format_alert(alert))
time.sleep(1)
log.info(f"β
Refreshed {len(self.tracker.get_collections())} collections, {len(alerts)} alerts")
except Exception as e:
log.error(f"Monitor loop error: {e}")
time.sleep(POLL_INTERVAL)
# ββ Main Loop βββββββββββββββββββββββββββββ
def run(self):
import threading
log.info("π NFTFloorBot started!")
threading.Thread(target=self._monitor_loop, daemon=True).start()
while self.running:
try:
updates = self.get_updates()
for update in updates:
self.offset = update["update_id"] + 1
msg = update.get("message", {})
if msg:
self.handle(msg)
except KeyboardInterrupt:
self.running = False
except Exception as e:
log.error(f"Polling error: {e}")
time.sleep(5)
# βββββββββββββββββββββββββββββββββββββββββββββ
# ENTRY POINT
# βββββββββββββββββββββββββββββββββββββββββββββ
if __name__ == "__main__":
import sys
if len(sys.argv) > 1 and sys.argv[1] == "check":
if len(sys.argv) < 3:
print("Usage: python nft_floor_tracker.py check <slug>")
sys.exit(1)
slug = sys.argv[2]
tracker = NFTFloorTracker(OPENSEA_API_KEY)
print(f"\nπΌοΈ Fetching: {slug}")
data = tracker.opensea.get_collection(slug)
if not data:
print(f"β Collection '{slug}' not found.")
sys.exit(1)
print(f"\nName : {data['name']}")
print(f"Floor : {data['floor_eth']:.4f} ETH (${data['floor_usd']:,.2f})")
print(f"Vol 24h : {data['volume_24h_eth']:.2f} ETH")
print(f"Vol 7d : {data['volume_7d_eth']:.2f} ETH")
print(f"Sales 24h : {data['sales_24h']}")
print(f"Supply : {data['supply']:,}")
print(f"Owners : {data['owners']:,}")
else:
bot = NFTFloorBot()
bot.run()