当我提交模式时,只会出现“出问题了”错误。
这是我的代码部分:
// Handle Submit Score Button
if (customId.startsWith('submit-score')) {
console.log(`Received customId: ${customId}`);
const matchId = customId.split('-')[2]; // Extract matchId from customId
console.log(`Extracted matchId: ${matchId}, Type: ${typeof matchId}`);
if (!matchId) {
return interaction.reply({ content: 'Invalid match ID.', ephemeral: true });
}
const guildId = interaction.guild.id;
try {
const matches = await getMatchesFromMongo(guildId);
if (!matches || matches.length === 0) {
return interaction.reply({ content: 'No matches found for this guild.', ephemeral: true });
}
const match = matches.find(m => m.match.id === parseInt(matchId));
if (!match) {
return interaction.reply({ content: 'Match not found.', ephemeral: true });
}
const participants = await fetchParticipants(guildId);
const participantsList = participants.map(p => p.participant);
const teamAName = getParticipantName(match.match.player1_id, participantsList);
const teamBName = getParticipantName(match.match.player2_id, participantsList);
const modal = new ModalBuilder()
.setCustomId(`submitScoreModal-${matchId}`)
.setTitle('Submit Score');
const teamAScoreInput = new TextInputBuilder()
.setCustomId('teamAScore')
.setLabel(`Enter score for ${teamAName}`)
.setStyle(TextInputStyle.Short)
.setPlaceholder(`${teamAName} Score`)
.setRequired(true);
const teamBScoreInput = new TextInputBuilder()
.setCustomId('teamBScore')
.setLabel(`Enter score for ${teamBName}`)
.setStyle(TextInputStyle.Short)
.setPlaceholder(`${teamBName} Score`)
.setRequired(true);
const teamARow = new ActionRowBuilder().addComponents(teamAScoreInput);
const teamBRow = new ActionRowBuilder().addComponents(teamBScoreInput);
modal.addComponents(teamARow, teamBRow);
await interaction.showModal(modal);
} catch (error) {
console.error('Error fetching matches or participants from MongoDB:', error);
return interaction.reply({ content: 'Error fetching match data.', ephemeral: true });
}
return;
}
// Handle Modal Submission
else if (interaction.isModalSubmit()) {
console.log('Modal submitted with customId:', interaction.customId);
if (interaction.customId.startsWith('submitScoreModal')) {
try {
// Step 1: Extract the match ID
const matchId = interaction.customId.split('-')[1];
console.log(`Extracted matchId: ${matchId}, Type: ${typeof matchId}`);
// Step 2: Safely extract the scores from the modal
let scoreTeamA, scoreTeamB;
try {
scoreTeamA = interaction.fields.getTextInputValue('teamAScore');
scoreTeamB = interaction.fields.getTextInputValue('teamBScore');
console.log(`Extracted scores -> Team A: ${scoreTeamA}, Team B: ${scoreTeamB}`);
} catch (fieldError) {
console.error('Error extracting scores from modal fields:', fieldError);
return interaction.reply({ content: 'Failed to extract scores. Please try again.', ephemeral: true });
}
// Step 3: Check if matchId or scores are missing
if (!matchId || !scoreTeamA || !scoreTeamB) {
console.error('Missing matchId or scores');
return interaction.reply({ content: 'Invalid match details or missing scores.', ephemeral: true });
}
// Ensure the scores are numeric
if (isNaN(scoreTeamA) || isNaN(scoreTeamB)) {
console.error('Invalid score values. Scores must be numbers.');
return interaction.reply({ content: 'Please enter valid numeric scores.', ephemeral: true });
}
// Step 4: Log the guild ID
const guildId = interaction.guild.id;
console.log(`Guild ID: ${guildId}`);
// Step 5: Acknowledge the interaction
try {
await interaction.deferReply({ ephemeral: true });
console.log('Reply successfully deferred');
} catch (deferError) {
console.error('Error deferring reply:', deferError);
return;
}
// Step 6: Fetch matches from MongoDB
console.log(`Fetching matches from MongoDB for guildId: ${guildId}`);
let matches;
try {
matches = await getMatchesFromMongo(guildId);
} catch (fetchError) {
console.error('Error fetching matches from MongoDB:', fetchError);
return interaction.followUp({ content: 'Error fetching match data.', ephemeral: true });
}
// Step 7: Check if matches were fetched
if (!matches || matches.length === 0) {
console.error('No matches found in MongoDB');
return interaction.followUp({ content: 'No matches found for this guild.', ephemeral: true });
}
// Step 8: Search for the match with the extracted matchId
console.log(`Looking for match with matchId: ${matchId}`);
const match = matches.find(m => m.match.id === parseInt(matchId));
if (!match) {
console.error('Match not found in MongoDB');
return interaction.followUp({ content: 'Match data not found.', ephemeral: true });
}
// Step 9: Log the match details for verification
console.log(`Match found: ${JSON.stringify(match)}`);
// Step 10: Determine the winner and loser based on the scores
let winnerId, loserId;
if (parseInt(scoreTeamA) > parseInt(scoreTeamB)) {
winnerId = match.match.player1_id;
loserId = match.match.player2_id;
} else {
winnerId = match.match.player2_id;
loserId = match.match.player1_id;
}
console.log(`Winner ID: ${winnerId}, Loser ID: ${loserId}`);
// Step 11: Submit the match score
console.log(`Submitting score for match ${matchId}`);
try {
await submitMatchScore(
interaction.guild,
matchId,
scoreTeamA,
scoreTeamB,
match.match.player1_id,
match.match.player2_id,
match.match.round,
null,
match.proofrequired,
interaction.user.id
);
} catch (submitError) {
console.error('Error submitting match score:', submitError);
return interaction.followUp({ content: 'Error submitting match score.', ephemeral: true });
}
// Step 12: Update the match result in MongoDB
const scoresCsv = `${scoreTeamA}-${scoreTeamB}`;
try {
await updateMatchResult(guildId, matchId, winnerId, loserId, scoresCsv);
} catch (updateError) {
console.error('Error updating match result in MongoDB:', updateError);
return interaction.followUp({ content: 'Error updating match data.', ephemeral: true });
}
// Step 13: Confirm successful score submission
console.log(`Score submitted and match updated successfully for match ${matchId}`);
await interaction.followUp({ content: `Score submitted successfully for match ${matchId}.`, ephemeral: true });
} catch (error) {
console.error('Error handling modal submission:', error);
await interaction.followUp({ content: 'An error occurred while submitting scores. Please try again later.', ephemeral: true });
}
}
return;
}
我尝试添加控制台日志,但在显示模式并尝试提交后,我在调试控制台中没有得到任何内容。所以我处于停滞状态,因为我没有其他想法来解释为什么这不起作用。我对discord.js 和编码比较陌生,所以也许我有什么问题?非常感谢任何帮助。
最可能的原因是您缺少用于处理模式提交的
interactionCreate
事件侦听器。如果未设置该侦听器,机器人将不知道如何在提交时处理模态数据,这就是为什么您在提交后在控制台中看不到任何内容。
确保你有这样的东西:
client.on('interactionCreate', async interaction => {
if (interaction.isModalSubmit()) {
// Handle your modal submission logic here
}
});
没有这个,你的模式提交就不会触发。