Repository navigation
Expand file tree
/
Copy pathcleaner.py
More file actions
648 lines (544 loc) · 25.8 KB
/
Copy pathcleaner.py
File metadata and controls
648 lines (544 loc) · 25.8 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
"""Playlist cleaner: list, delete, move, or rename your Spotify playlists by name pattern.
Every write command is a dry run unless you pass --apply. With --apply you are
asked to confirm unless you also pass --yes.
Examples:
python cleaner.py list
python cleaner.py list "daily mix"
python cleaner.py delete "^Untitled" --regex
python cleaner.py delete "*2019*" --glob --apply
python cleaner.py move "workout" --to "Gym (merged)" --apply
python cleaner.py rename "^old - " --regex --replace "" --apply
"""
import argparse
import fnmatch
import json
import re
import sys
import time
try:
from tabulate import tabulate
except ImportError: # tabulate is in requirements.txt; fall back to plain text
tabulate = None
SCOPES = " ".join([
"playlist-read-private",
"playlist-read-collaborative",
"playlist-modify-private",
"playlist-modify-public",
"user-library-modify",
"user-library-read",
])
DEFAULT_REDIRECT_URI = "http://127.0.0.1:7777/callback"
ADD_BATCH_SIZE = 100 # Spotify's maximum number of items per add request
# --------------------------------------------------------------------------
# Pattern matching
# --------------------------------------------------------------------------
def compile_pattern(pattern, mode="substring", case_sensitive=False):
"""Turn a user pattern into a compiled regex.
mode is "substring" (default), "glob" (shell wildcards: * ? [abc]), or "regex".
"""
flags = 0 if case_sensitive else re.IGNORECASE
if mode == "substring":
return re.compile(re.escape(pattern), flags)
if mode == "glob":
return re.compile(fnmatch.translate(pattern), flags)
if mode == "regex":
return re.compile(pattern, flags)
raise ValueError(f"Unknown match mode: {mode}")
def name_matches(regex, name, mode):
"""Glob patterns must match the whole name; the other modes match anywhere in it."""
if mode == "glob":
return regex.fullmatch(name) is not None
return regex.search(name) is not None
def filter_playlists(playlists, pattern=None, mode="substring", case_sensitive=False,
exclude=None, owner_id=None, visibility=None):
"""Return the playlists whose names match pattern and do not match exclude.
pattern=None means "no filter". An empty or blank pattern is rejected rather than
treated as "no filter", so an empty shell variable can never select every playlist.
If owner_id is given, only playlists owned by that user are kept.
visibility is None (any), "public", or "private"; see playlist_visibility().
"""
if visibility not in (None, "public", "private"):
raise ValueError(f"Unknown visibility: {visibility}")
for label, value in (("pattern", pattern), ("--exclude pattern", exclude)):
if value is not None and not value.strip():
raise ValueError(f"The {label} is empty. Pass a non-empty pattern.")
include_re = compile_pattern(pattern, mode, case_sensitive) if pattern is not None else None
exclude_re = compile_pattern(exclude, mode, case_sensitive) if exclude is not None else None
result = []
for pl in playlists:
name = pl.get("name") or ""
if owner_id and playlist_owner_id(pl) != owner_id:
continue
if visibility and playlist_is_public(pl) != (visibility == "public"):
continue
if include_re and not name_matches(include_re, name, mode):
continue
if exclude_re and name_matches(exclude_re, name, mode):
continue
result.append(pl)
return result
# --------------------------------------------------------------------------
# Field helpers that tolerate Spotify's February 2026 renames
# ("tracks" -> "items" on playlists, "track" -> "item" on playlist entries)
# --------------------------------------------------------------------------
def playlist_owner_id(pl):
return (pl.get("owner") or {}).get("id")
def playlist_is_public(pl):
"""True, False, or None when Spotify doesn't say. Collaborative playlists are never public."""
if pl.get("collaborative"):
return False
public = pl.get("public")
return public if isinstance(public, bool) else None
def playlist_visibility(pl):
if pl.get("collaborative"):
return "collaborative"
return {True: "public", False: "private", None: "unknown"}[playlist_is_public(pl)]
def playlist_track_total(pl):
for key in ("items", "tracks"):
value = pl.get(key)
if isinstance(value, dict) and "total" in value:
return value["total"]
return None
def entry_item(entry):
return entry.get("item") or entry.get("track")
# --------------------------------------------------------------------------
# Spotify reads
# --------------------------------------------------------------------------
def paginate(sp, first_page):
page = first_page
while page:
for item in page.get("items") or []:
yield item
page = sp.next(page) if page.get("next") else None
def fetch_all_playlists(sp):
"""Every playlist in the current user's library (owned and followed)."""
return [pl for pl in paginate(sp, sp.current_user_playlists(limit=50)) if pl]
def fetch_playlist_uris(sp, playlist_id):
"""Return (uris, skipped): the addable track/episode URIs in a playlist, in order, and
how many entries were skipped because the API cannot add them to another playlist
(local files, and entries whose track is no longer available)."""
uris, skipped = [], 0
for entry in paginate(sp, sp.playlist_items(playlist_id, limit=50)):
entry = entry or {}
item = entry_item(entry)
uri = (item or {}).get("uri")
if not uri or uri.startswith("spotify:local:") or entry.get("is_local"):
skipped += 1
continue
uris.append(uri)
return uris, skipped
# --------------------------------------------------------------------------
# Spotify writes
# --------------------------------------------------------------------------
def remove_playlist(sp, playlist):
"""Remove a playlist from the user's library.
Spotify has no hard delete: removing a playlist you own is how you delete it, and
you can restore it for 90 days at https://www.spotify.com/account/recover-playlists/.
The followers endpoint is tried first; if Spotify rejects it, the newer
/me/library endpoint is tried.
"""
import spotipy # local import so the pure helpers can be tested without spotipy
try:
sp.current_user_unfollow_playlist(playlist["id"])
except spotipy.SpotifyException as err:
if err.http_status not in (403, 404, 405, 410):
raise
sp._delete("me/library", uris=playlist.get("uri") or f"spotify:playlist:{playlist['id']}")
def find_destination(playlists, name, user_id):
"""The user's own playlist called `name` (case-insensitive), or None if there isn't one.
Never creates anything: the caller creates it only once it knows tracks will be added."""
owned = [pl for pl in playlists
if playlist_owner_id(pl) == user_id and (pl.get("name") or "").lower() == name.lower()]
if len(owned) > 1:
raise SystemExit(f'You own {len(owned)} playlists named "{name}". '
"Rename one so the destination is unambiguous.")
return owned[0] if owned else None
def create_destination(sp, name):
return sp.current_user_playlist_create(
name, public=False, description="Created by spotify-reeper cleaner")
def add_uris(sp, playlist_id, uris):
for i in range(0, len(uris), ADD_BATCH_SIZE):
sp.playlist_add_items(playlist_id, uris[i:i + ADD_BATCH_SIZE])
def dedupe(uris, existing=()):
seen = set(existing)
out = []
for uri in uris:
if uri not in seen:
seen.add(uri)
out.append(uri)
return out
# --------------------------------------------------------------------------
# Commands
# --------------------------------------------------------------------------
def print_table(playlists, extra=None):
if not playlists:
print("No playlists matched.")
return
rows = []
for i, pl in enumerate(playlists, 1):
owner = pl.get("owner") or {}
row = [i, pl.get("name"), owner.get("display_name") or owner.get("id"),
playlist_visibility(pl), playlist_track_total(pl), pl.get("id")]
if extra:
row.append(extra(pl))
rows.append(row)
headers = ["#", "Name", "Owner", "Visibility", "Tracks", "ID"] + (["New name"] if extra else [])
if tabulate:
print(tabulate(rows, headers=headers))
else:
print("\t".join(headers))
for row in rows:
print("\t".join("" if v is None else str(v) for v in row))
print(f"\n{len(playlists)} playlist(s).")
def discard_typeahead(stream=None):
"""Throw away keys pressed while a long job ran. The terminal keeps them, and the next
question would otherwise read them as its answer."""
stream = stream or sys.stdin
try:
if stream.isatty():
import termios
termios.tcflush(stream.fileno(), termios.TCIFLUSH)
except (ImportError, OSError, ValueError, AttributeError):
pass # not a terminal (or Windows): nothing buffered to worry about
def confirm(prompt, assume_yes, ask=None, flush=discard_typeahead, attempts=5):
"""Ask before changing anything. Only "yes" proceeds and only "no" cancels; anything
else (a stray key, an empty Enter) asks again rather than throwing the work away."""
if assume_yes:
return True
ask = ask or input
flush()
for _ in range(attempts):
try:
answer = ask(f"{prompt} Type 'yes' or 'no': ").strip().lower()
except EOFError:
return False
if answer == "yes":
return True
if answer in ("no", "n"):
return False
print("Please type yes or no.", file=sys.stderr)
return False
def cmd_list(sp, args, user_id):
playlists = select(sp, args, user_id)
print_table(playlists)
return 0
def cmd_delete(sp, args, user_id):
targets = select(sp, args, user_id)
print_table(targets)
if not targets:
return 0
if not args.apply:
print("\nDry run: nothing deleted. Re-run with --apply to remove these playlists.")
return 0
if not confirm(f"Remove {len(targets)} playlist(s) from your library?", args.yes):
print("Aborted.")
return 1
failures = 0
for pl in targets:
try:
remove_playlist(sp, pl)
print(f" removed {pl['name']}")
except Exception as err: # keep going; report at the end
failures += 1
print(f" FAILED {pl['name']}: {err}", file=sys.stderr)
print("Owned playlists can be restored for 90 days at "
"https://www.spotify.com/account/recover-playlists/")
return 1 if failures else 0
def cmd_move(sp, args, user_id):
all_playlists = fetch_all_playlists(sp)
dest = find_destination(all_playlists, args.to, user_id)
sources = [pl for pl in select(sp, args, user_id, all_playlists)
if dest is None or pl.get("id") != dest["id"]]
print_table(sources)
if not sources:
return 0
action = "copied into" if args.keep_source else "moved into"
if dest:
print(f'\nTracks will be {action} your existing playlist "{dest["name"]}".')
else:
print(f'\nTracks will be {action} a new private playlist "{args.to}" '
"(created only if there are tracks to add).")
if not args.keep_source:
print("Each source is then removed from your library, except sources that are empty or "
"contain local files or unavailable tracks, which can't be moved and are kept.")
if not args.apply:
print("Dry run: nothing changed. Re-run with --apply to do it.")
return 0
if not confirm(f"Proceed with {len(sources)} playlist(s)?", args.yes):
print("Aborted.")
return 1
# Read every source before writing anything, so a read failure can't leave a
# half-built destination behind.
failures = 0
plan = []
for pl in sources:
try:
uris, skipped = fetch_playlist_uris(sp, pl["id"])
except Exception as err:
failures += 1
print(f" FAILED {pl['name']}: could not read tracks: {err}", file=sys.stderr)
continue
plan.append((pl, uris, skipped))
if not any(uris for _, uris, _ in plan):
print("No tracks to add, so nothing was changed.")
return 1 if failures else 0
if dest is None:
dest = create_destination(sp, args.to)
existing = set()
print(f' created "{dest["name"]}"')
else:
try:
existing = set(fetch_playlist_uris(sp, dest["id"])[0])
except Exception as err:
print(f' FAILED could not read destination "{dest["name"]}": {err}\n'
"No changes were made.", file=sys.stderr)
return 1
for pl, uris, skipped in plan:
try:
new = dedupe(uris, existing) if args.dedupe else uris
add_uris(sp, dest["id"], new)
existing.update(new)
msg = f" {len(new):>4} added from {pl['name']}"
if len(new) != len(uris):
msg += f" ({len(uris) - len(new)} duplicates skipped)"
print(msg)
if args.keep_source:
continue
# Only remove a source when every one of its entries is now in the destination.
if skipped:
print(f" kept {pl['name']}: {skipped} local file(s) or unavailable "
"track(s) can't be moved through the API")
elif not uris:
print(f" kept {pl['name']}: it has no tracks")
else:
remove_playlist(sp, pl)
print(f" removed {pl['name']}")
except Exception as err:
# A source is only removed after its tracks were added, so a failure never loses tracks.
failures += 1
print(f" FAILED {pl['name']}: {err}", file=sys.stderr)
return 1 if failures else 0
def rename_preview(regex, replacement, mode):
"""Function giving a playlist's new name. In substring mode the replacement is literal
text; with --regex it is a template where \\1, \\g<name> refer to groups."""
repl = (lambda m: replacement) if mode == "substring" else replacement
return lambda pl: regex.sub(repl, pl.get("name") or "")
def cmd_rename(sp, args, user_id):
regex = compile_pattern(args.pattern, args.match, args.case_sensitive)
preview = rename_preview(regex, args.replace, args.match)
# Only playlists you own can be renamed.
targets = [pl for pl in select(sp, args, user_id, owned_only=True)
if preview(pl) != pl.get("name")]
print_table(targets, extra=preview)
if not targets:
return 0
if not args.apply:
print("\nDry run: nothing renamed. Re-run with --apply to rename.")
return 0
if not confirm(f"Rename {len(targets)} playlist(s)?", args.yes):
print("Aborted.")
return 1
failures = 0
for pl in targets:
new_name = preview(pl)
if not new_name.strip():
failures += 1
print(f" SKIPPED {pl['name']}: new name would be empty", file=sys.stderr)
continue
try:
sp.playlist_change_details(pl["id"], name=new_name)
print(f" renamed {pl['name']} -> {new_name}")
except Exception as err:
failures += 1
print(f" FAILED {pl['name']}: {err}", file=sys.stderr)
return 1 if failures else 0
def select(sp, args, user_id, playlists=None, owned_only=False):
playlists = playlists if playlists is not None else fetch_all_playlists(sp)
return filter_playlists(
playlists,
pattern=getattr(args, "pattern", None),
mode=args.match,
case_sensitive=args.case_sensitive,
exclude=args.exclude,
owner_id=user_id if (owned_only or args.mine) else None,
visibility=args.visibility,
)
# --------------------------------------------------------------------------
# CLI
# --------------------------------------------------------------------------
def build_parser():
common = argparse.ArgumentParser(add_help=False)
mode = common.add_mutually_exclusive_group()
mode.add_argument("--regex", dest="match", action="store_const", const="regex",
help="treat PATTERN as a regular expression")
mode.add_argument("--glob", dest="match", action="store_const", const="glob",
help="treat PATTERN as a shell wildcard matched against the whole name")
common.set_defaults(match="substring")
common.add_argument("--case-sensitive", action="store_true",
help="match case exactly (default: ignore case)")
common.add_argument("--exclude", metavar="PATTERN",
help="skip playlists whose names match this pattern (same mode)")
common.add_argument("--mine", action="store_true",
help="only playlists you own (skip ones you merely follow)")
visibility = common.add_mutually_exclusive_group()
visibility.add_argument("--public", dest="visibility", action="store_const", const="public",
help="only public playlists")
visibility.add_argument("--private", dest="visibility", action="store_const", const="private",
help="only private playlists (collaborative playlists count as private)")
common.set_defaults(visibility=None)
common.add_argument("--config", default="config.json", help="path to config.json")
writes = argparse.ArgumentParser(add_help=False)
writes.add_argument("--apply", action="store_true",
help="actually make changes (default is a dry run)")
writes.add_argument("-y", "--yes", action="store_true",
help="skip the confirmation prompt when using --apply")
parser = argparse.ArgumentParser(
description="List, delete, move, or rename Spotify playlists by name pattern "
"and public/private status.")
sub = parser.add_subparsers(dest="command", required=True)
p = sub.add_parser("list", parents=[common], help="list playlists, optionally filtered")
p.add_argument("pattern", nargs="?", help="name pattern (omit to list everything)")
p.set_defaults(func=cmd_list)
p = sub.add_parser("delete", parents=[common, writes],
help="remove matching playlists from your library")
p.add_argument("pattern", nargs="?",
help="name pattern (may be omitted if --public or --private is given)")
p.set_defaults(func=cmd_delete)
p = sub.add_parser("move", parents=[common, writes],
help="move matching playlists' tracks into one destination playlist")
p.add_argument("pattern")
p.add_argument("--to", required=True, metavar="NAME",
help="destination playlist name (created if you don't own one by that name)")
p.add_argument("--keep-source", action="store_true",
help="copy tracks but keep the source playlists")
p.add_argument("--no-dedupe", dest="dedupe", action="store_false",
help="add tracks even if the destination already has them")
p.set_defaults(func=cmd_move)
p = sub.add_parser("rename", parents=[common, writes],
help="rename matching playlists you own by substitution")
p.add_argument("pattern")
p.add_argument("--replace", required=True, metavar="TEXT",
help=r"replacement text (with --regex, \1 etc. refer to groups)")
p.set_defaults(func=cmd_rename)
return parser
def validate_patterns(args):
"""Reject empty, invalid, or unsupported patterns before logging in or touching anything."""
if args.command == "rename" and args.match == "glob":
raise SystemExit("Error: rename supports substring or --regex patterns, not --glob.")
if args.command == "delete" and args.pattern is None and args.visibility is None:
raise SystemExit("Error: delete needs a name pattern, --public, or --private "
"(refusing to select every playlist).")
try:
filter_playlists([], getattr(args, "pattern", None), args.match,
args.case_sensitive, args.exclude, visibility=args.visibility)
if args.command == "rename":
# Python checks the replacement template on use, even when nothing matches,
# so one trial substitution catches e.g. \1 with no capture group.
regex = compile_pattern(args.pattern, args.match, args.case_sensitive)
rename_preview(regex, args.replace, args.match)({"name": ""})
except (ValueError, re.error) as err:
raise SystemExit(f"Error: {err}")
def load_config(path):
try:
with open(path) as f:
return json.load(f)
except Exception as err:
raise SystemExit(f"Error loading {path}: {err}")
# --------------------------------------------------------------------------
# Rate limits
# --------------------------------------------------------------------------
MAX_RATE_LIMIT_WAIT = 30 # seconds; longer pauses stop with a message instead of waiting
class RateLimited(Exception):
"""Spotify asked this app to pause for longer than it's sensible to wait."""
http_status = 429
def __init__(self, seconds):
self.seconds = seconds
import datetime
until = datetime.datetime.now() + datetime.timedelta(seconds=seconds)
if seconds >= 3600:
span = f"about {seconds / 3600:.0f} hour{'s' if seconds >= 5400 else ''}"
else:
span = f"about {max(1, round(seconds / 60))} minute{'s' if seconds >= 90 else ''}"
super().__init__(
f"Spotify has paused requests from your Spotify app for {span} because it made too "
f"many requests (rate limit). Try again after {until:%a %H:%M}. Everything read so "
"far is saved, so the next run picks up where this one stopped.")
def retry_after(err):
"""Seconds Spotify asked us to wait, from a 429 error's Retry-After header."""
headers = getattr(err, "headers", None) or {}
try:
return int(float(headers.get("Retry-After") or headers.get("retry-after")))
except (TypeError, ValueError):
return None
def make_spotify(sleep=time.sleep, **kwargs):
"""A spotipy client that waits out short rate limits and stops on long ones.
spotipy's default retries honor any Retry-After, so a day-long rate limit would make the
program sit silently for a day. Here 429s are handled ourselves: a pause of up to
MAX_RATE_LIMIT_WAIT seconds is waited out (a few times), a longer one raises RateLimited.
"""
import requests
import spotipy
from urllib3.util.retry import Retry
class Spotify(spotipy.Spotify):
def _build_session(self):
# urllib3 retries any 429 that carries Retry-After, sleeping for as long as it
# says (even 22 hours), whatever status_forcelist says. Turn that off; 429s are
# handled in _internal_call below.
self._session = requests.Session()
retry = Retry(total=self.retries, connect=None, read=False,
allowed_methods=frozenset(["GET", "POST", "PUT", "DELETE"]),
status=self.status_retries, backoff_factor=self.backoff_factor,
status_forcelist=self.status_forcelist,
respect_retry_after_header=False)
adapter = requests.adapters.HTTPAdapter(max_retries=retry)
self._session.mount("http://", adapter)
self._session.mount("https://", adapter)
def _internal_call(self, method, url, payload, params):
for attempt in range(4):
try:
return super()._internal_call(method, url, payload, params)
except spotipy.SpotifyException as err:
if err.http_status != 429:
raise
wait = retry_after(err)
if wait is None:
wait = 2 ** attempt # server errors that ran out of retries
if wait > MAX_RATE_LIMIT_WAIT or attempt == 3:
raise RateLimited(wait) from err
sleep(max(1, wait))
kwargs.setdefault("status_forcelist", (500, 502, 503, 504)) # not 429: handled above
return Spotify(**kwargs)
def make_client(config):
from spotipy.oauth2 import SpotifyOAuth
redirect_uri = config.get("redirect_uri", DEFAULT_REDIRECT_URI)
auth = SpotifyOAuth(
client_id=config["client_id"],
client_secret=config["client_secret"],
redirect_uri=redirect_uri,
scope=SCOPES,
open_browser=True,
)
if not auth.validate_token(auth.cache_handler.get_cached_token()):
print(login_hint(redirect_uri), file=sys.stderr)
return make_spotify(auth_manager=auth)
def login_hint(redirect_uri):
return (
"Opening Spotify in your browser so you can approve access to your playlists.\n"
"This is needed once; the token is then saved in .cache.\n"
'If Spotify says "redirect_uri: Not matching configuration", add exactly\n'
f" {redirect_uri}\n"
"under Redirect URIs in your app's settings at https://developer.spotify.com/dashboard\n"
"(then click Save), or set \"redirect_uri\" in config.json to one already registered.\n"
)
def main(argv=None):
args = build_parser().parse_args(argv)
validate_patterns(args)
sp = make_client(load_config(args.config))
try:
user_id = sp.current_user()["id"]
return args.func(sp, args, user_id)
except RateLimited as err:
print(f"\n{err}", file=sys.stderr)
return 1
if __name__ == "__main__":
sys.exit(main())