import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='>', intents=discord.Intents.all())
@bot.command(name='test')
async def test(ctx: commands.Context) -> None:
images = [file for file in ctx.message.attachments if 'image' in file.content_type]
if not images:
return await ctx.reply('Прикрепите изображение(я)')
for image in images:
with open(image.filename, 'wb') as image_file:
await image.save(image_file)
await ctx.reply(f'Сохраненные изображения: ' + ', '.join(f'[{image.filename}](<{image.url}>)' for image in images))
bot.run('TOKEN')
在课堂上
discord.Message有一个属性
attachments将附加到此消息的文件列表存储为类的实例
discord.Attachment反过来,它具有以下属性:
content_type,将文件类型存储为字符串格式Media typefilename— 附件的名称url- 链接到文件以及其他内容,您也可以在文档中阅读。
接下来,我们从上下文中
ctx获取消息对象ctx.message,并从中获取其文件列表ctx.message.attachments。我们按文件类型过滤列表,以便仅保留图像,如果列表不为空,则保存所有文件并发送消息。
结果:
该文档包含所有信息。如果可能,请尝试首先自行学习处理命令时可以使用的类的内容。
以防万一,这里是使用文档的指南