Exception Fixing ban command discord.py - discord.py

I recently made a ban command for my bot but its not working, can anyone help? whenever i do !ban it just gives the exception and member.kick is blacked out, also i user kick insted of ban because of debugging purposes
Thanks!
Code:
#commands.command()
async def ban(self, ctx, member:nextcord.Member,*, reason="No Reason Provided"):
try:
if reason == None:
embed = nextcord.Embed(title="Member Banned!", description=f"{member.mention} has been banned from '{ctx.guild}'\n Reason: `No Reason Provided`", colour=BLUE_COLOUR)
embed.timestamp = datetime.datetime.utcnow()
embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/942086556980764722/967720168199426069/Ban_Command.gif")
await ctx.reply(embed=embed)
await member.kick(reason=reason)
else:
author = ctx.message.author.name
SendConfirmation = nextcord.Embed(title="Member Banned! ", description=f"Banned: {member.mention}\n Moderator: **{author}** \n Reason: **{reason}**", color=GOLD_COLOUR)
SendDM = nextcord.Embed(title="You Have been Banned", colour=BLUE_COLOUR)
embed.add_field(name="Server Name", value=f"{ctx.guild.name}", inline=True)
embed.add_field(name="Reason", value=f"{reason}", inline=True)
embed.timestamp = datetime.datetime.utcnow()
await member.send(embed=SendDM)
await ctx.reply(embed=SendConfirmation)
except Exception:
ErrorEmbed = nextcord.Embed(title="Something Went Wrong", description="There was an error trying to perform this command.", colour=ERROR_COLOUR)
ErrorEmbed.timestamp = datetime.datetime.utcnow()
await ctx.reply(embed=ErrorEmbed)
return

There were 2 issues with the code:
Your reason argument was never none because it was set by default on "No Reason Provided" so you would never use the if statement
you created the variable SendDM and then used the embed function on a new variable that was never defined (called embed)
#commands.command()
async def ban(self,ctx, member:nextcord.Member,*, reason=None):
if reason == None:
embed = nextcord.Embed(title="Member Banned!", description=f"{member.mention} has been banned from '{ctx.guild}'\n Reason: `No Reason Provided`")
embed.timestamp = datetime.datetime.utcnow()
embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/942086556980764722/967720168199426069/Ban_Command.gif")
await ctx.reply(embed=embed)
await member.ban(reason=reason)
else:
author = ctx.message.author.name
SendConfirmation = nextcord.Embed(title="Member Banned! ", description=f"Banned: {member.mention}\n Moderator: **{author}** \n Reason: **{reason}**")
SendDM = nextcord.Embed(title="You Have been Banned")
SendDM.add_field(name="Server Name", value=f"{ctx.guild.name}", inline=True)
SendDM.add_field(name="Reason", value=f"{reason}", inline=True)
SendDM.timestamp = datetime.datetime.utcnow()
await member.send(embed=SendDM)
await ctx.reply(embed=SendConfirmation)
await member.ban(reason=reason)
This code should work, I tested it on my machine, I took away embed colors and the try and except block but you can add them back.
One last thing, I suggest to remove the try and except block and handle errors with actual error handlers. You can find how to use them in the documentation of the nextcord library.

Related

I want to improve my kick command in discord.py

