繁体   English   中英

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

[英]How to check if a channel has any messages? 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()来获取包含频道消息的列表。 限制用于指定要回读的最大消息数。

您可以检查该列表是否为空,以检查频道中是否有消息。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM