使用Python Discord API下载Discord频道附件的方法
用discord.py下载Discord频道中的附件图片
嘿,你已经搞定了链接形式的图片下载,真棒!针对那种直接以附件发送的图片,用discord.py处理起来其实非常省心,官方API已经帮我们封装好了直接的方法,我给你一步步讲:
核心思路:利用消息对象的attachments属性
当用户发送带附件的消息时,discord.Message对象会有一个attachments属性,它是一个Attachment对象的列表——每个Attachment就对应一个发送的附件,不管是图片、文档还是其他文件。
代码示例:实时监听消息并下载附件
比如在你的消息监听事件里,可以直接遍历附件处理:
import discord from discord.ext import commands intents = discord.Intents.default() intents.message_content = True # 必须开启这个intent才能读取消息内容 client = commands.Bot(command_prefix="!", intents=intents) @client.event async def on_message(message): # 跳过机器人自己的消息,避免触发循环 if message.author == client.user: return # 处理直接发送的附件图片 for attachment in message.attachments: # 过滤出图片类型的附件(可选,如果你只需要图片的话) if attachment.content_type and attachment.content_type.startswith("image/"): # 直接调用save方法保存到本地,指定路径和文件名 await attachment.save(f"./downloaded_images/{attachment.filename}") print(f"成功下载附件:{attachment.filename}") # 这里保留你之前处理链接形式图片的代码 # 你的原有逻辑... client.run("你的机器人Token")
关键细节说明
attachment.save():这是discord.py提供的异步方法,内部已经帮你处理了HTTP请求、文件写入等操作,不用你自己去写requests下载,非常简便。- 过滤图片类型:通过
content_type判断是否为图片,避免下载其他类型的附件(比如文档、视频),如果不需要过滤可以去掉这个判断。 - 权限注意:确保你的机器人开启了
message_contentintent(上面代码里已经配置),并且拥有目标频道的「查看频道」和「读取消息历史」权限,这样才能获取到消息和附件信息。
扩展:批量下载历史消息中的附件
如果需要爬取频道历史里的附件图片,可以用channel.history()遍历历史消息:
async def download_historical_images(channel_id): channel = client.get_channel(channel_id) # limit=None表示获取所有历史消息,也可以指定具体数量比如limit=1000 async for message in channel.history(limit=None): for attachment in message.attachments: if attachment.content_type and attachment.content_type.startswith("image/"): await attachment.save(f"./historical_images/{attachment.filename}") print(f"已下载历史图片:{attachment.filename}") # 可以在某个命令里调用这个函数,比如: @client.command() async def download_history(ctx): await download_historical_images(ctx.channel.id) await ctx.send("历史图片下载完成!")
这样一来,不管是实时消息里的附件,还是历史消息里的,都能轻松下载啦,和你之前处理链接形式的逻辑配合,就能覆盖所有图片场景了。
内容的提问来源于stack exchange,提问作者niccalis




