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

如何让Discord机器人命令仅在私聊(DM)中生效?

让Discord机器人命令仅在私聊生效的解决方案

没问题!要实现这个需求很简单,只需要在你的消息处理逻辑里添加一个渠道类型检查,判断消息是否来自私聊(Direct Message)就行。

在Discord.py中,私聊渠道的类型是discord.ChannelType.private,我们可以利用这个属性来过滤消息:

方案1:所有命令仅在私聊生效

如果希望你的机器人所有命令都只响应私聊消息,可以在最开头先判断渠道类型,非私聊直接返回:

import discord

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    
    # 检查是否是私聊渠道,不是的话直接跳过
    if message.channel.type != discord.ChannelType.private:
        return
    
    if message.content.startswith('bb!help'):
        await message.channel.send('Huge long commands list')
    
    # 其他命令也会自动只在私聊生效

方案2:特定命令仅在私聊生效

如果只是想让某几个命令(比如bb!help)限制在私聊,其他命令不受影响,可以把渠道检查放到对应命令的判断里:

import discord

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    
    if message.content.startswith('bb!help'):
        # 仅当消息来自私聊时才执行
        if message.channel.type == discord.ChannelType.private:
            await message.channel.send('Huge long commands list')
        else:
            # 可选:在服务器里给用户提示
            await message.reply('请通过私聊使用这个命令哦!')
    
    # 其他命令可以正常在服务器里使用

这样就能精准控制命令的生效范围啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:25:02