You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从URL获取图片字节转Stream发送Discord时遇超时异常及方法适配咨询

问题解决:Discord发送图片Stream时的超时异常及Stream使用问题

1. 解决Timeouts are not supported on this stream异常

出现该异常的原因是MemoryStream本身不支持ReadTimeout属性,而Discord的AddFile方法内部尝试读取该属性,触发了异常。最简洁的解决方式是跳过字节数组转换步骤,直接通过HttpClient获取图片流:

using (var httpClient = new HttpClient())
{
   using (var imageStream = await httpClient.GetStreamAsync(response.Url))
   {
      // 重置流的读取位置到起始处(GetStreamAsync返回的流默认位置在末尾)
      imageStream.Position = 0;
      await new DiscordMessageBuilder()
          .AddFile("image.png", imageStream, false)
          .SendAsync(commandContext.Channel);
   }
}

如果必须基于已有的字节数组处理,可以自定义包装流重写ReadTimeout属性避免抛出异常,但这种方式不如直接使用GetStreamAsync高效:

public class NoTimeoutMemoryStream : MemoryStream
{
    public override int ReadTimeout => Timeout.Infinite;
    public override int WriteTimeout => Timeout.Infinite;
}

// 使用示例
using (var imageBuffer = new NoTimeoutMemoryStream(imageContent))
{
    await new DiscordMessageBuilder().AddFile("image.png", imageBuffer, false).SendAsync(commandContext.Channel);
}

2. 无需保存本地,直接发送Stream

AddFile方法并非仅接受FileStream,它提供了接受通用Stream类型的重载,完全可以直接使用内存中的流(如MemoryStream或网络流)发送内容,不需要将文件保存到本地存储,上述代码示例已验证这一点。

内容的提问来源于stack exchange,提问作者Marta flores calvo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 04:05:02