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

discord.py 2.0版本出现list index out of range错误,求修复帮助

修复discord.py升级后的"list index out of range"错误

错误原因

你遇到的list index out of range错误,是因为代码直接通过message.attachments[0]访问第一个附件,但discord.py新版本中,即便message.attachments布尔判断为真,也可能存在列表为空的情况;另外新版本默认未启用message_content意图,会导致消息附件加载异常。

修复后的代码

async def on_message(self, message):
    # 忽略机器人自身消息
    if message.author == self.bot.user:
        return

    # 明确判断目标用户且存在有效附件
    if message.author.id == 646937666251915264 and len(message.attachments) > 0:
        attachment = message.attachments[0]
        # 验证附件为图片格式
        if attachment.filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')):
            try:
                img_bytes = await attachment.read()
                img = Image.open(io.BytesIO(img_bytes))
                
                # 调整尺寸并转为灰度图优化OCR识别
                img = img.resize((500, 500)).convert('L')
                
                # 识别图片文本并发送
                text = pytesseract.image_to_string(img)
                await message.channel.send(f"```{text}```")
            except Exception as e:
                # 捕获异常防止机器人崩溃,可按需调整提示内容
                await message.channel.send(f"处理图片时出错:{str(e)}")

关键额外配置

discord.py v2.x及以上版本必须手动开启message_content意图,否则无法正常读取消息内容和附件:

  1. 登录Discord开发者门户,进入你的应用,在Bot选项卡中开启Message Content Intent
  2. 在代码初始化Bot时添加意图配置:
import discord

intents = discord.Intents.default()
intents.message_content = True

# 根据你的Bot类型选择初始化方式
bot = discord.Bot(intents=intents)
# 若使用commands.Bot则替换为:
# bot = commands.Bot(command_prefix='你的前缀', intents=intents)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 08:24:53