Subclassing Button class for each button, changing context interface for handlers

This commit is contained in:
Rafael Vargas 2022-07-27 17:20:57 -03:00
parent 4f11506c2b
commit ca754c6f62
36 changed files with 227 additions and 85 deletions

View File

@ -15,9 +15,9 @@ from Handlers.ResumeHandler import ResumeHandler
from Handlers.HistoryHandler import HistoryHandler
from Handlers.QueueHandler import QueueHandler
from Handlers.LoopHandler import LoopHandler
from Views.EmoteCogResponse import EmoteCommandResponse
from Views.EmbedCogResponse import EmbedCommandResponse
from Views.PlayerView import PlayerView
from UI.Responses.EmoteCogResponse import EmoteCommandResponse
from UI.Responses.EmbedCogResponse import EmbedCommandResponse
from UI.Views.PlayerView import PlayerView
from Music.VulkanBot import VulkanBot
helper = Helper()
@ -232,7 +232,7 @@ class MusicCog(Cog):
@command(name='rafael')
async def rafael(self, ctx: Context) -> None:
view = PlayerView()
view = PlayerView(self.__bot)
await ctx.send(view=view)

View File

@ -1,7 +1,7 @@
from abc import ABC, abstractmethod
from typing import List
from typing import List, Union
from discord.ext.commands import Context
from discord import Client, Guild, ClientUser, Member
from discord import Client, Guild, ClientUser, Interaction, Member, User
from Config.Messages import Messages
from Music.VulkanBot import VulkanBot
from Handlers.HandlerResponse import HandlerResponse
@ -11,7 +11,7 @@ from Config.Embeds import VEmbeds
class AbstractHandler(ABC):
def __init__(self, ctx: Context, bot: VulkanBot) -> None:
def __init__(self, ctx: Union[Context, Interaction], bot: VulkanBot) -> None:
self.__bot: VulkanBot = bot
self.__guild: Guild = ctx.guild
self.__ctx: Context = ctx
@ -22,6 +22,10 @@ class AbstractHandler(ABC):
self.__helper = Helper()
self.__embeds = VEmbeds()
self.__bot_member: Member = self.__get_member()
if isinstance(ctx, Context):
self.__author = ctx.author
else:
self.__author = ctx.user
@abstractmethod
async def run(self) -> HandlerResponse:
@ -39,6 +43,10 @@ class AbstractHandler(ABC):
def bot_user(self) -> ClientUser:
return self.__bot_user
@property
def author(self) -> User:
return self.__author
@property
def guild(self) -> Guild:
return self.__guild
@ -60,7 +68,7 @@ class AbstractHandler(ABC):
return self.__helper
@property
def ctx(self) -> Context:
def ctx(self) -> Union[Context, Interaction]:
return self.__ctx
@property

View File

@ -1,3 +1,5 @@
from typing import Union
from discord import Interaction
from discord.ext.commands import Context
from Music.VulkanBot import VulkanBot
from Handlers.AbstractHandler import AbstractHandler
@ -6,7 +8,7 @@ from Parallelism.ProcessManager import ProcessManager
class ClearHandler(AbstractHandler):
def __init__(self, ctx: Context, bot: VulkanBot) -> None:
def __init__(self, ctx: Union[Context, Interaction], bot: VulkanBot) -> None:
super().__init__(ctx, bot)
async def run(self) -> HandlerResponse:

View File

@ -1,18 +1,18 @@
from typing import Union
from discord.ext.commands import Context
from Config.Exceptions import VulkanError
from discord import Embed
from discord import Embed, Interaction
class HandlerResponse:
def __init__(self, ctx: Context, embed: Embed = None, error: VulkanError = None) -> None:
def __init__(self, ctx: Union[Context, Interaction], embed: Embed = None, error: VulkanError = None) -> None:
self.__ctx: Context = ctx
self.__error: VulkanError = error
self.__embed: Embed = embed
self.__success = False if error else True
@property
def ctx(self) -> Context:
def ctx(self) -> Union[Context, Interaction]:
return self.__ctx
@property

