Discord.js 解禁命令

Posted

技术标签:

【中文标题】Discord.js 解禁命令【英文标题】:Discord.js Unban command 【发布时间】:2021-04-18 14:22:26 【问题描述】:

我得到一个解禁命令代码,我在控制台中得到以下错误:

(node:9348) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'member' of undefined 在 Object.execute (C:\Users\19nik\Documents\GitHub\bot-project\commands\unban.js:9:22) 在客户端。 (C:\Users\19nik\Documents\GitHub\bot-project\gb.js:81:17) 在 Client.emit (events.js:315:20) 在 MessageCreateAction.handle (C:\Users\19nik\Documents\GitHub\bot-project\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14) 在 Object.module.exports [as MESSAGE_CREATE] (C:\Users\19nik\Documents\GitHub\bot-project\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32) 在 WebSocketManager.handlePacket (C:\Users\19nik\Documents\GitHub\bot-project\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31) 在 WebSocketShard.onPacket (C:\Users\19nik\Documents\GitHub\bot-project\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22) 在 WebSocketShard.onMessage (C:\Users\19nik\Documents\GitHub\bot-project\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10) 在 WebSocket.onMessage (C:\Users\19nik\Documents\GitHub\bot-project\node_modules\ws\lib\event-target.js:132:16) 在 WebSocket.emit (events.js:315:20)

这是我的代码:

const  MessageEmbed  = require('discord.js');
const fs = require("fs");

module.exports = 
    name: `unban`,
    description: `Unbans given user ID or mentioned user.`,
    async execute(bot, args, message) 

        if (!message.member.hasPermission(["BAN_MEMBERS"])) return message.channel.send("You do not have the required permissions to use the unban command.")

        if (!args[0]) return message.channel.send("Provide me a valid USER ID.");
        //This if() checks if we typed anything after "!unban"

        let bannedMember;
        //This try...catch solves the problem with the await
        try 
            bannedMember = await bot.users.cache.fetch(args[0])
         catch (e) 
            if (!bannedMember) return message.channel.send("That's not a valid USER ID.")
        

        //Check if the user is not banned
        try 
            await message.guild.fetchBan(args[0])
         catch (e) 
            message.channel.send('This user is not banned.');
            return;
        

        let reason = args.slice(1).join(" ")
        if (!reason) reason = "No reason provided."

        if (!message.guild.me.hasPermission(["BAN_MEMBERS"])) return message.channel.send("I am missing permissions to unban.")
        message.delete()
        try 
            message.guild.members.unban(bannedMember,  reason: reason )
            message.channel.send(`$bannedMember.tag has been unbanned.`)
            console.log(`AUDIT LOG: [UNBAN] $message.author.tag unbanned $member.user.tag from $message.guild.name.`);
            var readmessagefile = fs.readFileSync('./logging/UnbanLog.txt', 'utf-8');
            var writemessagefile = fs.writeFileSync('./logging/UnbanLog.txt', 'Type: [UNBAN] ' + 'Time ' + '(' + message.createdAt + ')' + ' | ' + member.user.tag + ' from ' + message.guild.name + ' | Moderator ' + message.author.tag + '\n' + readmessagefile)
            console.log('BOT LOG: [INTERNAL] Writing to unban log file.');
         catch (e) 
            console.log(e.message)
        
    

我不知道该怎么办。它还弹出无法读取未定义的属性'hasPermissions'的错误。

【问题讨论】:

看来message 是未定义的。你检查过它的价值吗? 我已将消息放在异步执行()上。我必须把它放在别的地方吗 你应该edit your post 并添加你如何调用.execute() 函数。 我确实包含了 async execute() 。但是,不用担心。有人给了我一个解决方案,但遇到了一个不同的问题...... 【参考方案1】:

我相信您的问题的主要来源是您的回调,在 messageargs 之前先调用了您的 client。 由于 JS 对回调参数的放置很敏感,因此您应该将回调编写如下:

async execute(message, args, bot)

【讨论】:

现在试试这个。 修复了无法读取的错误,但我现在遇到了一个新问题。我使用的用户 ID 已在服务器中被禁止,但机器人在聊天中返回以下消息,请提供有效的用户 ID。【参考方案2】:

第 9 行似乎有错误

if (!message.member.hasPermission(["BAN_MEMBERS"])) return message.channel.send("You do not have the required permissions to use the unban command.")

哪个没有错误,也许该命令是在 DMS 中运行的?也许使用:

if(!message.guild) return;

这应该可以解决问题。

【讨论】:

【参考方案3】:

两个可能的原因:

回调

确保 execute() 的参数与主文件中的顺序完全相同

命令在公会外使用

