I’m working on a Discord bot and want to create a dice rolling command. When users type a specific command, I need the bot to generate a random number and respond based on the result.
Here’s what I have so far:
var diceValue = (Math.floor(Math.random()*100)+1);
if (diceValue <= 50){
message.reply('Try again! Not high enough!');
} else {
message.reply('Congratulations! You won the roll!');
}
I’m struggling with connecting this logic to a command trigger. How do I set it up so when someone types the command, this dice rolling function executes? I’m still learning JavaScript so any help would be appreciated.
Wrap your dice logic in a command handler. If you’re using discord.js, try this:
client.on('messageCreate', message => {
if (message.content === '!roll') {
var diceValue = (Math.floor(Math.random()*100)+1);
if (diceValue <= 50){
message.reply('Try again! Not high enough!');
} else {
message.reply('Congratulations! You won the roll!');
}
}
});
This listens for messages and triggers when someone types !roll. You might want to add a message.author.bot check so other bots don’t trigger it. Your logic’s solid - just needed the command structure.
Add a prefix check before your dice code runs. Use if (message.content.startsWith('!dice')) then put your random logic inside. Don’t forget return; after so it stops processing other stuff. Works fine for basic bots - slash commands are overkill unless you want something fancy.
You should use slash commands instead of message-based ones - Discord’s moving that direction anyway. Here’s how:
const { SlashCommandBuilder } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('dice')
.setDescription('Roll a dice for a chance to win'),
async execute(interaction) {
const diceValue = Math.floor(Math.random() * 100) + 1;
if (diceValue <= 50) {
await interaction.reply(`You rolled ${diceValue}! Try again! Not high enough!`);
} else {
await interaction.reply(`You rolled ${diceValue}! Congratulations! You won the roll!`);
}
},
};
It’s more modern and users like it better. You’ll have to register the slash command with Discord first, but it’s worth it. Showing the actual dice value makes things way more transparent too.