如何检查一个频道是否有消息?Discord.py



所以我现在想要实现的是,找到并编写代码,所以每当我清除通道时,它将首先检查它是否有任何消息。如果没有,那么它将发送一个错误。唯一的问题是,我不知道客户是否可以先检查一下上面是否有消息。如果有人有任何想法或例子,我将非常乐意知道!

答案是:

@commands.command()
async def clear(self, ctx, *, limit=100):
await ctx.message.delete()
channel = ctx.channel
messages = await channel.history(limit=123).flatten()
if not messages:
await ctx.channel.send("I am really sorry but I can not purge an empty channel!")
return
else:
try:
await channel.purge(limit = limit)
return
except discord.Forbidden:
return await ctx.channel.send('I do not have perms')

您可以使用messages = await channel.history(limit=123).flatten()获取包含通道消息的列表。Limit用于指定回读消息的最大数目。

您可以检查该列表是否为空或不检查通道中是否有消息。

API参考:https://discordpy.readthedocs.io/en/latest/api.html?highlight=history#discord.TextChannel.history

最新更新