错误可能是因为该命令在公会外部使用来修复此问题,请将其添加到执行()下方的代码中

if (!message.guild) return;

【讨论】:

【参考方案4】:

const findUser = message.guild.members.cache.get(message.author.id)
if(!findUSer) return;
const isMemberHavePermission = findUser.hasPermission("BAN_MEMBERS")
iF(isMemberHavePermission)
  // Member Have Permission
 else
  // Member Have not Permission
 

【讨论】:

请在您的回答中提供更多详细信息。正如目前所写的那样,很难理解您的解决方案。【参考方案5】:

非常确定您使用的是 discord.js v12,还请确保您使用的是 node.js 的最新(或 v14)版本,如果不是至少在 v14 中,请在https://node.js.org下载

这是来自我的机器人,试试这个,它有效,我已将其更改为您的处理程序:


const  MessageEmbed  = require("discord.js")
const fs = require("fs")

module.exports = 
  name: "unban",
  description: "Unbans given user ID or mentioned user.",
  async execute(bot, message, args) 
    
    if (!message.member.hasPermission('BAN_MEMBERS')) return message.channel.send(`You need the permission **Ban Members** to execute this command.`)
    if (!message.guild.me.hasPermission('BAN_MEMBERS')) return message.channel.send(`**$client.user.tag** needs the permission **Ban Members** to execute this command.`)
    
    const id = args[0];
    
    if (!id) return message.channel.send(`Please mention the user's ID to unban.`)

const bannedMember = client.users.fetch(args[0]);    

    const bans = await message.guild.fetchBans();
    if (bans.size == 0) return message.channel.send(`There are no users banned on this server.`);
    let bUser = bans.find(b => b.user.id == id);
    if(!bUser) return message.channel.send(`This user is not banned or was not found.`)

      const reason = args.slice(1).join(" ")
      if (!reason) return message.channel.send('Please include a reason!');

    try 
                    message.guild.members.unban(bannedMember,  reason: reason )
            message.channel.send(`$bannedMember.tag has been unbanned.`)
            console.log(`AUDIT LOG: [UNBAN] $message.author.tag unbanned $member.user.tag from $message.guild.name.`);
            var readmessagefile = fs.readFileSync('./logging/UnbanLog.txt', 'utf-8');
            var writemessagefile = fs.writeFileSync('./logging/UnbanLog.txt', 'Type: [UNBAN] ' + 'Time ' + '(' + message.createdAt + ')' + ' | ' + member.user.tag + ' from ' + message.guild.name + ' | Moderator ' + message.author.tag + '\n' + readmessagefile)
            console.log('BOT LOG: [INTERNAL] Writing to unban log file.');

      catch (e) 
      console.error(e);

 


【讨论】:

【参考方案6】:

我认为这会奏效。

const  MessageEmbed  = require('discord.js');
const fs = require("fs");

module.exports = 
    name: `unban`,
    description: `Unbans given user ID or mentioned user.`,
    async execute(bot, args, message) 
        if(!message.guild) return message.channel.send("This Command Can't Be Executed In DMs.");
        if (!message.author.hasPermission(["BAN_MEMBERS"])) return message.channel.send("You do not have the required permissions to use the unban command.")

        if (!args[0]) return message.channel.send("Provide me a valid USER ID.");
        //This if() checks if we typed anything after "!unban"

        let bannedMember;
        //This try...catch solves the problem with the await
        try 
            bannedMember = await bot.users.cache.fetch(args[0])
         catch (e) 
            if (!bannedMember) return message.channel.send("That's not a valid USER ID.")
        

        //Check if the user is not banned
        try 
            await message.guild.fetchBan(args[0])
         catch (e) 
            message.channel.send('This user is not banned.');
            return;
        

        let reason = args.slice(1).join(" ")
        if (!reason) reason = "No reason provided."

        if (!message.guild.me.hasPermission(["BAN_MEMBERS"])) return message.channel.send("I am missing permissions to unban.")
        message.delete()
        try 
            message.guild.members.unban(bannedMember,  reason: reason )
            message.channel.send(`$bannedMember.tag has been unbanned.`)
         catch (e) 
            console.log(e.message)
        
    

我删除了控制台日志记录部分,因为它可能会开始出现一些错误。

我是新手,可能是错误的

【讨论】:

以上是关于Discord.js 解禁命令的主要内容,如果未能解决你的问题,请参考以下文章

使用 discord.js v12 解禁命令

Discord.js 解禁所有用户

解禁命令 |不和谐.js

discord.js 如何使用代码撤销对被禁止用户的禁令?

如何使用命令解禁用户?

Discord 仅识别 discord.js 中的“ping”命令