Skip to content

Commit 098a280

Browse files
style(pre-commit): auto fixes from pre-commit.com hooks
1 parent b27b438 commit 098a280

File tree

5 files changed

+86
-65
lines changed

5 files changed

+86
-65
lines changed

discord/gateway.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -137,8 +137,8 @@ def __init__(
137137
interval: float | None = None,
138138
**kwargs: Any,
139139
) -> None:
140-
daemon: bool = kwargs.pop('daemon', True)
141-
name: str = kwargs.pop('name', f'keep-alive-handler:shard-{shard_id}')
140+
daemon: bool = kwargs.pop("daemon", True)
141+
name: str = kwargs.pop("name", f"keep-alive-handler:shard-{shard_id}")
142142
super().__init__(
143143
*args,
144144
**kwargs,

discord/member.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
import itertools
3131
import sys
3232
from operator import attrgetter
33-
from typing import TYPE_CHECKING, Any, TypeVar, Union
33+
from typing import TYPE_CHECKING, Any, TypeVar
3434

3535
import discord.abc
3636

@@ -51,9 +51,9 @@
5151
)
5252

5353
if TYPE_CHECKING:
54-
from .client import Client
5554
from .abc import Snowflake
5655
from .channel import DMChannel, VocalGuildChannel
56+
from .client import Client
5757
from .flags import PublicUserFlags
5858
from .guild import Guild
5959
from .message import Message
@@ -168,11 +168,11 @@ def __repr__(self) -> str:
168168
def _create_default(cls, channel: VocalGuildChannel, client: Client) -> VoiceState:
169169
self = cls(
170170
data={
171-
'channel_id': channel.id,
172-
'guild_id': channel.guild.id,
173-
'self_deaf': False,
174-
'self_mute': False,
175-
'user_id': client._connection.self_id, # type: ignore
171+
"channel_id": channel.id,
172+
"guild_id": channel.guild.id,
173+
"self_deaf": False,
174+
"self_mute": False,
175+
"user_id": client._connection.self_id, # type: ignore
176176
},
177177
channel=channel,
178178
)

