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

使用discord.js v14获取用户Spotify当前播放状态失败求助

问题分析与修复

你的代码存在几个关键问题,导致无法正确识别Spotify播放活动:

  1. 直接取第一个活动不可靠:用户Discord活动列表里,Spotify不一定是第一个(比如同时存在游戏、自定义状态等活动),直接访问activities[0]会错过目标活动。
  2. 大小写匹配错误:Discord中Spotify活动的name是首字母大写的"Spotify",你代码里判断的是小写"spotify",导致匹配失败。
  3. 未处理空值情况:若用户处于隐身状态,member.presence可能为null,直接访问member.presence.activities会触发运行时错误。

修复后的代码

const { SlashCommandBuilder, EmbedBuilder, ActivityType } = require("discord.js");
const { CustomRGB } = require("discordjs-colors-bundle");

module.exports = {
  data: new SlashCommandBuilder()
    .setName('spotify')
    .setDescription('Spotify信息查询!')
    .addSubcommand((sub) => 
      sub.setName('current').setDescription('获取当前播放状态')
    ),

  async execute(interaction, client) {
    if (interaction.options.getSubcommand() === "current") {
      const member = interaction.member;
      const Embed = new EmbedBuilder()
        .setTitle(`${interaction.user.username}的当前播放状态`);

      // 处理无在线状态或无活动的情况
      if (!member.presence || member.presence.activities.length === 0) {
        Embed.setColor(CustomRGB(255, 0, 0));
        Embed.setDescription("当前没有播放任何内容。");
        return interaction.reply({ embeds: [Embed], ephemeral: true });
      }

      // 从活动列表中筛选Spotify听歌活动
      const spotifyActivity = member.presence.activities.find(activity => 
        activity.type === ActivityType.Listening && activity.name === "Spotify"
      );

      if (!spotifyActivity) {
        Embed.setColor(CustomRGB(255, 0, 0));
        Embed.setDescription("当前没有播放任何内容。");
      } else {
        Embed.addFields(
          { name: "曲目名称", value: spotifyActivity.details || "未知", inline: true },
          { name: "艺术家", value: spotifyActivity.state || "未知", inline: true }
        );
        Embed.setColor(CustomRGB(0, 255, 170));
        // 可选:添加Spotify曲目封面图
        if (spotifyActivity.assets?.largeImage) {
          Embed.setThumbnail(`https://cdn.discordapp.com/${spotifyActivity.assets.largeImage}`);
        }
      }

      return interaction.reply({ embeds: [Embed], ephemeral: true });
    }
  },
};

关键修改说明

  • 使用官方枚举判断活动类型:引入ActivityType.Listening,避免手动拼写错误,判断更准确。
  • 遍历筛选Spotify活动:用Array.find()从活动列表中精准定位Spotify听歌活动,不受活动顺序影响。
  • 完善空值处理:提前检查member.presence和活动数组是否为空,避免报错。
  • 兼容未知字段:用|| "未知"处理details或state为空的情况,防止嵌入消息显示空白。
  • 可选添加封面图:利用Spotify活动自带的封面资源链接,让消息展示更直观。

另外,需确保你的机器人在Discord开发者后台的Bot设置中,已开启Presence Intent和Server Members Intent权限,否则无法正常获取用户活动信息。

内容的提问来源于stack exchange,提问作者Mohtasim Alam Sohom

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 18:30:20