Discord.js v12如何将JSON玩家警告数据发送至频道?
First, let's fix a small typo in your existing code: you wrote warn[user] instead of warns[user] in the line const warny = warn[user].warns;—that would throw an error, so correcting that first is crucial.
Next, to turn your sorted warning data into a readable leaderboard message and send it to a Discord channel, here's a step-by-step solution:
Step 1: Format Sorted Entries into a Human-Readable String
After sorting the data, we'll convert each entry into a line that matches your desired format. Since your JSON uses user IDs instead of usernames, we'll also fetch the user's display name from Discord (with a fallback to the ID if fetching fails).
Step 2: Send the Formatted Leaderboard
Once we have the leaderboard string, we'll send it to the channel where the command was triggered. We'll also handle empty cases to avoid sending blank messages.
Updated Code with Message Sending
client.on('message', async message => { if (message.content.startsWith('>topw')) { const sorted = []; const keys = Object.keys(warns); for (let user in warns) { // Fix the typo here: warn → warns const warny = warns[user].warns; // Correct entry creation to use the current user ID const entry = { [user]: warns[user] }; if (sorted.length === 0) { sorted.push(entry); continue; } let i = 0; while (sorted[i] !== undefined && sorted[i][Object.keys(sorted[i])].warns > warny) { i++; } sorted.splice(i, 0, entry); } // Build the leaderboard string let leaderboard = '**Warning Leaderboard**\n'; for (let index = 0; index < sorted.length; index++) { const userId = Object.keys(sorted[index])[0]; const userData = sorted[index][userId]; // Fetch username (fallback to ID if fetch fails) let username = userId; try { const user = await client.users.fetch(userId); username = user.username; } catch (error) { console.log(`Could not fetch user ${userId}: ${error}`); } // Add line to leaderboard (handle empty reason) leaderboard += `${index + 1}. Name: ${username} | Warns: ${userData.warns} | Reason: ${userData.reason || 'No reason provided'}\n`; } // Send the message if (leaderboard === '**Warning Leaderboard**\n') { message.channel.send('No warnings found in the database!'); } else { message.channel.send(leaderboard); } } });
Key Improvements:
- Fixed the typo and incorrect entry creation in your original sorting logic
- Added async/await to fetch user usernames from IDs (critical for readability)
- Formatted each entry with a position number, username, warn count, and reason
- Handled empty leaderboards to send a meaningful response
- Included a fallback for cases where user fetching fails
Quick Notes:
- Ensure your bot has permission to send messages in the target channel
- If you don't need usernames, you can skip the fetch step and use the user ID directly
- For large datasets, consider limiting the leaderboard to the top 10-20 users to avoid overly long messages
内容的提问来源于stack exchange,提问作者Qqxxe

