Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 10 additions & 28 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -30,44 +30,26 @@ repos:
name: TOML Structure
- id: check-merge-conflict
name: Merge Conflicts
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: 'v0.0.254'
hooks:
- id: ruff
args: [--fix, --exit-non-zero-on-fix]
- repo: https://github.com/psf/black
rev: 22.12.0
hooks:
- id: black
name: Black Formatting
language: python
types: [file, python]
language_version: python3.10
- repo: https://github.com/PyCQA/flake8
rev: 6.0.0
hooks:
- id: flake8
name: flake8 Formatting
language: python
types: [file, python]
args: [--ignore=E203 E301 E302 E501 E402 E704 W503 W504]
additional_dependencies:
- flake8-annotations
- flake8-bandit
- flake8-docstrings
- flake8-bugbear
- flake8-comprehensions
- flake8-raise
- flake8-deprecated
- flake8-print
- git+https://github.com/python-formate/flake8-dunder-all
language_version: python3.10
- id: black
name: Black Formatting
language: python
types: [ file, python ]
language_version: python3.10
# - repo: https://github.com/pycqa/isort
# rev: 5.11.4
# hooks:
# - id: isort
# name: isort Formatting
# language: python
# types: [file, python]
- repo: https://github.com/PyCQA/autoflake
rev: v2.0.0
hooks:
- id: autoflake
ci:
autoupdate_branch: "unstable"
autofix_prs: true
Expand Down
4 changes: 2 additions & 2 deletions interactions/api/events/processors/guild_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,11 @@ async def _on_raw_guild_create(self, event: "RawGatewayEvent") -> None:

guild = self.cache.place_guild_data(event.data)

self._user._guild_ids.add(to_snowflake(event.data.get("id"))) # noqa : w0212
self._user._guild_ids.add(to_snowflake(event.data.get("id")))

self._guild_event.set()

if self.fetch_members and not guild.chunked.is_set(): # noqa
if self.fetch_members and not guild.chunked.is_set():
# delays events until chunking has completed
await guild.chunk()

Expand Down
12 changes: 7 additions & 5 deletions interactions/api/gateway/gateway.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""This file outlines the interaction between interactions and Discord's Gateway API."""
"""Outlines the interaction between interactions and Discord's Gateway API."""
import asyncio
import sys
import time
Expand Down Expand Up @@ -160,7 +160,7 @@ async def run(self) -> None:
self.sequence = seq

if op == OPCODE.DISPATCH:
asyncio.create_task(self.dispatch_event(data, seq, event))
_ = asyncio.create_task(self.dispatch_event(data, seq, event))
continue

# This may try to reconnect the connection so it is best to wait
Expand Down Expand Up @@ -215,17 +215,19 @@ async def dispatch_event(self, data, seq, event) -> None:
case "RESUMED":
self.logger.info(f"Successfully resumed connection! Session_ID: {self.session_id}")
self.state.client.dispatch(events.Resume())
return
return None

case "GUILD_MEMBERS_CHUNK":
asyncio.create_task(self._process_member_chunk(data.copy()))
_ = asyncio.create_task(self._process_member_chunk(data.copy()))

case _:
# the above events are "special", and are handled by the gateway itself, the rest can be dispatched
event_name = f"raw_{event.lower()}"
if processor := self.state.client.processors.get(event_name):
try:
asyncio.create_task(processor(events.RawGatewayEvent(data.copy(), override_name=event_name)))
_ = asyncio.create_task(
processor(events.RawGatewayEvent(data.copy(), override_name=event_name))
)
except Exception as ex:
self.logger.error(f"Failed to run event processor for {event_name}: {ex}")
else:
Expand Down
4 changes: 2 additions & 2 deletions interactions/api/gateway/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,9 +117,9 @@ async def _ws_connect(self) -> None:
except WebSocketClosed as ex:
if ex.code == 4011:
raise NaffException("Your bot is too large, you must use shards") from None
elif ex.code == 4013:
if ex.code == 4013:
raise NaffException(f"Invalid Intents have been passed: {self.intents}") from None
elif ex.code == 4014:
if ex.code == 4014:
raise NaffException(
"You have requested privileged intents that have not been enabled or approved. Check the developer dashboard"
) from None
Expand Down
5 changes: 2 additions & 3 deletions interactions/api/gateway/websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,7 @@ def average_latency(self) -> float:
"""Get the average latency of the connection (seconds)."""
if self._latency:
return sum(self._latency) / len(self._latency)
else:
return float("inf")
return float("inf")

@property
def latency(self) -> float:
Expand Down Expand Up @@ -197,7 +196,7 @@ async def receive(self, force: bool = False) -> str:
await self.reconnect(code=resp.data, resume=resp.data != 1000)
continue

elif resp.type is WSMsgType.CLOSED:
if resp.type is WSMsgType.CLOSED:
if force:
raise RuntimeError("Discord unexpectedly closed the underlying socket during force receive!")

