How to check if a user has permission to use a command? Discordpy - discord

I am creating a custom help command and I have a problem. The default help command can somehow hide commands that are not available for a user that invoked the command. I was looking everywhere and I can't find any solution. I tried using hidden attribute of a command object but it is not working. The best solution would be a method like Member.can_use(command) that would return True or False but there is nothing like that in docs. Or at least I cannot find it.
Help would be appreciated.

Use the Command.can_run method, an example would be:
#bot.command()
async def can_it_run(ctx, command_name: str):
command = bot.get_command(command_name)
can_use = await command.can_run(ctx)
if can_use:
await ctx.send(f"You can use {command_name}")
else:
await ctx.send(f"You can't use {command_name}")
Sadly if a check raises an exception (like commands.guild_only) the exception(s) won't be suppressed, also if you want to check if someone else (not the invoker) can use the command you have to overwrite Context.author, a handy function would be:
async def can_run(ctx, command_name: str, member: discord.Member=None) -> bool:
command = bot.get_command(command_name)
if command is None: # Command doesn't exist / invalid command name
return False # Or raise an exception
if member is not None: # If a member is passed overwrite the attribute
ctx.author = member
try:
return await command.can_run(ctx)
except Exception:
return False
#bot.command()
async def can_it_run(ctx, command_name: str, member: discord.Member=None):
resp = await can_run(ctx, command_name, member)
await ctx.send(resp)

You could just check if the user countains a certain id by doing the following:
if (message.author.id == "WHoever ID1" || message.author.id == "Whoever ID2"):
#Do Something
If you want to put a bunch of ID's in then just do the following:
bool = false;
arr = ["ID1", "ID2", "ID3"]
for x in arr:
if(x == message.author.id):
bool = true;
if(bool):
#Do stuff
bool = false;
This is very vague code but it should be something similar to this

Related

Making an optional Argument in discord py

I want to make a code where if no one is mentioned then it should consider the person using it as a target.
Here is what I tried so far.
`#bot.command()
async def bal(ctx,*,member: discord.Member= None):
if member == None:
member = ctx.message.author
purse = db.get(member)
await ctx.send(purse)
`
But it's not working 🐱
first of all it should be
ctx.author
not
ctx.message.author
and u should put the * at the end I think
it should like sth like this
#bot.command()
async def bal(ctx,member: discord.Member= None,*):
if member == None:
member = ctx.author
purse = db.get(member)
await ctx.send(purse)
using * means that you are forcing the user to input keyword only arguements, but in your case it's not needed and i think is probably giving you an error since it's a bare *
so following on what bishoy did
#bot.command()
async def bal(ctx,member: discord.Member= None):
if member == None:
member = ctx.author
purse = db.get(member)
await ctx.send(purse)
this will remove the error, no need for the *

How do I get a list of all members in a discord server, preferably those who aren't bot

