I’m trying to build a Discord bot using C# and I’m facing an issue with command parameters. I want to set up a dice roll command where users can type d!roll [sides]
to receive a random value from 1 to the number of sides they choose.
The problem I’m running into is not being able to utilize the parameter value entered by the user. Here’s the code I have so far:
commands.CreateCommand("roll")
.Parameter("sides", ParameterType.Required)
.Do(async (message) =>
{
Random randomGen = new Random();
int rollResult = randomGen.Next(1, sides + 1);
await message.Channel.SendMessage($":game_die: You rolled a **{sides}** sided die and got **{rollResult}**!");
});
I’m encountering errors because sides
is not recognized as a variable. How can I correctly access the parameter value provided by the user? Any guidance would be very helpful since I’m quite new to C#.
u gotta get the param from the message object. Try message.GetArg("sides")
or use int.Parse(message.GetArg("sides"))
before using it in random.Next(). also, add some error handling in case they put in a non-number!
The problem is parameter scope in your command handler. Discord.NET’s legacy framework doesn’t make parameters directly available as variables - you have to grab them from the message event arguments instead. Use message.GetArg("sides")
and convert it to an integer since parameters always come as strings. I’d wrap that conversion in a try-catch block because users will definitely input garbage. Also, message.Channel.SendMessage
is deprecated now - switch to message.Channel.SendMessageAsync
. I ran into the same confusion when I started with Discord.NET. The parameter handling isn’t as straightforward as other frameworks.
You can’t just use sides
as a variable in Discord.NET. You need to grab it from the command arguments first. Use message.GetArg(0)
since it’s your first parameter, or message.GetArg("sides")
if you prefer using the name. Then parse it to an integer with int.Parse()
or Convert.ToInt32()
before using it for your random number generation. Definitely add validation to check it’s a positive number - your bot will crash if someone types “potato” instead of a number. The parameter system is confusing at first, but you’ll get used to pulling and converting arguments pretty quickly.