删除特定频道中的某些文件类型附件?

Deleting certain file type attachments in a specific channel?

我正在尝试将某些文件添加到 posted 到通用频道,因为我们为某些附件、剪辑、视频、音乐等指定了频道。我很乐意获取该机器人识别链接,但是,很难让它识别附件,更具体地说,.mp4 附件。

我在一个数组中添加了可接受附件的白名单,然后尝试检查邮件作者附件以查看是否可以post,如果是 .mp4 则应将其删除。

try 函数在 on_message 事件装饰器中。

whiteList = ['bmp','jpeg','jpg','png']
    try:
        for attachment in message.attachments:
            #Get general channel ID
            channel = client.get_channel(521376573245358081)
            if message.channel is channel and attachment['filename'].split('.')[-1] not in whiteList:
                await message.delete()
                botsMessage = await channel.send("{0.mention} Please refrain from posting videos in General. You may post them in #videos".format(message.author))
                await asyncio.sleep(5)
                await botsMessage.delete()
    except:
        print('Unknown error')

没有出现错误,因为当我对此进行测试时,附件仍然存在,bot 传递函数并打印控制台消息(用于调试以确保代码到达那么远)。有什么建议吗?

attachment['filename'].split('.')[-1]

您将 attachment 视为具有名为 filename 键的字典。
您应该将 attachment 视为具有名为 filename 的 属性 的对象,如下所示:

attachment.filename.split('.')[-1]

此外,您应该 break 每当消息被删除时循环,

# ...
botsMessage = await channel.send("{0.mention} Please refrain from posting videos in General. You may post them in #videos".format(message.author))
await asyncio.sleep(5)
await botsMessage.delete()
break
# ...

如果用户发送了多个视频文件,即使您删除了消息,循环仍会继续。这可能会导致它尝试删除已删除的消息
break 语句可防止上述情况发生。