如何异步运行命令文件夹中的命令文件

时间:2020-10-14 18:14:06

标签: discord discord.js

我想在我的Discord机器人中添加一个kick命令,该机器人使用await函数。我知道异步运行的唯一方法是

client.on("message", async (message) => {

但是,我不能在命令文件夹内的命令文件中执行此操作 我的踢命令

const { MessageEmbed } = require("discord.js");

module.exports = {
  name: "kick",
  description: "kicks a member",
  execute(client, args) {

    if (!message.member.hasPermission("KICK_MEMBERS")) return message.channel.send("Invalid Permissions")
    let member = message.mentions.members.first()
    if(!member)
      return message.reply("Please mention a valid member of this server");
    if(!member.kickable) 
      return message.reply("I cannot kick this user! Do they have a higher role? Do I have kick permissions?");
    
    let reason = args.slice(1).join(' ');
    if(!reason) reason = "No reason provided";
    
    await member.kick(reason)
      .catch(error => message.reply(`Sorry ${message.author} I couldn't kick because of : ${error}`));
    message.reply(`${member.user.tag} has been kicked by ${message.author.tag} because: ${reason}`)
    }}

对不起,如果这看起来像是一个愚蠢的问题,我对编码来说还很陌生

1 个答案:

答案 0 :(得分:1)

尝试将您的代码更改为:

module.exports = {
  name: "kick",
  description: "kicks a member",
  // vvv THIS LINE CHANGED vvv
  // vvv THIS LINE CHANGED vvv
  // vvv THIS LINE CHANGED vvv
  execute: async (client, args) => {

    if (!message.member.hasPermission("KICK_MEMBERS")) return message.channel.send("Invalid Permissions")
    let member = message.mentions.members.first()
    if(!member)
      return message.reply("Please mention a valid member of this server");
    if(!member.kickable) 
      return message.reply("I cannot kick this user! Do they have a higher role? Do I have kick permissions?");
    
    let reason = args.slice(1).join(' ');
    if(!reason) reason = "No reason provided";
    
    await member.kick(reason)
      .catch(error => message.reply(`Sorry ${message.author} I couldn't kick because of : ${error}`));
    message.reply(`${member.user.tag} has been kicked by ${message.author.tag} because: ${reason}`)
    }}

特定更改: execute(client, args) { 变成 execute: async (client, args) => {

从本质上讲,这是说函数是异步的,而您的代码只是声明将执行作为常规(同步)函数。另外,由于我不确定是否可以使用常规函数语法声明异步函数,因此将其更改为ES6箭头函数语法: 例如。 execute() {}execute: () => {} 您可以阅读有关箭头功能here

的更多信息