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

如何制作Discord Bot获取与指定用户的所有私人私信?

解决Discord Bot获取私信并输出到控制台的问题

一、方案一(requests调用API)的404错误解决

  • 错误原因:

    • CHANNEL_ID无效:DM频道ID必须准确获取——先开启Discord开发者模式(用户设置→高级→开发者模式),右键私信对话复制ID,确保是18位数字字符串。
    • Bot无访问权限:Bot必须和目标用户存在已建立的私信对话,或主动发起过私信(此时频道才会被API识别)。
    • API版本过时:当前Discord API稳定版为v10,建议替换URL中的v9为v10。
  • 修正后的代码:

import requests

DISCORD_TOKEN = '你的Bot令牌'
CHANNEL_ID = '正确的DM频道ID'
# limit控制单次获取条数,最多100,如需全量需分页处理
MESSAGE_URL = f'https://discord.com/api/v10/channels/{CHANNEL_ID}/messages?limit=100'

headers = {
    'Authorization': f'Bot {DISCORD_TOKEN}'
}

def fetch_messages(url):
    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        return response.json()
    else:
        print(f'请求失败,状态码: {response.status_code},响应内容: {response.text}')
        return None

messages = fetch_messages(MESSAGE_URL)
if messages:
    for message in messages:
        author = message["author"]
        print(f'{author["username"]} ({author["id"]}): {message["content"]}')
else:
    print('未获取到消息')

二、方案二(discord.py)的"Recipient not found"错误解决

  • 错误原因:

    • get_user()仅读取缓存:如果Bot刚启动、未和目标用户互动过,get_user()会因缓存中无用户信息返回None,必须用await client.fetch_user()从API主动拉取。
    • 用户ID格式错误:recipient_id需要是整数类型,不能直接传字符串,需转换为int(recipient_id)。
    • 权限缺失:discord.py v2.x+需要开启message_content意图,否则无法读取消息内容。
  • 修正后的代码:

import discord
from discord import Intents

TOKEN = '你的Bot令牌'

intents = Intents.default()
intents.messages = True
intents.message_content = True  # 必须开启,否则无法读取消息内容

client = discord.Client(intents=intents)

@client.event
async def on_ready():
    print(f'已登录为 {client.user}')

    recipient_id = 123456789012345678  # 替换为目标用户的整数ID
    try:
        recipient = await client.fetch_user(recipient_id)
        # 若DM频道不存在则创建
        dm_channel = recipient.dm_channel or await recipient.create_dm()
        await fetch_messages(dm_channel)
    except discord.NotFound:
        print('收件人不存在,请检查用户ID是否正确')

async def fetch_messages(channel):
    messages = []
    async for message in channel.history(limit=None):
        # 可根据需求筛选消息:
        # if message.author == client.user: 仅显示自己的消息
        # if message.author.id == 目标用户ID: 仅显示对方的消息
        messages.append(f'{message.author.username} ({message.author.id}): {message.content}')

    print(f'共获取到 {len(messages)} 条消息:')
    # reversed让消息按时间正序显示
    for msg in reversed(messages):
        print(msg)

client.run(TOKEN)

额外提示:

  • 确保Bot令牌正确,且Bot已被邀请到至少一个服务器(即使仅获取私信,Bot需要加入服务器才能正常运行)。
  • 若需要获取全量消息(超过API单次返回限制),方案一需实现分页逻辑,方案二中channel.history(limit=None)会自动处理分页。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 15:17:04