From 053f2339fd7add7c3c26b483c036421bf5797456 Mon Sep 17 00:00:00 2001 From: BarsTiger Date: Sun, 15 Oct 2023 23:40:28 +0300 Subject: [PATCH] Dev working with spotify --- bot/modules/spotify/song.py | 41 ++++++++++++++++++++++++++++++++++ bot/modules/spotify/spotify.py | 16 +++++++++++++ pyproject.toml | 2 ++ 3 files changed, 59 insertions(+) create mode 100644 bot/modules/spotify/song.py create mode 100644 bot/modules/spotify/spotify.py diff --git a/bot/modules/spotify/song.py b/bot/modules/spotify/song.py new file mode 100644 index 0000000..e447ab6 --- /dev/null +++ b/bot/modules/spotify/song.py @@ -0,0 +1,41 @@ +from attrs import define +import spotipy + + +@define +class SongItem: + name: str + id: str + artists: list[str] + preview_url: str + thumbnail: str + + @classmethod + def from_spotify(cls, song_item: dict): + return cls( + name=song_item['name'], + id=song_item['id'], + artists=[artist['name'] for artist in song_item['artists']], + preview_url=song_item['preview_url'].split('?')[0], + thumbnail=song_item['album']['images'][1]['url'] + ) + + @property + def all_artists(self): + return ', '.join(self.artists) + + def __str__(self): + return f"{', '.join(self.artists)} - {self.name}" + + +@define +class Songs(object): + spotify: spotipy.Spotify + + def search(self, query: str, limit: int = 10) -> list[SongItem] | None: + r = self.spotify.search(query, limit=limit) + + if r is None: + return None + + return [SongItem.from_spotify(item) for item in r['tracks']['items']] diff --git a/bot/modules/spotify/spotify.py b/bot/modules/spotify/spotify.py new file mode 100644 index 0000000..dc66a9e --- /dev/null +++ b/bot/modules/spotify/spotify.py @@ -0,0 +1,16 @@ +import spotipy +from spotipy.oauth2 import SpotifyClientCredentials + +from .song import Songs + + +class Spotify(object): + def __init__(self, client_id, client_secret): + self.spotify = spotipy.Spotify( + client_credentials_manager=SpotifyClientCredentials( + client_id=client_id, + client_secret=client_secret + ) + ) + + self.songs = Songs(self.spotify) diff --git a/pyproject.toml b/pyproject.toml index 45766c4..7d4302e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -13,6 +13,8 @@ py-deezer = "^1.1.4.post1" soundcloud-lib = "^0.6.1" shazamio = { path = "lib/ShazamIO" } sqlitedict = "^2.1.0" +spotipy = "^2.23.0" +attrs = "^23.1.0" [build-system]