Search code examples
c#.netembedwebhooksdiscord.net

How to send file attachment with embed discord.net webhook c#


I've tried every solution on adding an embed on a web hook but none work on my case or am I missing something?

I'm using Discord.Net v2.2.0

here's part of my code

var DCW = new DiscordWebhookClient(DCWebhook)

using (var client = DCW)
{
    var eb = new EmbedBuilder();
        eb.WithDescription("some text")
      .Build();

    await client.SendFileAsync(filePath: "file.txt", text: null, embeds: eb);
}

this code shows an error

cannot convert from 'Discord.Embed' to System.Collections.Generic.IEnumerable<Discord.Embed>

I tried this code and had the error fixed

await client.SendFileAsync(filePath: "file.txt", text: null, embeds: (IEnumerable<Embed>)eb);

I built and ran the .exe file and an error occured on console

Unhandled Exception: System.InvalidCastException: Unable to cast object of type 'Discord.EmbedBuilder' to type System.Collections.Generic.IEnumerable 1[Discord.Embed].

references: Send a Discord Embed via Webhook C#

Discord.net bot Embed Message

ModifyAsync Not Working

https://discord.foxbot.me/docs/api/Discord.EmbedBuilder.html

I know most solutions above work but not in my case. I would really appreciate examples on how to solve this. thanks!


Solution

  • So from what I can see is, that you are trying to pass IEnumerable<Embed> to SendFileAsync. The thing is, that you can not cast EmbedBuilder to IEnumerable<Embed>. You need to pass it an IEnumerable<Embed> which you can get with something like an array (Embed[]).

    // This creates the Embed builder
    var eb = new EmbedBuilder();
        eb.AddField("RandomField", "Hello, my name is random Field"); 
    
    // Here you make an array with 1 entry, which is the embed ( from EmbedBuilder.Build() )
    Embed[] embedArray = new Embed[] { eb.Build() };
    
    // Now you pass it into the method like this: 'embeds: embedArray'
    await DCW.SendFileAsync(filePath: "C:\RandomFile.txt", text: "Embed", embeds: embedArray);