chore: remove unnecessary comments (#64)

This commit is contained in:
Slipstream 2025-06-11 16:51:15 -06:00 committed by GitHub
parent e199d5494b
commit ce670245c4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
27 changed files with 32 additions and 89 deletions

View File

@ -1,5 +1,3 @@
# disagreement/__init__.py
""" """
Disagreement Disagreement
~~~~~~~~~~~~ ~~~~~~~~~~~~
@ -31,7 +29,7 @@ from .errors import (
) )
from .color import Color from .color import Color
from .utils import utcnow, message_pager from .utils import utcnow, message_pager
from .enums import GatewayIntent, GatewayOpcode # Export enums from .enums import GatewayIntent, GatewayOpcode
from .error_handler import setup_global_error_handler from .error_handler import setup_global_error_handler
from .hybrid_context import HybridContext from .hybrid_context import HybridContext
from .ext import tasks from .ext import tasks

View File

@ -1,5 +1,3 @@
# disagreement/client.py
""" """
The main Client class for interacting with the Discord API. The main Client class for interacting with the Discord API.
""" """
@ -274,7 +272,6 @@ class Client:
print("Max connection retries reached. Giving up.") print("Max connection retries reached. Giving up.")
await self.close() # Ensure cleanup await self.close() # Ensure cleanup
raise raise
# Should not be reached if max_retries is > 0
if max_retries == 0: # If max_retries was 0, means no retries attempted if max_retries == 0: # If max_retries was 0, means no retries attempted
raise DisagreementException("Connection failed with 0 retries allowed.") raise DisagreementException("Connection failed with 0 retries allowed.")

View File

@ -1,10 +1,8 @@
# disagreement/enums.py
""" """
Enums for Discord constants. Enums for Discord constants.
""" """
from enum import IntEnum, Enum # Import Enum from enum import IntEnum, Enum
class GatewayOpcode(IntEnum): class GatewayOpcode(IntEnum):

View File

@ -1,10 +1,8 @@
# disagreement/errors.py
""" """
Custom exceptions for the Disagreement library. Custom exceptions for the Disagreement library.
""" """
from typing import Optional, Any # Add Optional and Any here from typing import Optional, Any
class DisagreementException(Exception): class DisagreementException(Exception):

View File

