My discord.py bot Commands aren't working - python

none of my commands are working. the only thing functioning is the ping to respond bot event. asides from that nothing else is working. here is the code. please help me. ive import important dependencies and more but could not include it here
#
#bot.event
async def on_ready():
await bot.change_presence(status=discord.Status.online, activity=discord.Game("waiting for a ping"))
print("Bot is ready!")
#
#bot.event
async def on_member_join(member):
channel = bot.get_channel(956655371634753607)
embedVar = discord.Embed(title="Ariza Bot", color= 1974050)
embedVar.add_field(name="Welcome", value=f"{member} Thank you For joining our discord server!\nEnjoy!", inline=False)
await channel.send(embed=embedVar)
role = member.guild.get_role(956583850975297576)
await member.add_roles(role)
#
#bot.command(name='kick')
#commands.has_role("Administrator")
async def kick(self, ctx, member : commands.MemberConverter, *, reason=None):
await member.kick(reason=reason)
await ctx.send(f"{member} has been kicked, reason: {reason}")
#kick.error
async def kick_error(self, ctx, error):
if isinstance(error, MissingPermissions):
await ctx.send("You don't have permission to kick members.")
#
#bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send("You cant do that!")
#
#bot.command(name='clear')
#commands.has_permissions(manage_messages=True)
async def clear(ctx, amount: int):
authors = {}
async for message in ctx.channel.history(limit=amount + 1):
if message.author not in authors:
authors[message.author] = 1
else:
authors[message.author] += 1
await message.delete()
#
#bot.command(name='warn')
#commands.has_role('Admin')
async def warn(ctx,member: discord.Member,reason: str):
channel = await member.create_dm()
embedVar = discord.Embed(title="Ariza Bot", color= 1974050)
embedVar.add_field(name="Warning", value=f"Warned: You Were Warned by {ctx.author}\nTo: {member}\n Reason: {reason}\nSuggestion: Please Don't Do this Again.", inline=False)
await channel.send(embed=embedVar)
await ctx.channel.send(embed=embedVar)

I will only talk about the kick command for the answer now. But the logic applies to the other commands as well.
Try removing the if statements in the error handlers. Do this:
#kick.error
async def kick_error(ctx, error):
await ctx.send(error)
A response is only sent if commands.MissingPermissions is raised. If some other error is raised, nothing happens. So removing the if conditions will help you know what error is happening in the command. I think it is a TypeError since member is of type discord.Member and not of commands.MemberConverter. Also mention reason is of type str, since it is declared as None which can raise TypeError.

You need add this before your commands or else it wont read them
await bot.process_commands(message)

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.

Not able to ban members out of the server .py cog

#commands.command()
#commands.guild_only()
#commands.has_guild_permissions(ban_members=True)
async def ban(self, ctx, member: discord.Member, *, reason=None):
if member.top_role >= ctx.author.top_role:
await ctx.send(f"You can only ban members below your role.")
return
channel = self.bot.get_channel(864083000211406849)
embed = discord.Embed(title=f"{ctx.author.name} banned: {member.name}", description=reason)
await channel.send(embed=embed)
await ctx.send(embed=embed)
await member.send(f"You've been banned from : `{ctx.guild}` for `reason`: {reason}.")
await ctx.guild.ban(user=member, reason=reason)
#ban.error
async def ban_error(self,ctx, error):
if isinstance(error, commands.CheckFailure):
title=f"{ctx.author.mention} you do not have the required permission(s)/role(s) to run this command!"
await ctx.send(title)
So I want my code to basically kick a member that has left my server using their ID. Ive looked in to previous questions but it seems to be no help for me.
You are converting the member input to a discord.Member, which needs to be in the server. Instead convert it to a discord.User, who does not need to be in your server.
async def ban(self, ctx, member: discord.User, *, reason=None):
Please keep in mind that your top role lookup and comparison will not work when you use the discord.User, you will have to get the actual member beforehand, like this:
server_member = ctx.guild.get_member(member.id)
if server_member != None:
if server_member.top_role >= ctx.author.top_role:
await ctx.send(f"You can only ban members below your role.")
return
Also you will get an error trying to message someone who does not share a server with your bot, or has blocked your bot etc., I would just use a try/except block for this:
try:
await member.send(f"You've been banned from : `{ctx.guild}` for `reason`: {reason}.")
except discord.errors.Forbidden:
pass

