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

discord.js如何实现展示被ping用户banner 现有代码仅显示命令发起者banner

问题原因

  • 现有代码的所有执行逻辑都包裹在if (!args[0])判断分支内,仅在没有传入参数时才会执行,完全没有处理传入了被@用户的场景
  • 固定取指令发起者message.author.id查询banner,没有读取被@用户的ID
  • 代码中${users.username}的users变量未定义,实际运行会直接报错
  • getUserBannerUrl函数定义放在了无参数分支内部,只有无参数场景下才会声明该函数,其他场景调用会报错

修复后完整代码

const Discord = require('discord.js');

module.exports = {
    name: 'banner',
    category: "utility",
    description: "Get a user's/your banner",
    run: async(client, message, args) => {
        // 工具函数移到外层,所有分支都可调用,新增size参数支持自定义分辨率
        async function getUserBannerUrl(userId, size = 512) {
            const user = await client.api.users(userId).get();
            return user.banner ? `https://cdn.discordapp.com/banners/${userId}/${user.banner}?size=${size}` : null;
        }

        // 确定目标用户:优先取被@的用户,没有的话取指令发起者
        let targetUser = message.mentions.users.first() || message.author;

        const bannerUrl = await getUserBannerUrl(targetUser.id, 4096);
        if (bannerUrl) {
            const embed = new Discord.MessageEmbed()
                .setTitle(`${targetUser.username}'s banner`)
                .setColor('#2f3136')
                .setImage(bannerUrl);
            message.channel.send(embed);
        } else {
            message.channel.send("buy discord boost you peasant");
        }
    }
}

主要修改点

  • 调整了工具函数getUserBannerUrl的位置与参数,支持自定义查询的banner分辨率,同时全场景可调用
  • 新增了目标用户识别逻辑:如果消息中存在@用户,就将被@用户作为查询对象,否则默认查询指令发起者的banner
  • 修复了原代码中未定义users变量的问题,统一从识别到的目标用户对象读取用户名
  • 移除了冗余的if (!args[0])分支限制,同时兼容有无参数两种使用场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 21:48:02