2

So i am creating a Discord Bot for my Discord Server but i can't figure out why it does not work. I think located the problem it's in my ReactionHandler but i am not sure what causes it?

I have tried to modify some of the code.. But i can't figure it out so i wanted to ask if somebody else knows what is wrong with my code... My code can be messy, but i hope it does not mind you. I will not show my "Commands" script because it's irrelevant to this problem!

private async Task Client_CheckTicket(SocketMessage arg)
{
    try
    {
        var Message = arg as SocketUserMessage;
        var Context = new SocketCommandContext(Client, Message);
        if (Context.Channel.Id == debugchannel)
        {
            Console.WriteLine("Detected a debug message i wont be taking any actions against it");
            return;
        }

        if (Context.User.IsBot)
        {
            String s = "";
            String path = @"C:\Users\Alex\source\repos\discbot\ids.txt";

            using (StreamReader sr = File.OpenText(path))
            {
                try
                {
                    while ((s = sr.ReadLine()) != null)
                    {
                        await DebugMessage("Checking this message: " + Message.Content);
                        if (Context.Message.Content.Contains(s))
                        {
                            messageid = Message.Id;
                            await DebugMessage("added");
                        }

                    }

                }
                catch (Exception e)
                {
                    await DebugMessage("Something went wrong... Exception was sent to console!");
                    Console.WriteLine(e);
                    return;
                }
                sr.Close();

            }
            if (messageid != 0)
            {
                path = @"C:\Users\Alex\source\repos\discbot\messageid.txt";
                using (StreamWriter sr = File.AppendText(path))
                {
                    sr.WriteLine(messageid);
                    sr.Close();
                }
            }
            else
            {
                await DebugMessage("MessageID was 0 so i will not add it to my database");
                return;
            }

        }
        else
        {
            await DebugMessage("No pass");
        }
    } catch(Exception e)
    {
       await DebugMessage(e.ToString());
    }
}

Whole code: https://pastebin.com/RrcBTdr0

Errors what i get from Output Debug:

Exception thrown: 'System.NullReferenceException' in discbot.dll
Exception thrown: 'System.NullReferenceException' in System.Private.CoreLib.dll

And on console i just get:

26.6.2019 17.20.10 at Gateway A ReactionAdded handler has thrown an unhandled exception.

I expect that the bot would message to a specific channel when a specific reaction is added to a "Ticket"

Without "Client.MessageReceived += Client_CheckTicket" and "Client.ReactionAdded += OnReactionAdded;" the other code works fine works. But when i add them back the thing just brakes...

Note: I do not get the DebugMessages on OnReactionAdded, so can there be something wrong with the execution?

