fix logging and made spotify + apple music optional because of v4

This commit is contained in:
cloudwithax 2024-02-01 21:11:42 -05:00
parent 9b18759864
commit bd78f47585
3 changed files with 16 additions and 53 deletions

View File

@ -15,10 +15,6 @@ repos:
hooks: hooks:
- id: black - id: black
language_version: python3.11 language_version: python3.11
- repo: https://github.com/asottile/blacken-docs
rev: 1.16.0
hooks:
- id: blacken-docs
- repo: https://github.com/asottile/pyupgrade - repo: https://github.com/asottile/pyupgrade
rev: v3.15.0 rev: v3.15.0
hooks: hooks:

View File

@ -66,13 +66,10 @@ After you have initialized your function, we need to fill in the proper paramete
- Set this value to `True` if you want Pomice to automatically switch all players to another available node if one disconnects. - Set this value to `True` if you want Pomice to automatically switch all players to another available node if one disconnects.
You must have two or more nodes to be able to do this. You must have two or more nodes to be able to do this.
* - `log_level` * - `logger`
- `LogLevel` - `Optional[logging.Logger]`
- The logging level for the node. The default logging level is `LogLevel.INFO`. - If you would like to receive logging information from Pomice, set this to your logger class
* - `log_handler`
- `Optional[logging.Handler]`
- The logging handler for the node. Set to `None` to default to the built-in logging handler.
::: :::
@ -93,13 +90,13 @@ await NodePool.create_node(
spotify_client_secret="<your spotify client secret here>" spotify_client_secret="<your spotify client secret here>"
apple_music=<True/False>, apple_music=<True/False>,
fallback=<True/False>, fallback=<True/False>,
log_level=<optional LogLevel here> logger=<your logger here>
) )
``` ```
:::{important} :::{important}
For features like Spotify and Apple Music, you are **not required** to fill in anything for them if you do not want to use them. If you do end up queuing a Spotify or Apple Music track anyway, they will **not work** because these options are not enabled. For features like Spotify and Apple Music, you are **not required** to fill in anything for them if you do not want to use them. If you do end up queuing a Spotify or Apple Music track, it is **up to you** on how you decide to handle it, whether it be through your own methods or a Lavalink plugin.
::: :::

View File

