Browse Source

Make global log variable in modules private

pull/7443/head
Rapptz 4 years ago
parent
commit
ea2d972666
  1. 24
      discord/client.py
  2. 2
      discord/ext/tasks/__init__.py
  3. 68
      discord/gateway.py
  4. 16
      discord/http.py
  5. 10
      discord/opus.py
  6. 28
      discord/player.py
  7. 8
      discord/shard.py
  8. 94
      discord/state.py
  9. 28
      discord/voice_client.py
  10. 8
      discord/webhook/async_.py
  11. 8
      discord/webhook/sync.py

24
discord/client.py

@ -76,7 +76,7 @@ __all__ = (
Coro = TypeVar('Coro', bound=Callable[..., Coroutine[Any, Any, Any]])
log: logging.Logger = logging.getLogger(__name__)
_log = logging.getLogger(__name__)
def _cancel_tasks(loop: asyncio.AbstractEventLoop) -> None:
tasks = {t for t in asyncio.all_tasks(loop=loop) if not t.done()}
@ -84,12 +84,12 @@ def _cancel_tasks(loop: asyncio.AbstractEventLoop) -> None:
if not tasks:
return
log.info('Cleaning up after %d tasks.', len(tasks))
_log.info('Cleaning up after %d tasks.', len(tasks))
for task in tasks:
task.cancel()
loop.run_until_complete(asyncio.gather(*tasks, return_exceptions=True))
log.info('All tasks finished cancelling.')
_log.info('All tasks finished cancelling.')
for task in tasks:
if task.cancelled():
@ -106,7 +106,7 @@ def _cleanup_loop(loop: asyncio.AbstractEventLoop) -> None:
_cancel_tasks(loop)
loop.run_until_complete(loop.shutdown_asyncgens())
finally:
log.info('Closing the event loop.')
_log.info('Closing the event loop.')
loop.close()
class Client:
@ -237,7 +237,7 @@ class Client:
if VoiceClient.warn_nacl:
VoiceClient.warn_nacl = False
log.warning("PyNaCl is not installed, voice will NOT be supported")
_log.warning("PyNaCl is not installed, voice will NOT be supported")
# internals
@ -363,7 +363,7 @@ class Client:
return asyncio.create_task(wrapped, name=f'discord.py: {event_name}')
def dispatch(self, event: str, *args: Any, **kwargs: Any) -> None:
log.debug('Dispatching event %s', event)
_log.debug('Dispatching event %s', event)
method = 'on_' + event
listeners = self._listeners.get(event)
@ -468,7 +468,7 @@ class Client:
passing status code.
"""
log.info('logging in using static token')
_log.info('logging in using static token')
data = await self.http.static_login(token.strip())
self._connection.user = ClientUser(state=self._connection, data=data)
@ -511,7 +511,7 @@ class Client:
while True:
await self.ws.poll_event()
except ReconnectWebSocket as e:
log.info('Got a request to %s the websocket.', e.op)
_log.info('Got a request to %s the websocket.', e.op)
self.dispatch('disconnect')
ws_params.update(sequence=self.ws.sequence, resume=e.resume, session=self.ws.session_id)
continue
@ -550,7 +550,7 @@ class Client:
raise
retry = backoff.delay()
log.exception("Attempting a reconnect in %.2fs", retry)
_log.exception("Attempting a reconnect in %.2fs", retry)
await asyncio.sleep(retry)
# Always try to RESUME the connection
# If the connection is not RESUME-able then the gateway will invalidate the session.
@ -652,10 +652,10 @@ class Client:
try:
loop.run_forever()
except KeyboardInterrupt:
log.info('Received signal to terminate bot and event loop.')
_log.info('Received signal to terminate bot and event loop.')
finally:
future.remove_done_callback(stop_loop_on_completion)
log.info('Cleaning up tasks.')
_log.info('Cleaning up tasks.')
_cleanup_loop(loop)
if not future.cancelled():
@ -1021,7 +1021,7 @@ class Client:
raise TypeError('event registered must be a coroutine function')
setattr(self, coro.__name__, coro)
log.debug('%s has successfully been registered as an event', coro.__name__)
_log.debug('%s has successfully been registered as an event', coro.__name__)
return coro
async def change_presence(

2
discord/ext/tasks/__init__.py

@ -50,7 +50,7 @@ from collections.abc import Sequence
from discord.backoff import ExponentialBackoff
from discord.utils import MISSING
log = logging.getLogger(__name__)
_log = logging.getLogger(__name__)
__all__ = (
'loop',

68
discord/gateway.py

@ -40,7 +40,7 @@ from .activity import BaseActivity
from .enums import SpeakingState
from .errors import ConnectionClosed, InvalidArgument
log = logging.getLogger(__name__)
_log = logging.getLogger(__name__)
__all__ = (
'DiscordWebSocket',
@ -101,7 +101,7 @@ class GatewayRatelimiter:
async with self.lock:
delta = self.get_delay()
if delta:
log.warning('WebSocket in shard ID %s is ratelimited, waiting %.2f seconds', self.shard_id, delta)
_log.warning('WebSocket in shard ID %s is ratelimited, waiting %.2f seconds', self.shard_id, delta)
await asyncio.sleep(delta)
@ -129,20 +129,20 @@ class KeepAliveHandler(threading.Thread):
def run(self):
while not self._stop_ev.wait(self.interval):
if self._last_recv + self.heartbeat_timeout < time.perf_counter():
log.warning("Shard ID %s has stopped responding to the gateway. Closing and restarting.", self.shard_id)
_log.warning("Shard ID %s has stopped responding to the gateway. Closing and restarting.", self.shard_id)
coro = self.ws.close(4000)
f = asyncio.run_coroutine_threadsafe(coro, loop=self.ws.loop)
try:
f.result()
except Exception:
log.exception('An error occurred while stopping the gateway. Ignoring.')
_log.exception('An error occurred while stopping the gateway. Ignoring.')
finally:
self.stop()
return
data = self.get_payload()
log.debug(self.msg, self.shard_id, data['d'])
_log.debug(self.msg, self.shard_id, data['d'])
coro = self.ws.send_heartbeat(data)
f = asyncio.run_coroutine_threadsafe(coro, loop=self.ws.loop)
try:
@ -161,7 +161,7 @@ class KeepAliveHandler(threading.Thread):
else:
stack = ''.join(traceback.format_stack(frame))
msg = f'{self.block_msg}\nLoop thread traceback (most recent call last):\n{stack}'
log.warning(msg, self.shard_id, total)
_log.warning(msg, self.shard_id, total)
except Exception:
self.stop()
@ -185,7 +185,7 @@ class KeepAliveHandler(threading.Thread):
self._last_ack = ack_time
self.latency = ack_time - self._last_send
if self.latency > 10:
log.warning(self.behind_msg, self.shard_id, self.latency)
_log.warning(self.behind_msg, self.shard_id, self.latency)
class VoiceKeepAliveHandler(KeepAliveHandler):
def __init__(self, *args, **kwargs):
@ -330,7 +330,7 @@ class DiscordWebSocket:
client._connection._update_references(ws)
log.debug('Created websocket connected to %s', gateway)
_log.debug('Created websocket connected to %s', gateway)
# poll event for OP Hello
await ws.poll_event()
@ -403,7 +403,7 @@ class DiscordWebSocket:
await self.call_hooks('before_identify', self.shard_id, initial=self._initial_identify)
await self.send_as_json(payload)
log.info('Shard ID %s has sent the IDENTIFY payload.', self.shard_id)
_log.info('Shard ID %s has sent the IDENTIFY payload.', self.shard_id)
async def resume(self):
"""Sends the RESUME packet."""
@ -417,7 +417,7 @@ class DiscordWebSocket:
}
await self.send_as_json(payload)
log.info('Shard ID %s has sent the RESUME payload.', self.shard_id)
_log.info('Shard ID %s has sent the RESUME payload.', self.shard_id)
async def received_message(self, msg, /):
self.log_receive(msg)
@ -432,7 +432,7 @@ class DiscordWebSocket:
self._buffer = bytearray()
msg = utils.from_json(msg)
log.debug('For Shard ID %s: WebSocket Event: %s', self.shard_id, msg)
_log.debug('For Shard ID %s: WebSocket Event: %s', self.shard_id, msg)
event = msg.get('t')
if event:
self._dispatch('socket_event_type', event)
@ -451,7 +451,7 @@ class DiscordWebSocket:
# "reconnect" can only be handled by the Client
# so we terminate our connection and raise an
# internal exception signalling to reconnect.
log.debug('Received RECONNECT opcode.')
_log.debug('Received RECONNECT opcode.')
await self.close()
raise ReconnectWebSocket(self.shard_id)
@ -481,11 +481,11 @@ class DiscordWebSocket:
self.sequence = None
self.session_id = None
log.info('Shard ID %s session has been invalidated.', self.shard_id)
_log.info('Shard ID %s session has been invalidated.', self.shard_id)
await self.close(code=1000)
raise ReconnectWebSocket(self.shard_id, resume=False)
log.warning('Unknown OP code %s.', op)
_log.warning('Unknown OP code %s.', op)
return
if event == 'READY':
@ -494,20 +494,20 @@ class DiscordWebSocket:
self.session_id = data['session_id']
# pass back shard ID to ready handler
data['__shard_id__'] = self.shard_id
log.info('Shard ID %s has connected to Gateway: %s (Session ID: %s).',
_log.info('Shard ID %s has connected to Gateway: %s (Session ID: %s).',
self.shard_id, ', '.join(trace), self.session_id)
elif event == 'RESUMED':
self._trace = trace = data.get('_trace', [])
# pass back the shard ID to the resumed handler
data['__shard_id__'] = self.shard_id
log.info('Shard ID %s has successfully RESUMED session %s under trace %s.',
_log.info('Shard ID %s has successfully RESUMED session %s under trace %s.',
self.shard_id, self.session_id, ', '.join(trace))
try:
func = self._discord_parsers[event]
except KeyError:
log.debug('Unknown event %s.', event)
_log.debug('Unknown event %s.', event)
else:
func(data)
@ -561,10 +561,10 @@ class DiscordWebSocket:
elif msg.type is aiohttp.WSMsgType.BINARY:
await self.received_message(msg.data)
elif msg.type is aiohttp.WSMsgType.ERROR:
log.debug('Received %s', msg)
_log.debug('Received %s', msg)
raise msg.data
elif msg.type in (aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.CLOSING, aiohttp.WSMsgType.CLOSE):
log.debug('Received %s', msg)
_log.debug('Received %s', msg)
raise WebSocketClosure
except (asyncio.TimeoutError, WebSocketClosure) as e:
# Ensure the keep alive handler is closed
@ -573,15 +573,15 @@ class DiscordWebSocket:
self._keep_alive = None
if isinstance(e, asyncio.TimeoutError):
log.info('Timed out receiving packet. Attempting a reconnect.')
_log.info('Timed out receiving packet. Attempting a reconnect.')
raise ReconnectWebSocket(self.shard_id) from None
code = self._close_code or self.socket.close_code
if self._can_handle_close():
log.info('Websocket closed with %s, attempting a reconnect.', code)
_log.info('Websocket closed with %s, attempting a reconnect.', code)
raise ReconnectWebSocket(self.shard_id) from None
else:
log.info('Websocket closed with %s, cannot reconnect.', code)
_log.info('Websocket closed with %s, cannot reconnect.', code)
raise ConnectionClosed(self.socket, shard_id=self.shard_id, code=code) from None
async def debug_send(self, data, /):
@ -630,7 +630,7 @@ class DiscordWebSocket:
}
sent = utils.to_json(payload)
log.debug('Sending "%s" to change status', sent)
_log.debug('Sending "%s" to change status', sent)
await self.send(sent)
async def request_chunks(self, guild_id, query=None, *, limit, user_ids=None, presences=False, nonce=None):
@ -666,7 +666,7 @@ class DiscordWebSocket:
}
}
log.debug('Updating our voice state to %s.', payload)
_log.debug('Updating our voice state to %s.', payload)
await self.send_as_json(payload)
async def close(self, code=4000):
@ -734,7 +734,7 @@ class DiscordVoiceWebSocket:
pass
async def send_as_json(self, data):
log.debug('Sending voice websocket frame: %s.', data)
_log.debug('Sending voice websocket frame: %s.', data)
await self.ws.send_str(utils.to_json(data))
send_heartbeat = send_as_json
@ -820,7 +820,7 @@ class DiscordVoiceWebSocket:
await self.send_as_json(payload)
async def received_message(self, msg):
log.debug('Voice websocket frame received: %s', msg)
_log.debug('Voice websocket frame received: %s', msg)
op = msg['op']
data = msg.get('d')
@ -829,7 +829,7 @@ class DiscordVoiceWebSocket:
elif op == self.HEARTBEAT_ACK:
self._keep_alive.ack()
elif op == self.RESUMED:
log.info('Voice RESUME succeeded.')
_log.info('Voice RESUME succeeded.')
elif op == self.SESSION_DESCRIPTION:
self._connection.mode = data['mode']
await self.load_secret_key(data)
@ -852,7 +852,7 @@ class DiscordVoiceWebSocket:
struct.pack_into('>I', packet, 4, state.ssrc)
state.socket.sendto(packet, (state.endpoint_ip, state.voice_port))
recv = await self.loop.sock_recv(state.socket, 70)
log.debug('received packet in initial_connection: %s', recv)
_log.debug('received packet in initial_connection: %s', recv)
# the ip is ascii starting at the 4th byte and ending at the first null
ip_start = 4
@ -860,15 +860,15 @@ class DiscordVoiceWebSocket:
state.ip = recv[ip_start:ip_end].decode('ascii')
state.port = struct.unpack_from('>H', recv, len(recv) - 2)[0]
log.debug('detected ip: %s port: %s', state.ip, state.port)
_log.debug('detected ip: %s port: %s', state.ip, state.port)
# there *should* always be at least one supported mode (xsalsa20_poly1305)
modes = [mode for mode in data['modes'] if mode in self._connection.supported_modes]
log.debug('received supported encryption modes: %s', ", ".join(modes))
_log.debug('received supported encryption modes: %s', ", ".join(modes))
mode = modes[0]
await self.select_protocol(state.ip, state.port, mode)
log.info('selected the voice protocol for use (%s)', mode)
_log.info('selected the voice protocol for use (%s)', mode)
@property
def latency(self):
@ -886,7 +886,7 @@ class DiscordVoiceWebSocket:
return sum(heartbeat.recent_ack_latencies) / len(heartbeat.recent_ack_latencies)
async def load_secret_key(self, data):
log.info('received secret key for voice connection')
_log.info('received secret key for voice connection')
self.secret_key = self._connection.secret_key = data.get('secret_key')
await self.speak()
await self.speak(False)
@ -897,10 +897,10 @@ class DiscordVoiceWebSocket:
if msg.type is aiohttp.WSMsgType.TEXT:
await self.received_message(utils.from_json(msg.data))
elif msg.type is aiohttp.WSMsgType.ERROR:
log.debug('Received %s', msg)
_log.debug('Received %s', msg)
raise ConnectionClosed(self.ws, shard_id=None) from msg.data
elif msg.type in (aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.CLOSE, aiohttp.WSMsgType.CLOSING):
log.debug('Received %s', msg)
_log.debug('Received %s', msg)
raise ConnectionClosed(self.ws, shard_id=None, code=self._close_code)
async def close(self, code=1000):

16
discord/http.py

@ -53,7 +53,7 @@ from .gateway import DiscordClientWebSocketResponse
from . import __version__, utils
from .utils import MISSING
log = logging.getLogger(__name__)
_log = logging.getLogger(__name__)
if TYPE_CHECKING:
from .file import File
@ -270,7 +270,7 @@ class HTTPClient:
try:
async with self.__session.request(method, url, **kwargs) as response:
log.debug('%s %s with %s has returned %s', method, url, kwargs.get('data'), response.status)
_log.debug('%s %s with %s has returned %s', method, url, kwargs.get('data'), response.status)
# even errors have text involved in them so this is safe to call
data = await json_or_text(response)
@ -280,13 +280,13 @@ class HTTPClient:
if remaining == '0' and response.status != 429:
# we've depleted our current bucket
delta = utils._parse_ratelimit_header(response, use_clock=self.use_clock)
log.debug('A rate limit bucket has been exhausted (bucket: %s, retry: %s).', bucket, delta)
_log.debug('A rate limit bucket has been exhausted (bucket: %s, retry: %s).', bucket, delta)
maybe_lock.defer()
self.loop.call_later(delta, lock.release)
# the request was successful so just return the text/json
if 300 > response.status >= 200:
log.debug('%s %s has received %s', method, url, data)
_log.debug('%s %s has received %s', method, url, data)
return data
# we are being rate limited
@ -299,22 +299,22 @@ class HTTPClient:
# sleep a bit
retry_after: float = data['retry_after']
log.warning(fmt, retry_after, bucket)
_log.warning(fmt, retry_after, bucket)
# check if it's a global rate limit
is_global = data.get('global', False)
if is_global:
log.warning('Global rate limit has been hit. Retrying in %.2f seconds.', retry_after)
_log.warning('Global rate limit has been hit. Retrying in %.2f seconds.', retry_after)
self._global_over.clear()
await asyncio.sleep(retry_after)
log.debug('Done sleeping for the rate limit. Retrying...')
_log.debug('Done sleeping for the rate limit. Retrying...')
# release the global lock now that the
# global rate limit has passed
if is_global:
self._global_over.set()
log.debug('Global rate limit is now over.')
_log.debug('Global rate limit is now over.')
continue

10
discord/opus.py

@ -53,7 +53,7 @@ __all__ = (
'OpusNotLoaded',
)
log: logging.Logger = logging.getLogger(__name__)
_log = logging.getLogger(__name__)
c_int_ptr = ctypes.POINTER(ctypes.c_int)
c_int16_ptr = ctypes.POINTER(ctypes.c_int16)
@ -106,14 +106,14 @@ signal_ctl: SignalCtl = {
def _err_lt(result, func, args):
if result < OK:
log.info('error has happened in %s', func.__name__)
_log.info('error has happened in %s', func.__name__)
raise OpusError(result)
return result
def _err_ne(result, func, args):
ret = args[-1]._obj
if ret.value != OK:
log.info('error has happened in %s', func.__name__)
_log.info('error has happened in %s', func.__name__)
raise OpusError(ret.value)
return result
@ -192,7 +192,7 @@ def libopus_loader(name):
if item[3]:
func.errcheck = item[3]
except KeyError:
log.exception("Error assigning check function to %s", func)
_log.exception("Error assigning check function to %s", func)
return lib
@ -276,7 +276,7 @@ class OpusError(DiscordException):
def __init__(self, code):
self.code = code
msg = _lib.opus_strerror(self.code).decode('utf-8')
log.info('"%s" has happened', msg)
_log.info('"%s" has happened', msg)
super().__init__(msg)
class OpusNotLoaded(DiscordException):

28
discord/player.py

@ -50,7 +50,7 @@ if TYPE_CHECKING:
AT = TypeVar('AT', bound='AudioSource')
FT = TypeVar('FT', bound='FFmpegOpusAudio')
log: logging.Logger = logging.getLogger(__name__)
_log = logging.getLogger(__name__)
__all__ = (
'AudioSource',
@ -165,19 +165,19 @@ class FFmpegAudio(AudioSource):
if proc is MISSING:
return
log.info('Preparing to terminate ffmpeg process %s.', proc.pid)
_log.info('Preparing to terminate ffmpeg process %s.', proc.pid)
try:
proc.kill()
except Exception:
log.exception("Ignoring error attempting to kill ffmpeg process %s", proc.pid)
_log.exception("Ignoring error attempting to kill ffmpeg process %s", proc.pid)
if proc.poll() is None:
log.info('ffmpeg process %s has not terminated. Waiting to terminate...', proc.pid)
_log.info('ffmpeg process %s has not terminated. Waiting to terminate...', proc.pid)
proc.communicate()
log.info('ffmpeg process %s should have terminated with a return code of %s.', proc.pid, proc.returncode)
_log.info('ffmpeg process %s should have terminated with a return code of %s.', proc.pid, proc.returncode)
else:
log.info('ffmpeg process %s successfully terminated with return code of %s.', proc.pid, proc.returncode)
_log.info('ffmpeg process %s successfully terminated with return code of %s.', proc.pid, proc.returncode)
self._process = self._stdout = MISSING
@ -480,18 +480,18 @@ class FFmpegOpusAudio(FFmpegAudio):
codec, bitrate = await loop.run_in_executor(None, lambda: probefunc(source, executable)) # type: ignore
except Exception:
if not fallback:
log.exception("Probe '%s' using '%s' failed", method, executable)
_log.exception("Probe '%s' using '%s' failed", method, executable)
return # type: ignore
log.exception("Probe '%s' using '%s' failed, trying fallback", method, executable)
_log.exception("Probe '%s' using '%s' failed, trying fallback", method, executable)
try:
codec, bitrate = await loop.run_in_executor(None, lambda: fallback(source, executable)) # type: ignore
except Exception:
log.exception("Fallback probe using '%s' failed", executable)
_log.exception("Fallback probe using '%s' failed", executable)
else:
log.info("Fallback probe found codec=%s, bitrate=%s", codec, bitrate)
_log.info("Fallback probe found codec=%s, bitrate=%s", codec, bitrate)
else:
log.info("Probe found codec=%s, bitrate=%s", codec, bitrate)
_log.info("Probe found codec=%s, bitrate=%s", codec, bitrate)
finally:
return codec, bitrate
@ -656,12 +656,12 @@ class AudioPlayer(threading.Thread):
try:
self.after(error)
except Exception as exc:
log.exception('Calling the after function failed.')
_log.exception('Calling the after function failed.')
exc.__context__ = error
traceback.print_exception(type(exc), exc, exc.__traceback__)
elif error:
msg = f'Exception in voice thread {self.name}'
log.exception(msg, exc_info=error)
_log.exception(msg, exc_info=error)
print(msg, file=sys.stderr)
traceback.print_exception(type(error), error, error.__traceback__)
@ -698,4 +698,4 @@ class AudioPlayer(threading.Thread):
try:
asyncio.run_coroutine_threadsafe(self.client.ws.speak(speaking), self.client.loop)
except Exception as e:
log.info("Speaking call in player failed: %s", e)
_log.info("Speaking call in player failed: %s", e)

8
discord/shard.py

@ -57,7 +57,7 @@ __all__ = (
'ShardInfo',
)
log: logging.Logger = logging.getLogger(__name__)
_log = logging.getLogger(__name__)
class EventType:
@ -153,7 +153,7 @@ class Shard:
return
if e.code != 1000:
self._queue_put(EventItem(EventType.close, self, e))
return
_log return
retry = self._backoff.delay()
log.error('Attempting a reconnect for shard ID %s in %.2fs', self.id, retry, exc_info=e)
@ -178,7 +178,7 @@ class Shard:
break
async def reidentify(self, exc: ReconnectWebSocket) -> None:
self._cancel_task()
_logf._cancel_task()
self._dispatch('disconnect')
self._dispatch('shard_disconnect', self.id)
log.info('Got a request to %s the websocket at Shard ID %s.', exc.op, self.id)
@ -377,7 +377,7 @@ class AutoShardedClient(Client):
def get_shard(self, shard_id: int) -> Optional[ShardInfo]:
"""Optional[:class:`ShardInfo`]: Gets the shard information at a given shard ID or ``None`` if not found."""
try:
parent = self.__shards[shard_id]
_logent = self.__shards[shard_id]
except KeyError:
return None
else:

94
discord/state.py

@ -129,14 +129,14 @@ class ChunkRequest:
future.set_result(self.buffer)
log: logging.Logger = logging.getLogger(__name__)
_log = logging.getLogger(__name__)
async def logging_coroutine(coroutine: Coroutine[Any, Any, T], *, info: str) -> Optional[T]:
try:
await coroutine
except Exception:
log.exception('Exception occurred during %s', info)
_log.exception('Exception occurred during %s', info)
class ConnectionState:
@ -202,7 +202,7 @@ class ConnectionState:
intents = Intents.default()
if not intents.guilds:
log.warning('Guilds intent seems to be disabled. This may cause state related issues.')
_log.warning('Guilds intent seems to be disabled. This may cause state related issues.')
self._chunk_guilds: bool = options.get('chunk_guilds_at_startup', intents.members)
@ -496,7 +496,7 @@ class ConnectionState:
)
return await asyncio.wait_for(request.wait(), timeout=30.0)
except asyncio.TimeoutError:
log.warning('Timed out waiting for chunks with query %r and limit %d for guild_id %d', query, limit, guild_id)
_log.warning('Timed out waiting for chunks with query %r and limit %d for guild_id %d', query, limit, guild_id)
raise
async def _delay_ready(self) -> None:
@ -523,7 +523,7 @@ class ConnectionState:
try:
await asyncio.wait_for(future, timeout=5.0)
except asyncio.TimeoutError:
log.warning('Shard ID %s timed out waiting for chunks for guild_id %s.', guild.shard_id, guild.id)
_log.warning('Shard ID %s timed out waiting for chunks for guild_id %s.', guild.shard_id, guild.id)
if guild.unavailable is False:
self.dispatch('guild_available', guild)
@ -712,14 +712,14 @@ class ConnectionState:
# guild_id won't be None here
guild = self._get_guild(guild_id)
if guild is None:
log.debug('PRESENCE_UPDATE referencing an unknown guild ID: %s. Discarding.', guild_id)
_log.debug('PRESENCE_UPDATE referencing an unknown guild ID: %s. Discarding.', guild_id)
return
user = data['user']
member_id = int(user['id'])
member = guild.get_member(member_id)
if member is None:
log.debug('PRESENCE_UPDATE referencing an unknown member ID: %s. Discarding', member_id)
_log.debug('PRESENCE_UPDATE referencing an unknown member ID: %s. Discarding', member_id)
return
old_member = Member._copy(member)
@ -774,14 +774,14 @@ class ConnectionState:
channel._update(guild, data)
self.dispatch('guild_channel_update', old_channel, channel)
else:
log.debug('CHANNEL_UPDATE referencing an unknown channel ID: %s. Discarding.', channel_id)
_log.debug('CHANNEL_UPDATE referencing an unknown channel ID: %s. Discarding.', channel_id)
else:
log.debug('CHANNEL_UPDATE referencing an unknown guild ID: %s. Discarding.', guild_id)
_log.debug('CHANNEL_UPDATE referencing an unknown guild ID: %s. Discarding.', guild_id)
def parse_channel_create(self, data) -> None:
factory, ch_type = _channel_factory(data['type'])
if factory is None:
log.debug('CHANNEL_CREATE referencing an unknown channel type %s. Discarding.', data['type'])
_log.debug('CHANNEL_CREATE referencing an unknown channel type %s. Discarding.', data['type'])
return
guild_id = utils._get_as_snowflake(data, 'guild_id')
@ -792,7 +792,7 @@ class ConnectionState:
guild._add_channel(channel) # type: ignore
self.dispatch('guild_channel_create', channel)
else:
log.debug('CHANNEL_CREATE referencing an unknown guild ID: %s. Discarding.', guild_id)
_log.debug('CHANNEL_CREATE referencing an unknown guild ID: %s. Discarding.', guild_id)
return
def parse_channel_pins_update(self, data) -> None:
@ -806,7 +806,7 @@ class ConnectionState:
channel = guild and guild._resolve_channel(channel_id)
if channel is None:
log.debug('CHANNEL_PINS_UPDATE referencing an unknown channel ID: %s. Discarding.', channel_id)
_log.debug('CHANNEL_PINS_UPDATE referencing an unknown channel ID: %s. Discarding.', channel_id)
return
last_pin = utils.parse_time(data['last_pin_timestamp']) if data['last_pin_timestamp'] else None
@ -820,7 +820,7 @@ class ConnectionState:
guild_id = int(data['guild_id'])
guild: Optional[Guild] = self._get_guild(guild_id)
if guild is None:
log.debug('THREAD_CREATE referencing an unknown guild ID: %s. Discarding', guild_id)
_log.debug('THREAD_CREATE referencing an unknown guild ID: %s. Discarding', guild_id)
return
thread = Thread(guild=guild, state=guild._state, data=data)
@ -833,7 +833,7 @@ class ConnectionState:
guild_id = int(data['guild_id'])
guild = self._get_guild(guild_id)
if guild is None:
log.debug('THREAD_UPDATE referencing an unknown guild ID: %s. Discarding', guild_id)
_log.debug('THREAD_UPDATE referencing an unknown guild ID: %s. Discarding', guild_id)
return
thread_id = int(data['id'])
@ -851,7 +851,7 @@ class ConnectionState:
guild_id = int(data['guild_id'])
guild = self._get_guild(guild_id)
if guild is None:
log.debug('THREAD_DELETE referencing an unknown guild ID: %s. Discarding', guild_id)
_log.debug('THREAD_DELETE referencing an unknown guild ID: %s. Discarding', guild_id)
return
thread_id = int(data['id'])
@ -864,7 +864,7 @@ class ConnectionState:
guild_id = int(data['guild_id'])
guild: Optional[Guild] = self._get_guild(guild_id)
if guild is None:
log.debug('THREAD_LIST_SYNC referencing an unknown guild ID: %s. Discarding', guild_id)
_log.debug('THREAD_LIST_SYNC referencing an unknown guild ID: %s. Discarding', guild_id)
return
try:
@ -900,13 +900,13 @@ class ConnectionState:
guild_id = int(data['guild_id'])
guild: Optional[Guild] = self._get_guild(guild_id)
if guild is None:
log.debug('THREAD_MEMBER_UPDATE referencing an unknown guild ID: %s. Discarding', guild_id)
_log.debug('THREAD_MEMBER_UPDATE referencing an unknown guild ID: %s. Discarding', guild_id)
return
thread_id = int(data['id'])
thread: Optional[Thread] = guild.get_thread(thread_id)
if thread is None:
log.debug('THREAD_MEMBER_UPDATE referencing an unknown thread ID: %s. Discarding', thread_id)
_log.debug('THREAD_MEMBER_UPDATE referencing an unknown thread ID: %s. Discarding', thread_id)
return
member = ThreadMember(thread, data)
@ -916,13 +916,13 @@ class ConnectionState:
guild_id = int(data['guild_id'])
guild: Optional[Guild] = self._get_guild(guild_id)
if guild is None:
log.debug('THREAD_MEMBERS_UPDATE referencing an unknown guild ID: %s. Discarding', guild_id)
_log.debug('THREAD_MEMBERS_UPDATE referencing an unknown guild ID: %s. Discarding', guild_id)
return
thread_id = int(data['id'])
thread: Optional[Thread] = guild.get_thread(thread_id)
if thread is None:
log.debug('THREAD_MEMBERS_UPDATE referencing an unknown thread ID: %s. Discarding', thread_id)
_log.debug('THREAD_MEMBERS_UPDATE referencing an unknown thread ID: %s. Discarding', thread_id)
return
added_members = [ThreadMember(thread, d) for d in data.get('added_members', [])]
@ -947,7 +947,7 @@ class ConnectionState:
def parse_guild_member_add(self, data) -> None:
guild = self._get_guild(int(data['guild_id']))
if guild is None:
log.debug('GUILD_MEMBER_ADD referencing an unknown guild ID: %s. Discarding.', data['guild_id'])
_log.debug('GUILD_MEMBER_ADD referencing an unknown guild ID: %s. Discarding.', data['guild_id'])
return
member = Member(guild=guild, data=data, state=self)
@ -975,14 +975,14 @@ class ConnectionState:
guild._remove_member(member) # type: ignore
self.dispatch('member_remove', member)
else:
log.debug('GUILD_MEMBER_REMOVE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])
_log.debug('GUILD_MEMBER_REMOVE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])
def parse_guild_member_update(self, data) -> None:
guild = self._get_guild(int(data['guild_id']))
user = data['user']
user_id = int(user['id'])
if guild is None:
log.debug('GUILD_MEMBER_UPDATE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])
_log.debug('GUILD_MEMBER_UPDATE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])
return
member = guild.get_member(user_id)
@ -1004,12 +1004,12 @@ class ConnectionState:
self.dispatch('user_update', user_update[0], user_update[1])
guild._add_member(member)
log.debug('GUILD_MEMBER_UPDATE referencing an unknown member ID: %s. Discarding.', user_id)
_log.debug('GUILD_MEMBER_UPDATE referencing an unknown member ID: %s. Discarding.', user_id)
def parse_guild_emojis_update(self, data) -> None:
guild = self._get_guild(int(data['guild_id']))
if guild is None:
log.debug('GUILD_EMOJIS_UPDATE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])
_log.debug('GUILD_EMOJIS_UPDATE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])
return
before_emojis = guild.emojis
@ -1022,7 +1022,7 @@ class ConnectionState:
def parse_guild_stickers_update(self, data) -> None:
guild = self._get_guild(int(data['guild_id']))
if guild is None:
log.debug('GUILD_STICKERS_UPDATE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])
_log.debug('GUILD_STICKERS_UPDATE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])
return
before_stickers = guild.stickers
@ -1063,7 +1063,7 @@ class ConnectionState:
try:
await asyncio.wait_for(self.chunk_guild(guild), timeout=60.0)
except asyncio.TimeoutError:
log.info('Somehow timed out waiting for chunks.')
_log.info('Somehow timed out waiting for chunks.')
if unavailable is False:
self.dispatch('guild_available', guild)
@ -1105,12 +1105,12 @@ class ConnectionState:
guild._from_data(data)
self.dispatch('guild_update', old_guild, guild)
else:
log.debug('GUILD_UPDATE referencing an unknown guild ID: %s. Discarding.', data['id'])
_log.debug('GUILD_UPDATE referencing an unknown guild ID: %s. Discarding.', data['id'])
def parse_guild_delete(self, data) -> None:
guild = self._get_guild(int(data['id']))
if guild is None:
log.debug('GUILD_DELETE referencing an unknown guild ID: %s. Discarding.', data['id'])
_log.debug('GUILD_DELETE referencing an unknown guild ID: %s. Discarding.', data['id'])
return
if data.get('unavailable', False):
@ -1154,7 +1154,7 @@ class ConnectionState:
def parse_guild_role_create(self, data) -> None:
guild = self._get_guild(int(data['guild_id']))
if guild is None:
log.debug('GUILD_ROLE_CREATE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])
_log.debug('GUILD_ROLE_CREATE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])
return
role_data = data['role']
@ -1173,7 +1173,7 @@ class ConnectionState:
else:
self.dispatch('guild_role_delete', role)
else:
log.debug('GUILD_ROLE_DELETE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])
_log.debug('GUILD_ROLE_DELETE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])
def parse_guild_role_update(self, data) -> None:
guild = self._get_guild(int(data['guild_id']))
@ -1186,7 +1186,7 @@ class ConnectionState:
role._update(role_data)
self.dispatch('guild_role_update', old_role, role)
else:
log.debug('GUILD_ROLE_UPDATE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])
_log.debug('GUILD_ROLE_UPDATE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])
def parse_guild_members_chunk(self, data) -> None:
guild_id = int(data['guild_id'])
@ -1195,7 +1195,7 @@ class ConnectionState:
# the guild won't be None here
members = [Member(guild=guild, data=member, state=self) for member in data.get('members', [])] # type: ignore
log.debug('Processed a chunk for %s members in guild ID %s.', len(members), guild_id)
_log.debug('Processed a chunk for %s members in guild ID %s.', len(members), guild_id)
if presences:
member_dict = {str(member.id): member for member in members}
@ -1214,7 +1214,7 @@ class ConnectionState:
if guild is not None:
self.dispatch('guild_integrations_update', guild)
else:
log.debug('GUILD_INTEGRATIONS_UPDATE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])
_log.debug('GUILD_INTEGRATIONS_UPDATE referencing an unknown guild ID: %s. Discarding.', data['guild_id'])
def parse_integration_create(self, data) -> None:
guild_id = int(data.pop('guild_id'))
@ -1224,7 +1224,7 @@ class ConnectionState:
integration = cls(data=data, guild=guild)
self.dispatch('integration_create', integration)
else:
log.debug('INTEGRATION_CREATE referencing an unknown guild ID: %s. Discarding.', guild_id)
_log.debug('INTEGRATION_CREATE referencing an unknown guild ID: %s. Discarding.', guild_id)
def parse_integration_update(self, data) -> None:
guild_id = int(data.pop('guild_id'))
@ -1234,7 +1234,7 @@ class ConnectionState:
integration = cls(data=data, guild=guild)
self.dispatch('integration_update', integration)
else:
log.debug('INTEGRATION_UPDATE referencing an unknown guild ID: %s. Discarding.', guild_id)
_log.debug('INTEGRATION_UPDATE referencing an unknown guild ID: %s. Discarding.', guild_id)
def parse_integration_delete(self, data) -> None:
guild_id = int(data['guild_id'])
@ -1243,19 +1243,19 @@ class ConnectionState:
raw = RawIntegrationDeleteEvent(data)
self.dispatch('raw_integration_delete', raw)
else:
log.debug('INTEGRATION_DELETE referencing an unknown guild ID: %s. Discarding.', guild_id)
_log.debug('INTEGRATION_DELETE referencing an unknown guild ID: %s. Discarding.', guild_id)
def parse_webhooks_update(self, data) -> None:
guild = self._get_guild(int(data['guild_id']))
if guild is None:
log.debug('WEBHOOKS_UPDATE referencing an unknown guild ID: %s. Discarding', data['guild_id'])
_log.debug('WEBHOOKS_UPDATE referencing an unknown guild ID: %s. Discarding', data['guild_id'])
return
channel = guild.get_channel(int(data['channel_id']))
if channel is not None:
self.dispatch('webhooks_update', channel)
else:
log.debug('WEBHOOKS_UPDATE referencing an unknown channel ID: %s. Discarding.', data['channel_id'])
_log.debug('WEBHOOKS_UPDATE referencing an unknown channel ID: %s. Discarding.', data['channel_id'])
def parse_stage_instance_create(self, data) -> None:
guild = self._get_guild(int(data['guild_id']))
@ -1264,7 +1264,7 @@ class ConnectionState:
guild._stage_instances[stage_instance.id] = stage_instance
self.dispatch('stage_instance_create', stage_instance)
else:
log.debug('STAGE_INSTANCE_CREATE referencing unknown guild ID: %s. Discarding.', data['guild_id'])
_log.debug('STAGE_INSTANCE_CREATE referencing unknown guild ID: %s. Discarding.', data['guild_id'])
def parse_stage_instance_update(self, data) -> None:
guild = self._get_guild(int(data['guild_id']))
@ -1275,9 +1275,9 @@ class ConnectionState:
stage_instance._update(data)
self.dispatch('stage_instance_update', old_stage_instance, stage_instance)
else:
log.debug('STAGE_INSTANCE_UPDATE referencing unknown stage instance ID: %s. Discarding.', data['id'])
_log.debug('STAGE_INSTANCE_UPDATE referencing unknown stage instance ID: %s. Discarding.', data['id'])
else:
log.debug('STAGE_INSTANCE_UPDATE referencing unknown guild ID: %s. Discarding.', data['guild_id'])
_log.debug('STAGE_INSTANCE_UPDATE referencing unknown guild ID: %s. Discarding.', data['guild_id'])
def parse_stage_instance_delete(self, data) -> None:
guild = self._get_guild(int(data['guild_id']))
@ -1289,7 +1289,7 @@ class ConnectionState:
else:
self.dispatch('stage_instance_delete', stage_instance)
else:
log.debug('STAGE_INSTANCE_DELETE referencing unknown guild ID: %s. Discarding.', data['guild_id'])
_log.debug('STAGE_INSTANCE_DELETE referencing unknown guild ID: %s. Discarding.', data['guild_id'])
def parse_voice_state_update(self, data) -> None:
guild = self._get_guild(utils._get_as_snowflake(data, 'guild_id'))
@ -1316,7 +1316,7 @@ class ConnectionState:
self.dispatch('voice_state_update', member, before, after)
else:
log.debug('VOICE_STATE_UPDATE referencing an unknown member ID: %s. Discarding.', data['user_id'])
_log.debug('VOICE_STATE_UPDATE referencing an unknown member ID: %s. Discarding.', data['user_id'])
def parse_voice_server_update(self, data) -> None:
try:
@ -1443,13 +1443,13 @@ class AutoShardedConnectionState(ConnectionState):
break
else:
if self._guild_needs_chunking(guild):
log.debug('Guild ID %d requires chunking, will be done in the background.', guild.id)
_log.debug('Guild ID %d requires chunking, will be done in the background.', guild.id)
if len(current_bucket) >= max_concurrency:
try:
await utils.sane_wait_for(current_bucket, timeout=max_concurrency * 70.0)
except asyncio.TimeoutError:
fmt = 'Shard ID %s failed to wait for chunks from a sub-bucket with length %d'
log.warning(fmt, guild.shard_id, len(current_bucket))
_log.warning(fmt, guild.shard_id, len(current_bucket))
finally:
current_bucket = []
@ -1470,7 +1470,7 @@ class AutoShardedConnectionState(ConnectionState):
try:
await utils.sane_wait_for(futures, timeout=timeout)
except asyncio.TimeoutError:
log.warning(
_log.warning(
'Shard ID %s failed to wait for chunks (timeout=%.2f) for %d guilds', shard_id, timeout, len(guilds)
)
for guild in children:

28
discord/voice_client.py

@ -84,7 +84,7 @@ __all__ = (
log: logging.Logger = logging.getLogger(__name__)
_log = logging.getLogger(__name__)
class VoiceProtocol:
"""A class that represents the Discord voice protocol.
@ -301,7 +301,7 @@ class VoiceClient(VoiceProtocol):
async def on_voice_server_update(self, data: VoiceServerUpdatePayload) -> None:
if self._voice_server_complete.is_set():
log.info('Ignoring extraneous voice server update.')
_log.info('Ignoring extraneous voice server update.')
return
self.token = data.get('token')
@ -309,7 +309,7 @@ class VoiceClient(VoiceProtocol):
endpoint = data.get('endpoint')
if endpoint is None or self.token is None:
log.warning('Awaiting endpoint... This requires waiting. ' \
_log.warning('Awaiting endpoint... This requires waiting. ' \
'If timeout occurred considering raising the timeout and reconnecting.')
return
@ -335,18 +335,18 @@ class VoiceClient(VoiceProtocol):
await self.channel.guild.change_voice_state(channel=self.channel)
async def voice_disconnect(self) -> None:
log.info('The voice handshake is being terminated for Channel ID %s (Guild ID %s)', self.channel.id, self.guild.id)
_log.info('The voice handshake is being terminated for Channel ID %s (Guild ID %s)', self.channel.id, self.guild.id)
await self.channel.guild.change_voice_state(channel=None)
def prepare_handshake(self) -> None:
self._voice_state_complete.clear()
self._voice_server_complete.clear()
self._handshaking = True
log.info('Starting voice handshake... (connection attempt %d)', self._connections + 1)
_log.info('Starting voice handshake... (connection attempt %d)', self._connections + 1)
self._connections += 1
def finish_handshake(self) -> None:
log.info('Voice handshake complete. Endpoint found %s', self.endpoint)
_log.info('Voice handshake complete. Endpoint found %s', self.endpoint)
self._handshaking = False
self._voice_server_complete.clear()
self._voice_state_complete.clear()
@ -360,7 +360,7 @@ class VoiceClient(VoiceProtocol):
return ws
async def connect(self, *, reconnect: bool, timeout: float) ->None:
log.info('Connecting to voice...')
_log.info('Connecting to voice...')
self.timeout = timeout
for i in range(5):
@ -388,7 +388,7 @@ class VoiceClient(VoiceProtocol):
break
except (ConnectionClosed, asyncio.TimeoutError):
if reconnect:
log.exception('Failed to connect to voice... Retrying...')
_log.exception('Failed to connect to voice... Retrying...')
await asyncio.sleep(1 + i * 2.0)
await self.voice_disconnect()
continue
@ -453,14 +453,14 @@ class VoiceClient(VoiceProtocol):
# 4014 - voice channel has been deleted.
# 4015 - voice server has crashed
if exc.code in (1000, 4015):
log.info('Disconnecting from voice normally, close code %d.', exc.code)
_log.info('Disconnecting from voice normally, close code %d.', exc.code)
await self.disconnect()
break
if exc.code == 4014:
log.info('Disconnected from voice by force... potentially reconnecting.')
_log.info('Disconnected from voice by force... potentially reconnecting.')
successful = await self.potential_reconnect()
if not successful:
log.info('Reconnect was unsuccessful, disconnecting from voice normally...')
_log.info('Reconnect was unsuccessful, disconnecting from voice normally...')
await self.disconnect()
break
else:
@ -471,7 +471,7 @@ class VoiceClient(VoiceProtocol):
raise
retry = backoff.delay()
log.exception('Disconnected from voice... Reconnecting in %.2fs.', retry)
_log.exception('Disconnected from voice... Reconnecting in %.2fs.', retry)
self._connected.clear()
await asyncio.sleep(retry)
await self.voice_disconnect()
@ -479,7 +479,7 @@ class VoiceClient(VoiceProtocol):
await self.connect(reconnect=True, timeout=self.timeout)
except asyncio.TimeoutError:
# at this point we've retried 5 times... let's continue the loop.
log.warning('Could not connect to voice... Retrying...')
_log.warning('Could not connect to voice... Retrying...')
continue
async def disconnect(self, *, force: bool = False) -> None:
@ -671,6 +671,6 @@ class VoiceClient(VoiceProtocol):
try:
self.socket.sendto(packet, (self.endpoint_ip, self.voice_port))
except BlockingIOError:
log.warning('A packet has been dropped (seq: %s, timestamp: %s)', self.sequence, self.timestamp)
_log.warning('A packet has been dropped (seq: %s, timestamp: %s)', self.sequence, self.timestamp)
self.checked_add('timestamp', opus.Encoder.SAMPLES_PER_FRAME, 4294967295)

8
discord/webhook/async_.py

@ -52,7 +52,7 @@ __all__ = (
'PartialWebhookGuild',
)
log = logging.getLogger(__name__)
_log = logging.getLogger(__name__)
if TYPE_CHECKING:
from ..file import File
@ -143,7 +143,7 @@ class AsyncWebhookAdapter:
try:
async with session.request(method, url, data=to_send, headers=headers, params=params) as response:
log.debug(
_log.debug(
'Webhook ID %s with %s %s has returned status code %s',
webhook_id,
method,
@ -157,7 +157,7 @@ class AsyncWebhookAdapter:
remaining = response.headers.get('X-Ratelimit-Remaining')
if remaining == '0' and response.status != 429:
delta = utils._parse_ratelimit_header(response)
log.debug(
_log.debug(
'Webhook ID %s has been pre-emptively rate limited, waiting %.2f seconds', webhook_id, delta
)
lock.delay_by(delta)
@ -170,7 +170,7 @@ class AsyncWebhookAdapter:
raise HTTPException(response, data)
retry_after: float = data['retry_after'] # type: ignore
log.warning('Webhook ID %s is rate limited. Retrying in %.2f seconds', webhook_id, retry_after)
_log.warning('Webhook ID %s is rate limited. Retrying in %.2f seconds', webhook_id, retry_after)
await asyncio.sleep(retry_after)
continue

8
discord/webhook/sync.py

@ -52,7 +52,7 @@ __all__ = (
'SyncWebhookMessage',
)
log = logging.getLogger(__name__)
_log = logging.getLogger(__name__)
if TYPE_CHECKING:
from ..file import File
@ -150,7 +150,7 @@ class WebhookAdapter:
with session.request(
method, url, data=to_send, files=file_data, headers=headers, params=params
) as response:
log.debug(
_log.debug(
'Webhook ID %s with %s %s has returned status code %s',
webhook_id,
method,
@ -168,7 +168,7 @@ class WebhookAdapter:
remaining = response.headers.get('X-Ratelimit-Remaining')
if remaining == '0' and response.status_code != 429:
delta = utils._parse_ratelimit_header(response)
log.debug(
_log.debug(
'Webhook ID %s has been pre-emptively rate limited, waiting %.2f seconds', webhook_id, delta
)
lock.delay_by(delta)
@ -181,7 +181,7 @@ class WebhookAdapter:
raise HTTPException(response, data)
retry_after: float = data['retry_after'] # type: ignore
log.warning('Webhook ID %s is rate limited. Retrying in %.2f seconds', webhook_id, retry_after)
_log.warning('Webhook ID %s is rate limited. Retrying in %.2f seconds', webhook_id, retry_after)
time.sleep(retry_after)
continue

Loading…
Cancel
Save