My mute command doesn't remove the roles properly - python

does anyone know if I have to use a database for a mute command now or what since if a member already has a role that lets them able to talk the muted role has no affect even regardless of the role hierarchy I made it where when I mute the member it takes all the roles away which works but when the time runs out or they get unmuted the member cant get their roles back anyone know how to deal with this?
#commands.command()
#commands.has_permissions(manage_messages=True)
async def mute(self, ctx, member: discord.Member=None, time=None, *, reason= None):
if time== None:
await ctx.send("you gotta set a duration.")
guild = ctx.guild
mutedrole=discord.utils.get(guild.roles, name="muted")
time_convert = {"s":1, "m":60, "h":3600,"d":86400}
tempmute= int(time[:-1]) * time_convert[time[-1]]
roles = [role for role in member.roles]
if not mutedrole:
mutedrole=await guild.create_role(name="muted", permissions=discord.Permissions(send_messages=False))
if reason== None:
reason= "No reason"
for channel in guild.channels:
await channel.set_permissions(mutedrole, speak=False, send_messages=False, add_reactions=False)
await member.edit(roles=[])
await member.add_roles(mutedrole, reason=reason)
embed= discord.Embed(description=f"**{member}** was muted for: {reason}")
await ctx.send(embed=embed)
embed= discord.Embed(description= f"You were muted in **{guild}** for: {reason}\n"
"\n **Tip**: don't be useless man!", color=0x000000)
await member.send(embed=embed)
await asyncio.sleep(tempmute)
await member.remove_roles(mutedrole)
await member.add_roles(roles)

