sendMessage method

Future<void> sendMessage([
  1. String? message,
  2. List<MessageEmbed>? embeds
])

Send a message to the TextChannel instance

Implementation

Future<void> sendMessage(
    [String? message, List<MessageEmbed>? embeds]) async {
  Map<String, dynamic> messageObject = {
    "content": message,
    "embeds": null,
  };

  if (embeds != null) {
    List<Map<String, dynamic>> embedsObjects = [];
    for (MessageEmbed embed in embeds) {
      Map<String, dynamic> embedObject = {
        "title": embed.title,
        "description": embed.description,
        "url": embed.url,
        "color": embed.color,
        "fields": null,
        "author": null,
        "footer": null
      };

      List<Map<String, dynamic>> fieldObjects = [];
      for (MessageEmbedTextField field in embed.fields ?? []) {
        fieldObjects.add({
          "name": field.name,
          "value": field.value,
          "inline": field.inline,
        });
      }
      if (fieldObjects.isNotEmpty) embedObject["fields"] = fieldObjects;

      MessageEmbedFooter? footer;
      if (footer != null) {
        embedObject["footer"] = {
          "text": footer.text,
          "icon_url": footer.iconURL,
        };
      }
      MessageEmbedAuthor? author;
      if (author != null) {
        embedObject["author"] = {
          "name": author.name,
          "url": author.url,
          "icon_url": author.iconURL,
        };
      }

      embedsObjects.add(embedObject);
    }

    messageObject["embeds"] = embedsObjects;
  }

  http.Response response = await http.post(
    Uri.parse("${constants.apiBaseURL}/channels/$id/messages"),
    headers: {
      "Authorization": "Bot ${config.botToken}",
      "Content-Type": "application/json",
    },
    body: jsonEncode(messageObject),
  );
  if (response.statusCode != 200) {
    throw Exception("Failed to send message. ($message)");
  }
}