0

I have an error in my Command Handler. System.NullReferenceException: 'Object reference not set to an instance of an object.'

Snippet

Client.MessageReceived += HandleCommand;

Full code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Discord.Commands;
using Discord.WebSocket;

namespace DotNetNuker
{
    public class CommandHandler
    {
        private CommandService Commands { get; set; }
        
        private DiscordSocketClient Client { get; set; }


        public async Task Init(DiscordSocketClient client)
        {
            this.Client = Client;
            Commands = new CommandService();

            await Commands.AddModulesAsync(Assembly.GetEntryAssembly(), null);
            Client.MessageReceived += HandleCommand;
        }

        private async Task HandleCommand(SocketMessage Msg)
        {
            var msg = Msg as SocketUserMessage;
            if (msg == null) return;

            int argPos = 0;
            if (!(msg.HasStringPrefix("n!", ref argPos) || msg.HasMentionPrefix(Client.CurrentUser, ref argPos))) return;

            var context = new CommandContext(Client, msg);

            var result = Commands.ExecuteAsync(context, argPos, null);

            if (!result.IsCompleted) await context.Channel.SendMessageAsync("Failed to execute command.");
        }
    }
}

  • 1
    At a glance, the line of code … `this.Client = Client;` … looks a little odd in a sense that the passed in `client` is never used and the property `Client` looks `null`. I am guessing that the line should be … `this.Client = client;` … ? – JohnG Oct 15 '21 at 03:17

1 Answers1

0

JohnG solved my question: At a glance, the line of code … this.Client = Client; … looks a little odd in a sense that the passed in client is never used and the property Client looks null. I am guessing that the line should be … this.Client = client;

I changed the code this.Client = Client; to this.Client = client;