如何在discord.js v13中为机器人的代码块实现语法高亮?
Fixing Syntax Highlighting for Discord Bot Terminal Command
Let's sort out why your code block isn't showing syntax highlighting and fix it up quickly.
The Root Problem
In your current code, you're mixing two incompatible ways to send formatted code blocks in Discord.js, which breaks the syntax highlighting:
- You wrapped the output in triple backticks (```), but also added a
code: "js"parameter to the send method. Discord doesn't recognize this combination—when using triple backticks, you specify the language right after the opening backticks instead of using thecodeoption. - Also, terminal output should use
bash(orshell) syntax highlighting instead ofjs, since you're executing shell commands.
Updated Code with Fixes
Here's the corrected run function, with improved error handling and proper syntax highlighting:
run: async (client, message, args) => { // Replace the empty string with your user ID if (message.author.id !== "") return; const command = args.join(" "); const errorCommand = new MessageEmbed() .setColor("RED") .setDescription("Please specify a command to execute"); if (!command) return message.reply({ embeds: [errorCommand] }); child.exec(command, (err, stdout, stderr) => { // Send command errors to the Discord channel instead of just logging to console if (err) { return message.channel.send(`\`\`\`bash\n${err.message.slice(0, 2000)}\`\`\``); } // Handle cases where the command has no output if (!stdout && !stderr) { return message.channel.send("Command executed successfully with no output."); } // Send output with bash syntax highlighting const output = stdout || stderr; message.channel.send(`\`\`\`bash\n${output.slice(0, 2000)}\`\`\``); }); }
Key Changes Explained:
- Removed the redundant
code: "js"parameter frommessage.channel.send - Added
bashright after the opening triple backticks (```bash) to trigger shell-appropriate syntax highlighting - Improved error visibility: now sends command execution errors to the Discord channel so you can see what went wrong directly
- Added handling for empty output (prevents sending blank messages when commands don't return anything)
- Split
stdoutandstderrto capture all possible command output and errors
How It Works
Discord's markdown renderer checks for the language identifier immediately after the opening triple backticks. By specifying bash, it applies syntax highlighting tailored for shell commands and their output. The slice(0, 2000) ensures you don't hit Discord's message length limit.
内容的提问来源于stack exchange,提问作者Anup Bhattarai
相关产品推荐
相关产品推荐

