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

Discord机器人无法给部分用户ID发送私信的问题求助

Discord私信命令问题分析与解决

错误根源

你遇到的AttributeError是因为bot.get_user(int(user_id))返回了None——也就是机器人的本地缓存里找不到这个用户。部分用户能正常发送,是因为这些用户和机器人在同一个服务器,机器人启动时把他们的信息加载到了缓存里;而你自己或小号可能没和机器人共享服务器,或者缓存没同步到这些用户的信息。

解决方案

1. 改用fetch_user()获取用户

get_user()依赖本地缓存,而fetch_user()会直接调用Discord API获取用户数据,不受缓存限制。修改你的命令代码如下:

@bot.slash_command(description="sends message to someone still testing",guild_ids=[GUILD_ID])
async def send_message(ctx, user_id: str, message: str):
    try:
        user = await bot.fetch_user(int(user_id))
        await user.send(message)
        await ctx.respond("消息发送成功!", ephemeral = True)
    except discord.NotFound:
        await ctx.respond("该用户不存在!", ephemeral=True)
    except discord.Forbidden:
        await ctx.respond("无法发送私信给该用户(可能对方关闭了私信,或机器人被拉黑)!", ephemeral=True)
    except Exception as e:
        await ctx.respond(f"发送失败:{str(e)}", ephemeral=True)

这段代码加入了异常处理,能明确反馈不同的失败原因,避免直接抛出错误。

2. 排查权限与隐私限制

  • 检查用户的隐私设置:如果用户关闭了"允许来自服务器成员的私信",机器人无法给对方发私信,会触发Forbidden异常。
  • 确认机器人是否被拉黑:用户拉黑机器人后,私信请求会被Discord拒绝,同样触发Forbidden异常。

额外优化建议

把命令参数从手动输入user_id改成直接选择用户,既减少输入错误,又更友好:

@bot.slash_command(description="sends message to someone still testing",guild_ids=[GUILD_ID])
async def send_message(ctx, user: discord.User, message: str):
    try:
        await user.send(message)
        await ctx.respond("消息发送成功!", ephemeral = True)
    except discord.Forbidden:
        await ctx.respond("无法发送私信给该用户(可能对方关闭了私信,或机器人被拉黑)!", ephemeral=True)
    except Exception as e:
        await ctx.respond(f"发送失败:{str(e)}", ephemeral=True)

这样用户使用命令时,可以直接@目标用户或者从列表里选择,不需要手动输入ID。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 14:20:26