Reputation: 107
I am adding a coinflip feature to my discord bot. This command has 3 arguments which is !coinflip, the side you want on the coin and the amount of money you want to gamble. This feature works fine. However, if the user writes those arguments wrong, or there are missing arguments, nothing will happen, and I will get an error in my console. How can I make the bot send a message that explains how to write the command, when a user writes the command wrong?
Here are the necessary parts of the code:
@bot.command()
async def coinflip(ctx, outcome, amount:int):
coin = random.choice(["heads", "tails"])
if outcome == coin:
coinflipEmbed = discord.Embed(title="Coinflip", description=f"The coin landed on **{coin}**, and you won **{amount}** money!", color=0x00FF00)
await ctx.send(embed=coinflipEmbed)
elif outcome != coin:
coinflipEmbed = discord.Embed(title="Coinflip", description=f"The coin landed on **{coin}**, and you lost **{amount}** money!", color=0xFF0000)
await ctx.send(embed=coinflipEmbed)
Upvotes: 2
Views: 3219
Reputation: 1594
You could:
*args
It would look like so:
@bot.command()
async def coinflip(ctx, *args):
# All args are here?
if len(args) != 2:
await ctx.send("Error message saying you want coin and amount")
return
# Are they valid?
outcome = args[0]
amount = args[1]
if not outcome_is_valid(outcome):
await ctx.send("Tell him its invalid and why")
return
if not amount_is_valid(outcome):
await ctx.send("Tell him its invalid and why")
return
# All good, proceed
coin = random.choice(["heads", "tails"])
if outcome == coin:
coinflipEmbed = discord.Embed(title="Coinflip", description=f"The coin landed on **{coin}**, and you won **{amount}** money!", color=0x00FF00)
await ctx.send(embed=coinflipEmbed)
elif outcome != coin:
coinflipEmbed = discord.Embed(title="Coinflip", description=f"The coin landed on **{coin}**, and you lost **{amount}** money!", color=0xFF0000)
await ctx.send(embed=coinflipEmbed)
Upvotes: 0
Reputation: 5889
You might want to create an error command below your coin_flip()
command.
The following code will only accept a MissingRequiredArgument
error btw.
Though you can easily change this by, removing the code block. Running the code again, typing something incorrect and find the main error. Then replace this commands.MissingRequiredArgument
with commands.your_error
.
@coinflip.error
async def flip_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send('Inccorrect arguments entered | **!command_name - outcome:str - amount:int'**)
Upvotes: 1