Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a user has provided an argument discord.py

I have just started trying to learn how to code in discord.py. However, I'm not sure how to check if a user has provided an arguement after the command. For example, if the user types !kick, wihout tagging a user after it, it should give them an error message saying something like "Please tag a user".

So my question is, How do I check if the user has tagged another user when using a command, and if not, give them an error message.

Here is my code:

#PyBot by RYAN#2302

import discord
from discord.ext import commands
from discord.ext.commands import Bot
import asyncio
import chalk

bot = commands.Bot(command_prefix='!')

@bot.event
async def on_ready():
    print ("Ready when you are xd")
    print ("I am running on " + bot.user.name)
    print ("With the ID: " + bot.user.id)

@bot.command(pass_context=True)
async def ping(ctx):
    await bot.say(":ping_pong: Ping! :ping_pong:")
    print ("!ping")

@bot.command(pass_context=True)
async def info(ctx, user: discord.Member):
    await bot.say("The users name is: {}".format(user.name))
    await bot.say("The users ID is: {}".format(user.id))
    await bot.say("The users status is: {}".format(user.status))
    await bot.say("The users highest role is: {}".format(user.top_role))
    await bot.say("The user joined at: {}".format(user.joined_at))
    print ("!info")

@bot.command(pass_context=True)
async def kick(ctx, user: discord.Member):
    await bot.say(":boot: Cya, {}. Ya loser!".format(user.name))
    await bot.kick(user)
    print ("!kick on {}".format(user.name))

Any help would be greatly appreciated, thanks!

like image 383
Ryan S Avatar asked Nov 08 '22 10:11

Ryan S


1 Answers

Give the user argument a default value of None, and then check to see if a submitted value is used instead

@bot.command(pass_context=True)
async def kick(ctx, user: discord.Member = None):
if user:    
    await bot.say(":boot: Cya, {}. Ya loser!".format(user.name))
    await bot.kick(user)
    print ("!kick on {}".format(user.name))
else:
    await bot.say("Please tag a user to kick")

All Member objects will be truthy, so the only time if user: will fail is if no user was supplied. If the input cannot be matched to a user, the command will do nothing, failing silently unless we also specify a error listener

@kick.error
async def kick_error(ctx, error):
    if isinstance(error, discord.ext.commands.BadArgument):
        await bot.say('Could not recognize user')
like image 187
Patrick Haugh Avatar answered Nov 14 '22 23:11

Patrick Haugh