首页 > 解决方案 > 如何让机器人显示它删除的消息的内容

问题描述

@client.command()
async def clear(ctx, amount=2):
    await ctx.channel.purge(limit=amount)
    await ctx.send(f'Note:I have cleared the previous two messages\nDeleted messages:{(ctx)}')

我正在尝试让机器人显示它已删除哪些消息,但我不知道该怎么做。

标签: pythonpython-3.xdiscord.py

解决方案


对于此用途,channel.history。这更好,因为虽然 channel.purge 会立即删除,但 channel.history 在删除之前会转到每条消息,这意味着您可以获得内容。

@client.command()
async def clear(ctx, amount:int=2):
    messagesSaved = [] # Used to save the messages that are being deleted to be shown later after deleting everything.
    async for msg in ctx.channel.history(limit=amount, before=ctx.message): # Before makes it that it deletes everything before the command therfore not deleting the command itself.
        await msg.delete() # Delets the messages
        messagesSaved.append(msg.content) # Put the message in the list
    await ctx.send(f'Note: I have cleared the previous {amount} messages.\nDeleted messages:\n'+'\n'.join(str(message) for message in messagesSaved))

将消息保存在列表中而不是在删除后说出来是好的,因此我们可以一次发送所有消息,而不是在删除后立即删除和发送消息,因为这可能会导致许多通知,尤其是在删除大量消息时。


推荐阅读