unban command discord.py rewrite - python

I need an efficent discord.py command for unban users by their tag, not their name and discriminator. how i can do?
This is the code that I made and it works with *unban name#1234.
#client.command()
#commands.has_any_role(702909770956406885, 545323952428417064, 545323570587369472)
async def unban(ctx, *, member):
banned_user = await ctx.guild.bans()
member_name, member_discriminator = member.split("#")
for ban_entry in banned_user:
user = ban_entry.user
if (user.name, user.discriminator) == (member_name, member_discriminator):
await ctx.guild.unban(user)
embed = discord.Embed(title="Fatto!", description=f"Ho sbannato {user.mention}!", color=discord.Color.green())
await ctx.send(embed=embed)
return
How can i make it work with tags? I know you can't directly tag a banned user but with his id you can do it. Thank you for answers!

Hope this helps
from discord.ext.commands import has_permissions
#bot.command()
#has_permissions(ban_members=True)
async def unban(ctx, userId: discord.User.id):
user = get(id=userId)
await ctx.guild.unban(user)

Use the member object as a parameter in your unban function.
Ex:
#client.command()
#commands.has_any_role(702909770956406885, 545323952428417064, 545323570587369472)
async def unban(ctx, *, member: discord.Member):
await ctx.guild.unban(member)
Then in discord you could execute the command by mentioning the user.
Ex: *unban #aleee

#client.command(description="bans a user with specific reason (only admins)") #ban
#commands.has_permissions(administrator=True)
async def ban (ctx, member:discord.User=None, reason =None):
try:
if (reason == None):
await ctx.channel.send("You have to specify a reason!")
return
if (member == ctx.message.author or member == None):
await ctx.send("""You cannot ban yourself!""")
else:
message = f"You have been banned from {ctx.guild.name} for {reason}"
await member.send(message)
await ctx.guild.ban(member, reason=reason)
print(member)
print(reason)
await ctx.channel.send(f"{member} is banned!")
except:
await ctx.send(f"Error banning user {member} (cannot ban owner or bot)")

Related

discord.py member.edit(nick=nickname) not working

I'm making a Discord bot using discord.ext. I want to change the users nickname on the command nick.
For that I wrote following code:
from discord.ext import commands
import discord
# set prefix as "w!"
bot = commands.Bot(command_prefix="w!")
# do stuff when certain error occurs
#bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.BotMissingPermissions):
await ctx.send("Error: Bot missing permissions.")
if isinstance(error, commands.CommandNotFound):
await ctx.send("Error: The command was not found")
if isinstance(error, commands.MissingPermissions):
await ctx.send("Error: You don't have permission to do that.")
#bot.command()
# check if the user has the permission to change their name
#commands.has_permissions(change_nickname=True)
async def nick(ctx, member: discord.Member, *, nickname):
await member.edit(nick=nickname)
await ctx.send(f"Nickname was changed to {member.mention}.")
# reset the nickname if no new name was given
#nick.error
async def nick_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
member = ctx.author
await member.edit(nick=None)
await ctx.send(f"Reset nickname to {member.mention}.")
bot.run("TOKEN")
When I enter w!nick test name in Discord it doesn't respond to the message and doesn't change my nickname. But when I just enter w!nick it resets my nickname.
Thanks to #Mr_Spaar for helping.
The solution:
#bot.command()
#commands.has_permissions(change_nickname=True)
async def nick(ctx, *, nickname):
member = ctx.author
await member.edit(nick=nickname)
await ctx.send(f"Nickname was changed to {member.mention}.")
Does this help?
client.command(pass_context=True)
#commands.has_permissions(change_nickname=True)
async def hnick(ctx, member: discord.Member, nick):
await member.edit(nick=nick)
await ctx.send(f'Nickname was changed for {member.mention} ')

Mute and unmute command in discord.py