View File

@ -3,11 +3,13 @@ from Music.VulkanBot import VulkanBot
from Handlers.AbstractHandler import AbstractHandler
from Handlers.HandlerResponse import HandlerResponse
from Utils.Utils import Utils
from typing import Union
from Parallelism.ProcessManager import ProcessManager
from discord import Interaction
class HistoryHandler(AbstractHandler):
def __init__(self, ctx: Context, bot: VulkanBot) -> None:
def __init__(self, ctx: Union[Context, Interaction], bot: VulkanBot) -> None:
super().__init__(ctx, bot)
async def run(self) -> HandlerResponse:

View File

@ -4,10 +4,12 @@ from Handlers.AbstractHandler import AbstractHandler
from Handlers.HandlerResponse import HandlerResponse
from Config.Exceptions import BadCommandUsage
from Parallelism.ProcessManager import ProcessManager
from typing import Union
from discord import Interaction
class LoopHandler(AbstractHandler):
def __init__(self, ctx: Context, bot: VulkanBot) -> None:
def __init__(self, ctx: Union[Context, Interaction], bot: VulkanBot) -> None:
super().__init__(ctx, bot)
async def run(self, args: str) -> HandlerResponse:

View File

@ -6,10 +6,12 @@ from Handlers.HandlerResponse import HandlerResponse
from Config.Exceptions import BadCommandUsage, VulkanError, InvalidInput, NumberRequired, UnknownError
from Music.Playlist import Playlist
from Parallelism.ProcessManager import ProcessManager
from typing import Union
from discord import Interaction
class MoveHandler(AbstractHandler):
def __init__(self, ctx: Context, bot: VulkanBot) -> None:
def __init__(self, ctx: Union[Context, Interaction], bot: VulkanBot) -> None:
super().__init__(ctx, bot)
async def run(self, pos1: str, pos2: str) -> HandlerResponse:

View File

@ -4,10 +4,12 @@ from Handlers.HandlerResponse import HandlerResponse
from Music.VulkanBot import VulkanBot
from Utils.Cleaner import Cleaner
from Parallelism.ProcessManager import ProcessManager
from typing import Union
from discord import Interaction
class NowPlayingHandler(AbstractHandler):
def __init__(self, ctx: Context, bot: VulkanBot) -> None:
def __init__(self, ctx: Union[Context, Interaction], bot: VulkanBot) -> None:
super().__init__(ctx, bot)
self.__cleaner = Cleaner()

View File

@ -4,10 +4,12 @@ from Handlers.HandlerResponse import HandlerResponse
from Parallelism.ProcessManager import ProcessManager
from Parallelism.Commands import VCommands, VCommandsType
from Music.VulkanBot import VulkanBot
from typing import Union
from discord import Interaction
class PauseHandler(AbstractHandler):
def __init__(self, ctx: Context, bot: VulkanBot) -> None:
def __init__(self, ctx: Union[Context, Interaction], bot: VulkanBot) -> None:
super().__init__(ctx, bot)
async def run(self) -> HandlerResponse:

View File

@ -12,10 +12,12 @@ from Parallelism.ProcessManager import ProcessManager
from Parallelism.ProcessInfo import ProcessInfo
from Parallelism.Commands import VCommands, VCommandsType
from Music.VulkanBot import VulkanBot
from typing import Union
from discord import Interaction
class PlayHandler(AbstractHandler):
def __init__(self, ctx: Context, bot: VulkanBot) -> None:
def __init__(self, ctx: Union[Context, Interaction], bot: VulkanBot) -> None:
super().__init__(ctx, bot)
self.__searcher = Searcher()
self.__down = Downloader()

View File

