Skip to content

Commit f231d72

Browse files
committed
missing imports
2 parents 8a6ae39 + 098a280 commit f231d72

File tree

5 files changed

+83
-66
lines changed

5 files changed

+83
-66
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,20 +26,21 @@
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 threading
3432
import time
33+
from collections import deque
34+
from collections.abc import Callable, Coroutine
3535
from typing import TYPE_CHECKING, Any
3636

3737
import aiohttp
3838

3939
from discord import utils
4040
from discord.enums import SpeakingState
4141
from discord.errors import ConnectionClosed
42-
from discord.gateway import DiscordWebSocket, KeepAliveHandler as KeepAliveHandlerBase
42+
from discord.gateway import DiscordWebSocket
43+
from discord.gateway import KeepAliveHandler as KeepAliveHandlerBase
4344

4445
from .enums import OpCodes
4546

@@ -59,8 +60,8 @@ def __init__(
5960
interval: float | None = None,
6061
**kwargs: Any,
6162
) -> None:
62-
daemon: bool = kwargs.pop('daemon', True)
63-
name: str = kwargs.pop('name', f'voice-keep-alive-handler:{id(self):#x}')
63+
daemon: bool = kwargs.pop("daemon", True)
64+
name: str = kwargs.pop("name", f"voice-keep-alive-handler:{id(self):#x}")
6465
super().__init__(
6566
*args,
6667
**kwargs,
@@ -70,17 +71,21 @@ def __init__(
7071

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

7883
def get_payload(self) -> dict[str, Any]:
7984
return {
80-
'op': int(OpCodes.heartbeat),
81-
'd': {
82-
't': int(time.time() * 1000),
83-
'seq_ack': self.ws.seq_ack,
85+
"op": int(OpCodes.heartbeat),
86+
"d": {
87+
"t": int(time.time() * 1000),
88+
"seq_ack": self.ws.seq_ack,
8489
},
8590
}
8691

@@ -119,47 +124,47 @@ async def _hook(self, *args: Any) -> Any:
119124
pass
120125

121126
async def send_as_json(self, data: Any) -> None:
122-
_log.debug('Sending voice websocket frame: %s.', data)
127+
_log.debug("Sending voice websocket frame: %s.", data)
123128
await self.ws.send_str(utils._to_json(data))
124129

125130
send_heartbeat = send_as_json
126131

127132
async def resume(self) -> None:
128133
payload = {
129-
'op': int(OpCodes.resume),
130-
'd': {
131-
'token': self.token,
132-
'server_id': str(self.state.server_id),
133-
'session_id': self.session_id,
134-
'seq_ack': self.seq_ack,
134+
"op": int(OpCodes.resume),
135+
"d": {
136+
"token": self.token,
137+
"server_id": str(self.state.server_id),
138+
"session_id": self.session_id,
139+
"seq_ack": self.seq_ack,
135140
},
136141
}
137142
await self.send_as_json(payload)
138143

139144
async def received_message(self, msg: Any, /):
140-
_log.debug('Voice websocket frame received: %s', msg)
141-
op = msg['op']
142-
data = msg.get('data', {}) # this key should ALWAYS be given, but guard anyways
143-
self.seq_ack = data.get('seq', self.seq_ack) # keep the seq_ack updated
145+
_log.debug("Voice websocket frame received: %s", msg)
146+
op = msg["op"]
147+
data = msg.get("data", {}) # this key should ALWAYS be given, but guard anyways
148+
self.seq_ack = data.get("seq", self.seq_ack) # keep the seq_ack updated
144149

145150
if op == OpCodes.ready:
146151
await self.ready(data)
147152
elif op == OpCodes.heartbeat_ack:
148153
if not self._keep_alive:
149154
_log.error(
150-
'Received a heartbeat ACK but no keep alive handler was set.',
155+
"Received a heartbeat ACK but no keep alive handler was set.",
151156
)
152157
return
153158
self._keep_alive.ack()
154159
elif op == OpCodes.resumed:
155160
_log.info(
156-
f'Voice connection on channel ID {self.state.channel_id} (guild {self.state.guild_id}) was '
157-
'successfully RESUMED.',
161+
f"Voice connection on channel ID {self.state.channel_id} (guild {self.state.guild_id}) was "
162+
"successfully RESUMED.",
158163
)
159164
elif op == OpCodes.session_description:
160165
self.state.mode = data['mode']
161166
elif op == OpCodes.hello:
162-
interval = data['heartbeat_interval'] / 1000.0
167+
interval = data["heartbeat_interval"] / 1000.0
163168
self._keep_alive = KeepAliveHandler(
164169
ws=self,
165170
interval=min(interval, 5),
@@ -171,12 +176,12 @@ async def received_message(self, msg: Any, /):
171176
async def ready(self, data: dict[str, Any]) -> None:
172177
state = self.state
173178

174-
state.ssrc = data['ssrc']
175-
state.voice_port = data['port']
176-
state.endpoint_ip = data['ip']
179+
state.ssrc = data["ssrc"]
180+
state.voice_port = data["port"]
181+
state.endpoint_ip = data["ip"]
177182

178183
_log.debug(
179-
f'Connecting to {state.endpoint_ip} (port {state.voice_port}).',
184+
f"Connecting to {state.endpoint_ip} (port {state.voice_port}).",
180185
)
181186

182187
await self.loop.sock_connect(
@@ -189,11 +194,13 @@ async def ready(self, data: dict[str, Any]) -> None:
189194
async def get_ip(self) -> tuple[str, int]:
190195
state = self.state
191196
packet = bytearray(75)
192-
struct.pack_into('>H', packet, 0, 1) # 1 = Send
193-
struct.pack_into('>H', packet, 2, 70) # 70 = Length
194-
struct.pack_into('>I', packet, 4, state.ssrc)
197+
struct.pack_into(">H", packet, 0, 1) # 1 = Send
198+
struct.pack_into(">H", packet, 2, 70) # 70 = Length
199+
struct.pack_into(">I", packet, 4, state.ssrc)
195200

196-
_log.debug(f'Sending IP discovery packet for voice in channel {state.channel_id} (guild {state.guild_id})')
201+
_log.debug(
202+
f"Sending IP discovery packet for voice in channel {state.channel_id} (guild {state.guild_id})"
203+
)
197204
await self.loop.sock_sendall(state.socket, packet)
198205

199206
fut: asyncio.Future[bytes] = self.loop.create_future()
@@ -206,31 +213,33 @@ def get_ip_packet(data: bytes) -> None:
206213
state.add_socket_listener(get_ip_packet)
207214
recv = await fut
208215

209-
_log.debug('Received IP discovery packet with data %s', recv)
216+
_log.debug("Received IP discovery packet with data %s", recv)
210217

211218
ip_start = 8
212219
ip_end = recv.index(0, ip_start)
213-
ip = recv[ip_start:ip_end].decode('ascii')
214-
port = struct.unpack_from('>H', recv, len(recv) - 2)[0]
215-
_log.debug('Detected IP %s with port %s', ip, port)
220+
ip = recv[ip_start:ip_end].decode("ascii")
221+
port = struct.unpack_from(">H", recv, len(recv) - 2)[0]
222+
_log.debug("Detected IP %s with port %s", ip, port)
216223

217224
return ip, port
218225

219226
@property
220227
def latency(self) -> float:
221228
heartbeat = self._keep_alive
222-
return float('inf') if heartbeat is None else heartbeat.latency
229+
return float("inf") if heartbeat is None else heartbeat.latency
223230

224231
@property
225232
def average_latency(self) -> float:
226233
heartbeat = self._keep_alive
227234
if heartbeat is None or not heartbeat.recent_ack_latencies:
228-
return float('inf')
235+
return float("inf")
229236
return sum(heartbeat.recent_ack_latencies) / len(heartbeat.recent_ack_latencies)
230237

231238
async def load_secret_key(self, data: dict[str, Any]) -> None:
232-
_log.debug(f'Received secret key for voice connection in channel {self.state.channel_id} (guild {self.state.guild_id})')
233-
self.secret_key = self.state.secret_key = data['secret_key']
239+
_log.debug(
240+
f"Received secret key for voice connection in channel {self.state.channel_id} (guild {self.state.guild_id})"
241+
)
242+
self.secret_key = self.state.secret_key = data["secret_key"]
234243
await self.speak(SpeakingState.none)
235244

236245
async def poll_event(self) -> None:
@@ -239,10 +248,14 @@ async def poll_event(self) -> None:
239248
if msg.type is aiohttp.WSMsgType.TEXT:
240249
await self.received_message(utils._from_json(msg.data))
241250
elif msg.type is aiohttp.WSMsgType.ERROR:
242-
_log.debug('Received %s', msg)
251+
_log.debug("Received %s", msg)
243252
raise ConnectionClosed(self.ws, shard_id=None) from msg.data
244-
elif msg.type in (aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.CLOSE, aiohttp.WSMsgType.CLOSING):
245-
_log.debug('Received %s', msg)
253+
elif msg.type in (
254+
aiohttp.WSMsgType.CLOSED,
255+
aiohttp.WSMsgType.CLOSE,
256+
aiohttp.WSMsgType.CLOSING,
257+
):
258+
_log.debug("Received %s", msg)
246259
raise ConnectionClosed(self.ws, shard_id=None, code=self._close_code)
247260

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

discord/voice/state.py

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -26,11 +26,11 @@
2626
from __future__ import annotations
2727

2828
import asyncio
29-
from collections.abc import Callable, Coroutine
3029
import logging
3130
import select
3231
import socket
3332
import threading
33+
from collections.abc import Callable, Coroutine
3434
from typing import TYPE_CHECKING, Any
3535

3636
from discord import utils
@@ -45,10 +45,7 @@
4545
from discord.user import ClientUser
4646
from discord.guild import Guild
4747
from discord.member import VoiceState
48-
from discord.types.voice import (
49-
SupportedModes,
50-
VoiceServerUpdate as VoiceServerUpdatePayload,
51-
)
48+
from discord.types.voice import SupportedModes
5249
from discord.raw_models import RawVoiceStateUpdateEvent, RawVoiceServerUpdateEvent
5350
from .client import VoiceClient
5451

@@ -58,10 +55,12 @@
5855

5956

6057
class SocketEventReader(threading.Thread):
61-
def __init__(self, state: VoiceConnectionState, *, start_paused: bool = True) -> None:
58+
def __init__(
59+
self, state: VoiceConnectionState, *, start_paused: bool = True
60+
) -> None:
6261
super().__init__(
6362
daemon=True,
64-
name=f'voice-socket-reader:{id(self):#x}',
63+
name=f"voice-socket-reader:{id(self):#x}",
6564
)
6665
self.state: VoiceConnectionState = state
6766
self.start_paused: bool = start_paused
@@ -115,7 +114,7 @@ def run(self) -> None:
115114
try:
116115
self._do_run()
117116
except Exception:
118-
_log.exception('Error while starting socket event reader at %s', self)
117+
_log.exception("Error while starting socket event reader at %s", self)
119118
finally:
120119
self.stop()
121120
self._running.clear()
@@ -131,7 +130,7 @@ def _do_run(self) -> None:
131130
readable, _, _ = select.select([self.state.socket], [], [], 30)
132131
except (ValueError, TypeError, OSError) as e:
133132
_log.debug(
134-
'Select error handling socket in reader, this should be safe to ignore: %s: %s',
133+
"Select error handling socket in reader, this should be safe to ignore: %s: %s",
135134
e.__class__.__name__,
136135
e,
137136
)
@@ -143,14 +142,18 @@ def _do_run(self) -> None:
143142
try:
144143
data = self.state.socket.recv(2048)
145144
except OSError:
146-
_log.debug('Error reading from socket in %s, this should be safe to ignore.', self, exc_info=True)
145+
_log.debug(
146+
"Error reading from socket in %s, this should be safe to ignore.",
147+
self,
148+
exc_info=True,
149+
)
147150
else:
148151
for cb in self._callbacks:
149152
try:
150153
cb(data)
151154
except Exception:
152155
_log.exception(
153-
'Error while calling %s in %s',
156+
"Error while calling %s in %s",
154157
cb,
155158
self,
156159
)

0 commit comments

Comments
 (0)