Skip to content

Commit

Permalink
Made emojis a dataclass, Using emojis from dataclass
Browse files Browse the repository at this point in the history
  • Loading branch information
shahriyardx committed Apr 4, 2022
1 parent b96ba56 commit 911392c
Show file tree
Hide file tree
Showing 9 changed files with 78 additions and 34 deletions.
4 changes: 3 additions & 1 deletion dismusic/_classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,6 @@
from wavelink import SoundCloudTrack, YouTubeMusicTrack, YouTubeTrack, YouTubePlaylist
from wavelink.ext.spotify import SpotifyTrack

Provider = Union[YouTubeTrack, YouTubePlaylist, YouTubeMusicTrack, SoundCloudTrack, SpotifyTrack]
Provider = Union[
YouTubeTrack, YouTubePlaylist, YouTubeMusicTrack, SoundCloudTrack, SpotifyTrack
]
13 changes: 9 additions & 4 deletions dismusic/_emojis.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
PREV = "⬅️"
NEXT = "➡️"
FIRST = "⏮️"
LAST = "⏭️"
from dataclasses import dataclass


@dataclass
class Emojis:
PREV = "⬅️"
NEXT = "➡️"
FIRST = "⏮️"
LAST = "⏭️"
4 changes: 3 additions & 1 deletion dismusic/checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ def predicate(ctx: commands.Context):
raise PlayerNotConnected("Player is not connected to any voice channel.")

if ctx.voice_client.channel.id != ctx.author.voice.channel.id:
raise MustBeSameChannel("You must be in the same voice channel as the player.")
raise MustBeSameChannel(
"You must be in the same voice channel as the player."
)

return True

Expand Down
4 changes: 3 additions & 1 deletion dismusic/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ class MusicEvents(commands.Cog):
def __init__(self, bot) -> None:
self.bot = bot

async def handle_end_stuck_exception(self, player: DisPlayer, track: wavelink.abc.Playable):
async def handle_end_stuck_exception(
self, player: DisPlayer, track: wavelink.abc.Playable
):
if player.loop == "CURRENT":
return await player.play(track)

Expand Down
18 changes: 14 additions & 4 deletions dismusic/music.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,9 @@ async def play_track(self, ctx: commands.Context, query: str, provider=None):
player: DisPlayer = ctx.voice_client

if ctx.author.voice.channel.id != player.channel.id:
raise MustBeSameChannel("You must be in the same voice channel as the player.")
raise MustBeSameChannel(
"You must be in the same voice channel as the player."
)

track_providers = {
"yt": YouTubeTrack,
Expand All @@ -54,7 +56,11 @@ async def play_track(self, ctx: commands.Context, query: str, provider=None):
if track_provider == "yt" and "playlist" in query:
provider = "ytpl"

provider: Provider = track_providers.get(provider) if provider else track_providers.get(player.track_provider)
provider: Provider = (
track_providers.get(provider)
if provider
else track_providers.get(player.track_provider)
)

nodes = self.get_nodes()
tracks = list()
Expand Down Expand Up @@ -91,7 +97,9 @@ async def play_track(self, ctx: commands.Context, query: str, provider=None):

async def start_nodes(self):
await self.bot.wait_until_ready()
spotify_credential = getattr(self.bot, "spotify_credentials", {"client_id": "", "client_secret": ""})
spotify_credential = getattr(
self.bot, "spotify_credentials", {"client_id": "", "client_secret": ""}
)

for config in self.bot.lavalink_nodes:
try:
Expand All @@ -102,7 +110,9 @@ async def start_nodes(self):
)
print(f"[dismusic] INFO - Created node: {node.identifier}")
except Exception:
print(f"[dismusic] ERROR - Failed to create node {config['host']}:{config['port']}")
print(
f"[dismusic] ERROR - Failed to create node {config['host']}:{config['port']}"
)

@commands.command(aliases=["con"])
@voice_connected()
Expand Down
45 changes: 29 additions & 16 deletions dismusic/paginator.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@

from discord import Color, Embed, Forbidden, InvalidArgument, NotFound, HTTPException

import _emojis as emojis
from ._emojis import Emojis


class Paginator:
def __init__(self, ctx, player) -> None:
Expand All @@ -30,20 +31,26 @@ def create_embed(self, tracks, current_page, total_pages):
)

if self.player.loop == "CURRENT":
next_song = f"Next > [{self.player.source.title}]({self.player.source.uri}) \n\n"
next_song = (
f"Next > [{self.player.source.title}]({self.player.source.uri}) \n\n"
)
else:
next_song = ""

description = next_song
queue_length = self.get_length(self.player.queue)

for index, track in enumerate(tracks):
description += f"{current_page * 10 + index + 1}. [{track.title}]({track.uri}) \n"
description += (
f"{current_page * 10 + index + 1}. [{track.title}]({track.uri}) \n"
)

