Hey Guys!
I am Back with another post and today We are gonna discuss about how to Accept user input. We will discuss about Error Handling in few post aheads when u will understand what type of errors You will usually see.
So Let's Begin...
Accepting User Input
What Exactly are we meant with accepting user input?
Well its quite simple. Accepting user input means you see what user want to tell us. For example there is a kick/ban/timeout command and if any user use that command without giving information about the user on whom action should be taken. How our bot will know whom to kick/ban/timeout. So in that cases we will take user input and take actions according to their information.
Let's Start by creating one command and use to understand what I mean:
Creating av
command:
so we will create an av
command will give avatar of user. So let's start by placing our decorator
@bot.command()
and under this decorator we will create our async def as usual
async def av(ctx,member):
await ctx.send()
This Time I am giving an arg Member. Now what will it do is it accept the input from user after our command
like this.
Now if someone is to use that command he can give any arg. like any string xyz
or any int 123
how will we know that it is a discord user. So we will set its type as discord.Member
. So to that we have to do it like this
@bot.command()
async def av(ctx,member: discord.Member):
await ctx.send()
now what will it do is accept the user input and store it as information of any member. Now can do few things with this member. But today we'll just get user avatar. So to get avatar of the member we use this member.display_avatar
.
@bot.command()
async def av(ctx,member: discord.Member):
await ctx.send(member.display_avatar)
so this is our basic command setup. Let's run our bot and see does that work or not.
So You can see that this things is working perfectly fine.
But there are still some issues like user can give strings or input as input or give no input at all which will cause error. But will discuss about handling these errors in future.
If you prefer slash (/) command, then there will be less chances of getting errors. Here's a code for slash (/) command. Logic is same as above.
@bot.tree.command(name="avatar",description="Get user avatar")
async def avatar(interaction:discord.Interaction,member:discord.Member):
await interaction.response.send_message(member.display_avatar)
So as you can see it tells us to select user. So the only option someone has is to select a discord.Member
.
So that's it for today. I hope u liked this post.
Github: https://github.com/MannuVilasara/discord.py-tutorial
Refrance : https://discordpy.readthedocs.io/
Discord: https://discord.gg/pvvJvZU6nS
Top comments (0)