Browse Source

Add Client.latency, AutoShardedClient.latency and latencies.

This should allow an easier way to query the Discord protocol gateway
latency, defined by the difference HEARTBEAT_ACK between and the last
sent HEARTBEAT.
pull/725/merge
Rapptz 8 years ago
parent
commit
0f7482ed6e
  1. 9
      discord/client.py
  2. 2
      discord/gateway.py
  3. 18
      discord/shard.py

9
discord/client.py

@ -172,6 +172,15 @@ class Client:
return m.group(1)
return invite
@property
def latency(self):
"""float: Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.
This could be referred to as the Discord WebSocket protocol latency.
"""
ws = self.ws
return float('nan') if not ws else ws.latency
@property
def user(self):
"""Optional[:class:`ClientUser`]: Represents the connected client. None if not logged in."""

2
discord/gateway.py

@ -346,6 +346,8 @@ class DiscordWebSocket(websockets.client.WebSocketClientProtocol):
if op == self.HELLO:
interval = data['heartbeat_interval'] / 1000.0
self._keep_alive = KeepAliveHandler(ws=self, interval=interval, shard_id=self.shard_id)
# send a heartbeat immediately
yield from self.send_as_json(self._keep_alive.get_payload())
self._keep_alive.start()
return

18
discord/shard.py

@ -149,6 +149,24 @@ class AutoShardedClient(Client):
ws = self.shards[shard_id].ws
yield from ws.send_as_json(payload)
@property
def latency(self):
"""float: Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.
This operates similarly to :meth:`.Client.latency` except it uses the average
latency of every shard's latency. To get a list of shard latency, check the
:attr:`latencies` property.
"""
return sum(latency for _, latency in self.latencies) / len(self.shards)
@property
def latencies(self):
"""List[Tuple[int, float]]: A list of latencies between a HEARTBEAT and a HEARTBEAT_ACK in seconds.
This returns a list of tuples with elements ``(shard_id, latency)``.
"""
return [(shard_id, shard.ws.latency) for shard_id, shard in self.shards.items()]
@asyncio.coroutine
def request_offline_members(self, *guilds):
"""|coro|

Loading…
Cancel
Save