In this lesson, you’ll learn another benefit of using commands: the ability to convert parameters. Sometimes, you require a parameter to be a certain type, but arguments to a
Command function are, by default, strings. A
Converter lets you convert those parameters to the type that you expect.
For example, if you want to build a
Command for your bot user to simulate rolling some dice, knowing what you have learnt so far, you might define that like this. You define a
roll() to take two parameters.
One is the number of dice to be rolled, and two, the number of sides per die. Then, you decorate it with the
.command so that you can invoke it with the
roll_dice command. Finally, you
.send() the results in a message back to the channel, just there. While this looks correct, it unfortunately isn’t.
What this means is that
range() can’t accept a string as an argument. Instead, it must be an
int. While you could cast each value to an
int, there is a better way. You can use a
Converter is defined by using Python 3’s function annotations.
There you have it! With that little change, your command now works. The difference is that you’re now converting the command arguments to
int, which makes them compatible with your function’s logic.
Become a Member to join the conversation.