From 93b7e57293d667bdbac470520a702b8afb104cd4 Mon Sep 17 00:00:00 2001 From: ayntee Date: Wed, 10 Feb 2021 18:55:25 +0400 Subject: [PATCH] feat(ws/shard): add sendWS() (#514) * feat(ws/shard): add sendWS() Closes #513 * Switch the order of the args * Remove additional info * Use sendWS() --- src/ws/shard.ts | 42 ++++++++++++++++++++++++------------------ 1 file changed, 24 insertions(+), 18 deletions(-) diff --git a/src/ws/shard.ts b/src/ws/shard.ts index c7984f465..eb9a1756a 100644 --- a/src/ws/shard.ts +++ b/src/ws/shard.ts @@ -7,6 +7,7 @@ import { import { DiscordBotGatewayData, DiscordHeartbeatPayload, + DiscordPayload, FetchMembersOptions, GatewayOpcode, ReadyPayload, @@ -182,25 +183,21 @@ function identify(shard: BasicShard, payload: IdentifyPayload) { }, ); - return shard.ws.send( - JSON.stringify( - { - op: GatewayOpcode.Identify, - d: { ...payload, shard: [shard.id, payload.shard[1]] }, - }, - ), - ); + sendWS({ + op: GatewayOpcode.Identify, + d: { ...payload, shard: [shard.id, payload.shard[1]] }, + }, shard.id); } function resume(shard: BasicShard, payload: IdentifyPayload) { - return shard.ws.send(JSON.stringify({ + sendWS({ op: GatewayOpcode.Resume, d: { token: payload.token, session_id: shard.sessionID, seq: shard.previousSequenceNumber, }, - })); + }, shard.id); } async function heartbeat( @@ -238,10 +235,9 @@ async function heartbeat( // Set it to false as we are issuing a new heartbeat heartbeating.set(shard.id, false); - shard.ws.send( - JSON.stringify( - { op: GatewayOpcode.Heartbeat, d: shard.previousSequenceNumber }, - ), + sendWS( + { op: GatewayOpcode.Heartbeat, d: shard.previousSequenceNumber }, + shard.id, ); eventHandlers.debug?.( { @@ -311,7 +307,7 @@ export function requestGuildMembers( return; } - shard?.ws.send(JSON.stringify({ + sendWS({ op: GatewayOpcode.RequestGuildMembers, d: { guild_id: guildID, @@ -322,7 +318,7 @@ export function requestGuildMembers( user_ids: options?.userIDs, nonce, }, - })); + }); } async function processGatewayQueue() { @@ -389,7 +385,7 @@ async function processGatewayQueue() { export function botGatewayStatusRequest(payload: BotStatusRequest) { basicShards.forEach((shard) => { - shard.ws.send(JSON.stringify({ + sendWS({ op: GatewayOpcode.StatusUpdate, d: { since: null, @@ -402,6 +398,16 @@ export function botGatewayStatusRequest(payload: BotStatusRequest) { status: payload.status, afk: false, }, - })); + }); }); } + +/** Enqueues the specified data to be transmitted to the server over the WebSocket connection, */ +export function sendWS(payload: DiscordPayload, shardID = 0) { + const shard = basicShards.get(shardID); + if (!shard) return false; + + const serialized = JSON.stringify(payload); + shard.ws.send(serialized); + return true; +}