add_roles() has a parameter called *roles which is an argument list of abc.SnowFlake representing a discord.Role. Means when you have multiple roles, add a * right before roles like that (same for remove_roles):
await member.add_roles(*roles)
BUT this doesn't work yet, since member.roles includes also the #everyone "role" which can't be added to a user (it's the default role). You need to remove it from the list.
The end result
roles = member.roles[1:] # discord.Member has an attribute roles
...
await asyncio.sleep(tempmute)
await member.remove_roles(mutedrole)
await member.add_roles(*roles)
References:
Member.add_roles()
Member.remove_roles()

Related

Can not seem to get mute commands to work with Discord py

I can not find a mute command for my discord bot, and I do not know how to write one. The tutorials and pieces of code out there are not working. The most recent code produces no errors messages, but the command will not initiate. How?
#commands.has_permissions(manage_messages=True)
async def mute(ctx, member: discord.member, *, reason=None):
guild =ctx.guild
mutedRole = discord.Utils.get(guild.roles, name="Muted")
if not mutedRole == await guild.create_role(name="Muted"):
for channel in guild.channels:
await channel.set_permissions(mutedRole, speak=False, sendmessages=False, read_message_history=False, read_messages=False)
await member.add_roles(mutedRole, reason = reason)
await ctx.send(f"Muted {member.mention} for reason {reason}")
await member.send(f"You were muted in {guild.name} for {reason}")```
There are many mistakes and typos in the code. Adding #bot.command(name=name) before #commands.has_permissions(manage_messages=True) fixed it for me:
intent = discord.Intents(messages=True, message_content=True, guilds=True)
bot = commands.Bot(command_prefix="", description="", intents=intent)
#See if you have "intents=<someintentobject>" and enable them in your Discord Developer Portal
#bot.event
async def on_ready():
print("It's online!")
#bot.event
async def on_message(message: discord.Message):
await bot.process_commands(message) #Let the commands process the message
#bot.command(name="mute") #This decorator tells that the mute function is a command the bot should process
#commands.has_permissions(manage_messages=True) #Run the mute command only if the message's author has the permission to manage messages
async def mute(ctx, member: discord.Member, reason=None): #Removed the extra arguments' asterisk (*)
#It's discord.Member, not discord.member
guild = ctx.guild
mutedRole = discord.utils.get(guild.roles, name="Muted") #utils, not Utils
if not mutedRole == await guild.create_role(name="Muted"):
for channel in guild.channels:
await channel.set_permissions(mutedRole, speak=False, send_messages=False, read_message_history=False,
read_messages=False) #send_messages, not sendmessages
await member.add_roles(mutedRole, reason=reason)
await ctx.send(f"Muted {member.mention} for reason {reason}")
await member.send(f"You were muted in {guild.name} for {reason}")
Add await bot.process_commands(message) in your on_message.
I've removed the * (args); it works fine without it. You can add it if you want.
See this example of a kick command.
#bot.command()
#commands.has_permissions(manage_messages=True)
async def mute(ctx, member: discord.Member, reason=None):
if member == ctx.author:
embed = discord.Embed(
color=discord.Colour.red(),
description="You can't mute yourself !"
)
await ctx.send(embed=embed)
return
muterole = discord.utils.get(ctx.guild.roles, name="MUTED")
if muterole is None:
muterole = await ctx.guild.create_role(name="MUTED")
for channel in ctx.guild.text_channels:
await channel.set_permissions(muterole, overwrite=discord.PermissionOverwrite(send_messages=False))
if muterole in member.roles:
embed = discord.Embed(
color=discord.Colour.red(),
description=f'This member is already muted'
)
await ctx.send(embed=embed)
return
await member.add_roles(muterole)
embed = discord.Embed(
color=discord.Colour.green(),
title=' Muted',
description=f'**{member.mention}** is now **permanently muted** reason: **{reason}**.'
)
embed.set_footer(text=f'Muted by {ctx.author}.')
await ctx.send(embed=embed)
basically what a "mute" command does is to create or directly assign a role to a member, the most important part is that the mute role to be correctly configured.
there's also more complex methods of mute command, for example temp mute command which allows you to mute someone for a certain amount of time specified by the mod, but these days is recommended that you use the timeout feature is a lot easier and more efficient. but there you have it, a basic mute command with the appropriate checks.

How can I reverse this function in discord.py?

So, I made a mute command, but cannot figure out what steps to take to remove the role "Muted" when "%unmute #user" is typed. This is the code for the mute command:
#commands.has_permissions(manage_messages=True)
#bot.command(name='mute', help='Use %help mute to see full description... Mutes the mentioned user by adding a role to them. If the role is absent, the bot will make one. Requires permissions: Manage Messages')
async def mute(ctx, member: discord.Member, *, reason=None):
guild = ctx.guild
mutedRole = discord.utils.get(guild.roles, name="Muted")
if not mutedRole:
mutedRole = await guild.create_role(name="Muted")
for channel in guild.channels:
await channel.set_permissions(mutedRole, speak=False)
embed = discord.Embed(title="muted", description=f"{member.mention} was muted ", colour=discord.Colour.light_gray())
embed.add_field(name="reason:", value=reason, inline=False)
await ctx.send(embed=embed)
await member.add_roles(mutedRole, reason=reason)
await member.send(f" you have been muted from: {guild.name} reason: {reason}")
Thank you!
I have figured it out! Here is the resulting code:
#bot.command(name='unmute', help='Unmutes the mentioned user. Requires permissions: Manage Messages')
async def unmute(ctx, member: discord.Member, *, reason=None):
guild = ctx.guild
mutedRole = discord.utils.get(guild.roles, name="Muted")
embed = discord.Embed(title="unmuted", description=f"{member.mention} was unmuted ", colour=discord.Colour.light_gray())
await ctx.send(embed=embed)
await member.remove_roles(mutedRole)
await member.send(f" you have been unmuted from: {guild.name}")
Sorry for bothering you guys!

Im trying to make it where the bot will tell you to specify a member to mute if they dont specify it. How do i do that? I tried to but it doesnt work

Mute code below. If a mod doesnt specify what member to mute, how can the bot tell them that? Thanks!
#bot.command()
#commands.has_permissions(manage_roles=True)
async def mute(ctx, member: discord.Member, reason=None):
if member.id == ctx.author.id:
await ctx.send(f"{ctx.author.mention}, YOU HAVE BEEN STOPPED BY ME YAY, you can't mute yourself!")
return
if discord.Member == None:
await ctx.send(f"{ctx.author.mention}, HEY you nugget, you need to specify who you want to mute!")
return
role = discord.utils.get(ctx.guild.roles, name='muted')
if role in ctx.guild.roles:
await member.add_roles(role)
embed=discord.Embed(title="Muted", description=f"Offender: {member.mention} has been muted until further notice!", color=0x00FFFF)
embed.add_field(name="Reason", value=f'{reason}', inline=True)
embed.add_field(name="Moderator", value=f'{ctx.author.name}', inline=True)
await ctx.send(embed=embed)
else:
await ctx.send(f"{ctx.author.mention}, Make sure your muted role is called `muted` in all lowercase! Then try again.")
Your thought was right, but you need to approach it a little differently.
Take a look at the following code:
#bot.command()
#commands.has_permissions(manage_roles=True)
async def mute(ctx, member: discord.Member, reason=None):
if member.id == ctx.message.author.id:
await ctx.send("You can't mute yourself")
if member:
# Do what you want if the member was given
What we only did is work with if statements.
If you want you can also use return await so the bot will no longer proceed.
You can also build in an error handler for different things. Have a look at the following code:
#mute.error
async def mute_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send("No member given")
You have to put the code under the actual mute command code.

Programming a Discord bot in Python- How do I make a mute command?

I'm trying to make a mute command for my bot, here's my code:
#client.command(pass_context = True)
async def mute(ctx, member: discord.Member):
role = discord.utils.get(member.guild.roles, name='Muted')
await client.add_roles(member, role)
embed=discord.Embed(title="User Muted!", description="**{0}** was muted by **{1}**!".format(member, ctx.message.author), color=random.choice(colors))
await ctx.send(embed=embed)
When triggered, it gives me this error: AttributeError: 'Bot' object has no attribute 'add_roles'. I also tried using ctx.add_roles, but that won't work either.
I'm new to programming, so any insight would be greatly appreciated.
As you can see in the error, discord.ext.commands.Bot object has no attribute add_roles, but discord.Member has.
#client.command(pass_context = True)
async def mute(ctx, member: discord.Member):
role = discord.utils.get(member.guild.roles, name='Muted')
await member.add_roles(role)
embed=discord.Embed(title="User Muted!", description="**{0}** was muted by **{1}**!".format(member, ctx.message.author), color=random.choice(colors))
await ctx.send(embed=embed)
Reference
discord.Member.add_roles
As others have said you need to use member.add_roles() but you should also get the role by it's ID with ctx.guild.get_role() because right now you are searching for the role in the roles the Member already has.
You can get this ID by enabling Developer Mode in User Settings > Appearance, then right click the Mute role in the server roles > copy ID.
#client.command(pass_context = True)
async def mute(ctx, member: discord.Member):
role = ctx.guild.get_role(<mute_role_id>)
await member.add_roles(role)
embed=discord.Embed(title="User Muted!", description="**{0}** was muted by **{1}**!".format(member, ctx.message.author), color=random.choice(colors))
await ctx.send(embed=embed)
In the newer versions of Discord.py, add_roles is a method on member objects, not the bot object. This is why you're seeing "'Bot' object has no attribute 'add_roles'".
You need to use await member.add_roles(role)

Discord.py Giving role

#client.command()
#commands.has_permissions(manage_messages=True)
async def mute(ctx, member: discord.Member):
try:
guild = ctx.guild
rolecreate = "MutedByCloudy"
await guild.create_role(rolecreate, colour=discord.Colour.red())
if member.guild_permissions > ctx.author.guild_permissions or member.guild_permissions.administrator:
await ctx.send("I can't mute that user. User probably has more perms than me or you")
else:
if member.id == 739424025205538817:
await ctx.send("Nice try. I can't mute myself.")
else:
role = get(member.guild.roles, name='MutedByCloudy')
await member.add_roles(role)
embed=discord.Embed(title="User Muted! :white_check_mark:", description=f"**{member}** was muted by **{ctx.message.author}**!", color=0x2f3136)
await ctx.send(embed=embed)
except:
await ctx.send(":x: Something happened. I don't know what.")
So i have this command that creates a role, and gives it to the user. But It doesnt create the role and doesnt throw any errors, can you guys help? The giving role part works but the creating role doesn't.
Well you aren't creating the role, you could try something like this:
role = discord.utils.get(ctx.guild.roles, name='MutedByCloudy')
if not role:
role = await ctx.guild.create_role(name='MutedByCloudy', reason='Role for muting, auto generated by Cloudy')
for channel in ctx.guild.channels:
await channel.set_permissions(role, send_messages=False,
read_message_history=False,
read_messages=False)
You could also add an try and except discord.Forbidden to handle permission errors

Categories

Resources