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

Discord.py命令私信触发报'User'无'roles'属性错误如何修复

问题原因

私信场景下,ctx.author返回的是User类对象,而角色roles是仅服务器成员Member类才有的属性——角色属于服务器维度的配置,私信环境没有关联的服务器,自然无法读取用户的角色信息。

解决方案

方案1:限制命令仅可在服务器内调用

直接给命令加上guild_only装饰器,私信触发时会自动拦截,你可以搭配全局错误处理给用户返回友好提示:

from discord.ext import commands

@client.command()
@commands.guild_only() # 新增该行即可限制仅服务器可用
async def test(ctx):
    await ctx.send(len(ctx.author.roles))

如果需要自定义私信触发时的提示,可以补充错误处理逻辑:

@test.error
async def test_error(ctx, error):
    if isinstance(error, commands.GuildOnly):
        await ctx.send("该命令仅可在服务器频道内使用")

方案2:主动判断场景兼容调用

如果不需要强制限制调用场景,可以在代码内先判断当前环境类型,再执行对应逻辑:

@client.command()
async def test(ctx):
    # 判断当前是否为服务器环境
    if ctx.guild is None:
        await ctx.send("当前为私信场景,无法读取角色信息")
        # 也可根据业务需求返回默认值,示例:return await ctx.send(0)
    else:
        await ctx.send(len(ctx.author.roles))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 17:27:04