discord/voice/enums.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
2323
DEALINGS IN THE SOFTWARE.
2424
"""
25+
2526
from __future__ import annotations
2627

2728
from discord.enums import Enum

discord/voice/gateway.py

Lines changed: 59 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -26,19 +26,20 @@
2626
from __future__ import annotations
2727

2828
import asyncio
29-
from collections import deque
30-
from collections.abc import Callable, Coroutine
3129
import logging
3230
import struct
3331
import time
32+
from collections import deque
33+
from collections.abc import Callable, Coroutine
3434
from typing import TYPE_CHECKING, Any
3535

3636
import aiohttp
3737

3838
from discord import utils
3939
from discord.enums import SpeakingState
4040
from discord.errors import ConnectionClosed
41-
from discord.gateway import DiscordWebSocket, KeepAliveHandler as KeepAliveHandlerBase
41+
from discord.gateway import DiscordWebSocket
42+
from discord.gateway import KeepAliveHandler as KeepAliveHandlerBase
4243

4344
from .enums import OpCodes
4445

@@ -56,8 +57,8 @@ def __init__(
5657
interval: float | None = None,
5758
**kwargs: Any,
5859
) -> None:
59-
daemon: bool = kwargs.pop('daemon', True)
60-
name: str = kwargs.pop('name', f'voice-keep-alive-handler:{id(self):#x}')
60+
daemon: bool = kwargs.pop("daemon", True)
61+
name: str = kwargs.pop("name", f"voice-keep-alive-handler:{id(self):#x}")
6162
super().__init__(
6263
*args,
6364
**kwargs,
@@ -67,17 +68,21 @@ def __init__(
6768

6869
self.ws: VoiceWebSocket = ws
6970
self.interval: float | None = interval
70-
self.msg: str = 'Keeping shard ID %s voice websocket alive with timestamp %s.'
71-
self.block_msg: str = 'Shard ID %s voice heartbeat blocked for more than %s seconds.'
72-
self.behing_msg: str = 'High socket latency, shard ID %s heartbeat is %.1fs behind.'
71+
self.msg: str = "Keeping shard ID %s voice websocket alive with timestamp %s."
72+
self.block_msg: str = (
73+
"Shard ID %s voice heartbeat blocked for more than %s seconds."
74+
)
75+
self.behing_msg: str = (
76+
"High socket latency, shard ID %s heartbeat is %.1fs behind."
77+
)
7378
self.recent_ack_latencies: deque[float] = deque(maxlen=20)
7479

7580
def get_payload(self) -> dict[str, Any]:
7681
return {
77-
'op': int(OpCodes.heartbeat),
78-
'd': {
79-
't': int(time.time() * 1000),
80-
'seq_ack': self.ws.seq_ack,
82+
"op": int(OpCodes.heartbeat),
83+
"d": {
84+
"t": int(time.time() * 1000),
85+
"seq_ack": self.ws.seq_ack,
8186
},
8287
}
8388

@@ -115,47 +120,47 @@ async def _hook(self, *args: Any) -> Any:
115120
pass
116121

117122
async def send_as_json(self, data: Any) -> None:
118-
_log.debug('Sending voice websocket frame: %s.', data)
123+
_log.debug("Sending voice websocket frame: %s.", data)
119124
await self.ws.send_str(utils._to_json(data))
120125

121126
send_heartbeat = send_as_json
122127

123128
async def resume(self) -> None:
124129
payload = {
125-
'op': int(OpCodes.resume),
126-
'd': {
127-
'token': self.token,
128-
'server_id': str(self.state.server_id),
129-
'session_id': self.session_id,
130-
'seq_ack': self.seq_ack,
130+
"op": int(OpCodes.resume),
131+
"d": {
132+
"token": self.token,
133+
"server_id": str(self.state.server_id),
134+
"session_id": self.session_id,
135+
"seq_ack": self.seq_ack,
131136
},
132137
}
133138
await self.send_as_json(payload)
134139

135140
async def received_message(self, msg: Any, /):
136-
_log.debug('Voice websocket frame received: %s', msg)
137-
op = msg['op']
138-
data = msg.get('data', {}) # this key should ALWAYS be given, but guard anyways
139-
self.seq_ack = data.get('seq', self.seq_ack) # keep the seq_ack updated
141+
_log.debug("Voice websocket frame received: %s", msg)
142+
op = msg["op"]
143+
data = msg.get("data", {}) # this key should ALWAYS be given, but guard anyways
144+
self.seq_ack = data.get("seq", self.seq_ack) # keep the seq_ack updated
140145

141146
if op == OpCodes.ready:
142147
await self.ready(data)
143148
elif op == OpCodes.heartbeat_ack:
144149
if not self._keep_alive:
145150
_log.error(
146-
'Received a heartbeat ACK but no keep alive handler was set.',
151+
"Received a heartbeat ACK but no keep alive handler was set.",
147152
)
148153
return
149154
self._keep_alive.ack()
150155
elif op == OpCodes.resumed:
151156
_log.info(
152-
f'Voice connection on channel ID {self.state.channel_id} (guild {self.state.guild_id}) was '
153-
'successfully RESUMED.',
157+
f"Voice connection on channel ID {self.state.channel_id} (guild {self.state.guild_id}) was "
158+
"successfully RESUMED.",
154159
)
155160
elif op == OpCodes.session_description:
156161
self.state.update_session_description(data)
157162
elif op == OpCodes.hello:
158-
interval = data['heartbeat_interval'] / 1000.0
163+
interval = data["heartbeat_interval"] / 1000.0
159164
self._keep_alive = KeepAliveHandler(
160165
ws=self,
161166
interval=min(interval, 5),
@@ -167,12 +172,12 @@ async def received_message(self, msg: Any, /):
167172
async def ready(self, data: dict[str, Any]) -> None:
168173
state = self.state
169174

170-
state.ssrc = data['ssrc']
171-
state.voice_port = data['port']
172-
state.endpoint_ip = data['ip']
175+
state.ssrc = data["ssrc"]
176+
state.voice_port = data["port"]
177+
state.endpoint_ip = data["ip"]
173178

174179
_log.debug(
175-
f'Connecting to {state.endpoint_ip} (port {state.voice_port}).',
180+
f"Connecting to {state.endpoint_ip} (port {state.voice_port}).",
176181
)
177182

178183
await self.loop.sock_connect(
@@ -185,11 +190,13 @@ async def ready(self, data: dict[str, Any]) -> None:
185190
async def get_ip(self) -> tuple[str, int]:
186191
state = self.state
187192
packet = bytearray(75)
188-
struct.pack_into('>H', packet, 0, 1) # 1 = Send
189-
struct.pack_into('>H', packet, 2, 70) # 70 = Length
190-
struct.pack_into('>I', packet, 4, state.ssrc)
193+
struct.pack_into(">H", packet, 0, 1) # 1 = Send
194+
struct.pack_into(">H", packet, 2, 70) # 70 = Length
195+
struct.pack_into(">I", packet, 4, state.ssrc)
191196

192-
_log.debug(f'Sending IP discovery packet for voice in channel {state.channel_id} (guild {state.guild_id})')
197+
_log.debug(
198+
f"Sending IP discovery packet for voice in channel {state.channel_id} (guild {state.guild_id})"
199+
)
193200
await self.loop.sock_sendall(state.socket, packet)
194201

195202
fut: asyncio.Future[bytes] = self.loop.create_future()
@@ -202,31 +209,33 @@ def get_ip_packet(data: bytes) -> None:
202209
state.add_socket_listener(get_ip_packet)
203210
recv = await fut
204211

205-
_log.debug('Received IP discovery packet with data %s', recv)
212+
_log.debug("Received IP discovery packet with data %s", recv)
206213

207214
ip_start = 8
208215
ip_end = recv.index(0, ip_start)
209-
ip = recv[ip_start:ip_end].decode('ascii')
210-
port = struct.unpack_from('>H', recv, len(recv) - 2)[0]
211-
_log.debug('Detected IP %s with port %s', ip, port)
216+
ip = recv[ip_start:ip_end].decode("ascii")
217+
port = struct.unpack_from(">H", recv, len(recv) - 2)[0]
218+
_log.debug("Detected IP %s with port %s", ip, port)
212219

213220
return ip, port
214221

215222
@property
216223
def latency(self) -> float:
217224
heartbeat = self._keep_alive
218-
return float('inf') if heartbeat is None else heartbeat.latency
225+
return float("inf") if heartbeat is None else heartbeat.latency
219226

220227
@property
221228
def average_latency(self) -> float:
222229
heartbeat = self._keep_alive
223230
if heartbeat is None or not heartbeat.recent_ack_latencies:
224-
return float('inf')
231+
return float("inf")
225232
return sum(heartbeat.recent_ack_latencies) / len(heartbeat.recent_ack_latencies)
226233

227234
async def load_secret_key(self, data: dict[str, Any]) -> None:
228-
_log.debug(f'Received secret key for voice connection in channel {self.state.channel_id} (guild {self.state.guild_id})')
229-
self.secret_key = self.state.secret_key = data['secret_key']
235+
_log.debug(
236+
f"Received secret key for voice connection in channel {self.state.channel_id} (guild {self.state.guild_id})"
237+
)
238+
self.secret_key = self.state.secret_key = data["secret_key"]
230239
await self.speak(SpeakingState.none)
231240

232241
async def poll_event(self) -> None:
@@ -235,10 +244,14 @@ async def poll_event(self) -> None:
235244
if msg.type is aiohttp.WSMsgType.TEXT:
236245
await self.received_message(utils._from_json(msg.data))
237246
elif msg.type is aiohttp.WSMsgType.ERROR:
238-
_log.debug('Received %s', msg)
247+
_log.debug("Received %s", msg)
239248
raise ConnectionClosed(self.ws, shard_id=None) from msg.data
240-
elif msg.type in (aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.CLOSE, aiohttp.WSMsgType.CLOSING):
241-
_log.debug('Received %s', msg)
249+
elif msg.type in (
250+
aiohttp.WSMsgType.CLOSED,
251+
aiohttp.WSMsgType.CLOSE,
252+
aiohttp.WSMsgType.CLOSING,
253+
):
254+
_log.debug("Received %s", msg)
242255
raise ConnectionClosed(self.ws, shard_id=None, code=self._close_code)
243256

244257
async def close(self, code: int = 1000) -> None:

discord/voice/state.py

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -25,26 +25,27 @@
2525

2626
from __future__ import annotations
2727

28-
import asyncio
29-
from collections.abc import Callable, Coroutine
3028
import logging
3129
import select
3230
import threading
31+
from collections.abc import Callable, Coroutine
3332
from typing import TYPE_CHECKING, Any
3433

3534
if TYPE_CHECKING:
36-
from .gateway import VoiceWebSocket
3735
from .client import VoiceClient
36+
from .gateway import VoiceWebSocket
3837

3938
SocketReaderCallback = Callable[[bytes], Any]
4039
_log = logging.getLogger(__name__)
4140

4241

4342
class SocketEventReader(threading.Thread):
44-
def __init__(self, state: VoiceConnectionState, *, start_paused: bool = True) -> None:
43+
def __init__(
44+
self, state: VoiceConnectionState, *, start_paused: bool = True
45+
) -> None:
4546
super().__init__(
4647
daemon=True,
47-
name=f'voice-socket-reader:{id(self):#x}',
48+
name=f"voice-socket-reader:{id(self):#x}",
4849
)
4950
self.state: VoiceConnectionState = state
5051
self.start_paused: bool = start_paused
@@ -98,7 +99,7 @@ def run(self) -> None:
9899
try:
99100
self._do_run()
100101
except Exception:
101-
_log.exception('Error while starting socket event reader at %s', self)
102+
_log.exception("Error while starting socket event reader at %s", self)
102103
finally:
103104
self.stop()
104105
self._running.clear()
@@ -114,7 +115,7 @@ def _do_run(self) -> None:
114115
readable, _, _ = select.select([self.state.socket], [], [], 30)
115116
except (ValueError, TypeError, OSError) as e:
116117
_log.debug(
117-
'Select error handling socket in reader, this should be safe to ignore: %s: %s',
118+
"Select error handling socket in reader, this should be safe to ignore: %s: %s",
118119
e.__class__.__name__,
119120
e,
120121
)
@@ -126,14 +127,18 @@ def _do_run(self) -> None:
126127
try:
127128
data = self.state.socket.recv(2048)
128129
except OSError:
129-
_log.debug('Error reading from socket in %s, this should be safe to ignore.', self, exc_info=True)
130+
_log.debug(
131+
"Error reading from socket in %s, this should be safe to ignore.",
132+
self,
133+
exc_info=True,
134+
)
130135
else:
131136
for cb in self._callbacks:
132137
try:
133138
cb(data)
134139
except Exception:
135140
_log.exception(
136-
'Error while calling %s in %s',
141+
"Error while calling %s in %s",
137142
cb,
138143
self,
139144
)
@@ -144,7 +149,9 @@ def __init__(
144149
self,
145150
client: VoiceClient,
146151
*,
147-
hook: Callable[[VoiceWebSocket, dict[str, Any]], Coroutine[Any, Any, Any]] | None = None,
152+
hook: (
153+
Callable[[VoiceWebSocket, dict[str, Any]], Coroutine[Any, Any, Any]] | None
154+
) = None,
148155
) -> None:
149156
...
150157
# TODO: finish this

0 commit comments

Comments
 (0)