/// <summary> /// Asynchronously opens a connection to the Slack RTM API. /// </summary> /// <param name="token">Your API token.</param> /// <param name="cancellationToken">A token to monitor for cancellation requests. The default value is <see cref="System.Threading.CancellationToken.None"/>.</param> /// <returns> /// A <see cref="System.Threading.Tasks.Task"/> that represents the asynchronous open operation. /// </returns> public async Task OpenAsync(string token, CancellationToken cancellationToken = default(CancellationToken)) { if (_isDisposed) { throw new ObjectDisposedException("Client"); } if (ConnectionState != ClientConnectionState.Disconnected) { throw new InvalidOperationException("Client must not be connected."); } ConnectionState = ClientConnectionState.Connecting; _token = token; try { var response = await Http.GetJsonAsync("https://slack.com/api/rtm.start", cancellationToken, "token", _token); if (response["ok"] == "true") { var ws = _websocket = new ClientWebSocket(); if (ConnectionState == ClientConnectionState.Connecting) { await ws.ConnectAsync(new Uri(response["url"]), cancellationToken); } ConnectionState = ClientConnectionState.Connected; if (ConnectionState == ClientConnectionState.Connected) { BeginReceive(ws); } var self = response.Object("self"); Id = self["id"]; var chans = response.ArrayObjects("channels"); } else { ConnectionState = ClientConnectionState.Disconnected; throw SlackException.FromStatusCode(response["error"]); } } catch (Exception ex) { //We need to reset the connection state to disconnected if it fails to connect //so that it will keep retying. ConnectionState = ClientConnectionState.Disconnected; throw; } }
/// <summary> /// Asynchronously sends the specified message. /// </summary> /// <param name="message">The message to send.</param> /// <param name="cancellationToken">A token to monitor for cancellation requests. The default value is <see cref="System.Threading.CancellationToken.None"/>.</param> /// <returns>The message.</returns> public async Task SendAsync(Message message, CancellationToken cancellationToken = default(CancellationToken)) { if (message == null) { throw new ArgumentNullException("message"); } if (_isDisposed) { throw new ObjectDisposedException("Client"); } if (ConnectionState != ClientConnectionState.Established) { throw new InvalidOperationException("Client must be connected."); } var json = message.ToJson(); var response = await Http.PostJsonAsync("https://slack.com/api/chat.postMessage", json, cancellationToken, "token", _token); if (response["ok"] != "true") { throw SlackException.FromStatusCode(response["error"]); } }