@ -5,10 +5,12 @@ from Handlers.HandlerResponse import HandlerResponse
from Parallelism.ProcessManager import ProcessManager
from Parallelism.Commands import VCommands, VCommandsType
from Music.VulkanBot import VulkanBot
from typing import Union
from discord import Interaction
class PrevHandler(AbstractHandler):
def __init__(self, ctx: Context, bot: VulkanBot) -> None:
def __init__(self, ctx: Union[Context, Interaction], bot: VulkanBot) -> None:
super().__init__(ctx, bot)
async def run(self) -> HandlerResponse:
@ -41,13 +43,13 @@ class PrevHandler(AbstractHandler):
process.start()
# Send a prev command, together with the user voice channel
prevCommand = VCommands(VCommandsType.PREV, self.ctx.author.voice.channel.id)
prevCommand = VCommands(VCommandsType.PREV, self.author.voice.channel.id)
queue = processInfo.getQueue()
queue.put(prevCommand)
return HandlerResponse(self.ctx)
def __user_connected(self) -> bool:
if self.ctx.author.voice:
if self.author.voice:
return True
else:
return False

View File

@ -5,10 +5,12 @@ from Music.Downloader import Downloader
from Utils.Utils import Utils
from Parallelism.ProcessManager import ProcessManager
from Music.VulkanBot import VulkanBot
from typing import Union
from discord import Interaction
class QueueHandler(AbstractHandler):
def __init__(self, ctx: Context, bot: VulkanBot) -> None:
def __init__(self, ctx: Union[Context, Interaction], bot: VulkanBot) -> None:
super().__init__(ctx, bot)
self.__down = Downloader()

View File

@ -6,10 +6,12 @@ from Config.Exceptions import BadCommandUsage, VulkanError, ErrorRemoving, Inval
from Music.Playlist import Playlist
from Parallelism.ProcessManager import ProcessManager
from Music.VulkanBot import VulkanBot
from typing import Union
from discord import Interaction
class RemoveHandler(AbstractHandler):
def __init__(self, ctx: Context, bot: VulkanBot) -> None:
def __init__(self, ctx: Union[Context, Interaction], bot: VulkanBot) -> None:
super().__init__(ctx, bot)
async def run(self, position: str) -> HandlerResponse:

View File

@ -4,10 +4,12 @@ from Handlers.HandlerResponse import HandlerResponse
from Parallelism.ProcessManager import ProcessManager
from Parallelism.Commands import VCommands, VCommandsType
from Music.VulkanBot import VulkanBot
from typing import Union
from discord import Interaction
class ResetHandler(AbstractHandler):
def __init__(self, ctx: Context, bot: VulkanBot) -> None:
def __init__(self, ctx: Union[Context, Interaction], bot: VulkanBot) -> None:
super().__init__(ctx, bot)
async def run(self) -> HandlerResponse:

View File

@ -4,10 +4,12 @@ from Handlers.HandlerResponse import HandlerResponse
from Parallelism.ProcessManager import ProcessManager
from Parallelism.Commands import VCommands, VCommandsType
from Music.VulkanBot import VulkanBot
from typing import Union
from discord import Interaction
class ResumeHandler(AbstractHandler):
def __init__(self, ctx: Context, bot: VulkanBot) -> None:
def __init__(self, ctx: Union[Context, Interaction], bot: VulkanBot) -> None:
super().__init__(ctx, bot)
async def run(self) -> HandlerResponse:

View File

@ -4,10 +4,12 @@ from Handlers.HandlerResponse import HandlerResponse
from Config.Exceptions import UnknownError
from Parallelism.ProcessManager import ProcessManager
from Music.VulkanBot import VulkanBot
from typing import Union
from discord import Interaction
class ShuffleHandler(AbstractHandler):
def __init__(self, ctx: Context, bot: VulkanBot) -> None:
def __init__(self, ctx: Union[Context, Interaction], bot: VulkanBot) -> None:
super().__init__(ctx, bot)
async def run(self) -> HandlerResponse:

View File