My Bot Missing Permission module not working discord.py

The error module is BotMissionPermissions. I made an error to handle it but it's not sending it. I have removed the permission of my bot which is ban_members. The main problem is, it's not sending the error message in discord. it should send in discord like I don't have permission to perform this command. if you understand please help!
#client.command()
#commands.has_permissions(ban_members=True)
#commands.bot_has_permissions(ban_members=True)
async def ban(ctx, member: discord.Member=None, *, reason=None):
if not member:
await ctx.send("**Please specify a `user`.**")
return
if reason==None:
return await ctx.send("**Please include a** **`valid reason`.**")
if member == ctx.message.author:
return await ctx.send("**You cannot ban** **`yourself`**.")
await member.ban(reason=None)
await ctx.channel.send(f"****Banned**** **`{member}`** **for the following reason :** **`{reason}` **")
await member.send(f"you have been banned from: {ctx.guild.name}")
#ban.error
async def banerror(ctx, error):
if isinstance(error, commands.errors.CommandInvokeError):
await ctx.send("**I don't have the permsission `ban members`.**")
#ban.error
async def banerrogr(ctx, error):
if isinstance(error, commands.BotMissingPermissions):
await ctx.send("**I don't have the permission `ban members`.**")
#ban.error
async def ban_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
embed=discord.Embed(color=0xff8800)
embed.add_field(name="Access denied", value="You do not have permission to ban members :no_entry:", inline=True)
await ctx.send(embed=embed)
Maybe this program works for you
#client.command()
#commands.has_permissions(ban_members=True)
#commands.bot_has_permissions(ban_members=True)
async def ban(ctx, member: discord.Member=None, *, reason=None):
if not member:
await ctx.send("**Please specify a `user`.**")
return
if reason==None:
return await ctx.send("**Please include a** **`valid reason`.**")
if member == ctx.message.author:
return await ctx.send("**You cannot ban** **`yourself`**.")
await member.ban(reason=None)
await ctx.channel.send(f"****Banned**** **`{member}`** **for the following reason :** **`{reason}` **")
await member.send(f"you have been banned from: {ctx.guild.name}")
#ban.error
async def banerror(ctx, error):
error = getattr(error, "original", error)
if isinstance(error, discord.Forbidden):
return await ctx.send("**I don't have the permsission `ban members`.**")
#ban.error
async def ban_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
embed=discord.Embed(color=0xff8800)
embed.add_field(name="Access denied", value="You do not have permission to ban members :no_entry:", inline=True)
await ctx.send(embed=embed)

You do not have permission to use this command Discord.py Rewrite

