Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor Last fm #20

Merged
merged 1 commit into from
Dec 26, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 0 additions & 40 deletions Utility.py
Original file line number Diff line number Diff line change
Expand Up @@ -2362,46 +2362,6 @@ async def recent_tweets(self, context):
final_tweet += f"> **Tweet ID:** {tweet.id} | **Tweet:** {tweet.text}\n"
return final_tweet

#################
# ## LAST FM ## #
#################

@staticmethod
def create_fm_payload(method, user=None, limit=None, time_period=None):
"""Creates the payload to be sent to Last FM"""
payload = {
'api_key': keys.last_fm_api_key,
'method': method,
'format': 'json'
}
if user:
payload['user'] = user
if limit:
payload['limit'] = limit
if time_period:
payload['period'] = time_period
return payload

async def get_fm_response(self, method, user=None, limit=None, time_period=None):
"""Receives the response from Last FM"""
async with self.session.get(keys.last_fm_root_url, headers=keys.last_fm_headers, params=self.create_fm_payload(method, user, limit, time_period)) as response:
return await response.json()

async def get_fm_username(self, user_id):
"""Gets Last FM username from the DB."""
return self.first_result(await self.conn.fetchrow("SELECT username FROM lastfm.users WHERE userid = $1", user_id))

async def set_fm_username(self, user_id, username):
"""Sets Last FM username to the DB."""
try:
if not await self.get_fm_username(user_id):
await self.conn.execute("INSERT INTO lastfm.users(userid, username) VALUES ($1, $2)", user_id, username)
else:
await self.conn.execute("UPDATE lastfm.users SET username = $1 WHERE userid = $2", username, user_id)
return True
except Exception as e:
log.console(e)
return e

#################
# ## PATREON ## #
Expand Down
18 changes: 9 additions & 9 deletions module/LastFM.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,11 @@ async def set_user(self, ctx, org_user, time_period=None):
if self.set_period(None, org_user) != "overall":
org_user = None
if not org_user:
user = await ex.get_fm_username(ctx.author.id)
user = await ex.u_last_fm.get_fm_username(ctx.author.id)
elif type(org_user) is str:
return org_user
elif type(org_user) is discord.User:
user = await ex.get_fm_username(org_user.id)
user = await ex.u_last_fm.get_fm_username(org_user.id)
if not user:
user = org_user.name
else:
Expand Down Expand Up @@ -101,7 +101,7 @@ async def fm(self, ctx, user: typing.Union[discord.User, str] = None):
try:
user = await self.set_user(ctx, user)
if user is not None:
response = await ex.get_fm_response('user.getinfo', user)
response = await ex.u_last_fm.get_fm_response('user.getinfo', user)
user_info = response['user']
title_desc = f"""Age: {user_info['age']}

Expand Down Expand Up @@ -133,7 +133,7 @@ async def setfm(self, ctx, username):
"""Attach a Last FM username to your Discord Account.
[Format: %setfm username]."""
try:
response = await ex.set_fm_username(ctx.author.id, username) # can be an Exception or True
response = await ex.u_last_fm.set_fm_username(ctx.author.id, username) # can be an Exception or True
if response:
await ctx.send(f"> **{username} (last.fm) is now attached to {ctx.author.display_name}.**")
else:
Expand All @@ -147,7 +147,7 @@ async def recenttracks(self, ctx, user: typing.Union[discord.User, str] = None):
"""Get the recent tracks of a Last FM Account by a discord user or a Last FM username"""
try:
user = await self.set_user(ctx, user)
response = await ex.get_fm_response('user.getRecentTracks', user)
response = await ex.u_last_fm.get_fm_response('user.getRecentTracks', user)
tracks_and_titles = self.get_recent_tracks(response, limit=10)
await ctx.send(embed=await self.create_fm_embed(f"{user} **Recent Tracks **", tracks_and_titles, inline=True))
except KeyError as e:
Expand All @@ -161,7 +161,7 @@ async def recent(self, ctx, user: typing.Union[discord.User, str] = None):
"""Get the last listened track of a Last FM Account by a discord user or a Last FM username"""
try:
user = await self.set_user(ctx, user)
response = await ex.get_fm_response('user.getRecentTracks', user)
response = await ex.u_last_fm.get_fm_response('user.getRecentTracks', user)
tracks_and_titles = self.get_recent_tracks(response, limit=1)
embed = await self.create_fm_embed(f"{user}'s **Most Recent Track**", tracks_and_titles, individual=True)
image_url = tracks_and_titles[0][2]
Expand All @@ -181,7 +181,7 @@ async def topartists(self, ctx, user: typing.Union[discord.User, str] = None, ti
Time period options are ``overall | week | month | 3month | 6month | year``. Time period defaults to overall."""
try:
user, time_period = await self.set_user(ctx, user, time_period), self.set_period(user, time_period)
response = await ex.get_fm_response('user.getTopArtists', user, limit=10, time_period=time_period)
response = await ex.u_last_fm.get_fm_response('user.getTopArtists', user, limit=10, time_period=time_period)
list_of_artists = response['topartists']['artist']
counter = 0
artist_and_titles = []
Expand All @@ -205,7 +205,7 @@ async def toptracks(self, ctx, user: typing.Union[discord.User, str] = None, tim
Time period defaults to overall."""
try:
user, time_period = await self.set_user(ctx, user, time_period), self.set_period(user, time_period)
response = await ex.get_fm_response('user.getTopTracks', user, limit=10, time_period=time_period)
response = await ex.u_last_fm.get_fm_response('user.getTopTracks', user, limit=10, time_period=time_period)
list_of_tracks = response['toptracks']['track']
counter = 0
tracks_and_titles = []
Expand All @@ -230,7 +230,7 @@ async def topalbums(self, ctx, user: typing.Union[discord.User, str] = None, tim
Time period defaults to overall."""
try:
user, time_period = await self.set_user(ctx, user, time_period), self.set_period(user, time_period)
response = await ex.get_fm_response('user.getTopAlbums', user, limit=10, time_period=time_period)
response = await ex.u_last_fm.get_fm_response('user.getTopAlbums', user, limit=10, time_period=time_period)
list_of_albums = response['topalbums']['album']
counter = 0
tracks_and_titles = []
Expand Down
36 changes: 35 additions & 1 deletion util/lastfm.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,39 @@


class LastFM(Utility):
pass
@staticmethod
def create_fm_payload(method, user=None, limit=None, time_period=None):
"""Creates the payload to be sent to Last FM"""
payload = {
'api_key': keys.last_fm_api_key,
'method': method,
'format': 'json'
}
if user:
payload['user'] = user
if limit:
payload['limit'] = limit
if time_period:
payload['period'] = time_period
return payload

async def get_fm_response(self, method, user=None, limit=None, time_period=None):
"""Receives the response from Last FM"""
async with self.session.get(keys.last_fm_root_url, headers=keys.last_fm_headers, params=self.create_fm_payload(method, user, limit, time_period)) as response:
return await response.json()

async def get_fm_username(self, user_id):
"""Gets Last FM username from the DB."""
return self.first_result(await self.conn.fetchrow("SELECT username FROM lastfm.users WHERE userid = $1", user_id))

async def set_fm_username(self, user_id, username):
"""Sets Last FM username to the DB."""
try:
if not await self.get_fm_username(user_id):
await self.conn.execute("INSERT INTO lastfm.users(userid, username) VALUES ($1, $2)", user_id, username)
else:
await self.conn.execute("UPDATE lastfm.users SET username = $1 WHERE userid = $2", username, user_id)
return True
except Exception as e:
log.console(e)
return e