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

如何通过用户ID发送Discord私信?代码报错AttributeError求助

Discord机器人DM命令报错修复

错误信息翻译

discord.ext.commands.errors.CommandInvokeError: 命令触发异常: AttributeError: 'NoneType' 对象没有 'send' 属性

问题原因

这个错误说明client.get_user(userID)返回了None,也就是机器人没找到目标用户,常见原因有三个:

  • 传入的用户ID是字符串类型,而Discord用户ID需要整数
  • 你的机器人和目标用户不在同一个服务器,get_user依赖本地缓存,无法获取外部用户
  • 用户ID输入错误

修复后的代码

import discord
from discord.ext import commands

@client.command()
async def dm(ctx, userID: int, *, message):
    try:
        # 通过API直接获取用户,不受共同服务器限制
        user = await client.fetch_user(userID)
        await user.send(message)
        await ctx.send(f"已成功给用户ID {userID} 发私信")
    except discord.NotFound:
        await ctx.send("找不到这个用户,检查ID是否正确")
    except discord.Forbidden:
        await ctx.send("发不了私信,可能用户关了私信或者拉黑了机器人")
    except Exception as e:
        await ctx.send(f"发送失败:{str(e)}")

关键改动说明

  • 补上了命令必须的ctx上下文参数,你之前的代码遗漏了这个核心参数
  • 给userID加上int类型注解,自动把输入的字符串转成整数ID
  • 用fetch_user替代get_user,fetch_user调用Discord API拉取用户信息,不需要依赖本地缓存
  • 增加异常处理,把常见错误反馈给发命令的人,方便排查问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 11:30:50