如何遍历名为images的folder?Discord Bot图片获取需求
遍历Discord Bot添加的"images"文件夹获取所有图片
实现思路
Discord中的频道文件夹本质是对频道内消息的分组,要获取其中的图片,需先定位到目标文件夹,再遍历文件夹内所有消息,过滤出带图片附件的内容。
代码实现(基于discord.py v2.x)
import discord from discord.ext import commands intents = discord.Intents.default() intents.message_content = True # 需开启消息内容权限 bot = commands.Bot(command_prefix="!", intents=intents) @bot.event async def on_ready(): print(f"已登录:{bot.user}") # 替换为你的服务器ID和目标频道ID guild = bot.get_guild(123456789012345678) channel = guild.get_channel(987654321098765432) # 定位名为"images"的文件夹 target_folder = None for folder in channel.folders: if folder.name == "images": target_folder = folder break if not target_folder: print("未找到名为'images'的文件夹") return # 遍历文件夹内所有消息,收集图片 images = [] async for message in target_folder.history(limit=None): # limit=None获取全部消息 for attachment in message.attachments: if attachment.content_type.startswith("image/"): images.append(attachment.url) # 保存图片URL,也可调用attachment.save()下载到本地 print(f"共找到{len(images)}张图片:") for img_url in images: print(img_url) bot.run("你的Bot令牌")
注意事项
- 确保Bot已加入目标服务器,且拥有读取消息历史和查看频道的权限
- 在Discord开发者门户中开启
Message Content Intent权限,否则无法读取消息附件 - 若文件夹内消息量极大,遍历过程耗时较长,可根据需求设置
limit参数分批获取
内容的提问来源于stack exchange,提问作者benz
相关产品推荐
相关产品推荐

