0
# User and Social Features
1
2
User profiles, listening history, social interactions, library access, and community features. This covers comprehensive user data access, social networking capabilities, and music library management through PyLast's user-centric objects.
3
4
## Capabilities
5
6
### User Objects
7
8
Core user representation with profile information, statistics, and listening data access.
9
10
```python { .api }
11
class User:
12
"""
13
Represents a Last.fm user.
14
15
Args:
16
user_name (str): Username
17
network: Network instance (LastFMNetwork or LibreFMNetwork)
18
"""
19
def __init__(self, user_name: str, network): ...
20
21
def get_name(self, properly_capitalized=False) -> str:
22
"""
23
Get username.
24
25
Args:
26
properly_capitalized (bool): Return properly capitalized username
27
28
Returns:
29
str: Username
30
"""
31
32
def get_playcount(self) -> int:
33
"""Get total play count for this user."""
34
35
def get_country(self) -> Country:
36
"""Get user's country as Country object."""
37
38
def is_subscriber(self) -> bool:
39
"""Check if user is a Last.fm subscriber."""
40
41
def get_registered(self) -> str:
42
"""Get user registration date as string."""
43
44
def get_unixtime_registered(self) -> int:
45
"""Get user registration date as Unix timestamp."""
46
47
def get_image(self, size=2) -> str:
48
"""
49
Get user avatar image URL.
50
51
Args:
52
size (int): Image size (SIZE_SMALL to SIZE_MEGA)
53
54
Returns:
55
str: Avatar image URL
56
"""
57
58
def get_url(self, domain_name=0) -> str:
59
"""Get Last.fm profile URL for this user."""
60
61
class AuthenticatedUser(User):
62
"""
63
Represents the authenticated user (inherits from User).
64
Automatically uses the authenticated user's data without requiring username.
65
66
Args:
67
network: Network instance with valid session key
68
"""
69
def __init__(self, network): ...
70
```
71
72
### Listening History
73
74
Access to user's music listening data, including recent tracks, loved tracks, and now playing information.
75
76
```python { .api }
77
def get_recent_tracks(self, limit=50, cacheable=True, stream=True, from_date=None, to_date=None, time_from=None, time_to=None) -> list[PlayedTrack]:
78
"""
79
Get user's recent tracks.
80
81
Args:
82
limit (int): Maximum number of tracks to retrieve
83
cacheable (bool): Enable caching for this request
84
stream (bool): Include streaming tracks
85
from_date (str, optional): Start date (YYYY-MM-DD)
86
to_date (str, optional): End date (YYYY-MM-DD)
87
time_from (int, optional): Start timestamp
88
time_to (int, optional): End timestamp
89
90
Returns:
91
list[PlayedTrack]: Recent played tracks with timestamps
92
"""
93
94
def get_loved_tracks(self, limit=50, cacheable=True) -> list[LovedTrack]:
95
"""
96
Get user's loved tracks.
97
98
Args:
99
limit (int): Maximum number of tracks to retrieve
100
cacheable (bool): Enable caching for this request
101
102
Returns:
103
list[LovedTrack]: Loved tracks with timestamps
104
"""
105
106
def get_now_playing(self) -> Track | None:
107
"""
108
Get currently playing track.
109
110
Returns:
111
Track | None: Currently playing track, or None if nothing playing
112
"""
113
114
def get_track_scrobbles(self, artist: str, track: str, from_date=None, to_date=None) -> list[PlayedTrack]:
115
"""
116
Get scrobbles for a specific track.
117
118
Args:
119
artist (str): Artist name
120
track (str): Track name
121
from_date (str, optional): Start date (YYYY-MM-DD)
122
to_date (str, optional): End date (YYYY-MM-DD)
123
124
Returns:
125
list[PlayedTrack]: Scrobbles for the specified track
126
"""
127
```
128
129
### Statistics and Top Content
130
131
User's top artists, albums, tracks, and tags with customizable time periods.
132
133
```python { .api }
134
def get_top_artists(self, period="overall", limit=None, cacheable=True) -> list[TopItem]:
135
"""
136
Get user's top artists.
137
138
Args:
139
period (str): Time period (PERIOD_OVERALL, PERIOD_7DAYS, etc.)
140
limit (int, optional): Maximum number of results
141
cacheable (bool): Enable caching for this request
142
143
Returns:
144
list[TopItem]: Top artists with play counts
145
"""
146
147
def get_top_albums(self, period="overall", limit=None, cacheable=True) -> list[TopItem]:
148
"""Get user's top albums for specified time period."""
149
150
def get_top_tracks(self, period="overall", limit=None, cacheable=True) -> list[TopItem]:
151
"""Get user's top tracks for specified time period."""
152
153
def get_top_tags(self, limit=None, cacheable=True) -> list[TopItem]:
154
"""Get user's top tags (most used tags)."""
155
```
156
157
### Tagged Content
158
159
Access to user's tagged music content organized by tags.
160
161
```python { .api }
162
def get_tagged_artists(self, tag: str, limit=None, cacheable=True) -> list[TopItem]:
163
"""
164
Get artists tagged by this user with specific tag.
165
166
Args:
167
tag (str): Tag name
168
limit (int, optional): Maximum number of results
169
cacheable (bool): Enable caching
170
171
Returns:
172
list[TopItem]: Artists tagged with specified tag
173
"""
174
175
def get_tagged_albums(self, tag: str, limit=None, cacheable=True) -> list[TopItem]:
176
"""Get albums tagged by this user with specific tag."""
177
178
def get_tagged_tracks(self, tag: str, limit=None, cacheable=True) -> list[TopItem]:
179
"""Get tracks tagged by this user with specific tag."""
180
```
181
182
### Social Connections
183
184
User's social network including friends and neighbors (users with similar taste).
185
186
```python { .api }
187
def get_friends(self, limit=50, cacheable=True) -> list[User]:
188
"""
189
Get user's friends.
190
191
Args:
192
limit (int): Maximum number of friends to retrieve
193
cacheable (bool): Enable caching
194
195
Returns:
196
list[User]: Friend users
197
"""
198
199
def get_neighbours(self, limit=50, cacheable=True) -> list[User]:
200
"""
201
Get user's neighbors (users with similar music taste).
202
203
Args:
204
limit (int): Maximum number of neighbors to retrieve
205
cacheable (bool): Enable caching
206
207
Returns:
208
list[User]: Neighbor users
209
"""
210
```
211
212
### Library Management
213
214
Access to user's music library with detailed play and tag statistics.
215
216
```python { .api }
217
class Library:
218
"""
219
Represents a user's music library.
220
221
Args:
222
user: User object
223
network: Network instance
224
"""
225
def __init__(self, user, network): ...
226
227
def get_user(self) -> User:
228
"""Get the User object this library belongs to."""
229
230
def get_artists(self, limit=50, cacheable=True, stream=True) -> list[LibraryItem]:
231
"""
232
Get artists in user's library.
233
234
Args:
235
limit (int): Maximum number of artists to retrieve
236
cacheable (bool): Enable caching
237
stream (bool): Stream results for large libraries
238
239
Returns:
240
list[LibraryItem]: Library artists with play counts and tag counts
241
"""
242
243
# Access library through user object
244
def get_library(self) -> Library:
245
"""
246
Get user's library object.
247
248
Returns:
249
Library: User's music library
250
"""
251
```
252
253
### Weekly Charts
254
255
Historical weekly chart data for tracking music trends over time.
256
257
```python { .api }
258
def get_weekly_chart_dates(self) -> list[tuple[str, str]]:
259
"""
260
Get available weekly chart date ranges.
261
262
Returns:
263
list[tuple[str, str]]: List of (from_date, to_date) tuples
264
"""
265
266
def get_weekly_artist_charts(self, from_date=None, to_date=None) -> list[TopItem]:
267
"""
268
Get weekly artist charts for date range.
269
270
Args:
271
from_date (str, optional): Start date
272
to_date (str, optional): End date
273
274
Returns:
275
list[TopItem]: Weekly top artists
276
"""
277
278
def get_weekly_album_charts(self, from_date=None, to_date=None) -> list[TopItem]:
279
"""Get weekly album charts for date range."""
280
281
def get_weekly_track_charts(self, from_date=None, to_date=None) -> list[TopItem]:
282
"""Get weekly track charts for date range."""
283
```
284
285
## Data Types
286
287
Key data structures for user and social data.
288
289
```python { .api }
290
from collections import namedtuple
291
292
PlayedTrack = namedtuple('PlayedTrack', ['track', 'album', 'playback_date', 'timestamp'])
293
"""
294
Represents a played track with timestamp.
295
296
Fields:
297
track (Track): The played track
298
album (Album): Album containing the track
299
playback_date (str): Human-readable playback date
300
timestamp (int): Unix timestamp of playback
301
"""
302
303
LovedTrack = namedtuple('LovedTrack', ['track', 'date', 'timestamp'])
304
"""
305
Represents a loved track with timestamp.
306
307
Fields:
308
track (Track): The loved track
309
date (str): Human-readable love date
310
timestamp (int): Unix timestamp when loved
311
"""
312
313
LibraryItem = namedtuple('LibraryItem', ['item', 'playcount', 'tagcount'])
314
"""
315
Represents a library item with statistics.
316
317
Fields:
318
item (Artist/Album/Track): The music item
319
playcount (int): Number of plays by the user
320
tagcount (int): Number of tags applied by the user
321
"""
322
323
TopItem = namedtuple('TopItem', ['item', 'weight'])
324
"""
325
Represents a top item with weight/ranking.
326
327
Fields:
328
item (Artist/Album/Track/Tag): The ranked item
329
weight (int): Ranking weight (higher = more popular)
330
"""
331
```
332
333
## Usage Examples
334
335
### User Profile and Statistics
336
337
```python
338
import pylast
339
340
network = pylast.LastFMNetwork(api_key=API_KEY, api_secret=API_SECRET)
341
342
# Get user profile
343
user = network.get_user("username")
344
print(f"User: {user.get_name()}")
345
print(f"Country: {user.get_country().get_name()}")
346
print(f"Total plays: {user.get_playcount():,}")
347
print(f"Registered: {user.get_registered()}")
348
print(f"Subscriber: {user.is_subscriber()}")
349
350
# Get top artists for different periods
351
periods = [
352
("7day", "Last 7 Days"),
353
("1month", "Last Month"),
354
("6month", "Last 6 Months"),
355
("overall", "All Time")
356
]
357
358
for period_key, period_name in periods:
359
top_artists = user.get_top_artists(period=period_key, limit=5)
360
print(f"\nTop Artists - {period_name}:")
361
for i, artist_item in enumerate(top_artists, 1):
362
artist = artist_item.item
363
plays = artist_item.weight
364
print(f"{i}. {artist.get_name()} ({plays} plays)")
365
```
366
367
### Recent Listening Activity
368
369
```python
370
# Get recent tracks
371
recent = user.get_recent_tracks(limit=20)
372
print("Recent Tracks:")
373
for played_track in recent:
374
track = played_track.track
375
album = played_track.album
376
date = played_track.playback_date
377
378
print(f"{track.get_artist().get_name()} - {track.get_title()}")
379
if album:
380
print(f" from '{album.get_title()}' on {date}")
381
else:
382
print(f" on {date}")
383
384
# Check what's currently playing
385
now_playing = user.get_now_playing()
386
if now_playing:
387
print(f"\nNow Playing: {now_playing.get_artist().get_name()} - {now_playing.get_title()}")
388
else:
389
print("\nNothing currently playing")
390
```
391
392
### Loved Tracks and Tagged Content
393
394
```python
395
# Get loved tracks
396
loved = user.get_loved_tracks(limit=10)
397
print("Loved Tracks:")
398
for loved_track in loved:
399
track = loved_track.track
400
date = loved_track.date
401
print(f"{track.get_artist().get_name()} - {track.get_title()} (loved on {date})")
402
403
# Get tagged content
404
rock_artists = user.get_tagged_artists("rock", limit=10)
405
print("\nArtists tagged as 'rock':")
406
for artist_item in rock_artists:
407
print(f"- {artist_item.item.get_name()}")
408
409
electronic_tracks = user.get_tagged_tracks("electronic", limit=5)
410
print("\nTracks tagged as 'electronic':")
411
for track_item in electronic_tracks:
412
track = track_item.item
413
print(f"- {track.get_artist().get_name()} - {track.get_title()}")
414
```
415
416
### Social Features
417
418
```python
419
# Get friends
420
friends = user.get_friends(limit=10)
421
print("Friends:")
422
for friend in friends:
423
print(f"- {friend.get_name()} ({friend.get_playcount():,} total plays)")
424
425
# Get music neighbors (similar taste)
426
neighbors = user.get_neighbours(limit=5)
427
print("\nMusic Neighbors (similar taste):")
428
for neighbor in neighbors:
429
print(f"- {neighbor.get_name()}")
430
431
# Compare top artists
432
neighbor_top = neighbor.get_top_artists(limit=3)
433
common_artists = []
434
user_top = user.get_top_artists(limit=10)
435
user_artist_names = {item.item.get_name().lower() for item in user_top}
436
437
for neighbor_artist in neighbor_top:
438
if neighbor_artist.item.get_name().lower() in user_artist_names:
439
common_artists.append(neighbor_artist.item.get_name())
440
441
if common_artists:
442
print(f" Common artists: {', '.join(common_artists)}")
443
```
444
445
### Library Analysis
446
447
```python
448
# Access user's library
449
library = user.get_library()
450
library_artists = library.get_artists(limit=50)
451
452
print("Library Analysis:")
453
print(f"Artists in library: {len(library_artists)}")
454
455
# Find most played artists
456
sorted_artists = sorted(library_artists, key=lambda x: x.playcount, reverse=True)
457
print("\nMost played artists in library:")
458
for i, lib_item in enumerate(sorted_artists[:10], 1):
459
artist = lib_item.item
460
plays = lib_item.playcount
461
tags = lib_item.tagcount
462
print(f"{i:2d}. {artist.get_name()} - {plays} plays, {tags} tags")
463
464
# Find most tagged artists
465
most_tagged = sorted(library_artists, key=lambda x: x.tagcount, reverse=True)
466
print("\nMost tagged artists:")
467
for lib_item in most_tagged[:5]:
468
if lib_item.tagcount > 0:
469
artist = lib_item.item
470
print(f"- {artist.get_name()} ({lib_item.tagcount} tags)")
471
```
472
473
### Weekly Charts Analysis
474
475
```python
476
# Get available chart periods
477
chart_dates = user.get_weekly_chart_dates()
478
if chart_dates:
479
# Get recent weekly chart
480
latest_from, latest_to = chart_dates[-1]
481
weekly_artists = user.get_weekly_artist_charts(latest_from, latest_to)
482
483
print(f"Weekly Chart ({latest_from} to {latest_to}):")
484
for i, artist_item in enumerate(weekly_artists[:10], 1):
485
artist = artist_item.item
486
plays = artist_item.weight
487
print(f"{i:2d}. {artist.get_name()} ({plays} plays)")
488
489
# Compare with previous week if available
490
if len(chart_dates) > 1:
491
prev_from, prev_to = chart_dates[-2]
492
prev_weekly = user.get_weekly_artist_charts(prev_from, prev_to)
493
494
print(f"\nTrending (vs previous week):")
495
current_names = {item.item.get_name(): item.weight for item in weekly_artists[:10]}
496
prev_names = {item.item.get_name(): item.weight for item in prev_weekly}
497
498
for name, current_plays in current_names.items():
499
if name in prev_names:
500
change = current_plays - prev_names[name]
501
if change > 0:
502
print(f"↗ {name} (+{change} plays)")
503
elif change < 0:
504
print(f"↘ {name} ({change} plays)")
505
else:
506
print(f"★ {name} (new entry)")
507
```
508
509
### Authenticated User Features
510
511
```python
512
# For authenticated users (requires session key)
513
if network.session_key:
514
auth_user = network.get_authenticated_user()
515
516
# Same methods as regular User, but automatically uses authenticated user's data
517
my_recent = auth_user.get_recent_tracks(limit=5)
518
my_loved = auth_user.get_loved_tracks(limit=5)
519
520
print("My Recent Tracks:")
521
for played_track in my_recent:
522
track = played_track.track
523
print(f"- {track.get_artist().get_name()} - {track.get_title()}")
524
525
print("\nMy Loved Tracks:")
526
for loved_track in my_loved:
527
track = loved_track.track
528
print(f"♥ {track.get_artist().get_name()} - {track.get_title()}")
529
```