@ -1,5 +1,3 @@
# disagreement/event_dispatcher.py
""" """
Event dispatcher for handling Discord Gateway events. Event dispatcher for handling Discord Gateway events.
""" """
@ -198,7 +196,7 @@ class EventDispatcher:
try: try:
self._listeners[event_name_upper].remove(coro) self._listeners[event_name_upper].remove(coro)
except ValueError: except ValueError:
pass # Listener not in list pass
def add_waiter( def add_waiter(
self, self,

View File

@ -1,5 +1,3 @@
# disagreement/ext/app_commands/__init__.py
""" """
Application Commands Extension for Disagreement. Application Commands Extension for Disagreement.

View File

@ -1,5 +1,3 @@
# disagreement/ext/app_commands/commands.py
import inspect import inspect
from typing import Any, Callable, Dict, List, Optional, Union, TYPE_CHECKING from typing import Any, Callable, Dict, List, Optional, Union, TYPE_CHECKING

View File

@ -1,5 +1,3 @@
# disagreement/ext/app_commands/context.py
from __future__ import annotations from __future__ import annotations
from typing import TYPE_CHECKING, Optional, List, Union, Any, Dict from typing import TYPE_CHECKING, Optional, List, Union, Any, Dict

View File

@ -1,5 +1,3 @@
# disagreement/ext/app_commands/converters.py
""" """
Converters for transforming application command option values. Converters for transforming application command option values.
""" """
@ -466,8 +464,8 @@ async def run_converters(
# If no specific converter, and it's not a basic type match, raise error or return raw # If no specific converter, and it's not a basic type match, raise error or return raw
# For now, let's raise if no converter found for a specific option type # For now, let's raise if no converter found for a specific option type
if option_type in DEFAULT_CONVERTERS: # Should have been handled if option_type in DEFAULT_CONVERTERS:
pass # This path implies a logic error above or missing converter in DEFAULT_CONVERTERS pass
# If it's a model type but no converter yet, this will need to be handled # If it's a model type but no converter yet, this will need to be handled
# e.g. if param_type is User and option_type is ApplicationCommandOptionType.USER # e.g. if param_type is User and option_type is ApplicationCommandOptionType.USER

View File

@ -1,5 +1,3 @@
# disagreement/ext/app_commands/decorators.py
import inspect import inspect
import asyncio import asyncio
from dataclasses import dataclass from dataclasses import dataclass
@ -134,7 +132,7 @@ def _extract_options_from_signature(
first_param = next(param_iter, None) # Consume 'self', get next first_param = next(param_iter, None) # Consume 'self', get next
if first_param and first_param.name == "ctx": # Consume 'ctx' if first_param and first_param.name == "ctx": # Consume 'ctx'
pass # ctx is handled, now iterate over actual command options pass
elif ( elif (
first_param first_param
): # If first_param was not 'self' and not 'ctx', it's a command option ): # If first_param was not 'self' and not 'ctx', it's a command option
@ -147,7 +145,7 @@ def _extract_options_from_signature(
if param.kind == param.VAR_POSITIONAL or param.kind == param.VAR_KEYWORD: if param.kind == param.VAR_POSITIONAL or param.kind == param.VAR_KEYWORD:
# *args and **kwargs are not directly supported by slash command options structure. # *args and **kwargs are not directly supported by slash command options structure.
# Could raise an error or ignore. For now, ignore. # Could raise an error or ignore. For now, ignore.
# print(f"Warning: *args/**kwargs ({param.name}) are not supported for slash command options.")
continue continue
option_name = param.name option_name = param.name
@ -190,7 +188,7 @@ def _extract_options_from_signature(
# More complex Unions are not directly supported by a single option type. # More complex Unions are not directly supported by a single option type.
# Could default to STRING or raise. # Could default to STRING or raise.
# For now, let's assume simple Optional[T] or direct types. # For now, let's assume simple Optional[T] or direct types.
# print(f"Warning: Complex Union type for '{option_name}' not fully supported, defaulting to STRING.")
actual_type_for_mapping = str actual_type_for_mapping = str
elif origin is list and len(args) == 1: elif origin is list and len(args) == 1:
@ -198,7 +196,7 @@ def _extract_options_from_signature(
# via repeated options or specific component interactions, not directly in slash command options. # via repeated options or specific component interactions, not directly in slash command options.
# This might indicate a need for a different interaction pattern or custom parsing. # This might indicate a need for a different interaction pattern or custom parsing.
# For now, treat List[str] as a string, others might error or default. # For now, treat List[str] as a string, others might error or default.
# print(f"Warning: List type for '{option_name}' not directly supported as a single option. Consider type {args[0]}.")
actual_type_for_mapping = args[ actual_type_for_mapping = args[
0 0
] # Use the inner type for mapping, but this is a simplification. ] # Use the inner type for mapping, but this is a simplification.
@ -247,7 +245,7 @@ def _extract_options_from_signature(
if not option_type: if not option_type:
# Fallback or error if type couldn't be mapped # Fallback or error if type couldn't be mapped
# print(f"Warning: Could not map type '{actual_type_for_mapping}' for option '{option_name}'. Defaulting to STRING.")
option_type = ApplicationCommandOptionType.STRING # Default fallback option_type = ApplicationCommandOptionType.STRING # Default fallback
required = (param.default == inspect.Parameter.empty) and not is_optional required = (param.default == inspect.Parameter.empty) and not is_optional

View File

@ -1,5 +1,3 @@
# disagreement/ext/app_commands/handler.py
import inspect import inspect
import json import json
import logging import logging
@ -341,7 +339,7 @@ class AppCommandHandler:
return value.lower() == "true" return value.lower() == "true"
return bool(value) return bool(value)
except (ValueError, TypeError): except (ValueError, TypeError):
pass # Conversion failed pass
return value # Return as is if no specific resolution or conversion applied return value # Return as is if no specific resolution or conversion applied
async def _resolve_value( async def _resolve_value(

View File

@ -1,5 +1,3 @@
# disagreement/ext/app_commands/hybrid.py
from typing import Any, Callable, List, Optional from typing import Any, Callable, List, Optional
from .commands import SlashCommand from .commands import SlashCommand

View File

@ -1,5 +1,3 @@
# disagreement/ext/commands/__init__.py
""" """
disagreement.ext.commands - A command framework extension for the Disagreement library. disagreement.ext.commands - A command framework extension for the Disagreement library.
""" """

View File

@ -1,5 +1,3 @@
# disagreement/ext/commands/cog.py
import inspect import inspect
import logging import logging
from typing import TYPE_CHECKING, List, Tuple, Callable, Awaitable, Any, Dict, Union from typing import TYPE_CHECKING, List, Tuple, Callable, Awaitable, Any, Dict, Union

View File

@ -1,4 +1,3 @@
# disagreement/ext/commands/converters.py
# pyright: reportIncompatibleMethodOverride=false # pyright: reportIncompatibleMethodOverride=false
from typing import TYPE_CHECKING, Any, Awaitable, Callable, TypeVar, Generic from typing import TYPE_CHECKING, Any, Awaitable, Callable, TypeVar, Generic

View File

@ -1,5 +1,3 @@
# disagreement/ext/commands/core.py
from __future__ import annotations from __future__ import annotations
import asyncio import asyncio
@ -567,9 +565,7 @@ class CommandHandler:
# If final_value_for_param was not set by greedy logic, try conversion # If final_value_for_param was not set by greedy logic, try conversion
if final_value_for_param is inspect.Parameter.empty: if final_value_for_param is inspect.Parameter.empty:
if ( if arg_str_value is None:
arg_str_value is None
): # Should not happen if view.get_word/get_quoted_string is robust
if param.default is not inspect.Parameter.empty: if param.default is not inspect.Parameter.empty:
final_value_for_param = param.default final_value_for_param = param.default
else: else:
@ -609,7 +605,7 @@ class CommandHandler:
final_value_for_param = None final_value_for_param = None
elif last_err_union: elif last_err_union:
raise last_err_union raise last_err_union
else: # Should not be reached if logic is correct else:
raise BadArgument( raise BadArgument(
f"Could not convert '{arg_str_value}' to any of {union_args} for param '{param.name}'." f"Could not convert '{arg_str_value}' to any of {union_args} for param '{param.name}'."
) )

View File

@ -1,4 +1,3 @@
# disagreement/ext/commands/decorators.py
from __future__ import annotations from __future__ import annotations
import asyncio import asyncio

View File

@ -1,5 +1,3 @@
# disagreement/ext/commands/errors.py
""" """
Custom exceptions for the command extension. Custom exceptions for the command extension.
""" """

View File

@ -1,5 +1,3 @@
# disagreement/ext/commands/help.py
from typing import List, Optional from typing import List, Optional
from .core import Command, CommandContext, CommandHandler from .core import Command, CommandContext, CommandHandler

View File

@ -1,5 +1,3 @@
# disagreement/ext/commands/view.py
import re import re
@ -47,7 +45,7 @@ class StringView:
word = match.group(0) word = match.group(0)
self.index += len(word) self.index += len(word)
return word return word
return "" # Should not happen if not eof and skip_whitespace was called return ""
def get_quoted_string(self) -> str: def get_quoted_string(self) -> str:
""" """

View File

@ -1,5 +1,3 @@
# disagreement/gateway.py
""" """
Manages the WebSocket connection to the Discord Gateway. Manages the WebSocket connection to the Discord Gateway.
""" """
@ -152,12 +150,11 @@ class GatewayClient:
self._last_heartbeat_sent = time.monotonic() self._last_heartbeat_sent = time.monotonic()
payload = {"op": GatewayOpcode.HEARTBEAT, "d": self._last_sequence} payload = {"op": GatewayOpcode.HEARTBEAT, "d": self._last_sequence}
await self._send_json(payload) await self._send_json(payload)
# print("Sent heartbeat.")
async def _keep_alive(self): async def _keep_alive(self):
"""Manages the heartbeating loop.""" """Manages the heartbeating loop."""
if self._heartbeat_interval is None: if self._heartbeat_interval is None:
# This should not happen if HELLO was processed correctly
logger.error("Heartbeat interval not set. Cannot start keep_alive.") logger.error("Heartbeat interval not set. Cannot start keep_alive.")
return return
@ -358,7 +355,7 @@ class GatewayClient:
del self._member_chunk_requests[nonce] del self._member_chunk_requests[nonce]
elif event_name == "INTERACTION_CREATE": elif event_name == "INTERACTION_CREATE":
# print(f"GATEWAY RECV INTERACTION_CREATE: {raw_event_d_payload}")
if isinstance(raw_event_d_payload, dict): if isinstance(raw_event_d_payload, dict):
interaction = Interaction( interaction = Interaction(
data=raw_event_d_payload, client_instance=self._client_instance data=raw_event_d_payload, client_instance=self._client_instance
@ -397,7 +394,7 @@ class GatewayClient:
event_data_to_dispatch = ( event_data_to_dispatch = (
raw_event_d_payload if isinstance(raw_event_d_payload, dict) else {} raw_event_d_payload if isinstance(raw_event_d_payload, dict) else {}
) )
# print(f"GATEWAY RECV EVENT: {event_name} | DATA: {event_data_to_dispatch}")
await self._dispatcher.dispatch(event_name, event_data_to_dispatch) await self._dispatcher.dispatch(event_name, event_data_to_dispatch)
else: else:
logger.warning("Received dispatch with no event name: %s", data) logger.warning("Received dispatch with no event name: %s", data)
@ -496,8 +493,6 @@ class GatewayClient:
await self._identify() await self._identify()
elif op == GatewayOpcode.HEARTBEAT_ACK: elif op == GatewayOpcode.HEARTBEAT_ACK:
self._last_heartbeat_ack = time.monotonic() self._last_heartbeat_ack = time.monotonic()
# print("Received heartbeat ACK.")
pass # Good, connection is alive
else: else:
logger.warning( logger.warning(
"Received unhandled Gateway Opcode: %s with data: %s", op, data "Received unhandled Gateway Opcode: %s with data: %s", op, data
@ -584,7 +579,7 @@ class GatewayClient:
try: try:
await self._keep_alive_task await self._keep_alive_task
except asyncio.CancelledError: except asyncio.CancelledError:
pass # Expected pass
if self._receive_task and not self._receive_task.done(): if self._receive_task and not self._receive_task.done():
current = asyncio.current_task(loop=self._loop) current = asyncio.current_task(loop=self._loop)
@ -593,7 +588,7 @@ class GatewayClient:
try: try:
await self._receive_task await self._receive_task
except asyncio.CancelledError: except asyncio.CancelledError:
pass # Expected pass
if self._ws and not self._ws.closed: if self._ws and not self._ws.closed:
await self._ws.close(code=code) await self._ws.close(code=code)

View File

@ -1,5 +1,3 @@
# disagreement/http.py
""" """
HTTP client for interacting with the Discord REST API. HTTP client for interacting with the Discord REST API.
""" """
@ -447,8 +445,6 @@ class HTTPClient:
text=error_text, text=error_text,
error_code=discord_error_code, error_code=discord_error_code,
) )
# Should not be reached if retries are exhausted by RateLimitError
raise DisagreementException( raise DisagreementException(
f"Failed request to {method} {endpoint} after multiple retries." f"Failed request to {method} {endpoint} after multiple retries."
) )

View File

@ -1,5 +1,3 @@
# disagreement/interactions.py
""" """
Data models for Discord Interaction objects. Data models for Discord Interaction objects.
""" """

View File

@ -1,5 +1,3 @@
# disagreement/models.py
""" """
Data models for Discord objects. Data models for Discord objects.
""" """
@ -714,7 +712,7 @@ class Member(User): # Member inherits from User
# We'd need to construct a partial user from top-level member fields if 'user' is missing. # We'd need to construct a partial user from top-level member fields if 'user' is missing.
# For now, assume 'user' object is present for full Member hydration. # For now, assume 'user' object is present for full Member hydration.
# If 'user' is missing, the User part might be incomplete. # If 'user' is missing, the User part might be incomplete.
pass # User fields will be missing or default if 'user' not in data. pass
super().__init__( super().__init__(
user_data if user_data else data user_data if user_data else data

View File

@ -1,5 +1,3 @@
# disagreement/shard_manager.py
"""Sharding utilities for managing multiple gateway connections.""" """Sharding utilities for managing multiple gateway connections."""
from __future__ import annotations from __future__ import annotations

View File

@ -147,7 +147,7 @@ class View:
async def on_timeout(self): async def on_timeout(self):
"""Called when the view times out.""" """Called when the view times out."""
pass # User can override this pass
async def _start(self, client: Client): async def _start(self, client: Client):
"""Starts the view's internal listener.""" """Starts the view's internal listener."""

View File

@ -1,4 +1,3 @@
# disagreement/voice_client.py
"""Voice gateway and UDP audio client.""" """Voice gateway and UDP audio client."""
from __future__ import annotations from __future__ import annotations