aboutsummaryrefslogtreecommitdiff
path: root/bot.py
blob: 4f53d02e43dc15ca9f77092fa5d06000004fb608 (plain)
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
from collections import Counter
import os
import sqlite3
import sys
import warnings

import aiohttp
import discord
from discord.ext import commands
from dotenv import load_dotenv
import spotipy
from spotipy.oauth2 import SpotifyOAuth
from urllib.parse import parse_qs, urlparse

load_dotenv()

REQUIRED_ENV = [
    "SPOTIFY_CLIENT_ID",
    "SPOTIFY_CLIENT_SECRET",
    "SPOTIFY_REDIRECT_URI",
    "DISCORD_BOT_TOKEN",
    "DISCORD_APP_ID",
]

for var in REQUIRED_ENV:
    if not os.getenv(var):
        print(f"❌ Error: Missing required environment variable '{var}' in .env file.")
        sys.exit(1)

SPOTIFY_CLIENT_ID = os.getenv("SPOTIFY_CLIENT_ID")
SPOTIFY_CLIENT_SECRET = os.getenv("SPOTIFY_CLIENT_SECRET")
SPOTIFY_REDIRECT_URI = os.getenv("SPOTIFY_REDIRECT_URI", "http://localhost:8888/callback")
DISCORD_BOT_TOKEN = os.getenv("DISCORD_BOT_TOKEN")
DISCORD_APP_ID = os.getenv("DISCORD_APP_ID")
DISCORD_IDENTITY_ID = os.getenv("DISCORD_IDENTITY_ID", "0")

SCOPE = "user-read-private user-top-read user-read-currently-playing user-read-playback-state user-read-recently-played"
# ==============================================================================
# 2. DATABASE SETUP
# ==============================================================================
conn = sqlite3.connect("tokens.db", check_same_thread=False)
cursor = conn.cursor()
cursor.execute(
    """
    CREATE TABLE IF NOT EXISTS user_tokens (
        discord_id TEXT PRIMARY KEY,
        refresh_token TEXT NOT NULL,
        time_range TEXT NOT NULL DEFAULT '4w'
    )
"""
)
# Migrate existing tables that don't yet have the time_range column
try:
    cursor.execute("ALTER TABLE user_tokens ADD COLUMN time_range TEXT NOT NULL DEFAULT '4w'")
except sqlite3.OperationalError:
    pass  # Column already exists
conn.commit()

# ==============================================================================
# 3. SPOTIFY API & AUTHENTICATION HELPERS
# ==============================================================================
def get_oauth() -> SpotifyOAuth:
    return SpotifyOAuth(
        client_id=SPOTIFY_CLIENT_ID,
        client_secret=SPOTIFY_CLIENT_SECRET,
        redirect_uri=SPOTIFY_REDIRECT_URI,
        scope=SCOPE,
    )


def get_spotify_client(discord_id: str) -> spotipy.Spotify | None:
    """Retrieves user's refresh token from SQLite and returns an authenticated Spotify client."""
    cursor.execute(
        "SELECT refresh_token FROM user_tokens WHERE discord_id = ?",
        (str(discord_id),),
    )
    row = cursor.fetchone()

    if not row:
        return None

    try:
        sp_oauth = get_oauth()
        token_info = sp_oauth.refresh_access_token(row[0])
        return spotipy.Spotify(auth=token_info["access_token"])
    except Exception as e:
        print(f"Error refreshing token for user {discord_id}: {e}")
        return None


def get_user_time_range(discord_id: str) -> str:
    """Returns the stored time range string for a user, defaulting to '4w'."""
    cursor.execute(
        "SELECT time_range FROM user_tokens WHERE discord_id = ?",
        (str(discord_id),),
    )
    row = cursor.fetchone()
    return row[0] if row else "4w"


