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

如何在discord.py中禁用机器人的私信功能?

禁止斜杠命令在机器人私信中执行的解决方案

你不需要完全禁用机器人的私信功能,只需在命令执行前判断交互场景是否为私信频道,若是则拒绝执行即可。以下是主流Discord机器人开发库的实现方案:

针对discord.py(v2.x版本)

单个命令处理

在每个斜杠命令的回调开头添加频道类型检查:

@tree.command(name="your_command", description="命令描述")
async def your_command(interaction: discord.Interaction):
    # 判定是否为私信频道
    if isinstance(interaction.channel, discord.DMChannel):
        await interaction.response.send_message("此命令无法在私信中使用,请在服务器频道内执行。", ephemeral=True)
        return
    # 原命令执行逻辑
    await interaction.response.send_message("命令执行成功!")

批量命令统一处理

如果命令数量多,可自定义装饰器实现批量禁用:

def disable_in_dm():
    def decorator(func):
        async def wrapper(interaction: discord.Interaction, *args, **kwargs):
            if isinstance(interaction.channel, discord.DMChannel):
                await interaction.response.send_message("此命令无法在私信中使用,请在服务器频道内执行。", ephemeral=True)
                return
            return await func(interaction, *args, **kwargs)
        return wrapper
    return decorator

# 给需要禁用的命令添加装饰器
@tree.command(name="your_command", description="命令描述")
@disable_in_dm()
async def your_command(interaction: discord.Interaction):
    await interaction.response.send_message("命令执行成功!")

针对discord.js(v14版本)

单个命令处理

在命令的execute方法中加入频道类型判断:

const { SlashCommandBuilder, ChannelType } = require('discord.js');

client.slashCommands.set('your_command', {
    data: new SlashCommandBuilder()
        .setName('your_command')
        .setDescription('命令描述'),
    async execute(interaction) {
        if (interaction.channel.type === ChannelType.DM) {
            return interaction.reply({ content: '此命令无法在私信中使用,请在服务器频道内执行。', ephemeral: true });
        }
        // 原命令执行逻辑
        await interaction.reply('命令执行成功!');
    }
});

全局批量拦截

通过监听interactionCreate事件,统一拦截所有私信中的斜杠命令:

const { ChannelType } = require('discord.js');

client.on('interactionCreate', async interaction => {
    if (!interaction.isChatInputCommand()) return;

    // 拦截私信中的斜杠命令
    if (interaction.channel.type === ChannelType.DM) {
        return interaction.reply({ content: '此命令无法在私信中使用,请在服务器频道内执行。', ephemeral: true });
    }

    // 执行正常命令逻辑
    const command = client.slashCommands.get(interaction.commandName);
    if (!command) return;

    try {
        await command.execute(interaction);
    } catch (error) {
        console.error(error);
        await interaction.reply({ content: '执行命令时发生错误!', ephemeral: true });
    }
});

说明:以上方案仅阻止斜杠命令在私信中执行,机器人仍可接收私信消息。若需完全禁止机器人处理私信,可额外监听messageCreate事件,忽略DM频道的消息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 22:52:23