You need to enable JavaScript to run this app. Discord.js机器人全局拉黑非当前服务器缓存用户的实现方法
优惠活动
大模型
产品
解决方案
定价
更多

Discord.js机器人全局拉黑非当前服务器缓存用户的实现方法

Discord.js 全局黑名单命令适配说明

基础背景

使用Discord.js(DJS)与Mongoose开发Discord机器人时,黑名单命令的整体运行逻辑正常,但存在功能限制:当前仅支持拉黑执行命令所在服务器的在册成员。
预期实现效果:支持 blacklist <userID> [reason] 命令格式,即使用户ID对应用户并非当前服务器成员、仅存在于机器人缓存中,也能完成全局拉黑操作。

原实现代码

const mongoose = require("mongoose")

module.exports = {
    name: "blacklist",
    aliases: ["b", "block"],
    cooldown: 5000,
    description: "Blocks a user from using Hexagon!",
    devOnly: true,
    category: "Developer",
    usage: "blacklist <user> [reason]",

    async run(client, message, args) {
        if(!args[0]) return message.reply('`[❌]` Incorrect Syntax: Missing Argument')

        const mentionedUser = message.mentions.members.first() || message.guild.members.cache.get(args[0]) || client.users.cache.fetch(args[0]);
        if(!mentionedUser) return message.reply('`[❌]` Incorrect Syntax: Provided User does not exist!')

        let reason = args.slice(1).join(" ")
        if(!reason) reason = "Reason not specified."

        let profile = blacklistedUsers.findOne({userID: mentionedUser.user.id})
        
        if(profile) return message.reply('`[❌]` Error: Mentioned User is already blacklisted!')

        profile = await new blacklistedUsers({
            userID: mentionedUser.user.id,
            reason
        }).save();
        message.channel.send(`\`❌👤\` ${mentionedUser.user.tag} was blacklisted!`)
    }
}

问题修正

编辑:该问题已解决!仅需使用client.users.cache.get(args[0])即可实现。

原代码在实现全局用户获取时存在两处可优化的细节,配合上述调整即可完整跑通功能:

  • 从client.users.cache获取到的是全局User对象,与服务器内获取的GuildMember对象结构不同:User对象本身就包含id、tag属性,不需要再读取.user子属性,否则会触发属性读取报错
  • 原代码的Mongoose查询语句未添加await,判断用户是否已拉黑的逻辑会因为拿到Promise对象而永远生效,无法正常完成后续拉黑写入操作

修正后核心逻辑片段

// 兼容不同来源的用户获取
const mentionedUser = message.mentions.members.first() 
  || message.guild.members.cache.get(args[0]) 
  || client.users.cache.get(args[0]);
if (!mentionedUser) return message.reply('`[❌]` Incorrect Syntax: Provided User does not exist!')

// 兼容两种用户对象的属性读取
const targetUser = mentionedUser.user ?? mentionedUser;
let reason = args.slice(1).join(" ") || "Reason not specified."

// 补全异步查询的await
let profile = await blacklistedUsers.findOne({userID: targetUser.id})
if (profile) return message.reply('`[❌]` Error: Mentioned User is already blacklisted!')

await new blacklistedUsers({
  userID: targetUser.id,
  reason
}).save();
message.channel.send(`\`❌👤\` ${targetUser.tag} was blacklisted!`)

内容的提问来源于stack exchange,提问作者Magma

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.25 06:45:03