I have made a bot in discord.py which has a kick command. But I want the bot to say "please tell me whom to kick" when someone uses the command without saying whom to kick. I mean if someone uses the kick command without mentioning whom to kick, the bot will say "please tell me whom to kick".
I am trying to make a good bot so please help me.
async def kick(ctx, member : discord.Member, *, reason=None):
if (ctx.message.author.permissions_in(ctx.message.channel).kick_members):
await member.kick(reason=reason)
await ctx.send(f"{member.mention} has successfully been kickded for {reason}")
if not (ctx.message.author.permissions_in(ctx.message.channel).kick_members):
await ctx.send("You don't perms to play football with Araforce and kick them. Sed")
if not user:
await ctx.message.delete()
msg = await ctx.send("You are a bit idiot, don't you know I can't kick anyone if you don't tell whom to kick? Tell me whom to kick and the go away.")
await sleep(4.7)
await msg.delete()
return
if not reason:
await ctx.message.delete()
msg2 = await ctx.send("Hmm.. Why I will kick him? Specify a reason please.")
await sleep(4.7)
await msg2.delete()
return```
async def kick(ctx, user: discord.User = None, *, reason=None):
if not user:
await ctx.message.delete()
msg = await ctx.send("You must specify a user.")
await sleep(4.7)
await msg.delete()
return
if not reason:
await ctx.message.delete()
msg2 = await ctx.send("You must specify a reason.")
await sleep(4.7)
await msg2.delete()
return
I changed ifs to the error handler, which is necessary because if you won't pass one of the arguments (user or reason) you would get an error.
Full code:
#client.command()
async def kick(ctx, member: discord.Member, *, reason): #if you will change "member" and "reason" to something else remember to also change it in error handler
await member.kick(reason=reason)
await ctx.send(f"{member.mention} has successfully been kicked for {reason}")
#kick.error #cool mini error handler
async def kick_error(ctx, error):
if isinstance(error, discord.ext.commands.errors.MissingRequiredArgument):
if str(error) == "member is a required argument that is missing.": #change this if you changed "member"
await ctx.message.delete()
await ctx.send("You are a bit idiot, don't you know I can't kick anyone if you don't tell whom to kick? Tell me whom to kick and then go away.", delete_after=4.7) #you don't have to use "await sleep" you can use "delete_after" parameter
elif str(error) == "reason is a required argument that is missing.": #change this if you changed "reason"
await ctx.message.delete()
await ctx.send("Hmm.. Why I will kick him? Specify a reason please.", delete_after=4.7)
elif isinstance(error, discord.ext.commands.errors.MissingPermissions):
await ctx.send("You don't have perms to play football with Araforce and kick them. Sed")
Discord error handling example

In embed.fields.0.value: This field is required error

#client.command()
async def hug(ctx, *, user: discord.Member = None):
hug_embed = discord.Embed(title='-w- hug -w-', description='', color=0xafe8fa)
hug_embed.add_field(name=f'{ctx.author.mention} hugged {user.mention}', value='', inline=False)
if user:
await ctx.message.channel.send(embed=hug_embed)
else:
await ctx.send('hug someone ;n;')
I got the error of
In embed.fields.0.value: This field is required
how do i mention another person, with it sending in an embed response
As the error suggests you need to put something in the value of the field. Right now you have '', try with 'something else'

Discord.py Verification System

I am making a verification system where if you type !verify "1. John 2. Mr. Teacher 3. Somewhere 4. Freshman 5. The Cool Mascot" it will send an embed in a channel looking like this: https://gyazo.com/ab808bafcd4a5f3ed05f63e007da20c1.
If someone reacts with the checkmark I want to dm the user saying that they have been accepted and if they get denied it will send a dm saying they have been denied but I seem to not get a dm when reacting and they do not get the Member role right after, and there are no tracebacks.
Code:
#bot.command(pass_context=True)
async def verify(ctx, message):
logem = discord.Embed(color=discord.Color.red())
logem.set_author(name=f"Verification Request!")
logem.add_field(name="User", value=f"{ctx.author.mention}")
logem.add_field(name="Application", value=f"{message}")
logem.set_footer(text=f"React with ✅ to accept the application and ❌ to deny the application",
icon_url="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/Exclamation_mark_red.png/50px-Exclamation_mark_red.png")
logemlog = bot.get_channel(820840787645956123)
msg = await logemlog.send(embed=logem)
await msg.add_reaction('✅')
await msg.add_reaction('❌')
async def on_raw_reaction_add(payload):
msgid = await ctx.fetch_message(msgID)
ourMessageID = msgid
if ourMessageID == payload.message_id:
member = payload.member
guild = member.guild
emoji = payload.emoji.name
if emoji == '✅':
role = discord.utils.get(guild.roles, name="Member")
print ('Accepted Someones Application')
em = discord.Embed(color=discord.Color.red())
em.set_author(name="Verified!")
em.set_footer(text=f"You Have Been Accepted Into The Official WHS Discord Server!",
icon_url="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/Exclamation_mark_red.png/50px-Exclamation_mark_red.png")
await member.send("You have been accepted!")
await member.add_roles(role)
elif emoji == '❌':
em = discord.Embed(color=discord.Color.red())
em.add_field(name="Denied!", value=f"{message}")
em.set_footer(text=f"You Have Been Denied Access Into The Official WHS Discord Server!",
icon_url="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/Exclamation_mark_red.png/50px-Exclamation_mark_red.png")
await ctx.member.send("You have been Denied!")
Use this instead of async def on_raw_reaction_add:
def check(reaction, user):
return reaction.emoji in ['✅', '❌'] and user == ctx.author
while True:
try:
reaction, user = await bot.wait_for('reaction_add', check=check)
except Exception as e:
print(e)
else:
if reaction.emoji == '✅':
role = discord.utils.get(guild.roles, name="Member")
print ('Accepted Someones Application')
em = discord.Embed(color=discord.Color.red())
em.set_author(name="Verified!")
em.set_footer(text=f"You Have Been Accepted Into The Official WHS Discord Server!",
icon_url="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/Exclamation_mark_red.png/50px-Exclamation_mark_red.png")
await member.send("You have been accepted!")
await member.add_roles(role)
if reaction.emoji == '❌':
em = discord.Embed(color=discord.Color.red())
em.add_field(name="Denied!", value=f"{message}")
em.set_footer(text=f"You Have Been Denied Access Into The Official WHS Discord Server!",
icon_url="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/Exclamation_mark_red.png/50px-Exclamation_mark_red.png")
await ctx.member.send("You have been Denied!")
Test it and let me know if it doesn't work.

How to make lockdown and unlock commands discord.py

Im trying to make a lockdown and unlock command using discord.py rewrite. I have the code but it doesn't work at all. Can someone help me?
#client.command()
#commands.has_permissions(manage_channels = True)
async def lockdown(ctx):
await ctx.channel.set_permissions(ctx.guild.default_role, send_messages=False)
await ctx.send( ctx.channel.mention + " ***is now in lockdown.***")
#client.command()
#commands.has_permissions(manage_channels=True)
async def unlock(ctx):
await ctx.channel.set_permissions(ctx.guild.default_role, send_messages=True)
await ctx.send(ctx.channel.mention + " ***has been unlocked.***")
I found out the issue. The commands work on every other server except for the one I'm testing it on. It turns out that That server makes everyone admin as soon as they join.
Try this, to enable the necessary bot permissions:
#client.command()
#has_permissions(manage_channels=True)
async def lockdown(ctx):
await ctx.channel.set_permissions(ctx.guild.default_role,send_messages=False)
await ctx.send( ctx.channel.mention + " ***is now in lockdown.***")
#client.command()
#has_permissions(manage_channels=True)
async def unlock(ctx):
await ctx.channel.set_permissions(ctx.guild.default_role, send_messages=True)
await ctx.send(ctx.channel.mention + " ***has been unlocked.***")
this is my unlock command hope it helps you
you have to use overwrites TextChannel.set_permissions
#client.command()
async def unlock(ctx, role:Optional[Role], channel:Optional[TextChannel]):
role = role or ctx.guild.default_role
channel = channel or ctx.channel
async with ctx.typing():
if ctx.author.permissions_in(channel).manage_permissions:
await ctx.channel.purge(limit=1)
overwrite = channel.overwrites_for(role)
overwrite.send_messages = True
await channel.set_permissions(role, overwrite=overwrite)
unlock_embed = discord.Embed(
title= ("UNLOCKED"),
description= (f"**{channel.mention}** HAS BEEN UNLOCKED FOR **{role}**"),
colour=0x00FFF5,
)
unlock_embed.set_footer(text=ctx.author.name, icon_url=ctx.author.avatar_url)
unlock_embed.set_author(name=client.user.name, icon_url=client.user.avatar_url)
unlock_embed.set_thumbnail(url=ctx.guild.icon_url)
await ctx.channel.send(embed=unlock_embed, delete_after=10)
print("unlock")
else:
error3_embed=discord.Embed(title="ERROR", description="YOU DONT HAVE PERMISSION", colour=0xff0000)
error3_embed.set_thumbnail(url='https://images.emojiterra.com/google/android-11/512px/274c.png')
error3_embed.set_footer(text=ctx.author.name, icon_url=ctx.author.avatar_url)
error3_embed.set_author(name=client.user.name, icon_url=client.user.avatar_url)
await ctx.channel.send(embed=error3_embed, delete_after=10)

Ban coroutine not executing [no errors] | Discord.py

I'm creating a new bot (my third time now, but it's been a while) and I am creating a simple ban command. It is line-for-line the same as my other commands, with the addition of the #commands.has_permissions() decorator and an embed to display the ban. However, after adding some prints to show where it gets to, it doesn't make it past await user.ban().
# ---BAN---
#client.command(name="ban", pass_ctx=True)
#commands.has_permissions(ban_members=True)
async def ban(ctx, user: discord.User=None, *, reason: str=None):
if not user:
await ctx.send("Specify a user")
return
embed = discord.Embed (
color = discord.Color.magenta()
)
embed.add_field(name=f"{user} was banned!", value=f"For reason: {reason}", inline=False)
await user.ban()
await ctx.send(embed=embed)
#ban.error
async def ban_error(ctx, error):
if isinstance(error, BadArgument):
await ctx.send("Please specify a **valid** user!")
No error is thrown, but it only gets to await user.ban() before just stopping. Is my user wrong somehow, or did I make an obvious mistake?
'User' object has no attribute 'ban' , instead you need to pass a member object:
async def ban(ctx, user: discord.Member=None, *, reason: str=None):
And you're not getting any errors because #ban.error is catching them but is only handling the BadArgument exception while the rest are ignored.

Resources