0

I've been working on a discord bot for the past few days, and I managed to get one of the functions working: (a command that sets a message it's supposed to dm users when they join). I can't seem to get the bot to send the actual message.

    private async Task Join(SocketGuildUser UID)
    {
        if (UID.IsBot || UID.IsWebhook) return;
         Welcometxt= File.ReadAllText([FILE]);
        await UID.SendMessageAsync("Your Message Was Sucessfully set!");
    }
        private async Task HandleCommandAsync(SocketMessage arg)
    {
        var message = arg as SocketUserMessage;
        var context = new SocketCommandContext(_client, message);
        if (message.Author.IsBot) return;

        int argPos = 0;
        if (message.HasStringPrefix("!", ref argPos))
        {
            var result = await _commands.ExecuteAsync(context, argPos, _services);
            if (!result.IsSuccess) Console.WriteLine(result.ErrorReason);
        }
    }

When i check the logs it gives a null reference error with the var message and context, I tried googling the error and changing up the code but to no avail any advice? I believe the error is in one of these two methods but im not 100% positive

  • Can share the error message? It will be easier for us to identify where the errors are. Also did you exactly use commands to send message to user when they are join ? If yes, I think you can user `UserJoined` event handler instead. – Cuppyzh Nov 30 '20 at 04:41
  • A MessageReceived handler has thrown an unhandled exception.: System.NullReferenceException: Object reference not set to an instance of an object. at Discord.Commands.SocketCommandContext..ctor(DiscordSocketClient client, SocketUserMessage msg) at UBot_CodeV2.Program.d__9.MoveNext() in C:\Users\sarah\source\repos\UBot_CodeV2\UBot_CodeV2\Program.cs:line 70 Line 70 would be var context – Sarah Lawarence Nov 30 '20 at 18:48

1 Answers1

0

I guess you can use UserJoined event to achieve this.

Define event handler for UserJoined

public async Task UserJoined(SocketGuildUser user)
{
   await user.SendMessageAsync("Hello");
}

Register it

private readonly DiscordSocketClient _client = new DiscordSocketClient();
private readonly CommandService _commandService = new CommandService();

public async Task MainAsync()
{
   ....
   _client.UserJoined += UserJoined;
   ....
}

I'm not sure enough if this is related, but check if the Server Member Intents is on enter image description here

Cuppyzh
  • 142
  • 2
  • 10
  • 1
    Thank you so much I cant believe I missed something like that! it is now sending welcome Dm's just the wrong one for some reason I likely set a variable incorrectly – Sarah Lawarence Nov 30 '20 at 18:43
  • 1
    I think you actually only need the 'Server member intent' for this to work, not the 'Presence intent'. – Thom Dec 17 '20 at 00:14