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

Discord.js v14模态框提交信息获取问题求助

问题分析与修复方案

你的代码存在三个核心问题,导致模态框提交信息无法正常获取:


1. 变量名拼写错误

在模态提交的监听代码中,你定义了emailUser变量,但console.log输出的是未定义的email:

// 错误写法
const emailUser = interaction.fields.getTextInputValue('emailTest');
console.log({ email }); 

// 正确写法
const email = interaction.fields.getTextInputValue('emailTest');
console.log({ email });

2. 事件监听器位置错误

你把InteractionCreate事件监听放在了命令模块内,而命令模块是被导出供主文件调用的,这里的client实例和主文件的客户端实例不是同一个,导致事件无法被正确触发。

正确做法:将模态提交的监听逻辑移到项目的主入口文件(比如index.js)中,和客户端初始化、命令注册逻辑放在一起。

3. 命令模块内重复创建Client实例

命令模块不需要单独创建Client对象,这个实例只需要在主入口文件中初始化一次即可。


修正后的代码示例

命令模块(比如ping.js)

const { ActionRowBuilder, ModalBuilder, TextInputBuilder, TextInputStyle, SlashCommandBuilder } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('ping')
        .setDescription('va permettre de confirmer ton email;)'),

    async execute(interaction) {
        const modal = new ModalBuilder()
            .setCustomId('myModal')
            .setTitle('Vérification Email Ynov')

        const emailInput = new TextInputBuilder()
            .setCustomId('emailTest')
            .setLabel("Quel est ton email Ynov?")
            .setPlaceholder('prenom.nom@ynov.com') // 修正原拼写错误:ynoc → ynov
            .setStyle(TextInputStyle.Short);

        const firstActionRow = new ActionRowBuilder().addComponents(emailInput);
        modal.addComponents(firstActionRow);

        await interaction.showModal(modal);
    }
}

主入口文件(比如index.js)

const { Client, GatewayIntentBits, Events } = require('discord.js');
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.MessageContent] });

// 假设你已经通过REST注册了命令,这里处理交互事件
client.on(Events.InteractionCreate, async interaction => {
    // 处理 slash 命令
    if (interaction.isChatInputCommand()) {
        const command = interaction.client.commands.get(interaction.commandName);
        if (!command) return;
        try {
            await command.execute(interaction);
        } catch (error) {
            console.error(error);
            await interaction.reply({ content: 'Une erreur est survenue!', ephemeral: true });
        }
    }
    // 处理模态框提交
    else if (interaction.isModalSubmit()) {
        if (interaction.customId !== 'myModal') return;
        
        const email = interaction.fields.getTextInputValue('emailTest');
        console.log('Email reçu:', email);
        // 必须回复模态提交,否则Discord会标记交互失败
        await interaction.reply({ content: `Ton email ${email} a été enregistré!`, ephemeral: true });
    }
});

client.login('TON_TOKEN_DISCORD');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 05:13:22