Expand Down
10 changes: 5 additions & 5 deletions interactions/api/http/http_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ def set_reset_time(self, delta: float) -> None:
Sets the reset time to the current time + delta.

To be called if a 429 is received.

Args:
delta: The time to wait before resetting the calls.
"""
Expand Down Expand Up @@ -373,7 +374,7 @@ async def request(
)
await lock.defer_unlock() # lock this route and wait for unlock
continue
elif lock.remaining == 0:
if lock.remaining == 0:
# Last call available in the bucket, lock until reset
self.log_ratelimit(
self.logger.debug,
Expand Down Expand Up @@ -407,12 +408,11 @@ async def _raise_exception(self, response, route, result) -> None:

if response.status == 403:
raise Forbidden(response, response_data=result, route=route)
elif response.status == 404:
if response.status == 404:
raise NotFound(response, response_data=result, route=route)
elif response.status >= 500:
if response.status >= 500:
raise DiscordError(response, response_data=result, route=route)
else:
raise HTTPException(response, response_data=result, route=route)
raise HTTPException(response, response_data=result, route=route)

def log_ratelimit(self, log_func: Callable, message: str) -> None:
"""
Expand Down
7 changes: 3 additions & 4 deletions interactions/api/http/http_requests/threads.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,10 +198,9 @@ async def create_thread(
payload=payload,
reason=reason,
)
else:
payload["type"] = thread_type or ChannelType.GUILD_PUBLIC_THREAD
payload["invitable"] = invitable
return await self.request(Route("POST", f"/channels/{channel_id}/threads"), payload=payload, reason=reason)
payload["type"] = thread_type or ChannelType.GUILD_PUBLIC_THREAD
payload["invitable"] = invitable
return await self.request(Route("POST", f"/channels/{channel_id}/threads"), payload=payload, reason=reason)

async def create_forum_thread(
self,
Expand Down
12 changes: 5 additions & 7 deletions interactions/api/voice/audio.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import audioop
import shutil
import subprocess # noqa: S404
import subprocess
import threading
import time
from abc import ABC, abstractmethod
Expand Down Expand Up @@ -88,7 +88,7 @@ def read(self, frame_size: int) -> bytes:
"""
Reads frame_size ms of audio from source.

returns:
Returns:
bytes of audio
"""
...
Expand Down Expand Up @@ -199,9 +199,7 @@ def _create_process(self, *, block: bool = True) -> None:
cmd[1:1] = before
cmd.extend(after)

self.process = subprocess.Popen( # noqa: S603
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.DEVNULL
)
self.process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.DEVNULL)
self.read_ahead_task.start()

if block:
Expand Down Expand Up @@ -246,7 +244,7 @@ def read(self, frame_size: int) -> bytes:
"""
Reads frame_size bytes of audio from the buffer.

returns:
Returns:
bytes of audio
"""
if not self.process:
Expand Down Expand Up @@ -293,7 +291,7 @@ def read(self, frame_size: int) -> bytes:
"""
Reads frame_size ms of audio from source.

returns:
Returns:
bytes of audio
"""
data = super().read(frame_size)
Expand Down
4 changes: 2 additions & 2 deletions interactions/api/voice/voice_gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ async def receive(self, force=False) -> str:
continue
raise VoiceWebSocketClosed(resp.data)

elif resp.type is WSMsgType.CLOSED:
if resp.type is WSMsgType.CLOSED:
if force:
raise RuntimeError("Discord unexpectedly closed the underlying socket during force receive!")

Expand Down Expand Up @@ -216,7 +216,7 @@ async def reconnect(self, *, resume: bool = False, code: int = 1012) -> None:
self._kill_bee_gees.set()
self.close()
self.logger.debug("Terminating VoiceGateway due to disconnection")
return
return None

self._voice_server_update.clear()

Expand Down
3 changes: 1 addition & 2 deletions interactions/client/auto_shard_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,7 @@ def latency(self) -> float:
if len(self._connection_states):
latencies = sum((g.latency for g in self._connection_states))
return latencies / len(self._connection_states)
else:
return float("inf")
return float("inf")

@property
def latencies(self) -> dict[int, float]:
Expand Down
29 changes: 14 additions & 15 deletions interactions/client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -541,7 +541,7 @@ def _sanity_check(self) -> None:

if self.fetch_members and Intents.GUILD_MEMBERS not in self._connection_state.intents:
raise BotException("Members Intent must be enabled in order to use fetch members")
elif self.fetch_members:
if self.fetch_members:
self.logger.warning("fetch_members enabled; startup will be delayed")

if len(self.processors) == 0:
Expand Down Expand Up @@ -926,7 +926,7 @@ def start(self, token: str | None = None) -> None:
if has_uvloop:
self.logger.info("uvloop is installed, using it")
if sys.version_info >= (3, 11):
with asyncio.Runner(loop_factory=uvloop.new_event_loop) as runner: # noqa: F821
with asyncio.Runner(loop_factory=uvloop.new_event_loop) as runner:
runner.run(self.astart(token))
else:
uvloop.install()
Expand Down Expand Up @@ -979,7 +979,7 @@ def dispatch(self, event: events.BaseEvent, *args, **kwargs) -> None:
) from e