I am trying to make a mute command. The code below doesn't give any errors, but it doesn't work.
#client.command()
#commands.has_permissions(manage_messages=True)
async def mute(ctx, member : discord.Member) :
guild = ctx.guild
user = member
global mute_role
for role in guild.roles:
if role.name == "MUTED" :
if role in user.roles:
await ctx.send(f'**{user.name} is already muted!**')
else:
await member.add_roles(role)
await ctx.send(f"{member.mention} has been muted by {ctx.author} ")
for role in guild.roles:
if role.name == "MUTED" not in guild.roles:
mute_role = await guild.create_role(name="MUTED")
perms = discord.PermissionOverwrite(send_messages=False)
for channel in guild.text_channels :
await channel.set_permissions(mute_role, overwrite=perms)
if role.name == "MUTED" not in user.roles:
await member.add_roles(mute_role)
await ctx.send(f'{member.mention} has been muted by {ctx.author.mention}')
return
I have tried multiple methods and "played around" with the variables but I have not managed to make a functional command. I would also like to make a timed mute command, but first I need to make this work.
I have searched for other mute commands on StackOverflow but I could not find anything functional or decent.
Also, if I am able to make this work, how would I go about making an unmute command too?
Well I know it is probably too late, but here is my mute command:
#client.command()
#commands.has_permissions(kick_members=True)
async def mute(ctx, member: discord.Member):
role = discord.utils.get(ctx.guild.roles, name="Muted")
guild = ctx.guild
if role not in guild.roles:
perms = discord.Permissions(send_messages=False, speak=False)
await guild.create_role(name="Muted", permissions=perms)
await member.add_roles(role)
await ctx.send("Successfully created Muted role and assigned it to mentioned user.")
else:
await member.add_roles(role)
await ctx.send(f"Successfully muted ({member})")
#mute.error
async def mute_error(ctx, error):
if isinstance(error, commands.MissingRole):
await ctx.send("You don't have the 'staff' role")
#mute.error
async def mute_error(ctx, error):
if isinstance(error, commands.BadArgument):
await ctx.send("That is not a valid member")
I, too, need an unmute command.

Discord.py (rewrite) mute command always returns the same response

I'm currently trying to build a discord.py mute command that sends an embed asking if the user is sure that they want to mute, and then when a reaction is added the mute is carried out and the embed is edited. I have run into some errors trying to do so.
#bot.command()
#commands.has_permissions(manage_guild=True)
async def mute(ctx, message, member: discord.Member = None):
guild = ctx.guild
user = member
if member == None:
await ctx.send(f'**{ctx.message.author},** please mention somebody to mute.')
return
if member == ctx.message.author:
await ctx.send(f'**{ctx.message.author},** you cannot mute yourself, silly.')
return
for role in guild.roles:
if role.name == "Muted":
if role in user.roles:
await ctx.send("**{}** is already muted.".format(user))
return
embedcheck=discord.Embed(title="Mute", colour=0xFFD166, description=f'Are you sure you want to mute **{user}?**')
embeddone=discord.Embed(title="Muted", colour=0x06D6A0,description=f'The mute has been done. **{user}** cannot talk in any channels anymore.')
embedfail=discord.Embed(title="Not Muted",colour=0xEF476F,description=f'The mute did not carry out as I did not receive a reaction in time.')
msg = await ctx.send(embed=embedcheck)
await message.add_reaction('✅','❌')
try:
def check(rctn, user):
return user.id == ctx.author.id and str(rctn) == '✅'
reaction, user = await bot.wait_for('reaction_add', timeout=60.0, check=check)
except asyncio.TimeoutError:
await msg.edit(embed=embedfail)
else:
for role in guild.roles:
if role.name == "Muted":
await member.add_roles(role)
await msg.edit(embed=embeddone)
When I run the command I always get the same output, "...please mention somebody to mute," even though I have mentioned somebody. When I don't mention anybody, I get the error
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: message is a required argument that is missing.
Leave out message in async def mute(ctx, message, member: discord.Member = None) and change await message.add_reaction(...) to await msg.add_reaction(...).
#bot.command()
#commands.has_permissions(manage_guild=True)
async def mute(ctx, member: discord.Member = None):
guild = ctx.guild
user = member
if member == None:
await ctx.send(f'**{ctx.message.author},** please mention somebody to mute.')
return
if member == ctx.message.author:
await ctx.send(f'**{ctx.message.author},** you cannot mute yourself, silly.')
return
for role in guild.roles:
if role.name == "Muted":
if role in user.roles:
await ctx.send("**{}** is already muted.".format(user))
return
embedcheck=discord.Embed(title="Mute", colour=0xFFD166, description=f'Are you sure you want to mute **{user}?**')
embeddone=discord.Embed(title="Muted", colour=0x06D6A0,description=f'The mute has been done. **{user}** cannot talk in any channels anymore.')
embedfail=discord.Embed(title="Not Muted",colour=0xEF476F,description=f'The mute did not carry out as I did not receive a reaction in time.')
msg = await ctx.send(embed=embedcheck)
await msg.add_reaction('✅')
await msg.add_reaction('❌')
try:
def check(rctn, user):
return user.id == ctx.author.id and str(rctn) == '✅'
reaction, user = await bot.wait_for('reaction_add', timeout=60.0, check=check)
except asyncio.TimeoutError:
await msg.edit(embed=embedfail)
else:
for role in guild.roles:
if role.name == "Muted":
await member.add_roles(role)
await msg.edit(embed=embeddone)
You mentioned a user that went to message instead of member. Not mentioning anyone leaves message empty and sends you an error because it is a required argument.
I didn't check if it will mute but this should fix your MissingRequiredArgument error.

