#Message Not Received in CommandHandler

1 messages · Page 1 of 1 (latest)

wild bronze
#

This actually comes through the logging event

#

anytime a message i have sent

#

in a channel

#

well anyone.

#

My other issue i had is archived which was the gate way intents which was fixed but now this has came along

#

no code changed after the gateway intents fix and this bug

naive rover
#

@lucid pagoda @wild bronze lets move it in here

wild bronze
#

thank you

#

so errors can come through

#

but no exception is in the arguement

#

when it gets logged

lucid pagoda
#

I don’t wanna!!!!

naive rover
wild bronze
#

my log event where it comes through

#

no exception is logged

lucid pagoda
#

Because it’s not an exception?

wild bronze
#

i know just showing theres no other error with it

#

it just logs that and does nothing

lucid pagoda
#

Do you have an event handler for message created?

wild bronze
#

at the moment i just have messagerecieved

#

m_Client being the discord socketclient

lucid pagoda
#

What is the logic for your handlecommandasync?

wild bronze
#
 /// <summary>
        /// Handle Command Async
        /// </summary>
        private async Task HandleCommandAsync(SocketMessage arg)
        {
            try
            {
                CheckForNewGuilds();

                if (arg is SocketUserMessage && arg != null)
                {

                    try
                    {
                        var message = arg as SocketUserMessage;

                        var textchannel = arg.Channel as SocketTextChannel;

                        if (textchannel != null)
                        {
                            ulong guildid = textchannel.Guild.Id;

                            int argPos = 0;

                            if (m_GuildsPrefix.ContainsKey(guildid))
                            {
                                bool doesNotHaveCharPrefix = !(message.HasCharPrefix(m_GuildsPrefix[guildid], ref argPos));
                                bool hasUserentioned = message.HasMentionPrefix(m_Client.CurrentUser, ref argPos);
                                bool isBot = message.Author.IsBot;

                                if (doesNotHaveCharPrefix || hasUserentioned || isBot)
                                    return;

                                var context = new SocketCommandContext(m_Client, message);

                                await m_Commands.ExecuteAsync(
                                    context: context,
                                    argPos: argPos,
                                    services: m_ServiceProvider);
                            }
                        }

                    }
                    catch (Exception e)
                    {
                        DiscordWorker.Log(string.Format("Error occured Handling Message:\r\n" +
                                          "Error: {0}", e.Message), LogType.Error);
                    }
                }
            }
            catch(Exception e)
            {
                DiscordWorker.Log($"Error Handling Command {e.Message}", LogType.Error);
            }

            return;
        }
#
        /// <summary>
        /// Check for New Guilds
        /// </summary>
        private void CheckForNewGuilds()
        {
            KeyValuePair<ulong, char> newguild;
            if (m_NewGuilds.Count > 0 && m_NewGuilds.TryDequeue(out newguild))
            {
                m_GuildsPrefix.Add(newguild.Key, newguild.Value);
            }
        }
lucid pagoda
#

Oof. I’m on mobile. Give me a min to hop on pc.

wild bronze
#

thank you appreciate it

lucid pagoda
#

why sockettextchannel and not socketguildchannel?

wild bronze
#

I am quite new still to the library

#

it never had a problem before hm

#

textchannel inherits it anyway

lucid pagoda
#

if that comes out as null, execution stops. which i think you intend. but i've not looked into forum channels and the other new types to know if that will always be NOT null in a channel a user can message in

wild bronze
#

yes i do

#

but even when i type a command of mine

#

it doesnt work

lucid pagoda
#

forum is separate from text channel

#

are you sending the message in a forum channel?

wild bronze
#

no no

#

literally

#

any message in any of my channels

#

spams that now

lucid pagoda
#

spams?

#

as in sends more than once for a given message?

wild bronze
#

anytime anyone messages

#

it just sends

#

doesntevent get to handling the command it just does the discord log

lucid pagoda
#

the "handling message" is never sent?

#

can we see your startup code? as in initializing the class that HandleCommandAsync resides in?

wild bronze
#

ye

#

ofcourse

