discord.py How to make a roll dice command
That's because it checks for 4 first, then 6, and so on... Even after you send 4, it'll check for 6, 8 and so on.. And when you send 6, it'll check for 4 first, then 6 and so on.. Why don't you try something like this instead:
@client.command()
async def rolldice(ctx):
message = await ctx.send("Choose a number:\n**4**, **6**, **8**, **10**, **12**, **20** ")
def check(m):
return m.author == ctx.author
try:
message = await client.wait_for("message", check = check, timeout = 30.0)
m = message.content
if m != "4" and m != "6" and m != "8" and m != "10" and m != "12" and m != "20":
await ctx.send("Sorry, invalid choice.")
return
coming = await ctx.send("Here it comes...")
time.sleep(1)
await coming.delete()
await ctx.send(f"**{random.randint(1, int(m))}**")
except asyncio.TimeoutError:
await message.delete()
await ctx.send("Procces has been canceled because you didn't respond in **30** seconds.")
Note: I recommend using await asyncio.sleep(1)
instead of time.sleep(1)
. That way other commands will still be functional. Remember to import asyncio
in this case.
Roll/Dice command?
If you create a function that takes in parameters you have to use those.
function getRandomIntInclusive(min, max) {
min = Math.min(min, max);
max = Math.max(max, min);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
let num1 = argsminus8[0];
let num2 = argsminus8[1];
if(!num1) return message.reply("Please enter a first number");
if(!num2) return message.reply("Please enter a second number");
const embed = new MessageEmbed()
.setTitle('Number:')
.setDescription(getRandomIntInclusive(num1, num2))
.setColor(0x0099ff)
.setTimestamp()
message.channel.send({ embed });
Implement this inside if(message.content.startsWith (prefix + 'random-number'))
.
This will create random numbers between 1 and 100, because for the min
parameter I said 1 and for the max
parameter I said 100.
You can change the numbers to whatever you like.
Basic one-message dice roller?
I think you are essentially asking how to concatenate strings together. That is done with the plus sign operator. If any of the operands are strings, it treats all the variables as strings:
if (message.content.toLowerCase().includes("rei!d100")) {
var response = [Math.floor(Math.random() * ((100 - 1) + 1) + 1)];
message.channel.send("You got... " + response + "!").then().catch(console.error); // "You got... 96!"
}
Alternatively, you can use template params like so (those are backticks, not quotes):
message.channel.send(`You got... ${response}!`);
Discord.py D&D dice roll command has far too many issues
With the commands
extension, you can't get rid of the space between your command and the die
variable. In order to get rid of it, you'd have to use an on_message
event to parse your command's content:
from random import sample
@client.event
async def on_message(message):
content = message.content
if content.startswith('|') and (content[1].isdigit() or content[1]=='d'):
content = content.split('+')
rolls = [int(content.pop(i)) for i in range(len(content)) if content[i].isdigit()]
for elem in content:
n, faces = elem.split('d') if elem.split('d')[0] != '' else (1, elem[1:])
rolls += [randint(1, int(faces)) for _ in range(int(n))]
rolls_str = ' + '.join([str(n) for n in rolls])
await message.channel.send(f"{rolls_str} = {sum(rolls)}")
else:
pass
await client.process_commands(message)
Discord.js DND Dice Roll Input Change Number
Use a regular expression instead of .includes
, and then extract the digits after the d
to randomize.
You don't need to subtract 1, then add 1 right after that - those cancel out, nor do you need to put the result into an array - interpolating just the random number generated into the message will work fine.
const match = message.content.match(/!rolld(\d+)/i);
if (match) {
const die = match[1];
const response = 1 + Math.floor(Math.random() * die);
const ayy = client.emojis.cache.find(emoji => emoji.name === "diceroll");
Discord bot dice roll error. Why does my code not reach its expected result?
I found 4 errors in your code:
- You said that you receieve no errors, that's because you're using bare
except
. Something as simple as
except Exception as e:
print(e)
would give you the error message. If you want more you could also print traceback to pinpoint the faulty code.
random.randint
takes 2 argumentsstart
andend
and both areint
.Right now you're passing only one and it's not even a
int
.sides[1]
will give you a string even if the string contains a number, but the type is still a string because.split
returns a list of strings. So for example you called!roll d3 5
then thesides
will be a list["d", "3"]
wheresides[1]
will be a string"3"
Your
rolls
is going to be a list of integers becauserandom.randint
returns anint
and you're usingrolls .append(result)
thusrolls
will be list of ints.So you can't use
", ".join(rolls)
because you would be joining integers to string", "
Instead you need to call
", ".join(str(number) for number in rolls)
or you can convert each append call to string right away.amount
is going to be passed as string so you can't userange(amount)
it needs to berange(int(amount))
So for the full code:
async def roll(ctx, sides, amount):
try:
sides = int(sides.split("d")[1])
rolls_list = []
for number in range(int(amount)):
# 1 is the minimum number the dice can have
rolls_list.append(random.randint(1, sides))
rolls = ", ".join(str(number) for number in rolls_list)
await ctx.send("Your dice rolls were: " + rolls)
except Exception as e:
# You should catch different exceptions for each problem and then handle them
# Exception is too broad
print(e)
await ctx.send("Incorrect format for sides of dice (try something like \"!roll d6 1\").")
You should also check for some input errors like if integers are negative aka amount
Adding more parameters to a Discord Bot?
You can easily combine all of the commands into one as follows, i don't know D&D so i didn't get what you meant by modifiers.
@bot.command()
async def dice(ctx, dice_type: int, amount: int):
results = []
for role in range(amount):
x = random.randint(1, dice_type)
results.append(x)
await ctx.send(f'You have rolled {dice_type} for {amount} times and got {results}')
Related Topics
Key Error When Selecting Columns in Pandas Dataframe After Read_Csv
Saving the Output of a Python Program
Json.Decoder.Jsondecodeerror: Expecting Value: Line 1 Column 1 (Char 0) Python
Copy All Values in a Column to a New Column in a Pandas Dataframe
Pandas Filtering for Multiple Substrings in Series
Filtering a Pyspark Dataframe Using Isin by Exclusion
Python: Opencv - Selecting Region of an Image
How to Convert Base64 String to Image
Find and Replace Specific Values Within 2D Array
Python: [Errno 10054] an Existing Connection Was Forcibly Closed by the Remote Host
Django: Check Whether an Object Already Exists Before Adding
Python - Regex Match Multiple Patterns in Multiple Lines
Update Json Element in Json Object Using Python
Programme to Print Mulitples of 5 in a Range Specified by User