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

如何使用Discord.py给指定用户发送私信?

问题原因&修复方案

1. 必要依赖缺失与重复实例化

你的代码没有导入commands模块,且重复实例化客户端对象,client = discord.Client()属于冗余代码会导致冲突,需删除。
开头需补充正确导入逻辑:

import discord
from discord.ext import commands

2. 缺少消息意图(Intents)配置

Discord现已强制要求开发者开启消息相关权限意图,否则机器人无法读取服务器消息,自然无法触发命令。
需要在实例化Bot前配置Intents:

intents = discord.Intents.default()
intents.message_content = True # 开启消息内容读取权限
# 同时要在Discord开发者后台的Bot设置页,开启Message Content Intent开关
client = commands.Bot(command_prefix=']', intents=intents)

3. 过时参数与调用逻辑错误

  • pass_context是discord.py v1.x的旧参数,v2.x版本已废弃无需填写
  • 你代码里写死了要发送的用户ID,没有使用传入的user_id参数,且user_id需要是整数类型不能用字符串包裹
  • 发送DM无需手动调用DMChannel.send,直接调用用户对象的send方法即可
  • 你输入]dmsend时没有传入user_id参数,会触发参数缺失报错,要么输入命令时带上用户ID(比如]dmsend 71123221123),要么给参数设置默认值

修正后的完整参考代码

import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.message_content = True
client = commands.Bot(command_prefix=']', intents=intents)

@client.command(name='dmsend')
async def dmsend(ctx, user_id: int = 71123221123): # 给user_id设置默认值,不传就用这个固定ID
    try:
        user = await client.fetch_user(user_id)
        await user.send("Put the message here")
        await ctx.send("私信发送成功")
    except Exception as e:
        await ctx.send(f"发送失败:{str(e)}")

# 最后填入你的Bot Token启动
client.run("你的机器人Token")

额外检查项

  • 确认你已经在Discord开发者后台的Bot设置中开启了Message Content Intent权限
  • 确认邀请机器人进服务器时,勾选了Send Messages、Read Message History等必要权限
  • 确认收信用户的隐私设置没有禁止服务器成员发送私信

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 13:36:04