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

如何在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 the code option.
  • Also, terminal output should use bash (or shell) syntax highlighting instead of js, 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 from message.channel.send
  • Added bash right 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 stdout and stderr to 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 13:07:50