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

使用Python通过用户ID发送Discord私信时报错404 Unknown User如何解决

问题描述

我开发了一款可通过用户ID发送Discord私信的机器人,目前无法正常运行,对应代码如下:

import discord
from discord.ext import commands
import json
 
bot = commands.Bot(command_prefix='?')
 
@bot.event
async def on_ready():
    print(' [!] messaging..\n')
 
    with open("ids.json", "r") as file:
        data = json.load(file)
 
    indx = 0
    for i in data:
        indx += 1
        member = await bot.fetch_user(i)
        try:
            await member.send("message to send")
            print(f" [+] Sent message {indx} / {len(data)}")
        except Exception as e:
            print(f" [!] {e}")
 
    print(" [+] Done")
 
bot.run("bot token", bot = False)

报错信息如下:

Ignoring exception in on_ready
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 17, in on_ready
    member = await bot.fetch_user(i)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 1384, in fetch_user
    data = await self.http.get_user(user_id)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 250, in request
    raise NotFound(r, data)
discord.errors.NotFound: 404 Not Found (error code: 10013): Unknown User

报错原因

  • 直接触发报错的原因是ids.json中存储的某个用户ID无效,Discord服务器无法找到对应用户,返回404错误。
  • 代码存在隐藏错误:bot.run()中设置了bot = False,该参数用于登录普通用户账号,如果你使用的是Discord开发者平台申请的机器人令牌,该参数会导致身份认证异常,增加接口报错概率,同时普通用户批量发私信属于违反Discord用户协议的行为,可能触发账号封禁。
  • 部分旧版本discord.py库对字符串格式的用户ID兼容不佳,从json文件读取的ID默认是字符串类型,未转换为整数也可能触发该报错。

修复方案

  1. 修正bot.run参数,删除bot=False配置,仅传入机器人令牌即可。
  2. 将用户查询逻辑移入try块内,遇到无效ID直接跳过,避免中断整个发送流程,同时增加ID类型转换兼容不同版本库。
  3. 若使用discord.py v2及以上版本,需要先在Discord开发者后台的机器人设置页面,开启Privileged Gateway Intents下的所有权限,否则无法正常拉取用户信息、发送私信。

修复后参考代码:

import discord
from discord.ext import commands
import json
 
# 声明运行所需意图
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='?', intents=intents)
 
@bot.event
async def on_ready():
    print(' [!] messaging..\n')
 
    with open("ids.json", "r") as file:
        data = json.load(file)
 
    indx = 0
    success_count = 0
    for user_id in data:
        indx += 1
        try:
            # 转换为整数ID兼容旧版本库
            member = await bot.fetch_user(int(user_id))
            await member.send("message to send")
            print(f" [+] Sent message {indx} / {len(data)}")
            success_count += 1
        except discord.errors.NotFound:
            print(f" [!] ID {user_id} 不存在,已跳过")
        except Exception as e:
            print(f" [!] 发送给ID {user_id} 失败: {str(e)}")
 
    print(f" [+] Done,成功发送{success_count}条,失败{len(data)-success_count}条")
 
bot.run("替换为你的机器人令牌")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 23:48:03