discord.py how to make a command has permissons - python

I am making a discord bot and have made a piece of code that mutes everybody in a voice channel. I want to make sure that only a Mod or someone with Administrator permissions can use this command.
Here is my code for my mute command:
#client.command()
async def vcmute(ctx):
vc = ctx.author.voice.channel
for member in vc.members:
await member.edit(mute=True)
await ctx.send('Mics are closed!')
And this is my unmute command (Which would use the same concept of only Administrator or Mod using it):
#client.command()
async def vcunmute(ctx):
vc = ctx.author.voice.channel
for member in vc.members:
await member.edit(mute=False)
await ctx.send('Mics are opened!')

To get permissions for the sender in his current channel you can use
perms = ctx.author.permissions_in(ctx.author.voice.channel). Then you can check if that user has muting permissions with
if perms.mute_members:
#whatever you want your command to do
else:
#no permission error msg

Use the has_permissions decorator
#client.command()
#commands.has_permissions(administrator=True) # Or whatever perms you want
async def vcmute(ctx):
...
# If you wanna send some message if the user doesn't have the needed permissions
#vcmute.error
async def vcmute_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send(f"You need {error.missing_perms} permissions to use this command.")

Related

Can someone tell me what i did wrong here discord.py dming system

I was was trying to get it to dm the user who used the command but it doesn't seem to work can someone explain what i did wrong?
#client.event
async def on_message(message):
if isinstance(message.channel, discord.DMChannel):
channel = client.get_channel(942903733262626836)
await channel.send(f"{message.author} sent:\n```{message.content}```")
await client.process_commands(message)
#client.command()
async def feedback(ctx, user: discord.User, *, message='Hello please let us know about your about your feedback.'):
message = message
await user.send(message)
await ctx.send('DM Sent Succesfully.')
If feedback is a command that the user has to write (ex. !feedback) then you can just use ctx.author.send() which will send the dm to the author of the command. What are you trying to do with the on_message function?
#client.command()
async def feedback(ctx, message='Hello please let us know about your about your feedback.'):
await ctx.author.send(message)
await ctx.send('DM Sent Succesfully.')
You made user an argument to the command & you're DMing that person instead of the author.
async def command(ctx, user: discord.User, ...)
must be used as
!command #user
where #user pings the user that will be DM'ed.
You said you wanted to DM the person that used the command, which is the author, so you should DM them instead. You can access the author using ctx.author, and DM them the same way you just DM'ed the other user.
# Instead of
await user.send(...)
# use
await ctx.author.send(...)

Send error message when the user don't have perm (Discord Bot)

I'm making a discord bot, and wanna add a ""you dont have permission to use this command" message when te user don't have perm to use a command
I tryed for a few hours (with if's and else's) and can't find a way
#commands.command(aliases=['limpar'])
#commands.has_permissions(manage_messages=True)
async def clear(self, ctx, amount : int):
await ctx.channel.purge(limit=amount+1)
embed=discord.Embed(title="", url="", description=f"Squeaky clean!!!", color=0x000000)
await ctx.send(embed=embed, delete_after=2)
print('Squeaky clean!!!')
You can use a error handler event, it will be for all the commands.
#commands.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send(f"You do not have {commands.MissingPermissions.missing_perms} to run this command.")
commands.MissingPermissions

How do I delete a dm message that was sent by my discord bot

I did a script where you can send a message to a specific dm using my discord bot
#client.command(pass_context=True)
async def dm(ctx, user: discord.User, *, message=None):
await ctx.channel.purge(limit=1)
message = message
await user.send(message)
But how am I to make a script that can delete all messages that was sent by the bot in a specific dm
You can iterate over the DMChannel.history() and delete the messages whose author is your client:
#client.command()
async def clear_dm(ctx, user: discord.User):
async for message in user.dm_channel.history():
if message.author == client.user:
await message.delete()
Keep in mind that you need read_message_history and manage_messages permissions respectively, otherwise a Forbidden exception will be raised.
Also, maybe it's a good idea to catch HTTPException as well, to continue the iteration if the removal of any message fails for some reason.
Never mind I fixed it. Here is the script
#client.command()
async def cleardm(ctx, user: discord.User):
#await ctx.channel.purge(limit=1) remove '#' if you want the bot to delete the command you typed in the discord server
async for message in user.history():
if message.author == client.user:
await message.delete()

Discord.py massban

I've been working really hard with a massban command but it doesn't work. Here is the code. Basically it doesn't do anything and I get no error in console.
#bot.command()
async def massban(ctx, user: discord.User ):
for user in ctx.guild.members:
try:
await user.ban(user)
except:
pass
If you want you can ban all members that your bot can see.
#bot.command()
async def massban(ctx):
for member in bot.get_all_members():
await member.ban()
It seems like the problem is here:
await user.ban(user)
You do not need to mention the user in the brackets. It is enough if you remove the "argument":
#bot.command()
async def massban(ctx):
for user in ctx.guild.members:
try:
await user.ban()
except:
pass
This command bans all the user from your guild.
so, you need a guild your bot can see.
#bot.command()
async def massban(ctx):
await ctx.message.delete()
guild = ctx.guild
for user in ctx.guild.members:
try:
await user.ban()
except:
pass

Mute command not working, no error message; Discord python

I am trying to create a mute command for my Discord bot. I typed all the code out and I am pretty sure it should be working. However whenever I type N?mute nothing happens and subsequently nothing shows up in my command prompt. No error message, no nothing. I tried putting a print just after the async def mute() and that didn't show up either.
I have the following code:
import random
import discord
from discord.ext import commands
import urllib.parse
import os
import pymongo
from pymongo import MongoClient
client = commands.Bot(command_prefix='N?')
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.command()
#commands.has_role(743487766796697720)
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)
embed=discord.Embed(title="User Muted!", description="**{0}** was muted by **{1}**!".format(member, ctx.message.author), color=0xff00f6)
await message.channel.send(embed=embed)
else:
await member.add_roles(role)
embed=discord.Embed(title="User Muted!", description="**{0}** was muted by **{1}**!".format(member, ctx.message.author), color=0xff00f6)
await message.channel.send(embed=embed)
#mute.error
async def mute_error(ctx, error):
if isinstance(error, commands.MissingRole):
embed=discord.Embed(title="Permission Denied.", description="You don't have permission to use this command.", color=0xff00f6)
await message.channel.send(embed=embed)
#mute.error
async def mute_error(ctx, error):
if isinstance(error, commands.BadArgument):
embed=discord.Embed(title="Permission Denied.", description="That is not a valid member.", color=0xff00f6)
await message.channel.send(embed=embed)
I tried making a kick command berore but after searching stackoverflow and dozen other websites to figure out why it didn't work, I gave up. Now I'm wondering why both client.commands have not worked so far. So far I have only used client.listen() and client.event() which both worked well. I don't know if it's simply an oversight or me doing something dumb but I'm at a loss right now. I'm fairly new to Discord.py so excuse my lack of skill :)
You dont have a message variable. Instead of message write ctx.
So
await message.channel.send(embed=embed)
should become
await ctx.channel.send(embed=embed)
To see the errors on your command prompt maybe first remove all you error commands. When I was making my bot, the error commands did not let me see errors on the command prompt. Maybe try that.
I fixed it by changing a bot.event to a bot.listen! Make sure you keep your events limited and mostly use listens and commands. I think having more than 1 bot.event killed my code. Thanks to everyone for their input and I hope this fixes it for whoever comes from Google :)

Categories