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

如何让Discord机器人支持群聊使用?当前仅单人私聊可用

问题分析与解决方案

你的机器人在多人私聊(Group DM)中无响应,核心原因是代码里的@commands.dm_only()装饰器——它仅允许命令在**单人私聊(Private DM)**中运行,而多人私聊的频道类型属于discord.ChannelType.group,不在该装饰器的允许范围内,因此命令被拦截。

修改步骤

1. 替换限制装饰器

移除@commands.dm_only(),替换为支持单人+多人私聊的自定义检查:

如果你想严格限制命令仅在私聊场景(无论单人还是多人)运行,可使用以下两种方式:

方式一:自定义装饰器

from discord import ChannelType
from discord.ext import commands

# 自定义检查:允许单人私聊和多人私聊
def allow_all_dms():
    def predicate(ctx):
        return ctx.channel.type in (ChannelType.private, ChannelType.group)
    return commands.check(predicate)

@bot.command()
@allow_all_dms()
async def meow(ctx: discord.ApplicationContext):
    log.info(f"{ctx.author} meows")
    maximum_meows = len(meows)
    # 修复索引越界问题:列表索引从0开始,randint范围改为0到maximum_meows-1
    meowindex = random.randint(0, maximum_meows - 1)
    meow = meows[meowindex][0]
    log.info(meow)
    await ctx.send(meow)

方式二:简洁匿名函数检查

@bot.command()
@commands.check(lambda ctx: ctx.channel.type in (discord.ChannelType.private, discord.ChannelType.group))
async def meow(ctx: discord.ApplicationContext):
    log.info(f"{ctx.author} meows")
    maximum_meows = len(meows)
    meowindex = random.randint(0, maximum_meows - 1)
    meow = meows[meowindex][0]
    log.info(meow)
    await ctx.send(meow)

2. 修复索引越界问题

原代码中random.randint(1, maximum_meows)会触发索引越界错误:Python列表索引从0开始,当maximum_meows等于len(meows)时,最大合法索引是len(meows)-1。除了修改randint范围,更推荐用random.choice直接随机选取元素,代码更简洁安全:

@bot.command()
@commands.check(lambda ctx: ctx.channel.type in (discord.ChannelType.private, discord.ChannelType.group))
async def meow(ctx: discord.ApplicationContext):
    log.info(f"{ctx.author} meows")
    meow = random.choice(meows)[0]
    log.info(meow)
    await ctx.send(meow)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 08:28:10