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

Discord.js如何在文本中间插入图片?

如何实现Discord机器人发送图文穿插的单条欢迎消息

问题背景

我开发了一个Discord机器人,需要发送如下格式的欢迎消息:

Some text1 
<img1>
Some text2
<img2>
Some text3

目前用以下代码实现,但所有图片都会显示在消息末尾:

const user = await client.users.fetch('<user ID>');

await user.send({ content:"Some text1\n",
                  files: [{ attachment: "img1" }] });

请问能否修改代码或采用其他方式实现该格式的消息?最好能在单条消息内完成。


解决方案

要实现图文穿插的单条消息,你需要利用Discord消息的附件占位符功能,直接在文本内容中指定图片的插入位置,而不是单纯把图片作为附件添加。

方法一:文本内容结合附件占位符

通过在content中使用![alt文本](attachment://文件名)的格式,将图片插入到指定文本位置,同时在files数组中指定对应的附件并命名,确保占位符与附件名称一致。代码示例:

const user = await client.users.fetch('<user ID>');

await user.send({
  content: `Some text1
![图片1描述](attachment://img1.png)
Some text2
![图片2描述](attachment://img2.png)
Some text3`,
  files: [
    { attachment: "你的图片路径/img1.png", name: "img1.png" },
    { attachment: "你的图片路径/img2.png", name: "img2.png" }
  ]
});

方法二:使用Embed嵌入消息

如果需要更规整的排版,也可以用Embed消息实现,同样结合附件占位符:

const user = await client.users.fetch('<user ID>');

await user.send({
  embeds: [{
    description: `Some text1
![图片1描述](attachment://img1.png)
Some text2
![图片2描述](attachment://img2.png)
Some text3`
  }],
  files: [
    { attachment: "你的图片路径/img1.png", name: "img1.png" },
    { attachment: "你的图片路径/img2.png", name: "img2.png" }
  ]
});

注意事项

  • 必须为每个附件指定name属性,且content或Embed描述中的attachment://xxx要与该名称完全匹配(包括文件扩展名)
  • 确保图片路径正确,本地文件需使用绝对路径或相对项目根目录的路径
  • 两种方法都能在单条消息内完成图文穿插的效果

内容的提问来源于stack exchange,提问作者Rougher

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 03:21:07