@ -5,10 +5,12 @@ from Handlers.HandlerResponse import HandlerResponse
from Music.VulkanBot import VulkanBot
from Parallelism.ProcessManager import ProcessManager
from Parallelism.Commands import VCommands, VCommandsType
from typing import Union
from discord import Interaction
class SkipHandler(AbstractHandler):
def __init__(self, ctx: Context, bot: VulkanBot) -> None:
def __init__(self, ctx: Union[Context, Interaction], bot: VulkanBot) -> None:
super().__init__(ctx, bot)
async def run(self) -> HandlerResponse:

View File

@ -4,10 +4,12 @@ from Handlers.HandlerResponse import HandlerResponse
from Music.VulkanBot import VulkanBot
from Parallelism.ProcessManager import ProcessManager
from Parallelism.Commands import VCommands, VCommandsType
from typing import Union
from discord import Interaction
class StopHandler(AbstractHandler):
def __init__(self, ctx: Context, bot: VulkanBot) -> None:
def __init__(self, ctx: Union[Context, Interaction], bot: VulkanBot) -> None:
super().__init__(ctx, bot)
async def run(self) -> HandlerResponse:

View File

@ -90,7 +90,6 @@ class Playlist:
self.__queue.appendleft(self.__current)
last_song = self.__songs_history.popleft() # Get the last song
print(f'Setando como {last_song} 2')
self.__current = last_song
return self.__current # return the song

View File

@ -34,12 +34,14 @@ class VulkanInitializer:
def __add_cogs(self, bot: Bot) -> None:
try:
cogsStatus = []
for filename in listdir(f'./{self.__config.COMMANDS_PATH}'):
if filename.endswith('.py'):
cogPath = f'{self.__config.COMMANDS_PATH}.{filename[:-3]}'
bot.load_extension(cogPath, store=True)
cogsStatus.append(bot.load_extension(cogPath, store=True))
if len(bot.cogs.keys()) != self.__getTotalCogs():
print(cogsStatus)
raise VulkanError(message='Failed to load some Cog')
except VulkanError as e:

View File

@ -195,6 +195,7 @@ class PlayerProcess(Process):
command: VCommands = self.__queue.get()
type = command.getType()
args = command.getArgs()
print(f'{self.name} received command {type}')
try:
self.__playerLock.acquire()

View File

@ -1,8 +1,8 @@
from multiprocessing import Queue, Lock
from multiprocessing.managers import BaseManager, NamespaceProxy
from typing import Dict
from typing import Dict, Union
from Config.Singleton import Singleton
from discord import Guild
from discord import Guild, Interaction
from discord.ext.commands import Context
from Parallelism.PlayerProcess import PlayerProcess
from Music.Playlist import Playlist
@ -23,12 +23,19 @@ class ProcessManager(Singleton):
self.__manager.start()
self.__playersProcess: Dict[Guild, ProcessInfo] = {}
def setPlayerContext(self, guild: Guild, context: ProcessInfo):
self.__playersProcess[guild.id] = context
def setPlayerInfo(self, guild: Guild, info: ProcessInfo):
self.__playersProcess[guild.id] = info
def getPlayerInfo(self, guild: Guild, context: Context) -> ProcessInfo:
"""Return the process info for the guild, if not, create one"""
def getPlayerInfo(self, guild: Guild, context: Union[Context, Interaction]) -> ProcessInfo:
"""Return the process info for the guild, if not and context is a instance
of discord.Context then create one, else return None"""
try:
if isinstance(context, Interaction):
if guild.id not in self.__playersProcess.keys():
return None
else:
return self.__playersProcess[guild.id]
if guild.id not in self.__playersProcess.keys():
self.__playersProcess[guild.id] = self.__createProcessInfo(context)
else:

24
UI/Buttons/BackButton.py Normal file
View File

