1

Get recently liked tracks

by
Published May 19, 2025

Finds and returns all tracks that the user has liked in the given time window from now. For example, specifying lookbackLength=5 and lookbackUnits='minutes' will find all tracks that have been liked in the past 5 minutes

Script spotify
  • Submitted by alec minchington932 Bun
    Created 473 days ago
    1
    import dayjs from '[email protected]';
    2
    import isBetween from 'dayjs/plugin/isBetween';
    3
    import { Client, Saved, Track } from '[email protected]';
    4
    
    
    5
    dayjs.extend(isBetween);
    6
    
    
    7
    type Spotify = {
    8
      token: string;
    9
    }
    10
    
    
    11
    const MAX_TRACKS_PER_PAGE = 50;
    12
    
    
    13
    export async function main(
    14
      spotifyCredentials: Spotify,
    15
      lookbackLength: number,
    16
      lookbackUnits: 'years' | 'months' | 'weeks' | 'days' | 'hours' | 'minutes' | 'seconds' | 'milliseconds' = 'minutes',
    17
      fetchIntervalMs: number = 1000,
    18
    ) {
    19
      const client = await Client.create({
    20
        token: spotifyCredentials.token,
    21
        userAuthorizedToken: true
    22
      });
    23
    
    
    24
      const now = dayjs();
    25
      const startTime = now.subtract(lookbackLength, lookbackUnits);
    26
    
    
    27
      console.log(`Finding ${client.user.displayName}'s liked tracks from the last ${lookbackLength} ${lookbackUnits}`);
    28
    
    
    29
      let offset = 0;
    30
      const results: Saved<Track>[] = [];
    31
      while (true) {
    32
        const likedTracks = await client.user.getSavedTracks({
    33
          limit: MAX_TRACKS_PER_PAGE,
    34
          offset: offset
    35
        });
    36
    
    
    37
        offset += likedTracks.length;
    38
    
    
    39
        console.log(`Searching ${likedTracks.length} liked tracks (${offset} searched total)`);
    40
    
    
    41
        let foundTracks = 0;
    42
        for (const track of likedTracks) {
    43
          if (dayjs(track.addedAt).isBetween(startTime, now)) {
    44
            console.log(`Found track '${track.item.name}' (liked at ${track.addedAt})`);
    45
            results.push(track);
    46
            foundTracks += 1;
    47
          }
    48
        }
    49
    
    
    50
        console.log(`Found ${foundTracks} recently liked tracks`);
    51
    
    
    52
        if (foundTracks === 0) {
    53
          break;
    54
        }
    55
    
    
    56
        // wait for a specified interval between calls to avoid being rate limited
    57
        await new Promise(res => setTimeout(res, fetchIntervalMs));
    58
      }
    59
    
    
    60
      console.log(`Found a total of ${results.length} liked tracks in the last ${lookbackLength} ${lookbackUnits}`);
    61
    
    
    62
      return results;
    63
    }
    64