【问题标题】:Deleting certain file type attachments in a specific channel?删除特定频道中的某些文件类型附件?
【发布时间】:2019-12-17 17:42:17
【问题描述】:

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

我在数组中添加了可接受附件的白名单,然后尝试检查邮件作者附件,看看是否可以发布,如果是 .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')

这没有错误,因为当我测试这个附件时,机器人会传递函数并打印控制台消息(用于调试以确保代码到达那个位置)。有什么建议吗?

【问题讨论】:

  • 我知道这是一篇旧帖子,但仅供其他人参考,使用裸 try ... except 语句通常不是一个好主意。至少做try ... except Exception as e: print(e) 这样你就会收到错误消息。

标签: discord python-3.7 discord.py discord.py-rewrite


【解决方案1】:
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 语句可防止上述情况发生。

【讨论】:

  • 你厌倦了回答我的问题了吗?大声笑,再次感谢您!效果很好。
猜你喜欢
  • 1970-01-01
  • 2021-09-12
  • 1970-01-01
  • 1970-01-01
  • 2020-09-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-05
  • 2013-07-28
相关资源
最近更新 更多