private async Task OnReactionAdded(Cacheable<IUserMessage, ulong> cache, ISocketMessageChannel channel, SocketReaction thereaction)
        {
            await DebugMessage("React func started");

Can it be that when i assign/create a new variable it will overwrite a other variable because of memory usage?

MessageRecever(ik that's a typo):

private async Task Client_MessageReceived(SocketMessage arg)
        {

            var Message = arg as SocketUserMessage;
            await ReactAsync(Message);
            var Context = new SocketCommandContext(Client, Message);

            if (Context.Message == null || Context.Message.Content == "") return;
            if (Context.User.IsBot) return;

            int ArgPos = 0;
            if (!(Message.HasStringPrefix("nuked!", ref ArgPos) || Message.HasMentionPrefix(Client.CurrentUser, ref ArgPos))) return;


            var Result = await Commands.ExecuteAsync(Context, ArgPos, null);
            if (!Result.IsSuccess)
            {
                Console.WriteLine($"{DateTime.Now} at Commands Something went wrong with executing a nuke launch. Text: {Context.Message.Content} | Error: {Result.ErrorReason}");
                await Context.Channel.SendMessageAsync($"{DateTime.Now} at Commands Something went wrong with executing a nuke launch. Text: {Context.Message.Content} | Error: {Result.ErrorReason}");
            }

        }

I have tried to locate the problem more and i think it's around here:

 using (StreamReader sr = File.OpenText(path))
                    {
                        try
                        {
                            while ((s = sr.ReadLine()) != null)
                            {
                                DebugMessage("Checking this message: " + Message.Content);
                                if (Context.Message.Content.Contains(s))
                                {
                                    messageid = Message.Id;
                                    DebugMessage("added");
                                }

                            }

                        }
                        catch (Exception e)
                        {
                            DebugMessage("Something went wrong... Exception was sent to console!");
                            Console.WriteLine(e);
                            return;
                        }
                        sr.Close();

                    }

Finally i got some more specific Error's:

System.NullReferenceException: Object reference not set to an instance of an object. at discbot.Program.DebugMessage(String a) in C:\Users\Alex\source\repos\discbot\discbot\Program.cs:line 103 at discbot.Program.Client_CheckTicket(SocketMessage arg) in C:\Users\Alex\source\repos\discbot\discbot\Program.cs:line 222

Line 103: await Client.GetGuild(593114638770634763).GetTextChannel(593430696874213384).SendMessageAsync(a);

Line 222: await DebugMessage("No pass");

Yes, it's a nullreference error and there are alot of answers for them but i can't figure this out..

Console.WriteLine(a);
            await Client.GetGuild(593114638770634763).GetTextChannel(593430696874213384).SendMessageAsync(a);

The WriteLine works, but the SenmessageAsync returns the NullReferenceException.. And i checked my server id and my channelid's are correct...

So the problem is in:

public async Task DebugMessage(string a)
        {
            Console.WriteLine(a);
            await Client.GetGuild(593114638770634763).GetTextChannel(593430696874213384).SendMessageAsync(a);

        }

and the null error is happening on the: Client.GetGuild(593114638770634763).GetTextChannel(593430696874213384).SendMessageAsync(a);

Because when i do await DebugMessage("No pass"); the Console.WriteLine works but the second one does not? Any idea why it does not work?

The string "a" is not the cause because i replaced the a variable with this: await Client.GetGuild(593114638770634763).GetTextChannel(593430696874213384).SendMessageAsync("ok");

And it still did not work...

And if you still don't understand what part is broken it's this:

await Client.GetGuild(593114638770634763).GetTextChannel(593430696874213384).SendMessageAsync(The variable is not causing this...);

Now i set it up like this:

public async Task DebugMessage(string a)
        {
            Console.WriteLine("Getting server");
            var server =  Client.GetGuild(593114638770634763);
            Console.WriteLine("Getting chat");
            var chat = server.GetTextChannel(593430696874213384);
            Console.WriteLine("Writing to Chat");
            await chat.SendMessageAsync(a);
            Console.WriteLine("Succeeded");

        }

And it failed on: await chat.SendMessageAsync(a);

Turpo
  • 27
  • 4
  • 1
    which line throws this exception? There are many places which can throw NullReferenceException here. Before using A.B.C you need to first be sure that A.B is not null, it's best to check it and put debug messages every time or use null-conditional operator like A?.B?.C. Also when you need to cast something, use (SocketUserMessage)arg that will throw InvalidCastException in case of failure. Using "as" without checking for nulls will let the code fail later but it will be not clear that the cast failed – Adassko Jun 26 '19 at 14:58
  • 26.6.2019 17.20.10 at Gateway A ReactionAdded handler has thrown an unhandled exception. that is the Errors that i get on console log – Turpo Jun 26 '19 at 15:20
  • why don't you break down your statements and use the debugger to try to figure out what is null, instead of chaining your calls together? Once you know which variable is null, someone can possibly provide assistance as to why it may be null. But definitely you first need to figure out what is null. – Anu6is Jun 26 '19 at 19:25
  • This is the line that causes the error or i think: `await Client.GetGuild(593114638770634763).GetTextChannel(593430696874213384).SendMessageAsync(a);` in `public async Task DebugMessage(string a) { Console.WriteLine(a); await Client.GetGuild(593114638770634763).GetTextChannel(593430696874213384).SendMessageAsync(a); } ` – Turpo Jun 26 '19 at 19:36
  • @Anu6is i made it more specific now... – Turpo Jun 26 '19 at 19:41
  • Like I said, don't chain the method calls. Do your GetGuild() and GetTextChannel() separately and ensure that neither are null. – Anu6is Jun 26 '19 at 20:04
  • ok, i will try now.. – Turpo Jun 26 '19 at 20:10
  • i tried `Console.WriteLine("Getting server"); var server = Client.GetGuild(schedulechannel); Console.WriteLine("Getting chat"); var chat = server.GetTextChannel(schedulechannel); Console.WriteLine("Writing to Chat"); await chat.SendMessageAsync(a); Console.WriteLine("Succeeded");` And it failed on `await chat.SendMessageAsync(a);` Do u have any clue why? @Anu6is – Turpo Jun 26 '19 at 20:16
  • Because `chat` is `null`... most likely because your ID is incorrect and no channel with a matching ID can be found in that guild. – Anu6is Jun 26 '19 at 20:30
  • it worked now i feel very dumb... i tought the id was right – Turpo Jun 26 '19 at 20:49

1 Answers1

-1

"Because chat is null... most likely because your ID is incorrect and no channel with a matching ID can be found in that guild." -Anu6is This worked....

Turpo
  • 27
  • 4