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

Discord.js v13.6.0斜杠命令报错:无法读取undefined的length属性

问题修复:Discord斜杠命令/ebay报错TypeError: Cannot read properties of undefined (reading 'length')

错误原因

你把前缀命令的逻辑和斜杠命令的逻辑混在一起了。斜杠命令执行时,execute方法的msg参数是undefined的,导致args变量从未被赋值,直接访问args.length就会抛出这个错误。而且你已经通过options.getString和options.getInteger拿到了listing和viewers,完全不需要再用args解析参数。

另外代码还有两个小问题:

  • 错误处理里的回复引用了未定义的ebayEmbed,实际定义的是errorEmbed
  • 循环里用args[2]和args[1]是前缀命令的参数位置,和斜杠命令的参数逻辑不匹配

修复后的完整代码

const { CommandInteraction, MessageEmbed } = require('discord.js');
const axios = require('axios');

module.exports = {
    name: "ebay",
    description: "Use this command to send viewers to your ebay listing",
    permission: "USE_APPLICATION_COMMANDS",
    options: [
        {
            name: "listing",
            description: "Input the link to your listing",
            type: "STRING",
            required: true
        },
        {
            name: "viewers",
            description: "Input the amount of viewers",
            type: "INTEGER",
            required: true
        }
    ],

    /**
     * @param {CommandInteraction} interaction 
     */
    async execute(interaction) {
        const { options } = interaction;
        const listing = options.getString("listing");
        const viewers = options.getInteger("viewers");

        // 参数合法性校验
        if (!listing || viewers < 1) {
            const errorEmbed = new MessageEmbed()
                .setColor("#E80E0E")
                .setTitle('Error Found! ❌')
                .setDescription(`Viewers cannot be sent at this time, make sure you're inputting the correct link and a valid viewer count (at least 1)`);
            return interaction.reply({ embeds: [errorEmbed], ephemeral: true });
        }

        // 循环发送请求
        for (let i = 0; i < viewers; i++) {
            try {
                await axios.get(listing, {
                    headers: {
                        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.5195.102 Safari/537.36'
                    }
                });
            } catch (err) {
                // 捕获单个请求失败,避免整个命令崩溃
                console.log(`请求失败:${err.message}`);
            }
        }

        const successEmbed = new MessageEmbed()
            .setColor("#5104DB")
            .setTitle("Successfully Sent Viewers! 🎉")
            .setDescription(`**${viewers}** viewers have been successfully sent to **${listing}**!`);

        return interaction.reply({ embeds: [successEmbed] });
    }
};

关键修改点

  • 删掉所有和msg、args相关的冗余代码,斜杠命令不需要这些逻辑
  • 修正错误Embed的变量引用问题
  • 增加参数合法性校验,确保观众数至少为1
  • 给axios请求添加try/catch,避免单个请求失败导致整个命令终止
  • 移除多余的Discord全局导入,只保留需要的解构类

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 06:39:37