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

如何修复Discord机器人报错:AttributeError: 'NoneType' object has no attribute 'send'

解决Discord机器人发送图片时的AttributeError报错

我尝试用Discord机器人将本地图片发送到指定频道,使用的代码如下:

# Create an Intents object with the `messages` attribute set to True
intents = discord.Intents(messages=True)

# Create the client with the specified intents
client = discord.Client(intents=intents)

@client.event
async def on_ready():
    # When the bot is ready, send the image to the specified channel
    channel = client.get_channel(CHANNEL_ID)
    with open(r"file path", 'rb') as f:
        file = discord.File(f)
        await channel.send(file=file)

client.run(TOKEN)

运行后出现如下报错:

Traceback (most recent call last):
  File "C:\Python\Python39\lib\site-packages\discord\client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "path", line 39, in on_ready
    await channel.send(file=file)
AttributeError: 'NoneType' object has no attribute 'send'

解决方法

  • 确认CHANNEL_ID的有效性
    client.get_channel()返回None,说明找不到对应ID的频道。要确保CHANNEL_ID是整数类型(不能用字符串),且是目标频道的正确ID。需开启Discord开发者模式(设置→高级→开发者模式),右键频道复制ID。

  • 检查机器人的频道权限
    机器人必须被邀请到目标服务器,并且在目标频道拥有发送消息和上传文件的权限。可在服务器设置→角色中给机器人配置对应权限,或直接在频道权限设置里单独调整。

  • 修复Intents配置
    新版本discord.py需要完整的Intents配置,仅开启messages不足以让机器人获取服务器和频道缓存。修改Intents初始化代码:

    intents = discord.Intents.default()
    intents.message_content = True  # 开启消息内容权限,支持发送文件等操作
    
  • 改用fetch_channel获取频道(推荐)
    get_channel依赖本地缓存,如果on_ready触发时缓存未加载完成,会返回None。改用fetch_channel直接从Discord API获取频道,不依赖缓存:

    @client.event
    async def on_ready():
        # 使用fetch_channel替代get_channel
        channel = await client.fetch_channel(CHANNEL_ID)
        with open(r"file path", 'rb') as f:
            file = discord.File(f)
            await channel.send(file=file)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 08:05:23