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

如何用discord.js通过API发送图片?宝可梦机器人无法同发名称与图片

问题原因

你直接将宝可梦名称和图片链接拼接为单一字符串发送时,Discord 不会识别内嵌在普通文本中的图片链接做自动渲染,只有当图片链接单独作为消息内容、或单独占一行时,才会被自动解析为图片展示。
同时你当前的随机数定义在函数外部,后续每次调用$poke命令都会复用同一个随机数,只会返回同一只宝可梦,也需要调整。

修改方案

你可以将名称和图片链接拆分返回,再按Discord可识别的格式发送即可,有两种常用实现方式:

  • 方案1:简单换行分隔
  • 方案2:使用Embed卡片封装,展示效果更美观

完整修改代码

第一步:调整接口请求函数,返回结构化数据

function getPoke() {
  // 随机数移到函数内部,每次调用生成新值,+1避免命中不存在的id=0的宝可梦
  const random = Math.floor(Math.random() * 800) + 1;
  return fetch("https://pokeapi.co/api/v2/pokemon/" + random)  
  .then(res => res.json())
  .then(data => {
    // 返回包含名称和图片的对象,不做字符串拼接
    return {
      name: data.name,
      img: data.sprites.front_default
    }
  })
}

第二步:修改命令触发逻辑

方案1:简单换行实现

if (msg.content === "$poke") {
  getPoke().then(pokemon => {
    // 名称在前,换行后放单独一行的图片链接
    msg.channel.send(`${pokemon.name}\n${pokemon.img}`)
  })
}

方案2:Embed卡片实现(更美观)

if (msg.content === "$poke") {
  getPoke().then(pokemon => {
    const pokeEmbed = {
      title: pokemon.name,
      image: {
        url: pokemon.img
      }
    };
    msg.channel.send({ embeds: [pokeEmbed] });
  })
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 03:54:02