Discord mute command

I'm currently trying to make a discord bot with the ability to .mute a user. I have created this script so far that allows people with a "staff" role to run the command, and gives the tagged user a "Muted" role. It also creates one if it doesn't exist already. The problem is the code below does not work. It doesn't say anything in the console but if you have the staff role and you run the command nothing happens.
#commands.has_role("staff")
async def mute(ctx, member: discord.Member=None):
guild = ctx.guild
if (not guild.has_role(name="Muted")):
perms = discord.Permissions(send_messages=False, speak=False)
await guild.create_role(name="Muted", permissions=perms)
role = discord.utils.get(ctx.guild.roles, name="Muted")
await member.add_roles(role)
print("🔨 "+member+" was muted.")
if (not member):
await ctx.send("Please specify a member to mute")
return
#mute.error
async def mute_error(ctx, error):
if isinstance(error, commands.CheckFailure):
await ctx.send("You don't have the 'staff' role")
This specific line:
print("🔨 "+member+" was muted.")
Prints it in the terminal, or wherever you ran the command. Try await ctx.send Also, try using f-strings if you have version > 3.6 of Python. Also, your error is wrong.
#client.command()
#commands.has_role("staff")
async def mute(ctx, member: discord.Member):
role = discord.utils.get(ctx.guild.roles, name="Muted")
guild = ctx.guild
if role not in guild.roles:
perms = discord.Permissions(send_messages=False, speak=False)
await guild.create_role(name="Muted", permissions=perms)
await member.add_roles(role)
await ctx.send(f"🔨{member} was muted.")
else:
await member.add_roles(role)
await ctx.send(f"🔨{member} was muted.")
#mute.error
async def mute_error(ctx, error):
if isinstance(error, commands.MissingRole):
await ctx.send("You don't have the 'staff' role")
#mute.error
async def mute_error(ctx, error):
if isinstance(error, commands.BadArgument):
await ctx.send("That is not a valid member")

I need help making a discord py temp mute command in discord py

I got my discord bot to have a mute command but you have to unmute the user yourself at a later time, I want to have another command called "tempmute" that mutes a member for a certain number of minutes/hours/ or days, this is my code so far, how would I make a temp mute command out of this?
#mute command
#client.command()
#commands.has_permissions(kick_members=True)
async def mute(ctx, member: discord.Member=None):
if not member:
await ctx.send("Who do you want me to mute?")
return
role = discord.utils.get(ctx.guild.roles, name="muted")
await member.add_roles(role)
await ctx.send("ok I did it")
Similar to how you gave them a role to mute them, just add another parameter to take in how long you want them to be muted in seconds. Then you can use await asyncio.sleep(mute_time) before removing that role.
The code will look something like:
import asyncio
#mute command
#client.command()
#commands.has_permissions(kick_members=True)
async def mute(ctx, member: discord.Member=None, mute_time : int):
if not member:
await ctx.send("Who do you want me to mute?")
return
role = discord.utils.get(ctx.guild.roles, name="muted")
await member.add_roles(role)
await ctx.send("ok I did it")
await asyncio.sleep(mute_time)
await member.remove_roles(role)
await ctx.send("ok times up")
import asyncio
#commands.command()
#commands.has_permissions(manage_messages=True)
async def mute(ctx, member: discord.Member,time):
muted_role=discord.utils.get(ctx.guild.roles, name="Muted")
time_convert = {"s":1, "m":60, "h":3600,"d":86400}
tempmute= int(time[0]) * time_convert[time[-1]]
await ctx.message.delete()
await member.add_roles(muted_role)
embed = discord.Embed(description= f"✅ **{member.display_name}#{member.discriminator} muted successfuly**", color=discord.Color.green())
await ctx.send(embed=embed, delete_after=5)
await asyncio.sleep(tempmute)
await member.remove_roles(muted_role)

Categories