Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set your subtitle preferences in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please refer to our video player troubleshooting guide for assistance.

Converting Parameters

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.

00:00 This is part 12, where you are going to find out about converting parameters automatically. The ability to convert parameters is another benefit of using commands.

00:10 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.

00:23 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.

00:35 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.

00:58 If you were to run your bot.py program and invoke the !roll_dice command in your Discord channel, you will get an error that looks like this.

01:06 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. In discord.py, a Converter is defined by using Python 3’s function annotations.

01:26 What this means is that you add : int, just like this, to the two

01:34 parameters that you expect to be of type int. Now, try the command again.

01:47 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.

01:59 Keep in mind that a Converter can be any callable, not merely a data type. The argument will be passed to the callable, and the return value will be passed into the Command.

02:10 Next up, you will learn about the Check object and how it can improve your commands.

Become a Member to join the conversation.