From 394c618ab1cdff84247d615edcbc47e945aa8c4e Mon Sep 17 00:00:00 2001 From: Choco <94597336+ChocoMeow@users.noreply.github.com> Date: Fri, 19 Jul 2024 10:45:54 +0800 Subject: [PATCH] Optimized some code --- views/help.py | 4 +- voicelink/filters.py | 151 ++++++++++++------------------------ voicelink/spotify/client.py | 12 +-- 3 files changed, 57 insertions(+), 110 deletions(-) diff --git a/views/help.py b/views/help.py index 1d5682a..6402e7a 100644 --- a/views/help.py +++ b/views/help.py @@ -56,8 +56,8 @@ class HelpView(discord.ui.View): self.response: discord.Message = None self.categorys: list[str] = [ name.capitalize() for name, cog in bot.cogs.items() if len([c for c in cog.walk_commands()]) ] - self.add_item(discord.ui.Button(label='Support', emoji=':support:915152950471581696', url=func.settings.invite_link)) - self.add_item(discord.ui.Button(label='Invite', emoji=':invite:915152589056790589', url=f'https://discord.com/oauth2/authorize?client_id={bot.user.id}&permissions=2184260928&scope=bot%20applications.commands')) + self.add_item(discord.ui.Button(label='Website', emoji='🌎', url='https://vocard.xyz')) + self.add_item(discord.ui.Button(label='Document', emoji=':support:915152950471581696', url='https://docs.vocard.xyz')) self.add_item(discord.ui.Button(label='Github', emoji=':github:1098265017268322406', url='https://github.com/ChocoMeow/Vocard')) self.add_item(discord.ui.Button(label='Donate', emoji=':patreon:913397909024800878', url='https://www.patreon.com/Vocard')) self.add_item(HelpDropdown(self.categorys)) diff --git a/voicelink/filters.py b/voicelink/filters.py index cbc40b0..f20d7d1 100644 --- a/voicelink/filters.py +++ b/voicelink/filters.py @@ -37,10 +37,19 @@ class Filter: these filters will not work. """ def __init__(self): - self.payload: Dict[str, List] = None - self.scope: Dict[str, List] = None + self.payload: Dict[str, float] = None + self.scope: Dict[str, List[int]] = None self.tag: str = None + def _init_with_scope(self, scope: Dict[str, List[int]], **kwargs): + self.scope = scope + for prop, (min_val, max_val) in scope.items(): + setattr(self, prop, kwargs.get(prop, scope[prop][0])) + if not min_val <= getattr(self, prop) <= max_val: + raise FilterInvalidArgument(f"{self.__class__.__name__} {prop} must be between {min_val} and {max_val}.") + self.tag = kwargs.get("tag") + self.payload = {self.__class__.__name__.lower(): {prop: getattr(self, prop) for prop in scope}} + class Filters: def __init__(self) -> None: self._filters: List[Filter] = [] @@ -187,18 +196,11 @@ class Timescale(Filter): rate: float = 1.0 ): super().__init__() - - self.scope = {"speed": [0, 5], "pitch": [0, 5], "rate": [0, 5]} - self.speed = speed - self.pitch = pitch - self.rate = rate - - for prop, (min_val, max_val) in self.scope.items(): - if not min_val <= getattr(self, prop) <= max_val: - raise FilterInvalidArgument(f"Timescale {prop} must be between {min_val} and {max_val}.") - - self.tag = tag - self.payload = {"timescale": {prop: getattr(self, prop) for prop in self.scope}} + self._init_with_scope({ + "speed": [0, 5], + "pitch": [0, 5], + "rate": [0, 5] + }, tag=tag, speed=speed, pitch=pitch, rate=rate) @classmethod def vaporwave(cls): @@ -238,19 +240,12 @@ class Karaoke(Filter): filter_width: float = 100.0 ): super().__init__() - - self.scope = {"level": [0, 5], "monoLevel": [0, 5], "filterBand": [0, 500], "filterWidth": [0, 300]} - self.level = level - self.monoLevel = mono_level - self.filterBand = filter_band - self.filterWidth = filter_width - - for prop, (min_val, max_val) in self.scope.items(): - if not min_val <= getattr(self, prop) <= max_val: - raise FilterInvalidArgument(f"Karaoke {prop} must be between {min_val} and {max_val}.") - - self.tag = tag - self.payload = {"karaoke": {prop: getattr(self, prop) for prop in self.scope}} + self._init_with_scope({ + "level": [0, 5], + "monoLevel": [0, 5], + "filterBand": [0, 500], + "filterWidth": [0, 300] + }, tag=tag, level=level, mono_level=mono_level, filter_band=filter_band, filter_width=filter_width) def __repr__(self): return (f" str: return f" str: return (f" str: return (f" str: return f"" \ No newline at end of file diff --git a/voicelink/spotify/client.py b/voicelink/spotify/client.py index 209e36a..1ea310a 100644 --- a/voicelink/spotify/client.py +++ b/voicelink/spotify/client.py @@ -26,7 +26,7 @@ import time import aiohttp from base64 import b64encode -from typing import List, Union +from typing import List, Union, Dict, Any from .objects import Track, Album, Artist, Playlist, Category from .exceptions import InvalidSpotifyURL, SpotifyRequestException @@ -54,8 +54,8 @@ class Client: self._bearer_token: str = None self._expiry: int = 0 self._auth_token: str = b64encode(f"{self._client_id}:{self._client_secret}".encode()) - self._grant_headers: dict[str, str] = {"Authorization": f"Basic {self._auth_token.decode()}"} - self._bearer_headers: dict[str, str] = None + self._grant_headers: Dict[str, str] = {"Authorization": f"Basic {self._auth_token.decode()}"} + self._bearer_headers: Dict[str, str] = None self._categories: List[Category] = [] @@ -68,13 +68,13 @@ class Client: f"Error fetching bearer token: {resp.status} {resp.reason}" ) - data: dict = await resp.json() + data: Dict = await resp.json() self._bearer_token = data["access_token"] self._expiry = time.time() + (int(data["expires_in"]) - 10) self._bearer_headers = {"Authorization": f"Bearer {self._bearer_token}"} - async def get_request(self, url: str) -> dict: + async def get_request(self, url: str) -> Dict: if not self._bearer_token or time.time() >= self._expiry: await self._fetch_bearer_token() @@ -134,7 +134,7 @@ class Client: f"Error while fetching results: {resp.status} {resp.reason}" ) - next_data: dict = await resp.json() + next_data: Dict = await resp.json() tracks += [ Track(track["track"])