Fix creating several heartbeat threads

This commit is contained in:
SeanOMik 2020-09-25 16:21:35 -05:00
parent 77e5a74141
commit 44d52848aa
No known key found for this signature in database
GPG Key ID: FA4D55AC05268A88
2 changed files with 66 additions and 55 deletions

View File

@ -37,7 +37,8 @@ You can view examples in the [examples](examples) directory.
# Todo:
- [x] Finish all REST API calls.
- [x] Handle all gateway events.
- [x] Reconnecting
- [x] Reconnecting.
- [ ] Configurable Logger.
- [ ] Add library to official Nimble package repository.
- [ ] Memory optimizations.
- [ ] Member

View File

@ -120,8 +120,11 @@ proc handleGatewayDisconnect(shard: Shard, error: string) {.async.} =
#TODO: Reconnecting may be done, just needs testing.
proc handleWebsocketPacket(shard: Shard) {.async.} =
var hasStartedHeartbeatThread = false;
while true:
# Skip if the websocket isn't open
if shard.ws.readyState == Open:
var packet = await shard.ws.receiveStrPacket()
shard.client.log.debug("[SHARD " & $shard.id & "] Received gateway payload: " & $packet)
@ -160,10 +163,14 @@ proc handleWebsocketPacket(shard: Shard) {.async.} =
shard.heartbeatInterval = json["d"]["heartbeat_interval"].getInt()
await shard.sendGatewayRequest(shard.getIdentifyPacket())
# Don't start a new
if (not shard.isHandlingHeartbeat):
# Don't start a new heartbeat thread if one is already started
echo "About to start a heartbeat thread! shard.heartbeatAcked is ", shard.heartbeatAcked
if not hasStartedHeartbeatThread:
echo "Starting new heartbeat thread! shard.heartbeatAcked is ", shard.heartbeatAcked
asyncCheck shard.handleHeartbeat()
shard.heartbeatAcked = true
hasStartedHeartbeatThread = true
else:
echo "Not gonna start a new heartbeat thread since. shard.heartbeatAcked is ", shard.heartbeatAcked
of ord(DiscordOpCode.opHeartbeatAck):
shard.heartbeatAcked = true
of ord(DiscordOpCode.opDispatch):
@ -233,12 +240,15 @@ proc startConnection*(client: DiscordClient, shardAmount: int = 1) {.async.} =
shard.ws = await newWebSocket(shard.client.endpoint & "/v=6&encoding=json")
asyncCheck shard.handleWebsocketPacket()
await shard.handleWebsocketPacket()
# Just wait. Don't poll while we're reconnecting
while true:
#[ while true:
if not shard.reconnecting:
try:
poll()
except WebSocketError:
echo "WebSocketError" ]#
else:
raise newException(IOError, "Failed to get gateway url, token may of been incorrect!")