Making a Discord Bot Roll a Die in Python

Making a Discord Bot Roll a Die in Python Featured Image

Making a bot say “Hello, World!” is one thing. Having it roll a die for you is a little more complicated. Luckily, I know you can handle it! Let’s get to it.

Table of Contents

Laying Out the Foundation

As promised, in this article, we’ll be creating a Discord bot that rolls a die and sends the results of that roll to a Discord channel. To do that, we’ll need to lay out a bit of a foundation. Fortunately, we already know what that looks like:

import discord
webhook = discord.Webhook.from_url("<your webhook url>", adapter=discord.RequestsWebhookAdapter())

That said, if this is your first time seeing an article from this series, I’ll quickly explain.

In the first line, we’re importing a set of tools from the Discord library. Among those tools is a function for generating webhook objects which we can use to send messages to Discord. We make this object using the code in line two.

From here, we can begin sending all sorts of messages. For example, we can send our usual “Hello, World!” message:

webhook.send("Hello, World!")

So, how would we go about getting this bot to roll a die? We’ll talk about that in the next section.

How to Generate a Number in Python

In order for us to roll a die, we’re going to need some way to generate a number. Luckily, Python has an entire library dedicated to generating random numbers called random. Just like with the Discord tools, we can import these random number generator tools as follows:

import random

Now, one thing I think is worth getting in the habit of is reading the documentation for any new library you decided to include in a project. For example, you can find the random documentation hereOpens in a new tab..

Right at the top, you’ll read that most of the utilities provided in this library are based on the random() function which generates a random number between zero and one:

>>> random.random()
0.12264457983876476

Unfortunately, I’m not aware of any real-world die that can generate continuous numbers like this. It’s more likely that we want to produce integers (e.g., 1 to 6). Surely, if we were clever with our math, we could convert the result of random() into a range of integers. However, I’d prefer to work smarter, not harder. Why don’t we take a look at the documentation once again to see if we can find anything useful.

As it turns out, in the heading titled “Functions for integersOpens in a new tab.“, there’s a function called randint that we might be able to use:

Return a random integer N such that a <= N <= b. Alias for randrange(a, b+1).

If we trust this description, we should be able to generate a random number between 1 and 6 as follows:

>>> random.randint(1, 6)
5
>>> random.randint(1, 6)
3
>>> random.randint(1, 6)
4
>>> random.randint(1, 6)
3

Alright, we have a way to roll a die! Now what?

How to Store Data in Python

At this point, we could go back to our bot and sort of call it a day. After all, we can generate a number, so surely we can send the result to our webhook:

import discord
import random
webhook = discord.Webhook.from_url("<your webhook url>", adapter=discord.RequestsWebhookAdapter())
webhook.send("Rolling a six-sided die!")
webhook.send(random.randint(1, 6))

And, this is totally fine. That said, it’s sometimes useful to save results of a function for later. For example, we already do that with our webhook. It’s perfectly possible to write code that looks like this:

import discord
import random
discord.Webhook.from_url("<your webhook url>", adapter=discord.RequestsWebhookAdapter()).send("Rolling a six-sided die!")
discord.Webhook.from_url("<your webhook url>", adapter=discord.RequestsWebhookAdapter()).send(random.randit(1, 6))

But, this is very messy and inefficient. If we compute a value, we should probably save it somewhere—even if we use it once. After all, how is anyone supposed to know the purpose of our random integer. Sure, they might be able to tell from the context of our first message, but it’s not clear otherwise. As a result, let’s try saving our random number in a variable:

import discord
import random
webhook = discord.Webhook.from_url("<your webhook url>", adapter=discord.RequestsWebhookAdapter())
webhook.send("Rolling a six-sided die!")
dice_roll = random.randint(1, 6)
webhook.send(dice_roll)

And there we go! We have a bot that can roll a die and share the result with a discord channel.

Taking on a Challenge

As it turns out, taking a Hello World bot and turning it into a die rolling bot is a matter of adding a couple more lines of code. While you wait on the release of the next article, why not try extending the code above in a couple of ways.

First, check out this article on string formatting. It’ll give you some tools for writing cleaner strings. For example, rather than sending two messages, you could send one that reads: “Rolling a six-sided die: 4”. Or maybe, you want your bots name to change based on your roll. The previous article shares a way you might do that.

Second, check out this article on operators. It’ll show you how to perform simple math operations like addition and subtraction. You might try taking that knowledge and modifying your bot to play craps (i.e., roll two dice and sum the results). Alternatively, you could make up your own use for random numbers and operators.

Once you’re done playing around with strings and numbers, make sure you have fun with your new bots with your friends. And while you’re at it, show them how to make one!

Looking Ahead

Now that we’ve had a chance to learn about variables in Python, we can start taking on more advanced Python topics. For example, in the next article, we’ll extend what we’ve learned about in terms of generating random numbers to have our programs start making decisions. If you want a primer on that, check out this articleOpens in a new tab..

In the meantime, you might enjoy these related Python articles:

Likewise, here are some resources from the folks at Amazon (#ad):

Otherwise, see you again soon! Take care.

Learn Python by Building Discord Bots (4 Articles)—Series Navigation

In 2021, I started toying with the idea of building discord bots. Very quickly, I got over my fear of learning something new when I realized I had nothing to be scared of. This feeling got me thinking: what if I created some teaching material around Discord bots? You could learn Python and build something cool at the same time! So, I decided to give it a go.

Jeremy Grifski

Jeremy grew up in a small town where he enjoyed playing soccer and video games, practicing taekwondo, and trading Pokémon cards. Once out of the nest, he pursued a Bachelors in Computer Engineering with a minor in Game Design. After college, he spent about two years writing software for a major engineering company. Then, he earned a master's in Computer Science and Engineering. Today, he pursues a PhD in Engineering Education in order to ultimately land a teaching gig. In his spare time, Jeremy enjoys spending time with his wife, playing Overwatch and Phantasy Star Online 2, practicing trombone, watching Penguins hockey, and traveling the world.

Recent Code Posts