1

I know this because of breakpoints here's code:

using DSharpPlus;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.Entities;
using DSharpPlus.EventArgs;
using DSharpPlus.Interactivity;
using DSharpPlus.Interactivity.Extensions;
using Newtonsoft.Json;
using System.Text;

interface IPermsLevel
{
    PermissionsLevel Suspended { get; set; }
    PermissionsLevel Unverified { get; set; }
    PermissionsLevel Member { get; set; }
    PermissionsLevel VIP { get; set; }
    PermissionsLevel Administrator { get; set; }
}
internal struct PermissionsLevel
{
    internal enum Permslvl : sbyte
    {
        Awaiting = -127,
        Suspended = -2,
        Unverified = -1,
        Member = 0,
        VIP = 1,
        Administrator = 2,
    }

    internal async Task<bool> UserAccessControl(Permslvl AccessLvl, Permslvl MinimumAccessLvl, Permslvl[]? BlockedAccessLvls = null)
    {
        PermissionsLevel.Permslvl permslvl = AccessLvl;
        PermissionsLevel.Permslvl RequestedPermLvl = MinimumAccessLvl;
        PermissionsLevel.Permslvl[] Blocked = BlockedAccessLvls ?? new PermissionsLevel.Permslvl[] { PermissionsLevel.Permslvl.Suspended };
        List<PermissionsLevel.Permslvl> Bypass = new() { PermissionsLevel.Permslvl.Administrator };
        if (Blocked.Length == 0)
        {
            Blocked = new PermissionsLevel.Permslvl[] { PermissionsLevel.Permslvl.Suspended };
        }
        if (Bypass.Contains(permslvl) || permslvl == RequestedPermLvl)
        {
            if (!Blocked.Contains(permslvl) || Bypass.Contains(permslvl))
            {
                await Console.Out.WriteLineAsync("Access Granted");
                return true;
            }
            else
            {
                await Console.Out.WriteLineAsync("Access Denied");
                return false;
            }
        }
        else
        {
            await Console.Out.WriteLineAsync("Acess Denied");
            return false;
        }
    }
}
internal class AccessException : Exception
{
    AccessException(string message, Exception? innerException) : base()
    {
        if (User.AccessExceptionFlagged == true && User.user.AccessLvl != PermissionsLevel.Permslvl.Suspended)
        {
            throw new AccessException("User did not have a role with high enough permissions to access this method!", null);
        }
        else
        {
            throw new AccessException("YOU ARE SUSPENDED", null);
        }
    }
}
internal class User
{
    internal string Name { get; set; } = "Deciding";
    internal PermissionsLevel.Permslvl AccessLvl { get; set; } = PermissionsLevel.Permslvl.Awaiting;
    internal static bool AccessExceptionFlagged = false;
    internal static User user = new();
    internal async static void UserGetInfo()
    {
        Console.Write("ENTER NAME:");
        string Name = Console.ReadLine() ?? "Unknown";
        Console.WriteLine("Verify with discord");
        Console.ReadKey();
        Discord discord = new();
        PermissionsLevel permissions = new();
        discord.RunAsync().GetAwaiter();
        bool Continue = true;
        while (user.AccessLvl == PermissionsLevel.Permslvl.Awaiting && Continue == true)
        {
            await Task.Delay(1000);
            if (user.AccessLvl != PermissionsLevel.Permslvl.Awaiting)
            {
                Continue = false;
            }
        }
        try
        {
            if (Continue == false)
            {
                bool V = await permissions.UserAccessControl(user.AccessLvl, PermissionsLevel.Permslvl.Unverified);
                AccessExceptionFlagged = V;
                await Console.Out.WriteLineAsync("Hello");
            }
        }
        catch (AccessException ex)
        {
            await Console.Out.WriteLineAsync($"Error You didn't meet requirements to access User method sorry ERROR: {ex}");
            await Console.Out.WriteLineAsync("Cheater");
        }
        finally
        {
            UserGetInfo();
        }
    }
}
internal class Discord
{
    internal DiscordClient Client { get; private set; }
    internal InteractivityExtension Interactivity { get; private set; }
    internal CommandsNextExtension Commands { get; private set; }
    internal async Task RunAsync()
    {
        var json = string.Empty;
        using (var fs = File.OpenRead(@"C:\Program Files (x86)\AFLLiveCoLTD\config.json"))
        using (var sr = new StreamReader(fs, new UTF8Encoding(false)))
            json = await sr.ReadToEndAsync();
        var ConfigJson = JsonConvert.DeserializeObject<ConfigJSON>(json);
        var config = new DiscordConfiguration()
        {
            Intents = DiscordIntents.All,
            Token = ConfigJson.Token,
            TokenType = TokenType.Bot,
            AutoReconnect = true,
        };
        Client = new DiscordClient(config);
        Client.UseInteractivity(new InteractivityConfiguration()
        {
            Timeout = TimeSpan.FromMinutes(1)
        });
        var commandsConfig = new CommandsNextConfiguration()
        {
            StringPrefixes = new string[] { ConfigJson.Prefix },
            EnableMentionPrefix = true,
            EnableDms = true,
        };
        Commands = Client.UseCommandsNext(commandsConfig);
        Commands.RegisterCommands<PermCommands>();
        await Client.ConnectAsync();
        await Task.Delay(-1);
    }
    private Task OnClientReady(ReadyEventArgs e)
    {
        return Task.CompletedTask;
    }