try:
asyncio.create_task(self._process_waits(event))
_ = asyncio.create_task(self._process_waits(event))
except RuntimeError:
# dispatch attempt before event loop is running
self.async_startup_tasks.append(self._process_waits(event))
Expand Down Expand Up @@ -1048,7 +1048,7 @@ def predicate(event) -> bool:
return False
if not author:
return True
elif author != to_snowflake(event.ctx.author):
if author != to_snowflake(event.ctx.author):
return False
return True

Expand Down Expand Up @@ -1178,7 +1178,7 @@ def add_listener(self, listener: Listener) -> None:

event_class_name = "".join([name.capitalize() for name in listener.event.split("_")])
if event_class := globals().get(event_class_name):
if required_intents := _INTENT_EVENTS.get(event_class): # noqa
if required_intents := _INTENT_EVENTS.get(event_class):
if all(required_intent not in self.intents for required_intent in required_intents):
self.logger.warning(
f"Event `{listener.event}` will not work since the required intent is not set -> Requires any of: `{required_intents}`"
Expand Down Expand Up @@ -1223,7 +1223,7 @@ def add_interaction(self, command: InteractionCommand) -> bool:
if isinstance(command, SlashCommand):
command._parse_parameters()

base, group, sub, *_ = command.resolved_name.split(" ") + [None, None]
base, group, sub, *_ = [*command.resolved_name.split(" "), None, None]

for scope in command.scopes:
if scope not in self.interactions_by_scope:
Expand All @@ -1233,7 +1233,7 @@ def add_interaction(self, command: InteractionCommand) -> bool:
raise ValueError(f"Duplicate Command! {scope}::{old_cmd.resolved_name}")

# if self.enforce_interaction_perms:
# command.checks.append(command._permission_enforcer) # noqa : w0212
# command.checks.append(command._permission_enforcer)

self.interactions_by_scope[scope][command.resolved_name] = command

Expand Down Expand Up @@ -1387,7 +1387,7 @@ async def wrap(*args, **kwargs) -> Absent[List[Dict]]:
return MISSING

results = await asyncio.gather(*[wrap(self.app.id, scope) for scope in bot_scopes])
results = dict(zip(bot_scopes, results))
results = dict(zip(bot_scopes, results, strict=False))

for scope, remote_cmds in results.items():
if remote_cmds == MISSING:
Expand All @@ -1408,8 +1408,7 @@ async def wrap(*args, **kwargs) -> Absent[List[Dict]]:
f"{'global' if scope == GLOBAL_SCOPE else scope}"
)
continue
else:
found.add(cmd_name)
found.add(cmd_name)
self._interaction_lookup[cmd.resolved_name] = cmd
cmd.cmd_id[scope] = int(cmd_data["id"])

Expand Down Expand Up @@ -1720,7 +1719,7 @@ async def __dispatch_interaction(
await ctx.send(str(response))

if self.post_run_callback:
asyncio.create_task(self.post_run_callback(ctx, **callback_kwargs))
_ = asyncio.create_task(self.post_run_callback(ctx, **callback_kwargs))
except Exception as e:
self.dispatch(error_callback(ctx=ctx, error=e))
finally:
Expand Down Expand Up @@ -1793,7 +1792,7 @@ def __load_module(self, module, module_name, **load_kwargs) -> None:
asyncio.get_running_loop()
except RuntimeError:
return
asyncio.create_task(self.synchronise_interactions())
_ = asyncio.create_task(self.synchronise_interactions())

def load_extension(
self,
Expand Down Expand Up @@ -1836,7 +1835,7 @@ def unload_extension(
raise ExtensionNotFound(f"No extension called {name} is loaded")

with contextlib.suppress(AttributeError):
teardown = getattr(module, "teardown")
teardown = module.teardown
teardown(**unload_kwargs)

for ext in self.get_extensions(name):
Expand All @@ -1850,7 +1849,7 @@ def unload_extension(
asyncio.get_running_loop()
except RuntimeError:
return
asyncio.create_task(self.synchronise_interactions())
_ = asyncio.create_task(self.synchronise_interactions())

def reload_extension(
self,
Expand Down Expand Up @@ -1900,7 +1899,7 @@ def reload_extension(
self.logger.info(f"Reverted extension {name} to previous state")
except Exception as ex:
sys.modules.pop(name, None)
raise ex from e # noqa: R101
raise ex from e

async def fetch_guild(self, guild_id: "Snowflake_Type") -> Optional[Guild]:
"""
Expand Down
2 changes: 1 addition & 1 deletion interactions/client/mixins/send.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,5 +98,5 @@ async def send(
if message_data:
message = self.client.cache.place_message_data(message_data)
if delete_after:
await message.delete(delay=delete_after) # noqa
await message.delete(delay=delete_after)
return message
Loading