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 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
111 changes: 88 additions & 23 deletions SwagLyricsBot/general_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import typing
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 Down Expand Up @@ -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, log):
"""
Wrapper around get_lyrics to parse lyrics into embeds for discord.
"""
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...")

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, member: typing.Optional[discord.Member], song=None, artists=None):
"""
Expand All @@ -67,21 +84,8 @@ async def get_lyrics_command(self, ctx, member: typing.Optional[discord.Member],
"""
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("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):
if not member:
Expand All @@ -95,15 +99,13 @@ async def send_lyrics():
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 log.add_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 @@ -112,11 +114,74 @@ 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("There was an error while processing your request. Please try again in a few seconds. \n"
"If the error persists, please shout at us at https://discord.swaglyrics.dev.")

await ctx.send("There was an error while processing your request. Please try again in a few seconds. \n "
"If the error persists, please shout at us at https://discord.swaglyrics.dev.")
finally:
await log.send_webhook()

@tasks.loop(seconds=5)
async def vibe_mode(self):
aadibajpai marked this conversation as resolved.
Show resolved Hide resolved
"""
Loop to continuously send lyrics as song updates.
Killed using $kill or no Spotify activity
"""
log = Log(self.session)

for user, info in self.current.items():
try:
song, artists = self.get_spotify_data(user)
if (song, artists) == info:
continue
# song has changed
self.current[user] = (song, artists)
artists_string = self.artists_to_string(artists)
debug_string = f"Getting lyrics for {song} by {artists_string}"
await log.add_log(debug_string)
await user.send(debug_string)

await self.send_lyrics(user, song, artists, log)
except LyricsError:
print('No activity detected, stopping loop.')
await user.send("No activity detected, killing the vibe.")
del self.current[user]
if not self.current:
print('stopping loop')
self.vibe_mode.cancel()

@commands.command(name="vibe", aliases=["loop"])
async def vibe(self, ctx):
"""
Starts vibe_mode loop if called in user DMs
"""
# check if DMs
if not ctx.guild:
if ctx.author not in self.current.keys():
# add current user to dict
self.current[ctx.author] = (None, None)
print(f"added {str(ctx.author)} to loop")
await ctx.send('One vibe mode coming right up.')
if len(self.current) == 1:
self.vibe_mode.start()
else:
await ctx.send("You're already vibing ;)")
else:
# DMs only to prevent spam
await ctx.send('$vibe in DMs only 👀')

@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?

if not ctx.guild:
del self.current[ctx.author]
print(f'killed vibe for {ctx.author}')
await ctx.send('Killed the vibe ✊🏻')
if not self.current:
print('stopping loop')
self.vibe_mode.cancel()
else:
# DMs only to prevent spam
await ctx.send('$kill in DMs only bb.')

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