Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Bug]: UserJoin doesn't fire despite correct intents and configuration #3085

Open
3 tasks done
MichaelGlaive opened this issue Mar 27, 2025 · 5 comments
Open
3 tasks done
Labels

Comments

@MichaelGlaive
Copy link

Check The Docs

  • I double checked the docs and couldn't find any useful information.

Verify Issue Source

  • I verified the issue was caused by Discord.Net.

Check your intents

  • I double checked that I have the required intents.

Description

I setup all the intents, and settings on discord, and my code requests ALL the intents (so I can't be missing them). Yet UserJoin doesn't fire when I test joining the user.

Version

3.17.2

Working Version

No response

Logs

info: DiscordDmBot.DiscordBotService[0]
      17:20:28 Gateway     Received Dispatch (GUILD_MEMBER_ADD)
info: DiscordDmBot.DiscordBotService[0]
      17:20:28 Gateway     Unsynced Guild (GUILD_MEMBER_ADD Guild=1354752827683242076).
info: DiscordDmBot.DiscordBotService[0]
      17:20:29 Gateway     Received Dispatch (PRESENCE_UPDATE)
info: DiscordDmBot.DiscordBotService[0]
      17:20:29 Gateway     Unsynced Guild (PRESENCE_UPDATE Guild=1354752827683242076).

Sample

using Discord;
using Discord.WebSocket;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace DiscordDmBot
{
    public class Program
    {
        public static async Task Main(string[] args)
        {
            // Create the service collection and configure it
            var services = new ServiceCollection()
                .AddSingleton(new DiscordSocketClient(new DiscordSocketConfig()
                {
                    LogLevel = LogSeverity.Debug,
                    MessageCacheSize = 10,
                    SuppressUnknownDispatchWarnings = true,
                    GatewayIntents = GatewayIntents.All,
                    AlwaysDownloadUsers = true,
                    LogGatewayIntentWarnings = true,
                }))
                .AddSingleton<DiscordBotService>()
                .AddLogging(builder => builder.AddConsole());

            // Build the service provider
            var serviceProvider = services.BuildServiceProvider();

            // Start the bot
            await serviceProvider.GetRequiredService<DiscordBotService>().StartAsync();

            // Keep the program running
            await Task.Delay(Timeout.Infinite);
        }
    }

    public class DiscordBotService
    {
        private readonly DiscordSocketClient _client;
        private readonly ILogger<DiscordBotService> _logger;
        private readonly string _token = "SECRET TOKEN HERE"; // Replace with your token

        public DiscordBotService(DiscordSocketClient client, ILogger<DiscordBotService> logger)
        {
            _client = client;
            _logger = logger;

            // Subscribe to client events
            _client.Log += LogAsync;
            _client.Ready += ReadyAsync;
            _client.MessageReceived += MessageReceivedAsync;
        }

        public async Task StartAsync()
        {
            await _client.LoginAsync(TokenType.Bot, _token);
            await _client.StartAsync();
        }

        private Task LogAsync(LogMessage log)
        {
            _logger.LogInformation(log.ToString());
            return Task.CompletedTask;
        }

        private Task ReadyAsync()
        {
            _logger.LogInformation("{User} is connected!", _client.CurrentUser);
            _client.UserJoined += UserJoinedAsync;
            _client.UserLeft += UserLeftAsync;
            _client.GuildMemberUpdated += MemberUpdatedAsync;

            return Task.CompletedTask;
        }

        private Task UserLeftAsync(SocketGuild guild, SocketUser user)
        {
            _logger.LogInformation("User {User} LEFT: {Guild}", user.Username, guild.Name);
            return Task.CompletedTask;
        }

        private Task MemberUpdatedAsync(Cacheable<SocketGuildUser, ulong> userCacheable, SocketGuildUser user)
        {
            _logger.LogInformation("Member UPDATED: {User}", user.Username);
            return Task.CompletedTask;
        }

        private async Task MessageReceivedAsync(SocketMessage message)
        {
            // Ignore messages from bots
            if (message.Author.IsBot) return;

            // Only process direct messages
            if (message.Channel is not IDMChannel) return;

            _logger.LogInformation("Received DM from {Username}: {Content}", message.Author.Username, message.Content);

            await message.Channel.SendMessageAsync($"You said: {message.Content}");
        }

        private async Task UserJoinedAsync(SocketGuildUser user)
        {
            var dmChannel = await user.CreateDMChannelAsync();
            await dmChannel.SendMessageAsync("Welcome to the server!, please paste your solaria user id here to get started...");
        }
    }
}

Packages

Discord.Net 3.17.2

Environment

macOS 14.6.1, Apple Silicon.

@Misha-133
Copy link
Member

Misha-133 commented Mar 28, 2025

Hey
Could you elaborate this a bit please

UserJoin doesn't fire

Do you mean the event itself does not fire (as in - you don't hit a breakpoint placed in a handler)
Or does it fail to create a DM channel & send a message (looking at the snippet you've provided)? Discord is pretty strict with bots sending DMs to users so that could the the actual issue.

@MichaelGlaive
Copy link
Author

I put a breakpoint, and the debugger doesn't stop there.

@a-727
Copy link

a-727 commented Mar 30, 2025

I put a breakpoint, and the debugger doesn't stop there.

Most debuggers do not stop for breakpoints in async functions. To debug async functions, you need to do it the old way - with some kind of output to the console.

@Misha-133
Copy link
Member

Visual Studio debugger (and the one rider uses) have no issues pausing in async methods. Very likely it's not the issue in this case.

@Misha-133
Copy link
Member

Regarding the original issue - i would recommend adding all event handlers in the constructor instead of the ready event handler.
a. There's no need to do that (unless you specifically want that)
b. The event may be fired multiple times, adding duplicate handlers

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants