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

如何用discord.py自定义函数给列表中所有用户发送私信?

问题分析与修复方案

你的代码存在几个核心问题导致私信无法正常发送:

核心问题点

  • 误用Python内置类型名list作为变量名,会覆盖内置功能引发潜在问题
  • dm_function是同步函数,但Discord API操作全是异步的,必须使用异步定义+await关键字
  • 循环中的user是字符串格式的ID,不是可操作的Discord用户对象,无法直接调用send
  • on_message事件中没有触发私信函数,且调用异步函数必须加await
  • 缺少异常处理,遇到用户关闭私信、用户不存在等情况会导致机器人崩溃

修复后的完整代码

import discord
import json

# 读取配置文件
with open("./config.json") as config:
    configData = json.load(config)
token = configData["Token"]

# 设置Intents
intents = discord.Intents.default()
intents.message_content = True
intents.members = True

client = discord.Client(intents=intents)

@client.event
async def on_ready():
    print(f'Logged in as {client.user}')

# 改用自定义变量名,避免覆盖内置list
user_ids = ["12345678910","111213141516171819"]

# 改为异步函数,处理用户对象获取与私信发送
async def dm_function():
    for user_id in user_ids:
        try:
            # 将字符串ID转为用户对象
            user = await client.fetch_user(int(user_id))
            # 发送私信内容
            await user.send("test")
            print(f"已成功发送私信给用户 {user_id}")
        except discord.NotFound:
            print(f"用户 {user_id} 不存在")
        except discord.Forbidden:
            print(f"无法发送私信给用户 {user_id}(用户已关闭私信或权限不足)")
        except Exception as e:
            print(f"发送私信给用户 {user_id} 时出错:{str(e)}")

@client.event
async def on_message(message):
    # 避免机器人自己触发命令
    if message.author == client.user:
        return
    
    if message.content.startswith('!testing'):
        # 调用异步私信函数,必须加await
        await dm_function()
        # 这里可以添加你原本的嵌入消息代码
        embed = discord.Embed(title="测试通知", description="已向邮件列表用户发送私信", color=discord.Color.green())
        await message.channel.send(embed=embed)

client.run(token)

关键修复说明

  1. 变量名修正:把list改成user_ids,避免破坏Python内置的list类型
  2. 异步化处理:将dm_function改为async def,所有Discord API调用(fetch_user、send)前加await
  3. 用户对象转换:用client.fetch_user(int(user_id))把字符串ID转为可操作的用户实例,注意要转成整数类型
  4. 触发私信函数:在on_message中调用await dm_function(),确保异步函数被正确执行
  5. 异常处理:捕获常见错误,避免因单个用户的问题导致整个机器人崩溃
  6. 排除机器人自身消息:添加if message.author == client.user: return,防止机器人响应自己发送的消息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 08:30:42