python-3.xdiscord.pymute

How to make discord bot timed mute automatic for 5 mins?


import discord
from discord.ext import commands

class AntiCog(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.Cog.listener()
    async def on_message(self, message):
      
        if message.author.id == 1234567891234567:
            mention = f'<@!1234567891234567>'
            if message.content == mention:
                await message.channel.send("grow up")
                user = message.author
                print(str(user))
                print(str(message.content))
                muted_role = discord.utils.get(message.guild.roles, name="Muted")
                await user.add_roles(muted_role)

            else:
                return 

            await self.client.process_commands(message)
      
def setup(client):
    client.add_cog(AntiCog(client))

This's a working code for muting a person if they ping another person, however, I would like to make it a timed mute for 5 min. All of the resources I found were on_command timed mute, however, this's an auto one, how can I do so. thank you!


Solution

  • All you would have to do is add asyncio.sleep, and then remove the role, so:

    import discord
    from discord.ext import commands
    import asyncio
    
    class AntiCog(commands.Cog):
        def __init__(self, client):
            self.client = client
    
        @commands.Cog.listener()
        async def on_message(self, message):
          
            if message.author.id == 1234567891234567:
                mention = f'<@!1234567891234567>'
                if message.content == mention:
                    await message.channel.send("grow up")
                    user = message.author
                    print(str(user))
                    print(str(message.content))
                    muted_role = discord.utils.get(message.guild.roles, name="Muted")
                    await user.add_roles(muted_role)
                    await asyncio.sleep(300) # you can change the time here
                    await user.remove_roles(muted_role)
    
                else:
                    return 
    
                await self.client.process_commands(message)
          
    def setup(client):
        client.add_cog(AntiCog(client))
    

    Be sure to import asyncio!