I'm making a discord bot in discord.py rewrite and I am trying to use a line of code to detect if a user has permission to use a command.
I would like to display an error message if the user does not have the permissions. I'm using this code but it won't work.
#client.command(aliases=['c'])
async def clear(ctx,amount=2):
perms = ctx.author.permissions_in(ctx.channel)
if perms.manage_messages:
await ctx.channel.purge(limit = 1)
await ctx.channel.purge(limit = amount)
em = discord.Embed(description = f"Successfully cleared {amount} messages", color = discord.Colour.red())
await ctx.send(embed = em, delete_after=3)
else:
em = discord.Embed(title = "Permissions Required!", description = f"{ctx.author.name} You do not have the required Permissions to use this command", color = discord.Colour.red())
await ctx.send(embed=em)
I don't get any errors on my server when I use it. when my discord mods try to use it they get the error message even though they have permissions.
I know I can use #commands.has_permission() but I want an error msg.
You have to request the permissions in another/easier way. What you missed is guild.
Simply use:
if ctx.message.author.guild_permissions.manage_messages:
A full code could be:
#client.command(aliases=['c'])
async def clear(ctx, amount=2):
if ctx.message.author.guild_permissions.manage_messages:
await ctx.channel.purge(limit=1)
await ctx.channel.purge(limit=amount)
em = discord.Embed(description=f"Successfully cleared {amount} messages", color=discord.Colour.red())
await ctx.send(embed=em, delete_after=3)
else:
em = discord.Embed(title="Permissions Required!",
description=f"{ctx.author.name} You do not have the required Permissions to use this command",
color=discord.Colour.red())
await ctx.send(embed=em)
This is a very similar question for Can't get discord.py to raise an error if user doesn't have permissions to kick
#_kick.error
async def kick_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send(f'Please pass in all requirements {ctx.message.author.mention} :rolling_eyes:.')
if isinstance(error, commands.MissingPermissions):
await ctx.send(f"You dont have all the requirements {ctx.message.author.mention} :angry:")
OR
#client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send("You do not have the permissions required for this command.")
return
OR
#client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
embed=discord.Embed(title="ERROR", description="An error has been occured!", color=0xff0000)
embed.set_author(name="YourBot", icon_url="https://cdn.discordapp.com/attachments/877796755234783273/879295069834850324/Avatar.png")
embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/877796755234783273/879298565380386846/sign-red-error-icon-1.png")
embed.add_field(name="Error", value="You don't have the permissions required to use this command!", inline=True)
await ctx.send(embed=embed)
return
if isinstance(error, commands.MissingRequiredArgument):
embed=discord.Embed(title="ERROR", description="An error has been occured!", color=0xff0000)
embed.set_author(name="YourBot", icon_url="https://cdn.discordapp.com/attachments/877796755234783273/879295069834850324/Avatar.png")
embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/877796755234783273/879298565380386846/sign-red-error-icon-1.png")
embed.add_field(name="Error", value="You haven't passed the needed arguments for this command to run properly", inline=True)
embed.add_field(name="Possible Fix", value="use `{bot_prefix}help all` to list out all the command and check the proper usage of the command you used", inline=True)
await ctx.send(embed=embed)
return
In the last snippet is the code that i used and it is a combination of both the first and the second snippets in this answer

Discord.py ban command