@ -0,0 +1,24 @@
from discord import ButtonStyle, Interaction
from discord.ui import Button
from Config.Emojis import VEmojis
from Handlers.PrevHandler import PrevHandler
from Music.VulkanBot import VulkanBot
class BackButton(Button):
def __init__(self, bot: VulkanBot):
super().__init__(label="Back", style=ButtonStyle.secondary, emoji=VEmojis().BACK)
self.__bot = bot
async def callback(self, interaction: Interaction) -> None:
await interaction.response.defer()
handler = PrevHandler(interaction, self.__bot)
response = await handler.run()
print(response)
print(response.success)
print(response.error)
print(response.error)
print(response.embed)
if response.embed:
await interaction.followup.send(embed=response.embed)

View File

@ -0,0 +1,11 @@
from discord import ButtonStyle, Interaction
from discord.ui import Button
from Config.Emojis import VEmojis
class LoopAllButton(Button):
def __init__(self):
super().__init__(label="Loop All", style=ButtonStyle.secondary, emoji=VEmojis().LOOP_ALL)
async def callback(self, interaction: Interaction) -> None:
pass

View File

@ -0,0 +1,11 @@
from discord import ButtonStyle, Interaction
from discord.ui import Button
from Config.Emojis import VEmojis
class LoopOffButton(Button):
def __init__(self):
super().__init__(label="Loop Off", style=ButtonStyle.secondary, emoji=VEmojis().LOOP_OFF)
async def callback(self, interaction: Interaction) -> None:
pass

View File

@ -0,0 +1,11 @@
from discord import ButtonStyle, Interaction
from discord.ui import Button
from Config.Emojis import VEmojis
class LoopOneButton(Button):
def __init__(self):
super().__init__(label="Loop One", style=ButtonStyle.secondary, emoji=VEmojis().LOOP_ONE)
async def callback(self, interaction: Interaction) -> None:
pass

11
UI/Buttons/PauseButton.py Normal file
View File

@ -0,0 +1,11 @@
from discord import ButtonStyle, Interaction
from discord.ui import Button
from Config.Emojis import VEmojis
class PauseButton(Button):
def __init__(self):
super().__init__(label="Pause", style=ButtonStyle.secondary, emoji=VEmojis().PAUSE)
async def callback(self, interaction: Interaction) -> None:
pass

11
UI/Buttons/PlayButton.py Normal file
View File

@ -0,0 +1,11 @@
from discord import ButtonStyle, Interaction
from discord.ui import Button
from Config.Emojis import VEmojis
class PlayButton(Button):
def __init__(self):
super().__init__(label="Play", style=ButtonStyle.secondary, emoji=VEmojis().PLAY)
async def callback(self, interaction: Interaction) -> None:
pass

11
UI/Buttons/SkipButton.py Normal file
View File

@ -0,0 +1,11 @@
from discord import ButtonStyle, Interaction
from discord.ui import Button
from Config.Emojis import VEmojis
class SkipButton(Button):
def __init__(self):
super().__init__(label="Skip", style=ButtonStyle.secondary, emoji=VEmojis().SKIP)
async def callback(self, interaction: Interaction) -> None:
pass

11
UI/Buttons/SongsButton.py Normal file
View File

@ -0,0 +1,11 @@
from discord import ButtonStyle, Interaction
from discord.ui import Button
from Config.Emojis import VEmojis
class SongsButton(Button):
def __init__(self):
super().__init__(label="Songs", style=ButtonStyle.secondary, emoji=VEmojis().QUEUE)
async def callback(self, interaction: Interaction) -> None:
pass

11
UI/Buttons/StopButton.py Normal file
View File

@ -0,0 +1,11 @@
from discord import ButtonStyle, Interaction
from discord.ui import Button
from Config.Emojis import VEmojis
class StopButton(Button):
def __init__(self):
super().__init__(label="Stop", style=ButtonStyle.secondary, emoji=VEmojis().STOP)
async def callback(self, interaction: Interaction) -> None:
pass

View File

