Python:不和谐 API

Python: Discord API

这是文档中我不明白的部分。

purge_from(channel, *, limit=100, check=None, before=None, after=None, around=None)

This function is a coroutine.

Purges a list of messages that meet the criteria given by the predicate check. If a check is not provided then all messages are deleted without discrimination.

You must have Manage Messages permission to delete messages even if they are your own. The Read Message History permission is also needed to retrieve message history.

Usable only by bot accounts.

Parameters: channel (Channel) – The channel to purge from. limit (int) – The number of messages to search through. This is not the number of messages that will be deleted, though it can be. check (predicate) – The function used to check if a message should be deleted. It must take a Message as its sole parameter.

Examples

Deleting bot’s messages

def is_me(m):
    return m.author == client.user

deleted = await client.purge_from(channel, limit=100, check=is_me)
await client.send_message(channel, 'Deleted {} message(s)'.format(len(deleted)))

我明白这里的一切,直到检查参数。我已尝试尽我所能使用该示例,但我做不到。我想要实现的目标是清除所有带有附件的邮件。 Message.Attachments returns 如果有 none,则为空列表。任何人都可以尽可能最好地解释这个例子,或者提供代码吗?谢谢。

我用过discord.py,但没真正用过purge_from()。这里是:

check 似乎是一个参数,要求具有一个 Message 类型参数的谓词类型函数。 return True 用作该函数参数的消息将被删除。这也可以用 lambda 重写以获得更紧凑的代码。

client.purge_from(channel, limit=100, check=lambda m: m.author == client.user)

记住:不要直接从 API 文档中复制,因为它很可能不起作用。我以前遇到过这个问题,我的答案是在命令上面使用@bot.command(pass_context=True),然后使用 async def clear(ctx, msglimit : int): deleted = await bot.purge_from(ctx.message.channel, limit=msglimit) await bot.say("Cleared **{}** Messages".format(len(deleted))) 在它下面。请记住仔细阅读文档和常见问题解答,并将消息限制设置为可以清除的数量。祝你的机器人编码顺利!