#NullReferenceException when I send a message in a thread in the latest nightly (1896)

1 messages · Page 1 of 1 (latest)

mellow marten
#

Hello,

I have a routine that create a thread inside a forum channel and send messages in it when it detect a change from a certain url. It worked fine on the 1735 nightly but since I upgraded to the 1896 one it throw a NullReferenceException. Here my code :

public static class LangsManager
{
    public static async void OnCheckLangFinished(object? _, CheckLangFinishedEventArgs e)
    {
        if (e.UpdatedLangsData.Count == 0)
        {
            return;
        }

        DiscordForumChannel? forum = await GetLangForumChannel();
        if (forum is null)
        {
            return;
        }

        DiscordThreadChannel thread = await CreateThreadAsync(forum, e.Type, e.Language);

        foreach (LangData updatedLangData in e.UpdatedLangsData)
        {
            Task delay = Task.Delay(1000);

            await SendLangMessageAsync(thread, updatedLangData);

            await delay;
        }
    }

    private static async Task<DiscordForumChannel?> GetLangForumChannel()
    {
        ulong id = Bot.Config.LangForumChannelId;
        if (id == 0)
        {
            return null;
        }

        try
        {
            DiscordChannel channel = await Bot.Client.GetChannelAsync(id);
            if (channel is DiscordForumChannel forum)
            {
                return forum;
            }

            Log.Error("The given lang channel is not a forum {ChannelId}", id);
        }
        catch
        {
            Log.Error("Unknown lang forum channel {ChannelId}", id);
        }

        return null;
    }

    private static async Task<DiscordThreadChannel> CreateThreadAsync(DiscordForumChannel forum, LangType type, LangLanguage language)
    {
        DateTime now = DateTime.Now;

        ForumPostBuilder postBuilder = new ForumPostBuilder()
            .WithName($"{type} {language} {now:dd-MM-yyyy HH\\hmm}")
            .WithMessage(new DiscordMessageBuilder().WithContent($"Diff des langs {Formatter.Bold(type.ToString())} de {now:HH\\hmm} le {now:dd/MM/yyyy} en {Formatter.Bold(language.ToString())}"));

        DiscordForumTag? typeTag = GetDiscordForumTagByName(forum, type.ToString());
        if (typeTag is not null)
        {
            postBuilder.AddTag(typeTag);
        }

        DiscordForumTag? languageTag = GetDiscordForumTagByName(forum, language.ToString());
        if (languageTag is not null)
        {
            postBuilder.AddTag(languageTag);
        }

        DiscordForumPostStarter post = await forum.CreateForumPostAsync(postBuilder);

        return post.Channel;
    }

    private static DiscordForumTag? GetDiscordForumTagByName(DiscordForumChannel forum, string name)
    {
        return forum.AvailableTags.FirstOrDefault(x => x.Name.Equals(name));
    }

    private static async Task<DiscordMessage> SendLangMessageAsync(DiscordThreadChannel thread, LangData langData)
    {
        DiscordMessageBuilder message = new DiscordMessageBuilder()
                .WithContent($"{(langData.New ? $"{Formatter.Bold("New")} lang" : "Lang")} {Formatter.Bold(langData.Name)} version {Formatter.Bold(langData.Version.ToString())}");

        string diffFilePath = langData.GetDiffFilePath();
        if (!File.Exists(diffFilePath))
        {
            return await thread.SendMessageAsync(message);
        }

        using FileStream fileStream = File.OpenRead(diffFilePath);
        return await thread.SendMessageAsync(message.AddFile($"{langData.Name}.as", fileStream));
    }
}
digital vectorBOT
#
Automated suggestion: You don't have the Message Content Intent enabled

As of September 1st 2022, Discord started requiring message content intent for bots that want to read message content. This is a privileged intent!

If your bot has under 100 guilds, all you have to do is flip the switch in the developer dashboard (over at https://discord.com/developers/applications, also see the image) and then specifying the intent in your DiscordConfiguration (see the code example)
If your bot has over 100 guilds, you'll need approval from Discord's end.

Even though you can just use this to get away with it, it is recommended by Discord to use Slash Commands whenever possible, so look into that if you can (Slash Commands Documentation)

More info:
https://support-dev.discord.com/hc/en-us/articles/4404772028055-Message-Content-Privileged-Intent-FAQ

Code Example:

DiscordConfiguration config = new() {
    // ...
    // If you do not set this, your bot will fail to start with the error code: "Disallowed intent(s)"
    Intents = DiscordIntents.AllUnprivileged | DiscordIntents.MessageContents,
    // ...
}
mellow marten
#

and the error :

blazing breach
#

what's the full stacktrace

mellow marten
#
   at DSharpPlus.Entities.DiscordChannel.<SendMessageAsync>d__88.MoveNext()
   at Cyberia.Salamandra.Managers.LangsManager.<SendLangMessageAsync>d__4.MoveNext() in C:\Users\xxxx\source\repos\Cyberia\Cyberia.Salamandra\Managers\LangsManager.cs:line 100
#

only this

mellow marten
#

NullReferenceException when I send a message in a thread the latest nightly (1896)

#

NullReferenceException when I send a message in a thread in the latest nightly (1896)

still mantle
#

Where does this thread entity comes from?

mellow marten
#

from the CreateThreadAsync method in the code above

#

i get it from the post i send

still mantle
#

ah ok i think i found the issue, im currently busy, will open a pr in 1-2h

mellow marten
#

thx !

still mantle
#

Can you test ##1690

wild tokenBOT
still mantle
#

hans tag pr artifacts

wild tokenBOT
# still mantle hans tag pr artifacts

To run the library off a pull request, you will need a GitHub account. Navigate to the pull request you want to use and click on the green check mark next to the latest commit: https://cdn.discordapp.com/attachments/379379415475552276/1075485948281888788/image.png

Then, go to "Details" and scroll all the way down to "Artifacts". Download the zip file and extract it into a folder of your choice.

Now, you need to add the packages to your project.

Using CLI:

Run dotnet add package <package-name> --source "path/to/your/package/folder"

Using Visual Studio:

Add your local folder as a package source in this dialog, reached through the little gear icon in your NuGet dialogue, see https://cdn.discordapp.com/attachments/959804202744422453/962070642432311366/unknown.png and https://cdn.discordapp.com/attachments/959804202744422453/962070737148051536/unknown.png. You'll want to click the plus icon to create a new package source, then enter your folder name at "Source".

Using your .csproj file:

(do not.)
Add <RestoreAdditionalPackageSources>path/to/your/package/folder</RestoreAdditionalPackageSources> to your head PropertyGroup.

In the latter two cases, you should then be able to update D#+ to the pull request build through your NuGet dialogue.

still mantle
#

Ok its merged now so you can simply test with the newest nightly

mellow marten
#

it works !