actually make logging optional lol

This commit is contained in:
cloudwithax 2024-02-01 22:03:30 -05:00
parent 4507b50b8b
commit a926616028
4 changed files with 100 additions and 58 deletions

View File

@ -96,7 +96,8 @@ class Client:
).decode()
token_data = json.loads(token_json)
self.expiry = datetime.fromtimestamp(token_data["exp"])
self._log.debug(f"Fetched Apple Music bearer token successfully")
if self._log:
self._log.debug(f"Fetched Apple Music bearer token successfully")
async def search(self, query: str) -> Union[Album, Playlist, Song, Artist]:
if not self.token or datetime.utcnow() > self.expiry:
@ -130,9 +131,10 @@ class Client:
)
data: dict = await resp.json(loads=json.loads)
self._log.debug(
f"Made request to Apple Music API with status {resp.status} and response {data}",
)
if self._log:
self._log.debug(
f"Made request to Apple Music API with status {resp.status} and response {data}",
)
data = data["data"][0]

View File

@ -298,7 +298,8 @@ class Player(VoiceProtocol):
self._last_update = int(state.get("time", 0))
self._is_connected = bool(state.get("connected"))
self._last_position = int(state.get("position", 0))
self._log.debug(f"Got player update state with data {state}")
if self._log:
self._log.debug(f"Got player update state with data {state}")
async def _dispatch_voice_update(self, voice_data: Optional[Dict[str, Any]] = None) -> None:
if {"sessionId", "event"} != self._voice_state.keys():
@ -319,7 +320,10 @@ class Player(VoiceProtocol):
data={"voice": data},
)
self._log.debug(f"Dispatched voice update to {state['event']['endpoint']} with data {data}")
if self._log:
self._log.debug(
f"Dispatched voice update to {state['event']['endpoint']} with data {data}",
)
async def on_voice_server_update(self, data: VoiceServerUpdate) -> None:
self._voice_state.update({"event": data})
@ -361,7 +365,8 @@ class Player(VoiceProtocol):
if isinstance(event, TrackStartEvent):
self._ending_track = self._current
self._log.debug(f"Dispatched event {data['type']} to player.")
if self._log:
self._log.debug(f"Dispatched event {data['type']} to player.")
async def _refresh_endpoint_uri(self, session_id: Optional[str]) -> None:
self._player_endpoint_uri = f"sessions/{session_id}/players"
@ -383,7 +388,8 @@ class Player(VoiceProtocol):
data=data or None,
)
self._log.debug(f"Swapped all players to new node {new_node._identifier}.")
if self._log:
self._log.debug(f"Swapped all players to new node {new_node._identifier}.")
async def get_tracks(
self,
@ -456,7 +462,8 @@ class Player(VoiceProtocol):
data={"encodedTrack": None},
)
self._log.debug(f"Player has been stopped.")
if self._log:
self._log.debug(f"Player has been stopped.")
async def disconnect(self, *, force: bool = False) -> None:
"""Disconnects the player from voice."""
@ -484,7 +491,8 @@ class Player(VoiceProtocol):
guild_id=self._guild.id,
)
self._log.debug("Player has been destroyed.")
if self._log:
self._log.debug("Player has been destroyed.")
async def play(
self,
@ -577,9 +585,10 @@ class Player(VoiceProtocol):
query=f"noReplace={ignore_if_playing}",
)
self._log.debug(
f"Playing {track.title} from uri {track.uri} with a length of {track.length}",
)
if self._log:
self._log.debug(
f"Playing {track.title} from uri {track.uri} with a length of {track.length}",
)
return self._current
@ -600,7 +609,8 @@ class Player(VoiceProtocol):
data={"position": position},
)
self._log.debug(f"Seeking to {position}.")
if self._log:
self._log.debug(f"Seeking to {position}.")
return self.position
async def set_pause(self, pause: bool) -> bool:
@ -613,7 +623,8 @@ class Player(VoiceProtocol):
)
self._paused = pause
self._log.debug(f"Player has been {'paused' if pause else 'resumed'}.")
if self._log:
self._log.debug(f"Player has been {'paused' if pause else 'resumed'}.")
return self._paused
async def set_volume(self, volume: int) -> int:
@ -626,7 +637,8 @@ class Player(VoiceProtocol):
)
self._volume = volume
self._log.debug(f"Player volume has been adjusted to {volume}")
if self._log:
self._log.debug(f"Player volume has been adjusted to {volume}")
return self._volume
async def move_to(self, channel: VoiceChannel) -> None:
@ -655,9 +667,11 @@ class Player(VoiceProtocol):
data={"filters": payload},
)
self._log.debug(f"Filter has been applied to player with tag {_filter.tag}")
if self._log:
self._log.debug(f"Filter has been applied to player with tag {_filter.tag}")
if fast_apply:
self._log.debug(f"Fast apply passed, now applying filter instantly.")
if self._log:
self._log.debug(f"Fast apply passed, now applying filter instantly.")
await self.seek(self.position)
return self._filters
@ -678,9 +692,11 @@ class Player(VoiceProtocol):
guild_id=self._guild.id,
data={"filters": payload},
)
self._log.debug(f"Filter has been removed from player with tag {filter_tag}")
if self._log:
self._log.debug(f"Filter has been removed from player with tag {filter_tag}")
if fast_apply:
self._log.debug(f"Fast apply passed, now removing filter instantly.")
if self._log:
self._log.debug(f"Fast apply passed, now removing filter instantly.")
await self.seek(self.position)
return self._filters
@ -709,9 +725,11 @@ class Player(VoiceProtocol):
guild_id=self._guild.id,
data={"filters": payload},
)
self._log.debug(f"Filter with tag {filter_tag} has been edited to {edited_filter!r}")
if self._log:
self._log.debug(f"Filter with tag {filter_tag} has been edited to {edited_filter!r}")
if fast_apply:
self._log.debug(f"Fast apply passed, now editing filter instantly.")
if self._log:
self._log.debug(f"Fast apply passed, now editing filter instantly.")
await self.seek(self.position)
return self._filters
@ -735,8 +753,10 @@ class Player(VoiceProtocol):
guild_id=self._guild.id,
data={"filters": {}},
)
self._log.debug(f"All filters have been removed from player.")
if self._log:
self._log.debug(f"All filters have been removed from player.")
if fast_apply:
self._log.debug(f"Fast apply passed, now removing all filters instantly.")
if self._log:
self._log.debug(f"Fast apply passed, now removing all filters instantly.")
await self.seek(self.position)