#
        public async Task Initialize(IServiceCollection serviceprovider)
        {
            m_ServiceProvider = serviceprovider;

            DiscordWorker.Log(string.Format("Initializing Bot"), LogType.Info);
            m_BotCommandService = new CommandService(new CommandServiceConfig { DefaultRunMode = RunMode.Async });

            m_BotCommandService.Log += LogHandlerAsync;

            //
            // Init Client
            //
            var config = new DiscordSocketConfig
            {
                AlwaysDownloadUsers = false,
                GatewayIntents = GatewayIntents.AllUnprivileged | GatewayIntents.MessageContent
            };

            m_SocketClient = new DiscordSocketClient(config);

            m_SocketClient.Log += Log;
            m_SocketClient.Connected += Connected;
            m_SocketClient.JoinedGuild += BotJoinedGuild;

            await m_SocketClient.LoginAsync(TokenType.Bot, m_DiscordToken);
            await m_SocketClient.StartAsync();

            //
            // Handles Logging Messages
            //
            MessageHandler.Initialise(m_SocketClient);
        }
lucid pagoda
#

(you spelled initialize two different ways....)

#

not a code problem....

wild bronze
#

once the bot connected and the event connected is called

#
            // 
            // Init CommandHandler
            //
            DiscordWorker.Log("Initialising Commands", LogType.Info);
            m_BotCommandHandler = new CommandHandler(m_SocketClient, m_BotCommandService, m_ServiceProvider.BuildServiceProvider(),              guildprefixes);
            await m_BotCommandHandler.InstallCommandsAsync();
#

this is ran

#

it connects etc

lucid pagoda
#

where is HandleCommandAsync called?

wild bronze
#
        /// <summary>
        /// Install Commands Async
        /// </summary>
        /// <returns></returns>
        public async Task InstallCommandsAsync()
        {
            m_Client.MessageReceived += HandleCommandAsync;

            // Add Modules Here
            await m_Commands.AddModulesAsync(assembly: Assembly.GetExecutingAssembly(), services: m_ServiceProvider);
        }
lucid pagoda
#

is this all in once class?

#

I'm having a little trouble following the flow, here

wild bronze
#

I see 2 mins

#
 public async Task Initialize(IServiceCollection serviceprovider)
        {
            m_ServiceProvider = serviceprovider;

            DiscordWorker.Log(string.Format("Initializing Bot"), LogType.Info);
            m_BotCommandService = new CommandService(new CommandServiceConfig { DefaultRunMode = RunMode.Async });

            m_BotCommandService.Log += LogHandlerAsync;

            //
            // Init Client
            //
            var config = new DiscordSocketConfig
            {
                AlwaysDownloadUsers = false,
                GatewayIntents = GatewayIntents.AllUnprivileged | GatewayIntents.MessageContent
            };

            m_SocketClient = new DiscordSocketClient(config);

            m_SocketClient.Log += Log;
            m_SocketClient.Connected += Connected;
            m_SocketClient.JoinedGuild += BotJoinedGuild;

            await m_SocketClient.LoginAsync(TokenType.Bot, m_DiscordToken);
            await m_SocketClient.StartAsync();

            //
            // Handles Logging Messages
            //
            MessageHandler.Initialise(m_SocketClient);
        }

This is called first

lucid pagoda
#

what is MessageHandler?

wild bronze
#

nothing ignore it

lucid pagoda
#

is "Initializing Commands" ever sent to console?

wild bronze
#

yes

#

so we do get to the commands being handled

lucid pagoda
#

if you put a breakpoint on this:

m_Client.MessageReceived += HandleCommandAsync;
is it hit? and is m_client not null?

wild bronze
#

no its not null i have a try catch that will log any issues with this

lucid pagoda
#

i dont think try/catch will show anything for internal nested tasks

#

honestly, it sounds like an issue with your event sub never being hit.

wild bronze
#
        public async Task InstallCommandsAsync()
        {
            if (m_Client != null)
            {
                try
                {
                    m_Client.MessageReceived += HandleCommandAsync;

                    // Add Modules Here
                    await m_Commands.AddModulesAsync(assembly: Assembly.GetExecutingAssembly(), services: m_ServiceProvider);
                }
                catch (Exception e)
                {
                    DiscordWorker.Log($"Error setting up modules: {e.Message}", LogType.Error);
                }
            }
            else
            {
                DiscordWorker.Log("Client not found", LogType.Error);
            }

        }
#

would this break anything?

lucid pagoda
#