if message.content.upper().startswith('!BAN'):
if "449706643710541824" in [role.id for role in message.author.roles]:
await
I have the base setup so only admins can ban. I want to make the ban command, but I'm not sure how to do it.
Try this:
import discord #Imports the discord module.
from discord.ext import commands #Imports discord extensions.
#The below code verifies the "client".
client = commands.Bot(command_prefix='pb?')
#The below code stores the token.
token = "Your token"
'''
The below code displays if you have any errors publicly. This is useful if you don't want to display them in your output shell.
'''
#client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send('Please pass in all requirements :rolling_eyes:.')
if isinstance(error, commands.MissingPermissions):
await ctx.send("You dont have all the requirements :angry:")
#The below code bans player.
#client.command()
#commands.has_permissions(ban_members = True)
async def ban(ctx, member : discord.Member, *, reason = None):
await member.ban(reason = reason)
#The below code unbans player.
#client.command()
#commands.has_permissions(administrator = True)
async def unban(ctx, *, member):
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split("#")
for ban_entry in banned_users:
user = ban_entry.user
if (user.name, user.discriminator) == (member_name, member_discriminator):
await ctx.guild.unban(user)
await ctx.send(f'Unbanned {user.mention}')
return
#The below code runs the bot.
client.run(token)
I hope this helps, good luck on your bot!
My ban command i got for my bot is , obviously dont keep the comment out for the ban part, I just put that there when i didn't know how to lock it to roles
#bans a user with a reason
#client.command()
#commands.has_any_role("Keyblade Master","Foretellers")
async def ban (ctx, member:discord.User=None, reason =None):
if member == None or member == ctx.message.author:
await ctx.channel.send("You cannot ban yourself")
return
if reason == None:
reason = "For being a jerk!"
message = f"You have been banned from {ctx.guild.name} for {reason}"
await member.send(message)
# await ctx.guild.ban(member, reason=reason)
await ctx.channel.send(f"{member} is banned!")
This is the best one
async def ban(ctx, member : discord.Member, reason=None):
"""Bans a user"""
if reason == None:
await ctx.send(f"Woah {ctx.author.mention}, Make sure you provide a reason!")
else:
messageok = f"You have been banned from {ctx.guild.name} for {reason}"
await member.send(messageok)
await member.ban(reason=reason)
I'd recommend to use discord.ext.commands to make commands, it's easier to use. The function to ban is discord.Client.ban(member, delete_message_days = 1). This is an example using discord.ext.commands:
bot = commands.Bot(command_prefix = "!")
#bot.command(pass_context = True)
async def ban(member: discord.Member, days: int = 1):
if "449706643710541824" in [role.id for role in message.author.roles]:
await bot.ban(member, days)
else:
await bot.say("You don't have permission to use this command.")
bot.run("<TOKEN>")
A ban command? It's actually very easy!
#commands.has_permissions(ban_members=True)
#bot.command()
async def ban(ctx, user: discord.Member, *, reason="No reason provided"):
await user.ban(reason=reason)
ban = discord.Embed(title=f":boom: Banned {user.name}!", description=f"Reason: {reason}\nBy: {ctx.author.mention}")
await ctx.message.delete()
await ctx.channel.send(embed=ban)
await user.send(embed=ban)
if you know kick you just need to change the user.kick into a user.ban because user.kick will kick a member so that means user.ban will ban a member.
According to Discord Official Documentation:-
#bot.command(name="ban", help="command to ban user")
#commands.has_permissions(ban_members=True)
async def _ban(ctx, member: discord.Member, *, reason=None):
""" command to ban user. Check !help ban """
try:
await member.ban(reason=reason)
await ctx.message.delete()
await ctx.channel.send(f'{member.name} has been banned from server'
f'Reason: {reason}')
except Exception:
await ctx.channel.send(f"Bot doesn't have enough permission to ban someone. Upgrade the Permissions")
#bot.command(name="unban", help="command to unban user")
#commands.has_permissions(administrator=True)
async def _unban(ctx, *, member_id: int):
""" command to unban user. check !help unban """
await ctx.guild.unban(discord.Object(id=member_id))
await ctx.send(f"Unban {member_id}")
#bot.command()
#commands.has_permissions(ban_members = True)
async def ban(ctx, member : discord.Member, *,reason=None):
if member == None or member == ctx.message.author:
await ctx.channel.send("You cannot ban yourself")
return
if reason == None:
reason = "For being a jerk!"
message = f"You have been banned from {ctx.guild.name} for {reason}"
await member.send(message)
await member.ban(reason=reason)
await ctx.send(f"{member} is banned!")
This is a ban command I use and it works perfectly fine for me. You have full permission to use the whole thing if you'd like.
async def ban(self, ctx, member:discord.Member, *, reason=None):
guild = ctx.guild
author = ctx.message.author
if author.guild_permissions.administrator == False:
embed4=discord.Embed(color=discord.Colour.red(), timestamp=datetime.datetime.utcnow(), title="Missing Permissions!", description="You don't have the required permissions to use this command!")
message1 = await ctx.send(embed=embed4)
sleeper=5
await asyncio.sleep(sleeper)
await message1.delete()
return
if member.guild_permissions.administrator and member != None:
embed=discord.Embed(color=discord.Colour.red(), title="Administrator", description="This user is an administrator and is not allowed to be banned.")
message2 = await ctx.send(embed=embed)
sleeper=5
await asyncio.sleep(sleeper)
await message2.delete()
return
if reason == None:
embed1=discord.Embed(color=discord.Colour.red(), title="Reason Required!", description="You must enter a reason to ban this member.")
message3 = ctx.send(embed=embed1)
sleeper=5
await asyncio.sleep(sleeper)
await message3.delete()
return
else:
guild = ctx.guild
await member.ban()
embed2=discord.Embed(color=discord.Colour.green(), timestamp=datetime.datetime.utcnow(), title="Member Banned", description=f"Banned: {member.mention}\n Moderator: **{author}** \n Reason: **{reason}**")
embed3=discord.Embed(color=discord.Colour.green(), timestamp=datetime.datetime.utcnow(), title=f"You've been banned from **{guild}**!", description=f"Target: {member.mention}\nModerator: **{author.mention}** \n Reason: **{reason}**")
message4 = await ctx.send(embed=embed2)
message5 = await ctx.send("✔ User has been notified.")
sleeper=5
await asyncio.sleep(sleeper)
await message4.delete()
await message5.delete()
await member.send(embed=embed3)

Categories

Resources