python 获取无效消息错误:列表索引超出discord.py2.0版本的范围

nhaq1z21  于 2023-02-28  发布在  Python
关注(0)|答案(1)|浏览(80)

下面是代码

async def on_message(self, message):
 
        if message.author == self.bot.user:
            return

      
        if message.attachments and message.author.id == 646937666251915264:
            
            attachment = message.attachments[0]
         
            if attachment.filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')):
             
                img_bytes = await attachment.read()
               
                img = Image.open(io.BytesIO(img_bytes))
                
                width, height = 500, 500
                img = img.resize((width, height))
            
                img = img.convert('L')
          
                text = pytesseract.image_to_string(img)
             
                await message.channel.send(f"```{text}```")

我使用的是旧版本的www.example.com和后转移到新版本我得到错误。请帮助我解决这个问题。discord.py and after shifting to new version I getting error. Pls help me to fix this.

nhjlsmyf

nhjlsmyf1#

Discord.py 将邮件附件定义为:
attachments¶邮件附件的列表。如果Intents.message_content未启用,则此列表将始终为空,除非提及bot或邮件为直接邮件。
您的行内容如下:

if message.attachments and message.author.id == 646937666251915264:

您正在设置参数。问题是discord总是返回附件列表,但是如果没有附件,它将为空,因此在您的行:

attachment = message.attachments[0]

index(你已经设置为0)可以返回null。你需要把我提到的第一行修改成更像这样的东西:

if len(message.attachments) > 0 and message.author.id == 646937666251915264:

这个检查列表的长度是否大于0。如前所述,不一致的邮件总是有一个附件列表,如果该列表是空的,它仍然会通过您设置的过滤器。所以您需要检查该列表中是否确实有内容。这是您索引错误的原因。

相关问题