View File

@ -247,7 +247,8 @@ class Node:
int(_version_groups[2] or 0),
)
self._log.debug(f"Parsed Lavalink version: {major}.{minor}.{fix}")
if self._log:
self._log.debug(f"Parsed Lavalink version: {major}.{minor}.{fix}")
self._version = LavalinkVersion(major=major, minor=minor, fix=fix)
if self._version < LavalinkVersion(3, 7, 0):
self._available = False
@ -306,7 +307,8 @@ class Node:
if self._version.major == 3:
data["resumingKey"] = self._resume_key
elif self._version.major == 4:
self._log.warning("Using a resume key with Lavalink v4 is deprecated.")
if self._log:
self._log.warning("Using a resume key with Lavalink v4 is deprecated.")
data["resuming"] = True
await self.send(
@ -321,7 +323,8 @@ class Node:
try:
msg = await self._websocket.recv()
data = json.loads(msg)
self._log.debug(f"Recieved raw websocket message {msg}")
if self._log:
self._log.debug(f"Recieved raw websocket message {msg}")
self._loop.create_task(self._handle_ws_msg(data=data))
except exceptions.ConnectionClosed:
if self.player_count > 0:
@ -335,14 +338,18 @@ class Node:
backoff = ExponentialBackoff(base=7)
retry = backoff.delay()
self._log.debug(f"Retrying connection to Node {self._identifier} in {retry} secs")
if self._log:
self._log.debug(
f"Retrying connection to Node {self._identifier} in {retry} secs",
)
await asyncio.sleep(retry)
if not self.is_connected:
self._loop.create_task(self.connect(reconnect=True))
async def _handle_ws_msg(self, data: dict) -> None:
self._log.debug(f"Recieved raw payload from Node {self._identifier} with data {data}")
if self._log:
self._log.debug(f"Recieved raw payload from Node {self._identifier} with data {data}")
op = data.get("op", None)
if op == "stats":
@ -395,9 +402,10 @@ class Node:
headers=self._headers,
json=data or {},
)
self._log.debug(
f"Making REST request to Node {self._identifier} with method {method} to {uri}",
)
if self._log:
self._log.debug(
f"Making REST request to Node {self._identifier} with method {method} to {uri}",
)
if resp.status >= 300:
resp_data: dict = await resp.json()
raise NodeRestException(
@ -405,20 +413,23 @@ class Node:
)
if method == "DELETE" or resp.status == 204:
self._log.debug(
f"REST request to Node {self._identifier} with method {method} to {uri} completed sucessfully and returned no data.",
)
if self._log:
self._log.debug(
f"REST request to Node {self._identifier} with method {method} to {uri} completed sucessfully and returned no data.",
)
return await resp.json(content_type=None)
if resp.content_type == "text/plain":
self._log.debug(
f"REST request to Node {self._identifier} with method {method} to {uri} completed sucessfully and returned text with body {await resp.text()}",
)
if self._log:
self._log.debug(
f"REST request to Node {self._identifier} with method {method} to {uri} completed sucessfully and returned text with body {await resp.text()}",
)
return await resp.text()
self._log.debug(
f"REST request to Node {self._identifier} with method {method} to {uri} completed sucessfully and returned JSON with body {await resp.json()}",
)
if self._log:
self._log.debug(
f"REST request to Node {self._identifier} with method {method} to {uri} completed sucessfully and returned JSON with body {await resp.json()}",
)
return await resp.json()
def get_player(self, guild_id: int) -> Optional[Player]:
@ -446,9 +457,10 @@ class Node:
await self._handle_version_check(version=version)
await self._set_ext_client_session(session=self._session)
self._log.debug(
f"Version check from Node {self._identifier} successful. Returned version {version}",
)
if self._log:
self._log.debug(
f"Version check from Node {self._identifier} successful. Returned version {version}",
)
self._websocket = await client.connect(
f"{self._websocket_uri}/v{self._version.major}/websocket",
@ -457,14 +469,16 @@ class Node:
)
if reconnect:
self._log.debug(f"Trying to reconnect to Node {self._identifier}...")
if self._log:
self._log.debug(f"Trying to reconnect to Node {self._identifier}...")
if self.player_count:
for player in self.players.values():
await player._refresh_endpoint_uri(self._session_id)
self._log.debug(
f"Node {self._identifier} successfully connected to websocket using {self._websocket_uri}/v{self._version.major}/websocket",
)
if self._log:
self._log.debug(
f"Node {self._identifier} successfully connected to websocket using {self._websocket_uri}/v{self._version.major}/websocket",
)
if not self._task:
self._task = self._loop.create_task(self._listen())
@ -473,7 +487,8 @@ class Node:
end = time.perf_counter()
self._log.info(f"Connected to node {self._identifier}. Took {end - start:.3f}s")
if self._log:
self._log.info(f"Connected to node {self._identifier}. Took {end - start:.3f}s")
return self
except (aiohttp.ClientConnectorError, OSError, ConnectionRefusedError):
@ -498,20 +513,23 @@ class Node:
for player in self.players.copy().values():
await player.destroy()
self._log.debug("All players disconnected from node.")
if self._log:
self._log.debug("All players disconnected from node.")
await self._websocket.close()
await self._session.close()
self._log.debug("Websocket and http session closed.")
if self._log:
self._log.debug("Websocket and http session closed.")
del self._pool._nodes[self._identifier]
self.available = False
self._task.cancel()
end = time.perf_counter()
self._log.info(
f"Successfully disconnected from node {self._identifier} and closed all sessions. Took {end - start:.3f}s",
)
if self._log:
self._log.info(
f"Successfully disconnected from node {self._identifier} and closed all sessions. Took {end - start:.3f}s",
)
async def build_track(self, identifier: str, ctx: Optional[commands.Context] = None) -> Track:
"""

View File

@ -63,7 +63,8 @@ class Client:
)
data: dict = await resp.json(loads=json.loads)
self._log.debug(f"Fetched Spotify bearer token successfully")
if self._log:
self._log.debug(f"Fetched Spotify bearer token successfully")
self._bearer_token = data["access_token"]
self._expiry = time.time() + (int(data["expires_in"]) - 10)
@ -91,9 +92,10 @@ class Client:
)
data: dict = await resp.json(loads=json.loads)
self._log.debug(
f"Made request to Spotify API with status {resp.status} and response {data}",
)
if self._log:
self._log.debug(
f"Made request to Spotify API with status {resp.status} and response {data}",
)
if spotify_type == "track":
return Track(data)