2 of 4
Build a dice roller that your Discord bot can use! This is a classic bot command ā users type !roll and the bot rolls dice for them.
Write three functions that work together to simulate dice rolling.
roll_die(sides)sidesrandom.randint(1, sides)roll_multiple(sides, count)roll_die() multiple timesformat_rolls(rolls)Rolls: 3, 5, 1 | Total: 9import random def roll_die(sides): # Return a random number from 1 to sides pass def roll_multiple(sides, count): # Roll the die 'count' times, collect results in a list pass def format_rolls(rolls): # Format the rolls nicely: "Rolls: 3, 5, 1 | Total: 9" pass # Test your functions: random.seed(42) single = roll_die(6) print(f"Single roll: {single}") rolls = roll_multiple(6, 4) print(f"Multiple rolls: {rolls}") print(format_rolls([3, 5, 1, 6])) # Output: Rolls: 3, 5, 1, 6 | Total: 15 print(format_rolls([20])) # Output: Rolls: 20 | Total: 20 # Final bot message: random.seed(99) my_rolls = roll_multiple(20, 3) print(f"š² Dice Bot š²") print(format_rolls(my_rolls))
Your exact numbers may differ when you remove the seed, but the format should match:
Single roll: 2
Multiple rolls: [1, 1, 6, 6]
Rolls: 3, 5, 1, 6 | Total: 15
Rolls: 20 | Total: 20
š² Dice Bot š²
Rolls: 5, 1, 9 | Total: 15
One line is all you need:
def roll_die(sides): return random.randint(1, sides)
Create an empty list, loop count times, and append each roll:
results = [] for i in range(count): results.append(roll_die(sides)) return results
To join a list of numbers into a string separated by commas:
roll_str = ", ".join(str(r) for r in rolls) total = sum(rolls) return f"Rolls: {roll_str} | Total: {total}"
import random def roll_die(sides): return random.randint(1, sides) def roll_multiple(sides, count): results = [] for i in range(count): results.append(roll_die(sides)) return results def format_rolls(rolls): roll_str = ", ".join(str(r) for r in rolls) total = sum(rolls) return f"Rolls: {roll_str} | Total: {total}"
roll_multiple calls roll_dieimport randomfor.append().join() to combine itemsWrite your code below. Click Run to test locally, then click Send to Discord to have the bot post your output to the server!