首页 > 解决方案 > 如何使用嵌入discord.net webhook c#发送文件附件

问题描述

我已经尝试了在网络钩子上添加嵌入的所有解决方案,但对我的情况没有任何作用,或者我错过了什么?

我正在使用 Discord.Net v2.2.0

这是我的代码的一部分

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);
}

此代码显示错误

无法从“Discord.Embed”转换为 System.Collections.Generic.IEnumerable<Discord.Embed>

我尝试了这段代码并修复了错误

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

我构建并运行了 .exe 文件,控制台出现错误

未处理的异常:System.InvalidCastException:无法将“Discord.EmbedBuilder”类型的对象转换为 System.Collections.Generic.IEnumerable 1[Discord.Embed]。

参考: 通过 Webhook C# 发送 Discord 嵌入

Discord.net 机器人嵌入消息

修改异步不起作用

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

我知道上面的大多数解决方案都有效,但在我的情况下不是。我非常感谢有关如何解决此问题的示例。谢谢!

标签: c#.netembedwebhooksdiscord.net

解决方案


因此,据我所知,您正试图传递IEnumerable<Embed>SendFileAsync. 问题是,你不能EmbedBuilder投到IEnumerable<Embed>. 您需要将其传递给IEnumerable<Embed>您可以通过数组 ( 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);

推荐阅读