@ -1,4 +1,4 @@
from Views.AbstractCogResponse import AbstractCommandResponse
from UI.Responses.AbstractCogResponse import AbstractCommandResponse
from Handlers.HandlerResponse import HandlerResponse

View File

@ -1,5 +1,5 @@
from Config.Emojis import VEmojis
from Views.AbstractCogResponse import AbstractCommandResponse
from UI.Responses.AbstractCogResponse import AbstractCommandResponse
from Handlers.HandlerResponse import HandlerResponse

30
UI/Views/PlayerView.py Normal file
View File

@ -0,0 +1,30 @@
from typing import Optional
from discord.ui import View
from Config.Emojis import VEmojis
from UI.Buttons.PauseButton import PauseButton
from UI.Buttons.BackButton import BackButton
from UI.Buttons.SkipButton import SkipButton
from UI.Buttons.StopButton import StopButton
from UI.Buttons.SongsButton import SongsButton
from UI.Buttons.PlayButton import PlayButton
from UI.Buttons.LoopAllButton import LoopAllButton
from UI.Buttons.LoopOneButton import LoopOneButton
from UI.Buttons.LoopOffButton import LoopOffButton
from Music.VulkanBot import VulkanBot
emojis = VEmojis()
class PlayerView(View):
def __init__(self, bot: VulkanBot, timeout: float = 180):
super().__init__(timeout=timeout)
self.__bot = bot
self.add_item(BackButton(self.__bot))
self.add_item(PauseButton())
self.add_item(PlayButton())
self.add_item(StopButton())
self.add_item(SkipButton())
self.add_item(SongsButton())
self.add_item(LoopOneButton())
self.add_item(LoopOffButton())
self.add_item(LoopAllButton())

View File

@ -1,47 +0,0 @@
from typing import Optional
from discord.ui import View, Button, button
from Config.Emojis import VEmojis
from discord import Interaction, ButtonStyle
emojis = VEmojis()
class PlayerView(View):
def __init__(self, timeout: Optional[float] = 180):
super().__init__(timeout=timeout)
@button(label="Back", style=ButtonStyle.secondary, emoji=emojis.BACK)
async def prevCallback(self, button: Button, interaction: Interaction) -> None:
await interaction.response.send_message("Hello")
@button(label="Pause", style=ButtonStyle.secondary, emoji=emojis.PAUSE)
async def pauseCallback(self, button: Button, interaction: Interaction) -> None:
await interaction.response.send_message("Hello")
@button(label="Play", style=ButtonStyle.secondary, emoji=emojis.PLAY)
async def playCallback(self, button: Button, interaction: Interaction) -> None:
await interaction.response.send_message("Hello")
@button(label="Stop", style=ButtonStyle.secondary, emoji=emojis.STOP)
async def stopCallback(self, button: Button, interaction: Interaction) -> None:
await interaction.response.send_message("Hello")
@button(label="Skip", style=ButtonStyle.secondary, emoji=emojis.SKIP)
async def skipCallback(self, button: Button, interaction: Interaction) -> None:
await interaction.response.send_message("Hello")
@button(label="Songs", style=ButtonStyle.secondary, emoji=emojis.QUEUE)
async def songsCallback(self, button: Button, interaction: Interaction) -> None:
await interaction.response.send_message("Hello")
@button(label="Loop Off", style=ButtonStyle.grey, emoji=emojis.LOOP_OFF)
async def loopOffCallback(self, button: Button, interaction: Interaction) -> None:
await interaction.response.send_message("Hello")
@button(label="Loop All", style=ButtonStyle.secondary, emoji=emojis.LOOP_ALL)
async def loopAllCallback(self, button: Button, interaction: Interaction) -> None:
await interaction.response.send_message("Hello")
@button(label="Loop One", style=ButtonStyle.secondary, emoji=emojis.LOOP_ONE)
async def loopOneCallback(self, button: Button, interaction: Interaction) -> None:
await interaction.response.send_message("Hello")