discord-net / Discord.Net

An unofficial .Net wrapper for the Discord API (https://discord.com/)
https://discordnet.dev
MIT License
3.3k stars 741 forks source link

[BUG] Command not executing everything #2141

Closed HAHOOS closed 2 years ago

HAHOOS commented 2 years ago

Hello, So it happened to me few times that when I make command and execute it, only few lines are executing and function ends(goes back where it was executed). Please help as I can't do anything, because of it.

REMINDER! SENT CODE SHOULD NOT BE COPIED AS I SPEND SOME TIME MAKING THIS GIVEAWAY COMMAND AND I DO NOT WANT SOMEONE COPY ME

Command Trigger:

public async static Task CommandExecuted(SocketSlashCommand command)
        {
            var currentTime = DateTime.Now;
            Console.WriteLine($"[{currentTime:G}] Command '{command.Data.Name}' has been executed");
            switch (command.Data.Name)
            {

                case "feedback":
                    await FeedbackCommand(command);
                    break;
                case "botinfo":
                    await BotInfoCommand(command);
                    break;
                case "announce":
                    await AnnounceCommand(command);
                    break;
                case "lockdown":
                    await LockdownCommand(command);
                    break;
                case "kick":
                    await KickCommand(command);
                    break;
                case "ban":
                    await BanCommand(command);
                    break;
                case "tip":
                    await TipCommand(command);
                    break;
                case "createproductinfo":
                    await CreateProductInfoCommand(command);
                    break;
                case "wipe-data":
                    await WipeDataCommand(command);
                    break;
                case "tax":
                    await TaxCommand(command);
                    break;
                case "giveaway":
                    await GiveawayCommand(command);
                    break;
            }
        }

Giveaway Command:

private async static Task GiveawayCommand(SocketSlashCommand command)
        {
            var fieldName = command.Data.Options.First().Name;
            if(fieldName == "start")
            {
                string prize = (string)command.Data.Options.First().Options.ToArray()[0].Value;
                string time = (string)command.Data.Options.First().Options.ToArray()[1].Value;
                int winnersCount = (int)command.Data.Options.First().Options.ToArray()[2].Value;
                string req = (string)command.Data.Options.First().Options.ToArray()[4].Value;
                ITextChannel chnl = (ITextChannel)command.Data.Options.First().Options.ToArray()[3].Value;
                req = req.Replace(null, "N/A");
                long timeConv = StringToDate(time);
                long milTimeConv = timeConv * 1000;
                int intMilTimeConv = (int)timeConv * 1000;
                var embed = new EmbedBuilder()
                    .WithTitle(prize)
                    .WithColor(Color.DarkBlue)
                    .WithFooter("Hub Manager | By HAHOOS#5942", iconUrl: "https://cdn.discordapp.com/attachments/919590140790321206/932654573829628025/Hub_Manager_Icon_v2.png")
                    .WithDescription($"New giveaway has been started! React to join.{Environment.NewLine}{Environment.NewLine}**Host:**{command.User.Mention}{Environment.NewLine}**Ends in: <t:{timeConv + DateTimeOffset.Now.ToUnixTimeSeconds()}:r>**{Environment.NewLine}{Environment.NewLine}**REQUIREMENTS:**{Environment.NewLine}{req}");
                IMessage msg = await chnl.SendMessageAsync("<:Giveaway:947065168368644136> **Giveaway has been started!** <:Giveaway:947065168368644136>", embed: embed.Build());
                IEmote emoji1 = new Emoji("🎉");
                await msg.AddReactionAsync(emoji1);
                await Task.Delay(intMilTimeConv);
                var peopleReacted = msg.GetReactionUsersAsync(emoji1, 500).FlattenAsync<IUser>().Result.ToArray();

                Random r = new Random();
                List<IUser> winners = new();
                for (int i = 0; i < winnersCount; i++)
                {
                    winners.Add(peopleReacted[r.Next(0, peopleReacted.Length)]);
                }
                string mentionText = "";
                foreach(var user in winners)
                {
                    mentionText += user.Mention + " ";
                }
                await chnl.SendMessageAsync($"<:Giveaway:947065168368644136> {mentionText}has won the giveaway! <:Giveaway:947065168368644136>");
            }else if(fieldName == "reroll")
            {
                IEmote emoji1 = new Emoji("🎉");
                ulong id = (ulong)command.Data.Options.First().Options.ToArray()[0].Value;
                var chnlGuild = command.Channel as IGuildChannel;
                var guild = chnlGuild.Guild;
                IMessage msg = command.Channel.GetMessageAsync(id).Result;
                var peopleReacted = msg.GetReactionUsersAsync(emoji1, 500).FlattenAsync<IUser>().Result.ToArray();

                Random r = new Random();

                await command.RespondAsync($"**REROLL** <:Giveaway:947065168368644136> {peopleReacted[r.Next(0, peopleReacted.Length)].Mention} has won the giveaway! <:Giveaway:947065168368644136>");
            }
        }
Almighty-Shogun commented 2 years ago

Can you maybe be more specific about which part gets executed and which not? It isn't very clear for me what the issue really is.

HAHOOS commented 2 years ago
var fieldName = command.Data.Options.First().Name;
            if(fieldName == "start")
            {
                string prize = (string)command.Data.Options.First().Options.ToArray()[0].Value;
                string time = (string)command.Data.Options.First().Options.ToArray()[1].Value;
                int winnersCount = (int)command.Data.Options.First().Options.ToArray()[2].Value;

Only These

HAHOOS commented 2 years ago

I was having problem with this with all commands

HAHOOS commented 2 years ago

Still don't know why

drobbins329 commented 2 years ago

this does not seem to be a bug with the Discord.Net lib, and more an issue of the code and how it is implemented. With the code provided, we do not have enough information to help diagnose the issue. For example, how is the slash command constructed in the first place?

HAHOOS commented 2 years ago

Slash command were constructed like that:

public async Task Create()
        {
            var guild = Program._client.GetGuild(934477185748705392);
            List<ApplicationCommandProperties> applicationCommandProperties = new();

            var feedbackCmd = new SlashCommandBuilder()
            .WithName("feedback")
            .WithDescription("Rate this tech group")
            .AddOption("title", ApplicationCommandOptionType.String, "Title of your feedback", isRequired: true)
            .AddOption("note", ApplicationCommandOptionType.String, "Note of your feedback", isRequired: true)
            /*
            .AddOption(new SlashCommandOptionBuilder()
             .WithName("channel")
             .WithDescription("Change channel where feedback will be sent")
             .WithType(ApplicationCommandOptionType.SubCommand)
             .AddOption("channel", ApplicationCommandOptionType.Channel, "Channel where feedback will be sent", isRequired: true)
           )
            */
            .AddOption(new SlashCommandOptionBuilder()
               .WithName("rating")
               .WithDescription("What rating are you giving?")
               .WithRequired(true)
               .AddChoice("5 Stars", 5)
               .AddChoice("4 Stars", 4)
               .AddChoice("3 Stars", 3)
               .AddChoice("2 Stars", 2)
               .AddChoice("1 Star", 1)
               .WithType(ApplicationCommandOptionType.Integer)
            );
            Console.WriteLine($"[{DateTime.Now:G}] Created slash command example 'feedback'");

            var announceCmd = new SlashCommandBuilder()

            .WithName("announce")
            .WithDescription("Send your announcement")
            .AddOption("title", ApplicationCommandOptionType.String, "Title of your announcement", isRequired: true)
            .AddOption("description", ApplicationCommandOptionType.String, "Description of your announcement", isRequired: true)
            .AddOption("channel", ApplicationCommandOptionType.Channel, "Channel where announcement will be sent", isRequired: true);

            Console.WriteLine($"[{DateTime.Now:G}] Created slash command example 'announce'");
            var botInfoCmd = new SlashCommandBuilder()
            .WithName("botinfo")
            .WithDescription("Info about this bot");
            Console.WriteLine($"[{DateTime.Now:G}] Created slash command example 'botinfo'");
            var lockdownCmd = new SlashCommandBuilder()
            .WithName("lockdown")
            .WithDescription("Lockdown this server")
            .AddOption("reason", ApplicationCommandOptionType.String, "Reason of lockdown", isRequired: true);
            Console.WriteLine($"[{DateTime.Now:G}] Created slash command example 'lockdown'");
            var kickCmd = new SlashCommandBuilder()
            .WithName("kick")
            .WithDescription("Kick user from this server")
            .AddOption("user", ApplicationCommandOptionType.User, "User that will be kicked", isRequired: true)
            .AddOption("reason", ApplicationCommandOptionType.String, "Reason of kicking user");
            Console.WriteLine($"[{DateTime.Now:G}] Created slash command example 'kick'");
            var banCmd = new SlashCommandBuilder()
            .WithName("ban")
            .WithDescription("Ban user from this server")
            .AddOption("user", ApplicationCommandOptionType.User, "User that will be banned", isRequired: true)
            .AddOption("reason", ApplicationCommandOptionType.String, "Reason of banning user");
            Console.WriteLine($"[{DateTime.Now:G}] Created slash command example 'ban'");
            var tipCmd = new SlashCommandBuilder()
           .WithName("tip")
           .WithDescription("Gives you random tip to improve your server");
            Console.WriteLine($"[{DateTime.Now:G}] Created slash command example 'tip'");
            var createproductinfoCmd = new SlashCommandBuilder()
            .WithName("createproductinfo")
            .WithDescription("Create info for your product");
            Console.WriteLine($"[{DateTime.Now:G}] Created slash command example 'createproductinfo'");
            var wipeDataCmd = new SlashCommandBuilder()
                .WithName("wipe-data")
                .WithDescription("Wipe data from your server");
            Console.WriteLine($"[{DateTime.Now:G}] Created slash command example 'wipe-data'");
            var taxCmd = new SlashCommandBuilder()
                .WithName("tax")
                .WithDescription("Calculate how much you will get from purchase and what price you will need to get amount inserted")
                .AddOption("amount", ApplicationCommandOptionType.Integer, "Amount of robux", true);            
            Console.WriteLine($"[{DateTime.Now:G}] Created slash command example 'tax'");
            var giveawayCmd = new SlashCommandBuilder()
                .WithName("giveaway")
                .WithDescription("Main command for giveaways")
                .AddOption(new SlashCommandOptionBuilder()
                  .WithType(ApplicationCommandOptionType.SubCommand)
                  .WithName("start")
                  .WithDescription("Start a giveaway")
                  .AddOption("prize", ApplicationCommandOptionType.String, "Prize of giveaway", true)
                  .AddOption("time", ApplicationCommandOptionType.String, "Time of giveaway", true)
                  .AddOption("winners", ApplicationCommandOptionType.Integer, "Winners of giveaway", true)
                  .AddOption("channel", ApplicationCommandOptionType.Channel, "Channel where will be posted giveaway", true)
                  .AddOption("requirements", ApplicationCommandOptionType.String, "Requirements to join giveaway")
                )
                .AddOption(new SlashCommandOptionBuilder()
                  .WithType(ApplicationCommandOptionType.SubCommand)
                  .WithName("reroll")
                  .WithDescription("Reroll winner of a giveaway")
                  .AddOption("id", ApplicationCommandOptionType.Number, "Message id of giveaway")
                )
               .AddOption(new SlashCommandOptionBuilder()
                  .WithType(ApplicationCommandOptionType.SubCommand)
                  .WithName("end")
                  .WithDescription("End a giveaway")
                  .AddOption("id", ApplicationCommandOptionType.Number, "Message id of giveaway")
                );
            Console.WriteLine($"[{DateTime.Now:G}] Created slash command example 'giveaway'");
            applicationCommandProperties.Add(feedbackCmd.Build());
            applicationCommandProperties.Add(announceCmd.Build());
            applicationCommandProperties.Add(botInfoCmd.Build());
            applicationCommandProperties.Add(lockdownCmd.Build());
            applicationCommandProperties.Add(kickCmd.Build());
            applicationCommandProperties.Add(banCmd.Build());
            applicationCommandProperties.Add(tipCmd.Build());
            applicationCommandProperties.Add(createproductinfoCmd.Build());
            applicationCommandProperties.Add(wipeDataCmd.Build());
            applicationCommandProperties.Add(taxCmd.Build());
            applicationCommandProperties.Add(giveawayCmd.Build());
            try
            {
                Console.WriteLine($"[{DateTime.Now:G}] Creating slash commands");
                await guild.BulkOverwriteApplicationCommandAsync(applicationCommandProperties.ToArray());
                Console.WriteLine($"[{DateTime.Now:G}] Created slash commands");
                isStarted = true;
            }
            catch (HttpException exception)
            {
                // If our command was invalid, we should catch an ApplicationCommandException. This exception contains the path of the error as well as the error message. You can serialize the Error field in the exception to get a visual of where your error is.
                var json = JsonConvert.SerializeObject(exception.Errors, Formatting.Indented);

                // You can send this error somewhere or just print it to the console, for this example we're just going to print it.
                Console.WriteLine(json);
            }

        }
drobbins329 commented 2 years ago

I see you have the last option for the command in question as optional, but are still trying to handle an input from it.

Anu6is commented 2 years ago

If the command is successfully called, that's all the lib is responsible for. The contents of the command method is up to you. If the code is stopping at a specific point during execution of the command, then an exception is being thrown. Start by capturing and reviewing that exception in order to come up with a solution.

HAHOOS commented 2 years ago

Well, changed some things and almost everything is working, one thing don't work, I cannot get winners

Almighty-Shogun commented 2 years ago

Well, changed some things and almost everything is working, one thing don't work, I cannot get winners

You should use try catch to check if there are any errors while doing it.

Edit: I also highly recommend using InteractionFramework. You can see Cenngo's demo for a good example.

quinchs commented 2 years ago

@HAHOOS Did you find a solution to your issue?