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

Add Vibe Mode #42

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 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
97 changes: 75 additions & 22 deletions SwagLyricsBot/general_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import discord
import re
from discord.ext import commands
from discord.ext import commands, tasks

from SwagLyricsBot import SpotifyClosed, LyricsError, ConsoleColors, NoActivityAccess, NotEnoughArguments
from SwagLyricsBot.logs import Log
Expand All @@ -11,9 +11,12 @@

class GeneralCommands(commands.Cog, name="General"):

def __init__(self, bot, session):
def __init__(self, bot, session, current=None):
if current is None:
current = {}
aadibajpai marked this conversation as resolved.
Show resolved Hide resolved
self.bot = bot
self.session = session
self.current = current

@commands.command(name="help")
async def help_message(self, ctx):
Expand All @@ -40,7 +43,7 @@ async def help_message(self, ctx):
def get_spotify_data(user):
from SwagLyricsBot.swaglyrics_bot import find_mutual_guild
"""
Reads data from discord spotify activity.
Reads data from discord spotify activity.
"""
if user.dm_channel:
print(" - Command was raised in DM, finding mutual guild with user...")
Expand All @@ -59,6 +62,20 @@ def get_spotify_data(user):
raise SpotifyClosed()
return spotify_activity[0].title, spotify_activity[0].artists

async def send_lyrics(self, ctx, song, artists):

aadibajpai marked this conversation as resolved.
Show resolved Hide resolved
lyrics = await get_lyrics(song, artists[0], self.session)
print('got lyrics')
# await log.add_sub_log("Lyrics fetched successfully, splitting it into fields...")
split_lyrics = self.chop_string_into_chunks(lyrics, 1024)
print('split lyrics')
# await log.add_sub_log("Split successfully. Packing into messages...")

artists_string = self.artists_to_string(artists)
await self.send_chunks(ctx, split_lyrics, song, artists_string)
# await log.add_sub_log("Lyrics sent successfully.", ConsoleColors.OKGREEN)
# log.change_log_success_status(True)

@commands.command(name="swaglyrics", aliases=["sl", "lyrics"])
async def get_lyrics_command(self, ctx, song=None, artists=None):
"""
Expand All @@ -67,37 +84,22 @@ async def get_lyrics_command(self, ctx, song=None, artists=None):
"""
log = Log(self.session)

async def send_lyrics():
lyrics = await get_lyrics(song, artists[0], self.session)
await log.add_sub_log("Lyrics fetched successfully, splitting it into fields...")
split_lyrics = self.chop_string_into_chunks(lyrics, 1024)
await log.add_sub_log("Split successfully. Packing into messages...")

await self.send_chunks(ctx, split_lyrics, song, artists_string)
await log.add_sub_log(f"Lyrics sent successfully.", ConsoleColors.OKGREEN)
log.change_log_success_status(True)

try:

await log.add_log(
f"User {ctx.author} from {ctx.guild or ctx.channel} guild requested lyrics"
)
await log.add_log(f"User {ctx.author} from {ctx.guild or ctx.channel} guild requested lyrics")

if not (song or artists):
await log.add_sub_log("Song data not provided, trying to fetch it automatically...")
song, artists = self.get_spotify_data(ctx.author)
elif artists is None:
raise NotEnoughArguments("Not enough arguments! For usage, check `$help`")
else:
tmp = artists
artists = list()
artists.append(tmp)
artists = list(artists)
artists_string = self.artists_to_string(artists)
debug_string = f"Getting lyrics for {song} by {artists_string}"
await log.add_sub_log(debug_string)
await ctx.send(debug_string)

await send_lyrics()
await self.send_lyrics(ctx, song, artists, log)
except LyricsError as ex:
await log.add_sub_log(f"Error raised: {ex}", ConsoleColors.FAIL)
log.change_log_success_status(None)
Expand All @@ -106,10 +108,61 @@ async def send_lyrics():
await log.add_sub_log(f"Error: {ex}", ConsoleColors.FAIL, True)
print(traceback.print_exception(type(ex), ex, ex.__traceback__))
log.change_log_success_status(False)
await ctx.send(f"There was an error while processing your request. Please try again in a few seconds.")
await ctx.send("There was an error while processing your request. Please try again in a few seconds.")
finally:
await log.send_webhook()

@tasks.loop(seconds=5)
async def vibe_mode(self):
aadibajpai marked this conversation as resolved.
Show resolved Hide resolved
print('this is inside the loop')
for user, info in self.current.items():
print(user.id, info)
channel = self.bot.get_channel(info['channel'])
await channel.send('ope')
try:
song, artists = self.get_spotify_data(user)
print(song, artists)
if (song, artists) == info['playing']:
print("continuing")
continue
# song has changed
self.current[user]['playing'] = (song, artists)
artists_string = self.artists_to_string(artists)
debug_string = f"Getting lyrics for {song} by {artists_string}"
# await log.add_sub_log(debug_string)
print('sending lyrics bb')
await channel.send(debug_string)

await self.send_lyrics(channel, song, artists)
except LyricsError as e:
print('No activity detected, stopping loop.')
await channel.send("No activity detected, killing the vibe.")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
await channel.send("No activity detected, killing the vibe.")
await channel.send("No activity detected. Killing the vibe.")

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it's not that bad is it?

del self.current[user]
if not self.current:
print('stopping loop')
self.vibe_mode.cancel()

@commands.command()
async def vibe(self, ctx):
prev = self.current.copy()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of copying the entire dict, you could just check whether the new dict has length equal to 1

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, check whether the user is already in self.current if you do this

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

alright

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, check whether the user is already in self.current if you do this

what do you mean by this

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

look at the updated commit and see if that's ok?

# add current user to dict
self.current[ctx.author] = {'playing': (None, None),
'channel': ctx.channel.id}
await ctx.send('one vibe mode coming right up.')
aadibajpai marked this conversation as resolved.
Show resolved Hide resolved
print(prev)
if not prev: # compare using previous current
print("starting loop")
self.vibe_mode.start()

@commands.command()
async def kill(self, ctx):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe rename this to kill_vibe or something to prevent ambiguity

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ambiguity with what?

del self.current[ctx.author]
print('killed vibe')
await ctx.send('https://www.youtube.com/watch?v=GF8aaTu2kg0')
if not self.current:
print('stopping loop')
self.vibe_mode.cancel()

async def send_chunks(self, ctx, chunks, song, artists):
messages = self.pack_into_messages(chunks)
i = 0
Expand Down
3 changes: 2 additions & 1 deletion SwagLyricsBot/lyrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ async def fetch(session, url, **kwargs):
"""
Uses aiohttp to make http GET requests
"""
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36'}
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
aadibajpai marked this conversation as resolved.
Show resolved Hide resolved
'Chrome/84.0.4147.89 Safari/537.36'}
async with session.get(url, headers=headers, **kwargs) as resp:
return await resp.text()

Expand Down