/// <summary> /// Returns an object containing information needed to connect to the Discord Gateway API via a Bot token /// </summary> /// <param name="rest"><see cref="Rest"/> controller used to query Discord's REST API</param> /// <param name="ct">CancellationToken used to cancel the request</param> /// <exception cref="HttpRequestException">If the request is unsuccessful</exception> /// <returns>Returns a <see cref="Json.Objects.GetGatewayBotResponseObject"/> containing Gateway connection information</returns> public static async Task <Json.Objects.GetGatewayBotResponseObject> GetBotGatewayAsync(Rest rest, CancellationToken ct) { string endpoint = $"{Rest.RestBaseUrl}{BotGatewayEndpoint}?v={ApiVersion}&encoding={Encoding.ToString().ToLowerInvariant()}"; Json.Objects.GetGatewayBotResponseObject response = await rest.GetAsync <Json.Objects.GetGatewayBotResponseObject>( endpoint, null, ct ); return(response); }
/// <summary> /// Asynchronously connects to the Gateway with the given connection info. /// Returns a <see cref="Task"/> which may be awaited to block the calling thread. /// Throws a <see cref="Utility.SessionLimitException"/> if the maximum number of sessions have been used up. /// </summary> /// <param name="token"></param> /// <returns>a <see cref="Task"/> that may be awaited to block the calling thread</returns> /// <throws><see cref="Utility.SessionLimitException"/> if maximum session count has been reached.</throws> public virtual async Task <Task> ConnectAsync(CancellationToken token, Json.Objects.GetGatewayResponseObject connectionInfo) { //if the user has provided a cancelled token, abuse them token.ThrowIfCancellationRequested(); if (Credentials.IsBotToken) { Json.Objects.GetGatewayBotResponseObject botConnectionInfo = connectionInfo as Json.Objects.GetGatewayBotResponseObject; if (botConnectionInfo.session_start_limit.remaining < 1) { throw new Utility.SessionLimitException(botConnectionInfo.session_start_limit.reset_after); } } //To allow reconnecting to the same gateway instance, we recreate our internal token source if it has previously been cancelled if (GatewayTokenSource.IsCancellationRequested) { GatewayTokenSource = new CancellationTokenSource(); } Task blockable = await Connector.ConnectAsync(token, connectionInfo); return(blockable); }