如何在discord.py中通过斜杠命令给用户发送私信?
解决Discord机器人斜杠命令发私信报错问题
你遇到的discord.Object object has no attribute 'send'错误,根源是discord.Object只是一个仅包含ID的基础通用对象,它没有send方法,没法用来发送私信。要实现发私信功能,必须获取到真正的discord.User或discord.Member实例。
方法一:直接使用交互对象中的发起用户(最简便)
直接从interaction里拿到发起命令的用户对象,这个对象自带send方法:
@tree.command(name="dm", description="a command to DM", guild=discord.Object(id=ID)) async def dm(interaction: discord.Interaction): # 给发起命令的用户发私信 await interaction.user.send("This is a test message") # 必须给Discord的交互一个回应,否则会显示命令执行失败 await interaction.response.send_message("已给你发送私信!", ephemeral=True)
注:ephemeral=True可以让回应只有发起命令的用户能看到,避免刷屏。
方法二:通过用户ID获取用户对象(适用于给指定用户发私信)
如果需要给特定ID的用户发私信,用机器人的fetch_user方法拉取完整用户对象:
@tree.command(name="dm", description="a command to DM", guild=discord.Object(id=ID)) async def dm(interaction: discord.Interaction): # 替换成目标用户的ID target_user_id = 1234567890 user = await interaction.bot.fetch_user(target_user_id) await user.send("This is a test message") await interaction.response.send_message("已发送私信!", ephemeral=True)
内容的提问来源于stack exchange,提问作者beackers
相关产品推荐
相关产品推荐