    internal struct ConfigJSON
    {
        [JsonProperty("token")]
        internal string Token { get; private set; }
        [JsonProperty("prefix")]
        internal string Prefix { get; private set; }
    }
}
internal class PermCommands : BaseCommandModule
{
    [Command("verifyplvl")]
    internal async Task Permlvl(CommandContext ctx)
    {
        var oermissions = new User();
        IEnumerable<DiscordRole>? role = ctx.Member.Roles;
        if (role.Any() == false)
        {
            User.user.AccessLvl = PermissionsLevel.Permslvl.Unverified;
        }
        else
        {
            if (role.Any(r => r.Id == 894527137250422795))
            {
                User.user.AccessLvl = PermissionsLevel.Permslvl.Administrator;
            }
            else if (role.Any(r => r.Id == 894526951119802368))
            {
                User.user.AccessLvl = PermissionsLevel.Permslvl.Administrator;
            }
            else if (role.Any(r => r.Id == 894525017780551691))
            {
                User.user.AccessLvl = PermissionsLevel.Permslvl.VIP;
            }
            else if (role.Any(r => r.Id == 894522335640580196))
            {
                User.user.AccessLvl = PermissionsLevel.Permslvl.Member;
            }
            else if (role.Any(r => r.Id == 895258073239785472))
            {
                User.user.AccessLvl = PermissionsLevel.Permslvl.Suspended;
            }
        }
        await Console.Out.WriteLineAsync(User.user.AccessLvl.ToString());
        await ctx.Channel.SendMessageAsync($"Your Permission Level is {User.user.AccessLvl}");
    }
}
class Program
{
    public static void Main()
    {
        User.UserGetInfo();
    }
}