embed.description = description

if total_pages == 1:
embed.set_footer(text=f"{len(self.player.queue._queue)} tracks, {queue_length}")
embed.set_footer(
text=f"{len(self.player.queue._queue)} tracks, {queue_length}"
)
else:
embed.set_footer(
text=f"Page {current_page + 1}/{total_pages}, {len(self.player.queue._queue)} tracks, {queue_length}"
Expand Down Expand Up @@ -71,32 +78,38 @@ async def start(self):

if total_pages > 1:
try:
await msg.add_reaction(emojis.FIRST)
await msg.add_reaction(emojis.PREV)
await msg.add_reaction(emojis.NEXT)
await msg.add_reaction(emojis.LAST)
await msg.add_reaction(Emojis.FIRST)
await msg.add_reaction(Emojis.PREV)
await msg.add_reaction(Emojis.NEXT)
await msg.add_reaction(Emojis.LAST)
except (HTTPException, Forbidden, NotFound, InvalidArgument) as e:
print(e)
pass
else:
break

def check(reaction, user):
valid_reactions = [emojis.FIRST, emojis.PREV, emojis.NEXT, emojis.LAST]
return user == self.ctx.author and str(reaction.emoji) in valid_reactions and reaction.message.id == msg.id
valid_reactions = [Emojis.FIRST, Emojis.PREV, Emojis.NEXT, Emojis.LAST]
return (
user == self.ctx.author
and str(reaction.emoji) in valid_reactions
and reaction.message.id == msg.id
)

try:
reaction, user = await self.ctx.bot.wait_for("reaction_add", timeout=60.0, check=check)
reaction, user = await self.ctx.bot.wait_for(
"reaction_add", timeout=60.0, check=check
)
except asyncio.TimeoutError:
break

if str(reaction.emoji) == emojis.PREV:
if str(reaction.emoji) == Emojis.PREV:
current_page = max(0, current_page - 1)
elif str(reaction.emoji) == emojis.NEXT:
elif str(reaction.emoji) == Emojis.NEXT:
current_page = min(total_pages - 1, current_page + 1)
elif str(reaction.emoji) == emojis.FIRST:
elif str(reaction.emoji) == Emojis.FIRST:
current_page = 0
elif str(reaction.emoji) == emojis.LAST:
elif str(reaction.emoji) == Emojis.LAST:
current_page = total_pages - 1

await msg.remove_reaction(reaction.emoji, user)
8 changes: 6 additions & 2 deletions dismusic/player.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,9 @@ async def set_loop(self, loop_type: str) -> None:
loop_type = "NONE"

if loop_type.upper() == "PLAYLIST" and len(self.queue._queue) < 1:
raise NotEnoughSong("There must be 2 songs in the queue in order to use the PLAYLIST loop")
raise NotEnoughSong(
"There must be 2 songs in the queue in order to use the PLAYLIST loop"
)

if loop_type.upper() not in valid_types:
raise InvalidLoopMode("Loop type must be `NONE`, `CURRENT` or `PLAYLIST`.")
Expand All @@ -75,7 +77,9 @@ async def invoke_player(self, ctx: commands.Context = None) -> None:
if not track:
raise NothingIsPlaying("Player is not playing anything.")

embed = discord.Embed(title=track.title, url=track.uri, color=discord.Color(0x2F3136))
embed = discord.Embed(
title=track.title, url=track.uri, color=discord.Color(0x2F3136)
)
embed.set_author(
name=track.author,
url=track.uri,
Expand Down
10 changes: 8 additions & 2 deletions examples/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,19 @@ async def on_ready():
@bot.command()
async def rickroll(ctx: Context):
"""Never gonna give you up"""
await ctx.invoke(bot.get_command("play"), query="https://www.youtube.com/watch?v=dQw4w9WgXcQ")
await ctx.invoke(
bot.get_command("play"), query="https://www.youtube.com/watch?v=dQw4w9WgXcQ"
)
await ctx.send("Never gonna give you up")


@bot.command()
async def kids(ctx: Context):
"""Test playlist playing"""
await ctx.invoke(bot.get_command("play"), query="https://www.youtube.com/playlist?list=PL2MHGlY_k-FG_Wc83QiOWj1-P5aXv-Tsm")
await ctx.invoke(
bot.get_command("play"),
query="https://www.youtube.com/playlist?list=PL2MHGlY_k-FG_Wc83QiOWj1-P5aXv-Tsm",
)
await ctx.send("Some kids song added for you")


Expand Down
6 changes: 3 additions & 3 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
aiohttp==3.8.1
async-timeout==4.0.2
wavelink>=1.2.1
aiohttp>=3.8.1
async-timeout>=4.0.2
wavelink>=1.2.4

0 comments on commit 911392c

Please sign in to comment.