i... dont know. i've not playing with the locale stuff yet

wild bronze
#

ah i see

#

i know its not straight forward sorry

lucid pagoda
#

try putting a Console.Writeline() right after the AddModulesAsync line, to confirm that all above it has been run

#

I use a debug only logger in development. If the exe was built in debug mode, i get a ton of logging. if built as release, they're all skipped.

wild bronze
#
                try
                {
                    m_Client.MessageReceived += HandleCommandAsync;

                    // Add Modules Here
                    await m_Commands.AddModulesAsync(assembly: Assembly.GetExecutingAssembly(), services: m_ServiceProvider);
                    DiscordWorker.Log("Modules have been added", LogType.Info);
                }
                catch (Exception e)
                {
                    DiscordWorker.Log($"Error setting up modules: {e.Message}", LogType.Error);
                }
lucid pagoda
#

ok. that confirms that the event sub was passed.

#

something is breaking between that point, and when it receives its first message.

wild bronze
#

yes my handlecommandasyc is never called

lucid pagoda
#

you dont have client.messagereceived -= HandleCommandAsync anywhere, do you?

#

what is the difference between m_client and m_socketclient?

wild bronze
#
        /// <summary>
        /// Install Commands Async
        /// </summary>
        /// <returns></returns>
        public async Task InstallCommandsAsync()
        {
            if (m_SocketClient != null)
            {
                try
                {
                    m_SocketClient.MessageReceived += HandleCommandAsync;
                    // Add Modules Here
                    await m_Commands.AddModulesAsync(assembly: Assembly.GetExecutingAssembly(), services: m_ServiceProvider);
                    DiscordWorker.Log("Modules have been added", LogType.Info);
                }
                catch (Exception e)
                {
                    DiscordWorker.Log($"Error setting up modules: {e.Message}", LogType.Error);
                }
            }
            else
            {
                DiscordWorker.Log("Client not found", LogType.Error);
            }

        }
#

my naming isnt consistent

#

😅

lucid pagoda
#

but they are in fact the same client object?

wild bronze
#

yes

#

in different classes

lucid pagoda
#

🤔

wild bronze
#

one handles the initialising of the bot

#

one is handling the commands

lucid pagoda
#

i havent seen anything in the code you've shown so far, that would stand out as causing the issue. Without seeing the rest of the code, i'm limited to some assumptions.

wild bronze
#

i know its infuriating

#

just tell me im shit and find the problem

#

I literally had the message intent enabling config issue the othe rweek

#

fixed it

#

no other issues for a week

#

then it just breaks

#

it does not know the channel

#

so is it not to do with downloading the channels

#

forwhatever reason

lucid pagoda
#

only thing i can think of is that you have two different clients in your code somehow. and the wrong one is having the event subscribed to.

wild bronze
#

they are both the same

lucid pagoda
#

your bot has permission to read the messages?

wild bronze
lucid pagoda
#

what version of d.net are you on?

wild bronze
#

DiscordBot is what creates the socketclient

#
        /// <summary>
        /// Main Async
        /// </summary>
        /// <returns></returns>
        public async Task Initialize(IServiceCollection serviceprovider)
        {
            m_ServiceProvider = serviceprovider;

            DiscordWorker.Log(string.Format("Initializing Bot"), LogType.Info);
            m_BotCommandService = new CommandService(new CommandServiceConfig { DefaultRunMode = RunMode.Async });

            m_BotCommandService.Log += LogHandlerAsync;

            //
            // Init Client
            //
            var config = new DiscordSocketConfig
            {
                AlwaysDownloadUsers = false,
                GatewayIntents = GatewayIntents.AllUnprivileged | GatewayIntents.MessageContent
            };

            m_SocketClient = new DiscordSocketClient(config);

            m_SocketClient.Log += Log;
            m_SocketClient.Connected += Connected;
            m_SocketClient.JoinedGuild += BotJoinedGuild;

            await m_SocketClient.LoginAsync(TokenType.Bot, m_DiscordToken);
            await m_SocketClient.StartAsync();

            //
            // Handles Logging Messages
            //
            MessageHandler.Initialise(m_SocketClient);
        }

This is where socket client is being created and event handles added

lucid pagoda
#

what is calling CommandHandler?

wild bronze
#

on connected

#