I've been trying to find a way to make it wait for the discord bot to finish the command because it changes a value that's required for a method to spit out the information a method would want but now I have a strange issue there are no errors but it exists right when it does what I said earlier. it's supposed to keep running it's a discord bot after all and also it's supposed to execute the method UserAccessConstrol(); after the command is requested in the discord server. Sorry for the messy code, this was a test to see how things work. It ends at json = await sr.ReadToEndAsync(); there isn't a null exception happening when I run the program but I'll debug it in the future for exception proofing but this is not the issue the issue is that the program exits in json = await sr.ReadToEndAsync(); and want the rest of the discord.RunAsync(); to run also how it got this bad and went from working to not working is that I wanted to wait until value: internal PermissionsLevel.Permslvl AccessLvl { get; set; } = PermissionsLevel.Permslvl.Awaiting; has changed form awaiting to any value so method: internal async Task<bool> UserAccessControl(Permslvl AccessLvl, Permslvl MinimumAccessLvl, Permslvl[]? BlockedAccessLvls = null) has a value that the user actually has because if it runs early it will work but it will not match to what the user's role/access level actually is.

  • Welcome to Stack Overflow. Please explain clearly what it is you are doing and what your inputs are, as well as the expected outputs and the actual output. Where is it stopping? – ewokx Apr 11 '23 at 01:44
  • ok, my input for the name is anything because it doesn't matter but I always provide a value then I just press enter because of Console.ReadKey() method the last input gets received online in the discord server but it doesn't even get there the program exists before it even gets there so it doesn't become online. it ends at json = await sr.ReadToEndAsync(); I know this cause I used breakpoints. – Yesalter Yesalt Lastersonal Apr 11 '23 at 01:48
  • `internal async static void UserGetInfo()` You can't wait for this method to finish, because it doesn't return a `Task` ... Is that your question? – Jeremy Lakeman Apr 11 '23 at 01:50
  • no, my question is that the program exists before the discord bot loads and also I want to wait until one of the discord bot commands finishes executing because it modifies a value required for another method called UserAccessControl() – Yesalter Yesalt Lastersonal Apr 11 '23 at 01:52
  • also when I'm done rectifying all the errors and finishing methods I may turn this into an assembly – Yesalter Yesalt Lastersonal Apr 11 '23 at 02:07
  • also if this helps here's every warning I have CS8602 Deference of a possibly null reference line 173 col 42, CS8618 Non-nullable property 'Client' must contain a non-null value when exiting constructor. Consider declaring the property as nullable, CS8618 Non-nullable property 'Interactivity' must contain a non-null value when exiting constructor. Consider declaring property as nullable – Yesalter Yesalt Lastersonal Apr 11 '23 at 02:15
  • Those warnings mean that you're not checking for `null` when you should, so it's a very safe bet, a near certainty, that you have an unhandled `NullReferenceException`. – madreflection Apr 11 '23 at 04:22
  • Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – madreflection Apr 11 '23 at 04:22
  • here's the problem nothing is returning null so even if it were to crash for that reason in this case when I was running every path had a value so it's something else also if there where a null it was going to get a value anyways and unfortunately it doesn't make it to that part of the program it exits before in json = await sr.ReadToEndAsync(); – Yesalter Yesalt Lastersonal Apr 11 '23 at 17:32
  • but me will try to rectify these warnings – Yesalter Yesalt Lastersonal Apr 11 '23 at 17:32
  • Edited post for clarification – Yesalter Yesalt Lastersonal Apr 11 '23 at 17:41

1 Answers1

1
  1. Make UserGetInfo returning Task instead of void
internal async static Task UserGetInfo()
  1. Change your main method to be like this :
static void Main(string[] args)
    {
        Task.Run(async () =>
        {
            await User.UserGetInfo();
        }).GetAwaiter().GetResult();
    }

Lastly, add await in the finally block :

        finally
        {
            await UserGetInfo();
        }

Edit :

You can also use async main to make the code much cleaner :

public static async Task Main()
{
    await User.UserGetInfo();
}
Fitri Halim
  • 584
  • 4
  • 11
  • Or just `static async Task Main` so you don't need to use `Task.Run`. No need to overcomplicate things. – madreflection Apr 11 '23 at 04:24
  • In C#7.1 or less this `static async Task Main` is not allowed : https://stackoverflow.com/questions/9208921 @madreflection – Fitri Halim Apr 11 '23 at 04:38
  • Non-issue: C# 11 is tagged. And besides, you can use the certain features, like that one, with older runtimes because there's nothing added to the runtime to support them. You just have to set the language version explicitly. – madreflection Apr 11 '23 at 08:36
  • It works but now I'm going to have to solve other issues that I've made thanks for the help – Yesalter Yesalt Lastersonal Apr 11 '23 at 17:47
  • @YesalterYesaltLastersonal sure, you are welcome, feel free to share the other issues if you need help – Fitri Halim Apr 11 '23 at 22:02