I'm attempting checks if a username is in a valid username in the server. The check is done by the following code
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='!logan',
intents=intents,
helpCommand=helpCommand)
Users = [# Need help getting users]
async def Fight(ctx, User):
if ctx.author.name != User:
if User in Users:
open_file = open(str(ctx.author.name), "w")
open_file.write(User + "\n300\nTurn")
open_file.close()
open_file = open(User, "w")
open_file.write(str(ctx.author.name) + "\n300\nNot")
open_file.close()
await ctx.author.send("You are now fighting " + User)
#await ctx.User.send("You are now fighting " + ctx.author.name)
else:
await ctx.send("User is not in this server")
else:
await ctx.send("You Cannot Fight Yourself")
I've tried googling, but I haven't found a valid answer
There are other ways to get your guild name, but here's a possible method to get it and get the member list from it.
In member (and user so), there is the ".bot" that is a boolean, 0 if not a bot.
listMembers = []
#bot.command(name="init")
async def FuncInit (ctx) :
global listMembers
guilde = ctx.message.guild
for member in guilde.members :
if not member.bot :
listMembers.append(member.name)

get more input from one command (discord.py)

I'm trying to make an embed system that asks multiple questions and then put them together and send the embed with all the info given, but I can't figure out how to get multiple inputs in one command.
Based on what I understand from your question, you're only checking for one possible input with m.content == "hello". You can either remove it or add an in statement. Do view the revised code below.
#commands.command()
async def greet(ctx):
await ctx.send("Say hello!")
def check(m):
return m.channel == channel # only check the channel
# alternatively,
# return m.content.lower() in ["hello", "hey", "hi"] and m.channel == channel
msg = await bot.wait_for("message", check=check)
await ctx.send(f"Hello {msg.author}!")
In the case of the newly edited question, you can access the discord.Message class from the msg variable. For example, you can access the message.content. Do view the code snippet below.
#commands.command()
async def test(ctx):
def check(m):
return m.channel == ctx.channel and m.author == ctx.author
# return message if sent in current channel and author is command author
em = discord.Embed()
await ctx.send("Title:")
msg = await bot.wait_for("message",check=check)
em.title = msg.content
# in this case, you can continue to use the same check function
await ctx.send("Description:")
msg = await bot.wait_for("message",check=check)
em.description = msg.content
await ctx.send(embed=em)

Delete messages from specifc user using Discord py

I wanted to create a clear command where if example .clear #user#0000 100 it will clear the last 100 messages #user#0000 sent. Here is my code:
#commands.command()
#commands.has_permissions(manage_messages=True)
async def clear(self, ctx, amount=1):
await ctx.channel.purge(limit=amount + 1)
#clear.error
async def clear_error(self, ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send('Sorry, you are missing the ``MANAGE_MESSAGES`` permission to use this command.')
This code i provided only deletes depeneding how many messages will be deleted in a channel. I want to make a code where the bot will delete messages from a specific user. If this is possible, please let me know. I will use the code as future reference. Much appreciated.
You can use check kwarg to purge messages from specific user:
from typing import Optional
#commands.command()
#commands.has_permissions(manage_messages=True)
async def clear(self, ctx, member: Optional[discord.Member], amount: int = 1):
def _check(message):
if member is None:
return True
else:
if message.author != member:
return False
_check.count += 1
return _check.count <= amount
_check.count = 0
await ctx.channel.purge(limit=amount + 1 if member is None else 1000, check=_check)

Discordpy Mod Logs Command

I'm trying to make a mod logs, I'm not really good at this, I scripted myself and kinda worked but it didn't worked. So basically my plan is when someone types .modlogs #channel, bot is gonna get the channel id and type it to json file with guild id, i made that it works very well I'm stuck on getting key info from json file, im printing the values and they are same.
#commands.command(aliases=['purge'])
#commands.guild_only()
#commands.has_permissions(manage_messages=True)
async def clear(self,ctx, arg: int = None):
if arg is None:
await ctx.send(':x: You need to state a value!')
else:
with open('./logs.json', 'r') as f:
logsf = json.load(f)
if ctx.guild.id in logsf:
embedv = discord.Embed(color = discord.Colour.random())
embedv.add_field(name='Event Type:', value="Clear")
embedv.add_field(name='Channel:', value= ctx.channel)
embedv.add_field(name='Moderator:', value=ctx.message.author)
embedv.footer(text='Epifiz Logging')
schannel = commands.get_channel(logsf[ctx.guild.id])
await ctx.channel.purge(limit=arg)
await discord.schannel.send(embed=embedv)
await ctx.send('Done')
elif ctx.guild.id not in logsf:
await ctx.channel.purge(limit=arg)
await ctx.send(':white_check_mark: Successfully cleared {} messages.'.format(arg))
also my json file:
{
"838355243817369620": 853297044922564608
}
Also guild id is on json file, its not wrong.
Output
You made multiple mistakes in your code. The reason why you are getting the error is because this line here if ctx.guild.id in logsf: returns False even if the guild's id is in your JSON file. Here is why:
logsf = json.load(f) returns a dictionary. You'll get {"838355243817369620": 853297044922564608} it's unclear whether 838355243817369620 or 853297044922564608 is your guild id but think of it this way:
s = {1:2}
2 in s return False
and the second mistake is inserting "838355243817369620" as a str rather than an int like this 838355243817369620.
The solution is to use list() as follow if ctx.guild.id in list(logsf): and to insert "838355243817369620" as an int in your JSON file so it looks like this:
{
838355243817369620: 853297044922564608
}
#rather than this
{
"838355243817369620": 853297044922564608
}
value in embeds accepts str not discord objects. Use f"{input}" rather than the object as an input.
embedv.add_field(name='Channel:', value= f"{ctx.channel}")
embedv.add_field(name='Moderator:', value=f"{ctx.message.author}")
await schannel.send(embed=embedv) rather than await discord.schannel.send(embed=embedv)
From this line schannel = commands.get_channel(logsf[ctx.guild.id]) I can assume that 838355243817369620 is your server's id. So, I think that you can use:
if ctx.guild.id in logsf.keys(): instead of if ctx.guild.id in list(logsf):
and make sure to convert its keys values into int rather than str to make it work.

Resources