@ -30,8 +30,6 @@ from . import applemusic
from . import spotify from . import spotify
from .enums import * from .enums import *
from .enums import LogLevel from .enums import LogLevel
from .exceptions import AppleMusicNotEnabled
from .exceptions import InvalidSpotifyClientAuthorization
from .exceptions import LavalinkVersionIncompatible from .exceptions import LavalinkVersionIncompatible
from .exceptions import NodeConnectionFailure from .exceptions import NodeConnectionFailure
from .exceptions import NodeCreationError from .exceptions import NodeCreationError
@ -97,7 +95,6 @@ class Node:
"_apple_music_client", "_apple_music_client",
"_route_planner", "_route_planner",
"_log", "_log",
"_log_handler",
"_stats", "_stats",
"available", "available",
) )
@ -121,8 +118,7 @@ class Node:
spotify_client_secret: Optional[str] = None, spotify_client_secret: Optional[str] = None,
apple_music: bool = False, apple_music: bool = False,
fallback: bool = False, fallback: bool = False,
log_level: LogLevel = LogLevel.INFO, logger: Optional[logging.Logger] = None,
log_handler: Optional[logging.Handler] = None,
): ):
if not isinstance(port, int): if not isinstance(port, int):
raise TypeError("Port must be an integer") raise TypeError("Port must be an integer")
@ -138,8 +134,6 @@ class Node:
self._resume_timeout: int = resume_timeout self._resume_timeout: int = resume_timeout
self._secure: bool = secure self._secure: bool = secure
self._fallback: bool = fallback self._fallback: bool = fallback
self._log_level: LogLevel = log_level
self._log_handler = log_handler
self._websocket_uri: str = f"{'wss' if self._secure else 'ws'}://{self._host}:{self._port}" self._websocket_uri: str = f"{'wss' if self._secure else 'ws'}://{self._host}:{self._port}"
self._rest_uri: str = f"{'https' if self._secure else 'http'}://{self._host}:{self._port}" self._rest_uri: str = f"{'https' if self._secure else 'http'}://{self._host}:{self._port}"
@ -154,7 +148,7 @@ class Node:
self._version: LavalinkVersion = LavalinkVersion(0, 0, 0) self._version: LavalinkVersion = LavalinkVersion(0, 0, 0)
self._route_planner = RoutePlanner(self) self._route_planner = RoutePlanner(self)
self._log = self._setup_logging(self._log_level) self._log = logger
if not self._bot.user: if not self._bot.user:
raise NodeCreationError("Bot user is not ready yet.") raise NodeCreationError("Bot user is not ready yet.")
@ -232,21 +226,6 @@ class Node:
"""Alias for `Node.latency`, returns the latency of the node""" """Alias for `Node.latency`, returns the latency of the node"""
return self.latency return self.latency
def _setup_logging(self, level: LogLevel) -> logging.Logger:
logger = logging.getLogger("pomice")
handler = None
if self._log_handler:
handler = self._log_handler
logger.setLevel(handler.level)
if handler:
logger.handlers.clear()
logger.addHandler(handler)
return logger
async def _handle_version_check(self, version: str) -> None: async def _handle_version_check(self, version: str) -> None:
if version.endswith("-SNAPSHOT"): if version.endswith("-SNAPSHOT"):
# we're just gonna assume all snapshot versions correlate with v4 # we're just gonna assume all snapshot versions correlate with v4
@ -580,13 +559,13 @@ class Node:
for filter in filters: for filter in filters:
filter.set_preload() filter.set_preload()
if URLRegex.AM_URL.match(query): # Due to the inclusion of plugins in the v4 update
if not self._apple_music_client: # we are doing away with raising an error if pomice detects
raise AppleMusicNotEnabled( # either a Spotify or Apple Music URL and the respective client
"You must have Apple Music functionality enabled in order to play Apple Music tracks." # is not enabled. Instead, we will just only parse the URL
"Please set apple_music to True in your Node class.", # if the client is enabled and the URL is valid.
)
if self._apple_music_client and URLRegex.AM_URL.match(query):
apple_music_results = await self._apple_music_client.search(query=query) apple_music_results = await self._apple_music_client.search(query=query)
if isinstance(apple_music_results, applemusic.Song): if isinstance(apple_music_results, applemusic.Song):
return [ return [
@ -645,14 +624,7 @@ class Node:
uri=apple_music_results.url, uri=apple_music_results.url,
) )
elif URLRegex.SPOTIFY_URL.match(query): elif self._spotify_client and URLRegex.SPOTIFY_URL.match(query):
if not self._spotify_client_id and not self._spotify_client_secret:
raise InvalidSpotifyClientAuthorization(
"You did not provide proper Spotify client authorization credentials. "
"If you would like to use the Spotify searching feature, "
"please obtain Spotify API credentials here: https://developer.spotify.com/",
)
spotify_results = await self._spotify_client.search(query=query) # type: ignore spotify_results = await self._spotify_client.search(query=query) # type: ignore
if isinstance(spotify_results, spotify.Track): if isinstance(spotify_results, spotify.Track):
@ -985,8 +957,7 @@ class NodePool:
session: Optional[aiohttp.ClientSession] = None, session: Optional[aiohttp.ClientSession] = None,
apple_music: bool = False, apple_music: bool = False,
fallback: bool = False, fallback: bool = False,
log_level: LogLevel = LogLevel.INFO, logger: Optional[logging.Logger] = None,
log_handler: Optional[logging.Handler] = None,
) -> Node: ) -> Node:
"""Creates a Node object to be then added into the node pool. """Creates a Node object to be then added into the node pool.
For Spotify searching capabilites, pass in valid Spotify API credentials. For Spotify searching capabilites, pass in valid Spotify API credentials.
@ -1013,8 +984,7 @@ class NodePool:
spotify_client_secret=spotify_client_secret, spotify_client_secret=spotify_client_secret,
apple_music=apple_music, apple_music=apple_music,
fallback=fallback, fallback=fallback,
log_level=log_level, logger=logger,
log_handler=log_handler,
) )
await node.connect() await node.connect()