for the socketclient event

#
        /// <summary>
        /// Connected Event
        /// </summary>
        private async Task Connected()
        {
            if (!m_Initialized)
            {
                m_Initialized = true;
                DiscordWorker.Log("CONNECTED BOT!", LogType.Info);

                try
                {
                    await GetGuildsAsync();
                }
                catch (Exception e)
                {
                    DiscordWorker.Log("Error Establishing Guilds: " + e.Message, LogType.Error); 
                }
            }
        }
#

this is the mothed.

lucid pagoda
#

i dont see a call to CommandHandler....

wild bronze
#
     /// <summary>
        /// Get Guilds Async
        /// </summary>
        private async Task GetGuildsAsync()
        {
            List<GuildItem> guilds = new List<GuildItem>();
            Dictionary<ulong, char> guildprefixes = new Dictionary<ulong, char>();
            try
            {
                // guild code
            }
            catch(Exception e)
            {
                DiscordWorker.Log($"Error: {e.Message}", LogType.Error);
            }

            // 
            // Init CommandHandler
            //
            DiscordWorker.Log("Initialising Commands", LogType.Info);
            m_BotCommandHandler = new CommandHandler(m_SocketClient, m_BotCommandService, m_ServiceProvider.BuildServiceProvider(), guildprefixes);
            try
            {
                await m_BotCommandHandler.InstallCommandsAsync();
            }
            catch (Exception e)
            {
                DiscordWorker.Log($"Error installing commands: {e.Message}", LogType.Error);
            }
        }
#

the GetGuildsAsync

lucid pagoda
#

ah. ok.

wild bronze
#
        public async Task InstallCommandsAsync()
        {
            if (m_SocketClient != null)
            {
                try
                {
                    m_SocketClient.MessageReceived += HandleCommandAsync;
                    // Add Modules Here
                    await m_Commands.AddModulesAsync(assembly: Assembly.GetExecutingAssembly(), services: m_ServiceProvider);
                    DiscordWorker.Log("Modules have been added", LogType.Info);
                }
                catch (Exception e)
                {
                    DiscordWorker.Log($"Error setting up modules: {e.Message}", LogType.Error);
                }
            }
            else
            {
                DiscordWorker.Log("Client not found", LogType.Error);
            }

        }

Then we see the log here that confirms the modules being added

#

and all i get told is the channel is unknown in the message_crate intent

lucid pagoda
#

i have no idea

wild bronze
#

might open an issue

#

on the github

lucid pagoda
#

maybe change the topic here from "unknown channel" to "messages not received"?

wild bronze
#

Message Not Received in CommandHandler

#

its a gateway problem

#

the log says

#

i wonder if its a firewall issue

#

but it retrieves the channel id

#

in the log

#

but must have 0 clue what the guild is it seems

#

that it is in

lucid pagoda
#

to be fair, this is my logging right now, and my bot is working fine...

#

the bit at the bottom is me pinging the bot

wild bronze
#

LMAO

#

hmm

#

interesting

lucid pagoda
#

🤔 try that, instead of the prefix

#

a ping.

#

or mention

wild bronze
#

so these actualy log

lucid pagoda
#

whatever you call it

wild bronze
#

with any message

#

just us typing

#

would log it

lucid pagoda
#

trying pinging the bot, and see if that hits the logging message in your handler

wild bronze
#

sorry how do i do that

lucid pagoda
#

@bot_name_here

wild bronze
#

i did that

lucid pagoda
#

i honestly dont know then.

wild bronze
#

firewall issue maybe

#

if i cant even ping it

lucid pagoda
#

still thinking that there's an issue with the event sub for MessageReceived

wild bronze
#

ye

lucid pagoda
#

you're certain that the MessageContent intent is still on in the bot portal for this bot?

wild bronze
#

Yes it is 🙂

#

I had a post the other week when I didn’t have it turned on lol

wild bronze
#

@lucid pagoda

#

so that guild available

#

gets the data on the guild

#

and because it was throwing that error

#

it never gets the data

#

so when people send message

#

with the channel id

#

it has 0 clue what the guild is

#

as that event has crashed

#

=====================Solved=====================
If there is any error within the GUILD_AVAILABLE gateway intent. The bot will not receive the information on the guilds it is in. There for message handling will not work.