I’m working on a Discord bot using VB.NET and I need help with validating user mentions in commands. Here’s my current code:
Case "-assign"
If message.serverpermission.Administrator = true then
Dim targetUser = message.Message.MentionedUsers.FirstOrDefault()
Dim selectedRole = message.Server.FindRoles(argument, True).FirstOrDefault()
Await targetUser.AddRoles(selectedRole)
The problem is that when an admin runs this command without mentioning a user, my bot crashes with a System.NullReferenceException because targetUser is null. I want to add proper validation to check if a user was actually mentioned before trying to assign roles. If no user is mentioned, the bot should send a friendly error message like “Please mention a user” or “No user found with that name” instead of crashing. How can I properly validate the mentioned user before proceeding with the role assignment?
just wrap it in a simple if statement dude. something like If targetUser IsNot Nothing Then should do the trick before calling AddRoles. thats how i fixed mine when it kept crashing on empty mentions
To handle the issue with user mentions in your VB.NET Discord bot, ensure you perform a null check on the targetUser object before proceeding with the role assignment. This way, if no user is mentioned, you can send them a friendly reminder. Here’s a potential solution:
Case "-assign"
If message.serverpermission.Administrator = true then
Dim targetUser = message.Message.MentionedUsers.FirstOrDefault()
If targetUser Is Nothing Then
Await message.Channel.SendMessage("Please mention a valid user to assign the role to.")
Return
End If
Dim selectedRole = message.Server.FindRoles(argument, True).FirstOrDefault()
If selectedRole Is Nothing Then
Await message.Channel.SendMessage("Role not found.")
Return
End If
Await targetUser.AddRoles(selectedRole)
Additionally, remember to check for the existence of selectedRole to avoid similar null reference errors.
I encountered similar issues while developing my Discord bot. To ensure that your bot doesn’t crash due to a null reference, first verify that the UsersMentioned collection is not empty before calling FirstOrDefault(). You can achieve this by adding a condition to check its count, like If message.Message.MentionedUsers.Count = 0 Then. This adjustment will prevent your bot from processing empty collections. Additionally, it’s prudent to surround the role assignment operation with a try-catch block to handle any unexpected exceptions gracefully, especially when interacting with the Discord API.