def parse_time_range(range_str: str) -> tuple[str, str, str]:
    """Parses a time range string (e.g. '4w', '30d', '6m', '1y') into
    a (spotify_time_range, human_label, tier_note) tuple.

    Spotify only supports three fixed ranges:
      short_term  ≈ last 4 weeks
      medium_term ≈ last 6 months
      long_term   ≈ several years (Spotify's maximum)

    Mapping:
      d (days):   1–28  → short_term, 29–180 → medium_term, >180 → long_term
      w (weeks):  1–4   → short_term, 5–26   → medium_term, >26  → long_term
      m (months): 1     → short_term, 2–6    → medium_term, >6   → long_term
      y (years):  any   → long_term
    """
    range_str = range_str.strip().lower()
    if not range_str:
        raise ValueError("Empty range string.")

    unit = range_str[-1]
    if unit not in ("d", "w", "m", "y"):
        raise ValueError(f"Unknown unit '{unit}'. Use d (days), w (weeks), m (months), y (years).")

    try:
        value = int(range_str[:-1])
    except ValueError:
        raise ValueError(f"Invalid number in range '{range_str}'.")

    if value <= 0:
        raise ValueError("Range value must be a positive integer.")

    # Human-readable label
    unit_names = {"d": "day", "w": "week", "m": "month", "y": "year"}
    unit_name = unit_names[unit]
    label = f"{value} {unit_name}{'s' if value != 1 else ''}"

    # Map to Spotify API time range
    if unit == "d":
        days = value
    elif unit == "w":
        days = value * 7
    elif unit == "m":
        days = value * 30
    else:  # y
        days = value * 365

    if days <= 28:
        spotify_range = "short_term"
        tier_note = "Spotify tier: **~last 4 weeks** (Spotify's shortest window)"
    elif days <= 180:
        spotify_range = "medium_term"
        tier_note = "Spotify tier: **~last 6 months**"
    else:
        spotify_range = "long_term"
        tier_note = "Spotify tier: **~last 1–2 years** (Spotify's maximum — going beyond 6 months always uses this cap)"

    return spotify_range, label, tier_note


class SpotifyAPI:

    @staticmethod
    def get_profile_picture(sp: spotipy.Spotify, user_info: dict = None) -> str | None:
        try:
            user = user_info or sp.current_user()
            if not user or not isinstance(user, dict):
                print("[ProfilePic] No user_info returned from Spotify.")
                return None

            images = user.get("images")
            print(f"[ProfilePic] Private profile images: {images}")

            if isinstance(images, list) and len(images) > 0:
                first_image = images[0]
                if isinstance(first_image, dict):
                    url = first_image.get("url")
                    print(f"[ProfilePic] Resolved from private profile: {url}")
                    return url

            # Fallback to public profile if images list is empty
            if "id" in user:
                print(f"[ProfilePic] Private images empty, trying public profile for id={user['id']}")
                public_user = sp.user(user["id"])
                public_images = public_user.get("images")
                print(f"[ProfilePic] Public profile images: {public_images}")
                if isinstance(public_images, list) and len(public_images) > 0:
                    first_public_image = public_images[0]
                    if isinstance(first_public_image, dict):
                        url = first_public_image.get("url")
                        print(f"[ProfilePic] Resolved from public profile: {url}")
                        return url

            print("[ProfilePic] No profile picture found in either private or public profile.")
        except Exception as e:
            print(f"[ProfilePic] Error fetching Spotify profile picture: {e}")
        return None

    @staticmethod
    def get_top_track(sp: spotipy.Spotify, time_range="short_term") -> dict | None:
        res = sp.current_user_top_tracks(limit=1, time_range=time_range)
        items = res.get("items", [])
        if not items:
            return None

        track = items[0]
        return {
            "title": track["name"],
            "artist": track["artists"][0]["name"],
            "album_art": track["album"]["images"][0]["url"]
            if track["album"]["images"]
            else None,
            "url": track["external_urls"]["spotify"],
        }

    @staticmethod
    def get_top_artist(sp: spotipy.Spotify, time_range="short_term") -> dict | None:
        res = sp.current_user_top_artists(limit=1, time_range=time_range)
        items = res.get("items", [])
        if not items:
            return None

        artist = items[0]
        return {
            "name": artist["name"],
            "image_url": artist["images"][0]["url"] if artist["images"] else None,
            "url": artist["external_urls"]["spotify"],
        }

    @staticmethod
    def get_top_album(sp: spotipy.Spotify, time_range="short_term") -> dict | None:
        res = sp.current_user_top_tracks(limit=50, time_range=time_range)
        tracks = res.get("items", [])
        if not tracks:
            return None

        album_counts = Counter(t["album"]["id"] for t in tracks)
        top_album_id = album_counts.most_common(1)[0][0]

        for t in tracks:
            if t["album"]["id"] == top_album_id:
                album = t["album"]
                return {
                    "title": album["name"],
                    "artist": album["artists"][0]["name"],
                    "cover_art"