discord.py向用户发送DM时报错discord.client无get_user属性如何解决
你遇到的AttributeError: module 'discord.client' has no attribute 'get_user'报错,核心原因是你错误将discord.client模块当作已初始化的客户端实例调用,同时可能存在实例混用、权限意图未配置的问题,可按照以下步骤解决:
解决步骤
- 第一步:修正实例调用逻辑
你代码中使用commands.Bot类注册指令,Bot本身是discord.Client的子类,直接用已初始化的bot实例调用get_user即可,无需额外调用client。修改后的代码如下:
@bot.command() async def test(ctx): # 优先从本地缓存获取用户,速度快无速率限制 user = bot.get_user(499642019191324692) if not user: # 缓存不存在时调用API拉取用户,可保证拿到正确数据 user = await bot.fetch_user(499642019191324692) await user.send('Hello')
- 第二步:确认实例初始化逻辑(如果你需要单独使用
client变量)
如果你确实需要单独声明client实例,需要确保你是实例化discord.Client类,而非直接导入模块当作实例使用:
错误写法示例:
# 错误:直接导入模块当作实例使用 import discord.client as client
正确写法示例:
# 正确:实例化Client类生成可用实例 import discord client = discord.Client(intents=discord.Intents.default())
- 第三步:配置必要的访问意图
discord.py v2.x及以上版本需要开启对应权限意图才能正常获取用户数据:
- 初始化
bot/client实例时开启成员意图:
import discord from discord.ext import commands intents = discord.Intents.default() # 开启成员访问权限,用于获取用户数据 intents.members = True # 开启消息内容访问权限,用于正常识别指令 intents.message_content = True bot = commands.Bot(command_prefix='你设定的指令前缀', intents=intents)
- 打开Discord开发者平台,进入对应应用的「Bot」设置页,开启
Privileged Gateway Intents下的Server Members Intent和Message Content Intent开关。
内容的提问来源于stack exchange,提问作者Axel Garcia
相关产品推荐
相关产品推荐

