0

I want my discord.py Bot to remove the muted role after a certain amount of time, which would be specified by the moderator running the "Mute" command.

I tried putting an argument after 'ctx', which would be the time specified to mute.

@bot.command(name='mute', pass_context=True)
@commands.has_role('mod')
async def mute(ctx, member=None, val: int=None):
  ab = member
  ab = ab.replace("<","")
  ab = ab.replace(">","")
  ab = ab.replace("@","")
  ab = ab.replace("!","")
  member = ctx.guild.get_member(int(ab))
  role = discord.utils.get(ctx.guild.roles, name="muted")
  await member.add_roles(role)
  await ctx.send("muted")

it would raise the error 'AttributeError: 'NoneType' object has no attribute 'add_roles''

golger
  • 21
  • 2
  • Does this answer your question? [Why do I get AttributeError: 'NoneType' object has no attribute 'something'?](https://stackoverflow.com/questions/8949252/why-do-i-get-attributeerror-nonetype-object-has-no-attribute-something) – CrazyChucky Mar 30 '23 at 22:52

1 Answers1

0

It's possible for member to be None after get_member if the user couldn't be found in the guild, so you have to handle that case:

@bot.command(name='mute')
@commands.has_role('mod')
async def mute(ctx, user: discord.User, mute_duration_in_minutes: int=60):
  if user is None:
    # Do something here to handle user not being present in command.

  member = ctx.guild.get_member(user.id)
  
  if member is None:
    # Do something here to handle member not being found in the guild.

  role = discord.utils.get(ctx.guild.roles, name="muted")
  await member.add_roles(role)
  await ctx.send("muted")

The same would be the case for things like the user, role, and mute_duration_in_minutes (or whatever the name is).

As for removing the role again after the delay, you could, for example, store information about the user and when they should be unmuted when you give them the muted role, and have a thread that keeps checking every minute for users that need to have the muted role removed:

import threading

def check_and_remove_expired_muted_role():
  # Retrieve stored users and remove role if needed.

# Start checking when starting up the bot.
threading.Timer(60.0, check_and_remove_expired_muted_role).start()
  
rdieleman
  • 64
  • 4
  • How would i store the muted users and how long they are muted for? – golger Mar 31 '23 at 01:46
  • @golger Probably a dictionary that stores the user's id and the datetime for when to unmute them. Whenever you mute someone you can just add/update that user's id with the new timestamp. The background thread doing the unmuting could then unmute and remove them. It's probably also a good idea to persist the data so nobody gets stuck with the muted rule if the bot shuts down for some reason. – rdieleman Mar 31 '23 at 12:27