Why can't my bot dm users a welcome message? (Discord.net C#)

1.1k Views Asked by At

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

1

There are 1 best solutions below

2
On BEST ANSWER

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