Discord bot获取附件重传触发FileNotFoundError错误如何解决?
问题原因
discord.File 仅支持读取本地文件路径或者二进制类文件对象,你直接传入Discord CDN的远程链接,程序会将该URL视为本地文件路径在磁盘中查找,自然触发FileNotFoundError。此前唯一一次成功属于极端巧合,大概率是当时你的本地磁盘刚好存在与该附件同名的文件。
解决方案
方案1:兼容所有discord.py版本(手动下载到内存)
不需要将文件存储到本地磁盘,全程在内存中处理即可,需先引入依赖模块:
import io import aiohttp
修改后的事件逻辑:
async def on_message(message): if message.author == client.user: return # 转小写判断,同时兼容anon和Anon两种开头 if message.content.lower().startswith("anon "): if message.attachments: attachment = message.attachments[0] # 异步下载附件内容 async with aiohttp.ClientSession() as session: async with session.get(attachment.url) as resp: if resp.status != 200: await message.channel.send("文件下载失败") return file_bytes = io.BytesIO(await resp.read()) # 发送内存中的文件,保留原文件名保证格式正常 await message.channel.send( content = message.content[5:], file = discord.File(fp=file_bytes, filename=attachment.filename) )
方案2:discord.py 2.0+ 专属简化方案
2.0及以上版本的Attachment对象自带to_file()方法,无需自行实现下载逻辑,代码更简洁:
async def on_message(message): if message.author == client.user: return if message.content.lower().startswith("anon "): if message.attachments: forward_file = await message.attachments[0].to_file() await message.channel.send(content=message.content[5:], file=forward_file)
内容的提问来源于stack exchange,提问作者ttt
相关产品推荐
相关产品推荐

