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

discord.py获取消息附件URL时触发IndexError列表索引越界错误

错误根因

你触发的IndexError是因为直接访问了空列表的第0位元素:on_message事件会响应所有服务器内的新消息(包括纯文本消息、机器人自身发送的消息、系统通知消息等无附件的消息),此时message.attachments为空列表,直接取[0]必然触发越界报错。

修复步骤
  • 首先添加机器人自身消息过滤逻辑,避免机器人发的消息二次触发事件
  • 限定仅处理你指定的投稿频道的消息,避免其他无关频道的无附件消息触发逻辑
  • 取值前先判断消息是否携带附件,无附件直接跳过处理
  • embed.set_image的url参数需要传入附件的url属性,不能直接传入附件对象
修正后代码示例
@client.event
async def on_message(message):
    # 过滤机器人自身发送的消息
    if message.author.bot:
        return
    # 替换为你的投稿频道ID,仅处理该频道的消息
    submit_channel = client.get_channel(替换为实际投稿频道ID)
    # 替换为你的美术展示频道ID
    art_channel = client.get_channel(替换为实际美术频道ID)
    if message.channel.id != submit_channel.id:
        return
    # 判断是否有附件,无附件直接跳过
    if not message.attachments:
        return
    # 取第一个附件
    attachment = message.attachments[0]
    art_name = message.content

    embed = discord.Embed(
        title = art_name,
        colour = discord.Colour.red()
    )
    embed.set_author(
        name = message.author,
        icon_url = message.author.avatar_url
    )
    # 传入附件url属性
    embed.set_image(url = attachment.url)
    # 发送到美术频道
    await art_channel.send(embed=embed)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 21:06:02