首页 > 解决方案 > SyntaxError:非法返回语句 [Discord.js]

问题描述

以下行引发错误:

if (!client.commands.has(command)) return;

我正在关注本教程=教程

const fs = require('fs');
const Discord = require('discord.js');
const { prefix, token } = require("./config.json")
const client = new Discord.Client();
client.commands = new Discord.Collection();
    
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
    
for (const file of commandFiles) {
   const command = require(`./commands/${file}`);
   client.commands.set(command.name, command);
}
    
client.on('message', message => {
      if (!message.content.startsWith(prefix) || message.author.bot) return;
    
     const args = message.content.slice(prefix.length).trim().split(/ +/);
      const command = args.shift().toLowerCase();
    
      if (message.content === `${prefix}serverinfo`) {
        message.channel.send(message.guild.name)
        message.channel.send(`Total Members: ${message.guild.memberCount}`)
      } else if (message.content === `${prefix}me`) {
        message.channel.send(`Username: ${message.author.username}`)
        message.channel.send(`ID: ${message.author.id}`)
      } else if (message.content === `${prefix}boi`) {
        message.channel.send('BOI')
      }
});
    
if (!client.commands.has(command)) return;

标签: javascriptnode.jsdiscord.jssyntax-errorbots

解决方案


您不能return在顶级范围内,return必须在函数内。

您可以将逻辑放在if语句中

if (client.commands.has(command)) {
  const command = client.commands.get(command);
  try {
    command.execute(message, args);
  } catch (error) {
    console.error(error);
    message.reply("There was an issue executing that command!")
  }
  client.login(token);
}

或者将逻辑包装在函数中,IIFE可能是一个不错的选择:

(() => {
  if (!client.commands.has(command)) return;

  const command = client.commands.get(command);
  try {
    command.execute(message, args);
  } catch (error) {
    console.error(error);
    message.reply("There was an issue executing that command!")
  }
  client.login(token);
})();

推荐阅读