This Ban command does not work... How can I fix it? - discord.py

Here is my ban command! Everytime I want to ban someone it dosen't go thru else! To be honest it dosen't do anything other than the if! Please help!
#bot.command() #ban (verified works)
#commands.has_permissions(ban_members = True)
async def ban(ctx, member : discord.Member, *, reason = None):
if member == ctx.author or member.id == bot.user.id:
await ctx.send("Unfortunatly I cannot do that!")
return
else:
await ctx.send('Banned the member {}'.format(ctx.member.mention))
await member.ban(reason = reason)
await ctx.message.delete()

I recommend not using the role to check if the user can use the command, rather try using something like this:
#client.command()
#commands.has_permissions(ban_members=True)
async def ban(ctx, member : discord.Member,*,reason=None):
try:
await member.ban(reason=reason)
embed = discord.Embed(description=f":white_check_mark: succesfully banned {member.mention}!",color=0x00ced1)
await ctx.send(embed=embed)
except:
e2 = discord.Embed(description="You don't have permission to use this command",color=0xff0000)
await ctx.send(embed=e2)
This allows you to use the bot in multiple servers, who don't necessarily have the same roles, and also narrows it down to a certain permission.

Related

Advanced Discord Ban Command

i need a ban command that bans a member and than dms the banned member to inform them about it and when it happened.
I have a few problems:
What if the user's dms are closed?
It is not dming the banned member.
Also includes a perm ban like `!Ban
If anyone can help me out that will be great and i will greatly appricate it.
Thanks!
Like you want, this is example of simple ban member for discord.py
#client.command()
async def ban(ctx, member:discord.Member, *, reason=None)
await member.ban
await member.send(f"You've been banned by {ctx.author}\nReason = {reason}")
If you looking for .cogs version
#commands.command()
async def ban(self, ctx, member:discord.Member, *, reason = None)
await member.ban
await member.send(f"You've been banned by {ctx.author}\nReason = {reason}") ##this send message by DMs for banned member to tell him/her why getting banned
If you using discord-py-slash-command you can create new question
for the 1:
try:
await user.send("msg")
except discord.errors.Forbidden:
code here
I don't know if this can help you

trying to ban all but only attempting to ban the bot executing

I'm making a ban all function for proof of concept but whenever I execute it, the code only attempts to ban the bot that is running the command (and fails) and doesn't ban anyone one else, no error message either.
code:
async def ban(ctx):
await ctx.message.delete()
print(f"{colorama.Fore.CYAN}[+]{colorama.Fore.YELLOW} beginning test\n")
print(f"{colorama.Fore.CYAN}[+]{colorama.Fore.YELLOW} Banning has begun.\n")
try:
for member in ctx.guild.members:
await member.ban()
print(f"{colorama.Fore.CYAN}Smited {colorama.Fore.YELLOW}{member}.")
except:
print(f"{colorama.Fore.CYAN}Unable to ban {colorama.Fore.YELLOW}{member}.")
pass
Place your try statement around the ban function rather than around the for loop
async def ban(ctx):
await ctx.message.delete()
print(f"{colorama.Fore.CYAN}[+]{colorama.Fore.YELLOW} beginning test\n")
print(f"{colorama.Fore.CYAN}[+]{colorama.Fore.YELLOW} Banning has begun.\n")
for member in ctx.guild.members:
try:
await member.ban()
print(f"{colorama.Fore.CYAN}Smited {colorama.Fore.YELLOW}{member}.")
except:
print(f"{colorama.Fore.CYAN}Unable to ban {colorama.Fore.YELLOW}{member}.")
continue

is there another command should i use?

So, I can't use the "?roast" command and "?roast #(user)" at the same time...
#client.event
async def on_ready():
await client.change_presence(status=discord.Status.dnd, activity=discord.Game(' "?" Booe'))
print('Bot is ready to play!')
#client.command()
async def roast(ctx, member:discord.Member):
roast_messages = [
f'{ctx.message.author.mention}You are useless as the UEUE in Queue {member.mention}',
]
await ctx.send(random.choice(roast_messages))
There is always a way to solve that , discord gives us a way like this
#client.command()
async def roast(ctx, member:discord.Member=None):#None is if nothing is given then its None
if member == None:
member = ctx.author
roast_messages = [
f'{ctx.message.author.mention}You are useless as the UEUE in Queue {member.mention}',]
await ctx.send("imagine roasting yourself")#Your Choice Absolutely :)
await ctx.send(random.choice(roast_messages))
here if the member isnt specified , the function is called taking member as none , later gives the none value to the ctx.author itself (dont try to write ctx.author instead of none in the async def roast it gives error as ctx aint defined. also i forgot your roast messages wont make sense then so make sure to edit them too TY :)

Is there a way to record the specific user of a command for future use without a database?

So I'm working on a discord bot using discord.py and I'm trying to create a bot for the moderation team in a server, the bot will swap the 'Moderator' role with a 'Leave of absence' role for when they're not active, however the code I have come up with has a slight loopholing problem that I just can't figure out, the code for the commands is this
...
#client.command()
#commands.has_role('Moderator')
async def sl(ctx, member: discord.Member = None):
if not member:
member = ctx.author
loa = ctx.guild.get_role(848032714715561985)
mod = ctx.guild.get_role(848032880709074944)
await member.add_roles(loa)
await member.remove_roles(mod)
await ctx.send("I have filed your Leave, take care, we look forward to your return!")
#client.command()
async def sr(ctx, member: discord.Member = None):
if not member:
member = ctx.author
mod = ctx.guild.get_role(848032880709074944)
loa = ctx.guild.get_role(848032714715561985)
await member.add_roles(mod)
await member.remove_roles(loa)
await ctx.send("Welcome back!")
...
as you can see anyone could use the second command to just give themselves a moderator role, I can't set the second command to be moderator only use as the moderator will no longer have said role from using the first command, I'm racking my brain to think of a work around i.e. logging the command users id to a whitelist and having only those whitelisted id's be able to use the second command, I've done many googlesearches for this but have come back with no results, any suggestions would be appreciated, please forgive that this question is a bit lengthy and I'm still very new to coding in general so any help at all, even if you don't fully understand what I'm blabbering on about would be very appreciated, thank you.
Check for the loa role in the command (ex):
mod = None
for role in ctx.author.roles:
if role.id == 848032714715561985: mod = True
if mod:
#your code here
So from your question, I'm guessing that you would like to code basically a "storage" file and make sure the person on the leave of absence was previously a moderator.
What you could do is create a csv file, for example records.csv (in the same folder as your main .py file of course), and every time someone calls the sl command, the program will record the user that used it.
import csv
#client.command()
#commands.has_role('Moderator')
async def sl(ctx, member: discord.Member = None):
if not member:
member = ctx.author
loa = ctx.guild.get_role(848032714715561985)
mod = ctx.guild.get_role(848032880709074944)
await member.add_roles(loa)
await member.remove_roles(mod)
file = open("records.csv", "w")
file.writelines(str(ctx.author.id))
file.close()
await ctx.send("I have filed your Leave, take care, we look forward to your return!")
#client.command()
async def sr(ctx, member: discord.Member = None):
if not member:
member = ctx.author
mod = ctx.guild.get_role(848032880709074944)
loa = ctx.guild.get_role(848032714715561985)
found = False
with open('records.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
if row[0] == str(ctx.author.id):
found = True
break
if found = False:
await member.add_roles(mod)
await member.remove_roles(loa)
await ctx.send("Welcome back!")
else:
await ctx.send("We do not have history of you having a moderator role.")
Are you running the program through an online environment like Repl.it? If so, this may not be the best way to approach this problem since people would have access to your this records.csv file (which you may not care about but just in case). If you are running the program through your desktop file directories, then there should be no privacy concerns.

I want to make a command that deletes a channel discord.py

Here is what I got so far
It is saying that "await" is outside of async function and I am just confused on how to fix this. I copied part of the code from a giveaway command because that is my only source of Q&A code I have
#commands.has_permissions(administrator = True)
async def cdelete(ctx):
embed=discord.Embed(title = Which channel would you like to delete?)
await ctx.send(embed=embed)
answer = []
def check(m):
return m.author == cx.author and m.channel == ctx.channel
try:
await client.wait_for('message', timeout=15, check=check)
except asyncio.TimeoutError:
await ctx.send("Timeout. Please run the command again")
else:
answer.append(message.content)
try:
c_id= int(answer[0][2:-1])
await ctx.channel.delete
await ctx.send("Channel Deleted")
except:
await ctx.send("Thats not a valid channel!")```
If you just want a command you can make it a lot easier if you just execute a command with the channel name. You can have a look at the following:
#client.command()
#commands.has_permissions(administrator=True)
async def cdelete(ctx, channel_name):
"""Deletes a channel by name or ID."""
channel_id = int(''.join(i for i in channel_name if i.isdigit())) # Get channel ID
existing_channel = client.get_channel(channel_id) # Get channel ID with defined method
if existing_channel: # If channel with the name/ID exists
await existing_channel.delete()
else: # If the channel does not exist
await ctx.send(f'**No channel named `{channel_name}` was found.**')
We have a method to catch the channel ID and also pass that in as a valid argument. If the ID or channel name then exists we delete the channel.
You can here either mention the channel or pass in the ID.
Usage would be: cdelete #channel/ID.
If you want to avoid a long console output if you input no channel/ID/name you can build in an error handler:
#cdelete.error
async def cdelete_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send("You need to name a channel.")
The problem you have here is with the check() function. According to the doc you only can use await inside of an async function. To solve the problem change def check(m): into async def check(m):

Resources