Cooldown mapping | Discord.py

南楼画角 提交于 2021-01-28 12:52:29

问题


I am using on_message to scan the code for specific keywords so that the bot can respond accordingly, and no, I cannot use commands to achieve this.

I want to prevent people from spamming these keywords by turning on a cooldown so the bot will wait before checking again

What the documentation says:

class SomeCog(commands.Cog):
    def __init__(self):
        self._cd = commands.CooldownMapping.from_cooldown(1.0, 60.0, commands.BucketType.user)

    async def cog_check(self, ctx):
        bucket = self._cd.get_bucket(ctx.message)
        retry_after = bucket.update_rate_limit()
        if retry_after:
            # you're rate limited
            # helpful message here
            pass
        # you're not rate limited

What I have:

class Listener(commands.Cog):
    def __init__(self, bot):
        self._cd = commands.CooldownMapping.from_cooldown(1.0, 10.0, commands.BucketType.user)

    @commands.Cog.listener()
    async def on_message(self, message):    

        async def cog_check(self, message):
            bucket = self._cd.get_bucket(message)
            retry_after = bucket.update_rate_limit()
            if retry_after:
                print('test')
                pass
        

            elif (message.guild is None):  
                return '.'

            else:
          . . . . . #code which tests for the keywords

回答1:


class SomeCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self._cd = commands.CooldownMapping.from_cooldown(1.0, 60.0, commands.BucketType.user) # Put your params here
                                                        # rate, per, BucketType

    def ratelimit_check(self, message):
        """Returns the ratelimit left"""
        bucket = self._cd.get_bucket(message)
        return bucket.update_rate_limit()


    @commands.Cog.listener()
    async def on_message(self, message):
        if 'check if the message contains certain words here':
            # Getting the ratelimit that's left
            retry_after = self.ratelimit_check(message)
            if retry_after is None:
                # You're not ratelimited
            else:
                # You're ratelimited, you can delete the message here
                await message.delete()
                await message.channel.send(f"You can't use those words for another {round(retry_after)} seconds.")

The code here evaluates if the message contains certain words, if it does, checks for ratelimit, if there is one - deletes the message and sends a message.



来源:https://stackoverflow.com/questions/65230432/cooldown-mapping-discord-py

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!