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

如何通过Discord.js机器人访问Guild安全操作并永久暂停私信?

Discord.js机器人操作服务器安全设置及永久禁用私信方案

关于服务器安全操作的API访问

Discord官方API(包括Discord.js封装的接口)目前没有提供专门的"服务器安全操作"统一模块,大部分安全相关功能需要通过权限管理、事件监听等方式实现。

永久暂停服务器内私信的实现方案

Discord的私信(DM)属于用户个人层面的功能,并非服务器管辖范围,官方没有提供服务器级别的强制禁用选项(无论手动还是API都无法直接修改用户的私信权限)。但可以通过以下两种方式实现类似需求:

1. 机器人拦截私信事件

通过监听私信消息事件,对来自服务器成员的私信进行处理(如删除、警告甚至踢出服务器)。注意:这种方式只能监控到发送给机器人的私信,成员之间直接发送的私信无法被机器人捕获。

示例代码:

const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({ 
  intents: [
    GatewayIntentBits.DirectMessages, 
    GatewayIntentBits.Guilds,
    GatewayIntentBits.MessageContent
  ] 
});

client.on('messageCreate', async message => {
  // 仅处理来自服务器成员的私信
  if (message.channel.type === 'DM' && !message.author.bot) {
    // 检查用户是否属于目标服务器
    const targetGuild = client.guilds.cache.get('你的服务器ID');
    if (!targetGuild || !targetGuild.members.cache.has(message.author.id)) return;

    // 删除私信并发送提示
    await message.delete().catch(err => console.error(err));
    await message.author.send('本服务器禁止成员通过私信沟通,请在服务器频道内交流。').catch(err => console.error(err));
    
    // 可选:违规踢出服务器
    const member = targetGuild.members.cache.get(message.author.id);
    await member?.kick('发送违反规则的私信').catch(err => console.error(err));
  }
});

client.login('你的机器人Token');

2. 监控服务器频道内的违规引导

通过机器人监控服务器频道中的消息,拦截引导他人发送私信的内容(如"私我""DM我"等关键词),从源头减少私信行为。

示例代码:

const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({ 
  intents: [
    GatewayIntentBits.GuildMessages, 
    GatewayIntentBits.MessageContent,
    GatewayIntentBits.Guilds
  ] 
});

// 自定义禁止的关键词
const forbiddenKeywords = ['私我', '私信我', 'DM我', '加我私信'];

client.on('messageCreate', async message => {
  if (message.guild && !message.author.bot) {
    const hasForbiddenWord = forbiddenKeywords.some(keyword => message.content.includes(keyword));
    if (hasForbiddenWord) {
      await message.delete().catch(err => console.error(err));
      const warningMsg = await message.reply('本服务器禁止引导他人发送私信,请在频道内公开沟通。');
      setTimeout(() => warningMsg.delete(), 5000);
    }
  }
});

client.login('你的机器人Token');

注意事项

  • 由于Discord的DM系统设计,没有任何方法可以完全强制禁止服务器成员之间的直接私信,上述方案仅能起到引导和部分约束的作用。
  • 如果需求是禁止成员与机器人发私信,可直接在机器人的开发者面板中关闭"接收私信"选项,或在代码中忽略所有DM消息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 17:26:00