login method

void login(
  1. String token
)

Authenticates the Client at the discord gateway and listens for any event

Implementation

void login(String token) async {
  _setToken(token);

  // TODO: Pass through discord gateway intent code instead of setting a default
  const int intents = 3276799;

  _channel.stream.listen(
    (var msg) {
      Map<String, dynamic> decodedMessage = jsonDecode(msg);

      int opCode = decodedMessage["op"];
      switch (opCode) {
        case 0:
          String type = decodedMessage["t"].toString();
          _handleEvent(type, decodedMessage);
          break;
        case 10:
          int heartbeatInterval = decodedMessage["d"]["heartbeat_interval"];

          // Send a heartbeat to the gateway every [heartbeatInterval]
          // milliseconds to keep the connection alive
          Timer.periodic(Duration(milliseconds: heartbeatInterval),
              (Timer timer) {
            _channel.sink.add(jsonEncode({
              "op": 1,
              "d": null,
            }));
          });

          // Authenticate the user to the discord API
          Map<String, dynamic> authenticationMessage = {
            "op": 2,
            "d": {
              "token": config.botToken,
              "intents": intents,
              "properties": {
                "\$os": Platform.operatingSystem,
                "\$browser": "dartcord",
                "\$device": "dartcord"
              },
              "presence": {"status": "online", "activities": [], "afk": false}
            }
          };

          _channel.sink.add(jsonEncode(authenticationMessage));
          break;
      }
    },
    onDone: () {},
    onError: (var err) {
      // TODO: Handle errors
      print("[CLIENT] ERROR: $err");
    },
    cancelOnError: true,
  );
}