Ejemplo n.º 1
0
 public Program()
 {
     Client = new DiscordClient
              (
         new DiscordConfiguration
     {
         UseInternalLogHandler = true,
         Token     = MainCFG.Token,
         TokenType = TokenType.Bot
     }
              );
     Interactivity = Client.UseInteractivity
                     (
         new InteractivityConfiguration()
                     );
     CommandsNext = Client.UseCommandsNext
                    (
         new CommandsNextConfiguration
     {
         StringPrefixes      = MainCFG.Prefixes,
         EnableDms           = MainCFG.EnableDms,
         EnableDefaultHelp   = false,
         EnableMentionPrefix = true
     }
                    );
     CommandsNext.RegisterCommands(Assembly.GetEntryAssembly());
 }
Ejemplo n.º 2
0
        public override BaseHelpFormatter WithCommand(Command cmd)
        {
            name        = ((cmd is CommandGroup) ? "Group: " : "Command: ") + cmd.QualifiedName;
            description = cmd.Description;

            if (cmd.Overloads?.Any() ?? false)
            {
                foreach (var overload in cmd.Overloads.OrderByDescending(o => o.Priority))
                {
                    var args = new StringBuilder();
                    foreach (var arg in overload.Arguments)
                    {
                        args.Append(Formatter.InlineCode($"[{CommandsNext.GetUserFriendlyTypeName(arg.Type)}]"));
                        args.Append(" ");
                        args.Append(arg.Description ?? "No description provided.");
                        if (arg.IsOptional)
                        {
                            args.Append(" (def: ").Append(Formatter.InlineCode(arg.DefaultValue is null ? "None" : arg.DefaultValue.ToString())).Append(")");
                            args.Append(" (optional)");
                        }
                        args.AppendLine();
                    }
                    output.AddField($"{(cmd.Overloads.Count > 1 ? $"Overload #{overload.Priority}" : "Arguments")}", args.ToString() ?? "No arguments.");
                }
            }

            if (cmd.Aliases?.Any() ?? false)
            {
                output.AddField("Aliases", string.Join(", ", cmd.Aliases.Select(a => Formatter.InlineCode(a))), inline: true);
            }
            return(this);
        }
Ejemplo n.º 3
0
        private void RegisterCommands()
        {
            Log.Logger.Debug("Registering commands");
            var commandsNextConfiguration = new CommandsNextConfiguration
            {
                StringPrefixes = Settings.Prefixes,
                Services       = Services
            };

            CommandsNext = Discord.UseCommandsNext(commandsNextConfiguration);
            CommandsNext.SetHelpFormatter <CustomHelpFormatter>();

            // Registering command classes
            CommandsNext.RegisterCommands <UserCommands>();
            CommandsNext.RegisterCommands <AdminCommands>();
            CommandsNext.RegisterCommands <DemonstrationCommands>();
            CommandsNext.RegisterCommands <RecognizerCommands>();
            CommandsNext.RegisterCommands <FunCommands>();
            CommandsNext.RegisterCommands <OsuCommands>();

            var slashCommandsConfiguration = new SlashCommandsConfiguration()
            {
                Services = Services
            };

            SlashCommands = Discord.UseSlashCommands(slashCommandsConfiguration);

            // Register slash commands modules
            SlashCommands.RegisterCommands <OsuSlashCommands>(WAV_UID);

            // Registering OnCommandError method for the CommandErrored event
            CommandsNext.CommandErrored += OnCommandError;
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Converts a argument to the specific type.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public async Task <T> ConvertArgumentAsync <T>(string key)
        {
            if (TryGetString(key, out var str))
            {
                return((T)(await CommandsNext.ConvertArgument <T>(str, Context)));
            }

            throw new KeyNotFoundException($"There is no value for the specified argument {key}");
        }
Ejemplo n.º 5
0
    /// <summary>
    /// Show help of the given command
    /// </summary>
    /// <param name="commandName">Command name</param>
    /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
    public async Task ShowHelp(string commandName)
    {
        var cmd = CommandsNext.FindCommand("help " + commandName, out var customArgs);

        if (cmd != null)
        {
            var fakeContext = CommandsNext.CreateFakeContext(Member ?? User, Channel, "help " + commandName, Prefix, cmd, customArgs);

            await CommandsNext.ExecuteCommandAsync(fakeContext)
            .ConfigureAwait(false);
        }
    }
Ejemplo n.º 6
0
        public override BaseHelpFormatter WithCommand(Command command)
        {
            Command = command;

            Embed.Description +=
                // ReSharper disable once UseStringInterpolation
                string.Format("{0}{1}: {2}", Environment.NewLine, Formatter.InlineCode(command.Name),
                              (Enumerable.Contains(command.Description, ']')
                        ? command.Description.Substring(command.Description.IndexOf(']') + 1)
                        : command.Description) ?? "No description provided");

            if (command is CommandGroup cGroup && cGroup.IsExecutableWithoutSubcommands)
            {
                Embed.WithFooter("This group can be executed as a standalone command");
            }

            if (command.Aliases?.Any() == true)
            {
                Embed.AddField("Aliases", string.Join(", ", command.Aliases.Select(Formatter.InlineCode)));
            }

            if (command.Overloads?.Any() != true)
            {
                return(this);
            }
            var sb = new StringBuilder();

            foreach (var ovl in command.Overloads.OrderByDescending(x => x.Priority))
            {
                sb.Append('`').Append($"Full Command: {command.QualifiedName}");

                foreach (var arg in ovl.Arguments)
                {
                    sb.Append(arg.IsOptional || arg.IsCatchAll ? " [" : " <").Append(arg.Name)
                    .Append(arg.IsCatchAll ? "..." : "").Append(arg.IsOptional || arg.IsCatchAll ? ']' : '>');
                }

                sb.Append($"`{Environment.NewLine}");

                foreach (var arg in ovl.Arguments)
                {
                    sb.Append('`').Append(arg.Name).Append(" (").Append(CommandsNext.GetUserFriendlyTypeName(arg.Type)).Append(")`: ")
                    .Append(arg.Description ?? "No description provided.").Append(Environment.NewLine);
                }

                sb.Append(Environment.NewLine);
            }

            Embed.AddField("Arguments", sb.ToString().Trim());

            return(this);
        }
Ejemplo n.º 7
0
            public override BaseHelpFormatter WithCommand(Command command)
            {
                Command = command;

                EmbedBuilder.WithDescription(
                    $"{Formatter.InlineCode(command.Name)}: {command.Description ?? "No description provided."}");

                if (command is CommandGroup cgroup && cgroup.IsExecutableWithoutSubcommands)
                {
                    EmbedBuilder.WithDescription(
                        $"{EmbedBuilder.Description}\n\nThis group can be executed as a standalone command.");
                }

                if (command.Aliases?.Any() == true)
                {
                    EmbedBuilder.AddField("Aliases", string.Join(", ", command.Aliases.Select(Formatter.InlineCode)),
                                          false);
                }

                if (command.Overloads?.Any() != true)
                {
                    return(this);
                }
                var sb = new StringBuilder();

                foreach (var ovl in command.Overloads.OrderByDescending(x => x.Priority))
                {
                    sb.Append('`').Append(command.QualifiedName);

                    foreach (var arg in ovl.Arguments)
                    {
                        sb.Append(arg.IsOptional || arg.IsCatchAll ? " [" : " <").Append(arg.Name)
                        .Append(arg.IsCatchAll ? "..." : "")
                        .Append(arg.IsOptional || arg.IsCatchAll ? ']' : '>');
                    }

                    sb.Append("`\n");

                    foreach (var arg in ovl.Arguments)
                    {
                        sb.Append('`').Append(arg.Name).Append(" (")
                        .Append(CommandsNext.GetUserFriendlyTypeName(arg.Type)).Append(")`: ")
                        .Append(arg.Description ?? "No description provided.").Append('\n');
                    }

                    sb.Append('\n');
                }

                EmbedBuilder.AddField("Arguments", sb.ToString().Trim(), false);
                return(this);
            }
Ejemplo n.º 8
0
        private void SetUpCommands()
        {
            var deps = new ServiceCollection().AddSingleton(Config);

            var cncfg = new CommandsNextConfiguration
            {
                StringPrefixes      = Config.Prefix,
                EnableDms           = true,
                EnableMentionPrefix = true,
                Services            = deps.BuildServiceProvider()
            };

            CommandsNext = Client.UseCommandsNext(cncfg);
            CommandsNext.RegisterCommands(typeof(Bot).GetTypeInfo().Assembly);
        }
Ejemplo n.º 9
0
        private void RegisterCommands()
        {
            var commandsNextConfiguration = new CommandsNextConfiguration
            {
                StringPrefixes = Settings.Prefixes,
            };

            CommandsNext = Discord.UseCommandsNext(commandsNextConfiguration);
            // Registering command classes
            CommandsNext.RegisterCommands <UserCommands>();
            CommandsNext.RegisterCommands <AdminCommands>();
            CommandsNext.RegisterCommands <OwnerCommands>();
            CommandsNext.RegisterCommands <DemonstrationCommands>();
            CommandsNext.RegisterCommands <VoiceCommands>();

            // Registering OnCommandError method for the CommandErrored event
            CommandsNext.CommandErrored += OnCommandError;
        }
Ejemplo n.º 10
0
    /// <summary>
    ///     Sets the command this help message will be for.
    /// </summary>
    /// <param name="command">Command for which the help message is being produced.</param>
    /// <returns>This help formatter.</returns>
    public override BaseHelpFormatter WithCommand(Command command)
    {
        Command = command;
        EmbedBuilder.WithDescription(
            $"{Formatter.InlineCode(command.Name)}: {command.Description ?? Lang.HelpCommandNoDescription}");
        if (command is CommandGroup cgroup && cgroup.IsExecutableWithoutSubcommands)
        {
            EmbedBuilder.WithDescription($"{EmbedBuilder.Description}\n{Lang.HelpCommandGroupCanBeExecuted}");
        }

        if (command.Aliases?.Any() == true)
        {
            EmbedBuilder.AddField(Lang.HelpCommandGroupAliases,
                                  string.Join(", ", command.Aliases.Select(Formatter.InlineCode)));
        }

        if (command.Overloads?.Any() == true)
        {
            var sb = new StringBuilder();
            foreach (var ovl in command.Overloads.OrderByDescending(x => x.Priority).Select(ovl => ovl.Arguments))
            {
                sb.Append('`').Append(command.QualifiedName);
                foreach (var arg in ovl)
                {
                    sb.Append(arg.IsOptional || arg.IsCatchAll ? " [" : " <").Append(arg.Name)
                    .Append(arg.IsCatchAll ? "..." : "").Append(arg.IsOptional || arg.IsCatchAll ? ']' : '>');
                }

                sb.Append("`\n");
                foreach (var arg in ovl)
                {
                    sb.Append('`').Append(arg.Name).Append(" (").Append(CommandsNext.GetUserFriendlyTypeName(arg.Type))
                    .Append(")`: ").Append(arg.Description ?? Lang.HelpCommandNoDescription).Append('\n');
                }

                sb.Append('\n');
            }

            EmbedBuilder.AddField(Lang.HelpCommandGroupArguments, sb.ToString().Trim());
        }

        return(this);
    }
Ejemplo n.º 11
0
        private Program()
        {
            Client = new DiscordClient(new DiscordConfiguration
            {
                Token                 = Config.Token,
                AutoReconnect         = false,
                UseInternalLogHandler = false,
                TokenType             = TokenType.Bot
            });

            CommandsNext = Client.UseCommandsNext(new CommandsNextConfiguration
            {
                PrefixResolver    = PrefixResolver,
                EnableDefaultHelp = false,
                EnableDms         = true
            });

            Interactivity = Client.UseInteractivity(new InteractivityConfiguration
            {
                PaginationBehaviour = PaginationBehaviour.WrapAround,
                Timeout             = TimeSpan.FromMinutes(10),
                PaginationDeletion  = PaginationDeletion.DeleteEmojis
            });
            foreach (var system in systems)
            {
                if (system.GetInterfaces().Contains(typeof(IApplyToInteractivity)))
                {
                    var instance = (IApplyToInteractivity)Activator.CreateInstance(system);
                    instance.ApplyToInteractivity(Interactivity);
                    Console.WriteLine($"[System] {system.Name} Loaded");
                }
                else if (system.GetInterfaces().Contains(typeof(IApplyToClient)))
                {
                    var instance = (IApplyToClient)Activator.CreateInstance(system);
                    instance.Activate();
                    instance.ApplyToClient(Client);
                    Console.WriteLine($"[System] {instance.Name} Loaded \n\tDescription : {instance.Description}");
                }
            }
            CommandsNext.RegisterCommands(GetExecutingAssembly());
        }
Ejemplo n.º 12
0
        public MiskDiscBot(IServiceProvider service)
        {
            _config = GetDiscordClientConfig();
            Client  = new DiscordClient(_config);

            Client.Ready += OnClientReady;

            // Make bot wait 5 minutes for user response
            Client.UseInteractivity(new InteractivityConfiguration
            {
                Timeout = TimeSpan.FromMinutes(5)
            });

            // Register and use the custom BotCommands
            Client.UseCommandsNext(GetCommandsNextConfig(Client));

            CommandsNext.RegisterCommands <GetInfoCommands>();
            CommandsNext.RegisterCommands <TeamCommands>();
            CommandsNext.RegisterCommands <InteractivityCommands>();
            CommandsNext.RegisterCommands <DALCommands>();

            Client.ConnectAsync();
        }
Ejemplo n.º 13
0
        public Dingo(BotConfig config)
        {
            Instance      = this;
            Configuration = config;
            Logger        = new Logger("BOT");

            Logger.Log("Creating Stack Exchange Client");
            Redis = new StackExchangeClient(config.Redis.Address, config.Redis.Database, Logger.CreateChild("REDIS"));
            Namespace.SetRoot(config.Redis.Prefix);

            Logger.Log("Creating new Bot");
            Discord = new DiscordClient(new DiscordConfiguration()
            {
                Token = config.Token
            });

            Logger.Log("Creating Instances");
            ReplyManager = new ReplyManager(this, Logger.CreateChild("REPLY"));
            SiegeManager = new SiegeManager(this, Logger.CreateChild("SIEGE"));
            LastManager  = new LastManager(this, Logger.CreateChild("LAST"));

            Logger.Log("Creating Command Next");
            var deps = new ServiceCollection()
                       .AddSingleton(this)
                       .BuildServiceProvider(true);

            CommandsNext = Discord.UseCommandsNext(new CommandsNextConfiguration()
            {
                PrefixResolver = ResolvePrefix, Services = deps
            });
            CommandsNext.RegisterConverter(new QueryConverter());
            CommandsNext.RegisterConverter(new CommandQueryArgumentConverter());
            CommandsNext.RegisterCommands(Assembly.GetExecutingAssembly());
            CommandsNext.CommandErrored += HandleCommandErrorAsync;

            this.Discord.ClientErrored += async(error) => await LogException(error.Exception);
        }
Ejemplo n.º 14
0
 public override BaseHelpFormatter WithCommand(Command command)
 {
     _command       = command;
     _builder.Title = $"{command.QualifiedName} ({(command is CommandGroup ? "Group" : "Command")})";
     if (_ctx.Channel.getMethodEnabled_ext(method: command.Name).False())
     {
         _builder.Title += " (disabled)";
     }
     if (command.Aliases.Any())
     {
         _builder.AddField("Aliases", string.Join(", ", command.Aliases.Select(s => $"`{s}`")));
     }
     if (command.Overloads.Any())
     {
         _builder.AddField("Overloads", string.Join("\n\n",
                                                    command.Overloads.OrderBy(s => s.Priority).Select(s =>
         {
             return
             ($"{command.QualifiedName}{(s.Arguments.Any() ? "\n" : "")}{string.Join("\n", s.Arguments.Select(a => { string tmp = $"-   `{a.Name} "; string type = CommandsNext.GetUserFriendlyTypeName(a.Type); if (a.IsCatchAll) tmp += $"[{type}...]"; else if (a.IsOptional) tmp += $"({type})"; else tmp += $"<{type}>"; return $"{tmp}`: {a.Description}"; }))}");
         })
                                                    ));
     }
     _builder.Description = command.Description;
     return(this);
 }
Ejemplo n.º 15
0
        public Wall_E()
        {
            Config = JsonConvert.DeserializeObject <Config>(File.ReadAllText(Directory.GetCurrentDirectory() + @"\Config.json"));

            Discord = new DiscordClient(new DiscordConfiguration {
                Token = Config.Token,
                UseInternalLogHandler   = true,
                TokenType               = Config.TokenType,
                AutoReconnect           = true,
                ReconnectIndefinitely   = true,
                GatewayCompressionLevel = GatewayCompressionLevel.Stream,
                LargeThreshold          = 250,
                LogLevel = LogLevel.Info,
                WebSocketClientFactory = WebSocket4NetCoreClient.CreateNew,
            });

            Lavalink = Discord.UseLavalink();

            CommandsNext = Discord.UseCommandsNext(new CommandsNextConfiguration {
                EnableDms           = Config.EnableDms,
                EnableMentionPrefix = true,
                EnableDefaultHelp   = false,
                StringPrefixes      = new[] { Config.Prefix },

                Services = new ServiceCollection()
                           .AddSingleton <CSPRNG>()
                           .AddSingleton(new MusicService(Discord))
                           .BuildServiceProvider(true)
            });

            DiscordChannel Log     = Discord.GetChannelAsync(valores.IdLogWall_E).Result;
            int            iterate = 0;

            CommandsNext.CommandErrored += async(args) => {
                var ctx = args.Context;

                CommandNotFoundException cntfe = (CommandNotFoundException)args.Exception;
                if (!String.IsNullOrEmpty(cntfe.CommandName))
                {
                    if (iterate == 1)
                    {
                        await args.Context.RespondAsync($"Nononononononono, esse comando: `{Config.Prefix}{cntfe.CommandName}` também non ecziste!");

                        iterate = 0;
                    }
                    else
                    {
                        await args.Context.RespondAsync($"Padre Quevedo te alerta, esse comando: `{Config.Prefix}{cntfe.CommandName}` non ecziste!");

                        iterate++;
                    }
                    Console.WriteLine(args.Exception.ToString());
                    await Log.SendMessageAsync($"O membro `{ctx.Member.DisplayName}` executou um comando inexistente: `{Config.Prefix}{cntfe.CommandName}`.\nChat: `{ctx.Channel}`\nDia e Hora: `{DateTime.Now}`\n-------------------------------------------------------\n");
                }
            };

            Discord.Ready += DiscordClient_Ready;

            async Task DiscordClient_Ready(ReadyEventArgs e)
            {
                await Discord.UpdateStatusAsync(new DiscordActivity("no Discord da UBGE!"));

                await Log.SendMessageAsync($"**Wall-E da Ética online!**\nLigado às: ``{DateTime.Now}``");

                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine($"[{DateTime.Now.Year}-{DateTime.Now.Month}-{DateTime.Now.Day} {DateTime.Now.Hour}:{DateTime.Now.Minute}:{DateTime.Now.Second} -03:00] [Wall-E] [DSharpPlus] Meu ping é: {Discord.Ping}ms!");
                Console.ResetColor();

                DiscordChannel Paulo = Discord.GetChannelAsync(valores.PauloCanal).Result;

                //await Paulo.SendMessageAsync($"Tenho: **{Discord.GetCommandsNext().RegisteredCommands.Count}** comandos!");
                Console.WriteLine($"[Wall-E] [DSharpPlus] Tenho: {Discord.GetCommandsNext().RegisteredCommands.Count} comandos!");

                IRC(Discord);
            }

            CommandsNext.RegisterCommands(Assembly.GetEntryAssembly());

            Interactivity = Discord.UseInteractivity(new InteractivityConfiguration {
                PaginationBehavior = TimeoutBehaviour.DeleteMessage,
                PaginationTimeout  = TimeSpan.FromMinutes(3),
                Timeout            = TimeSpan.FromMinutes(3)
            });
        }
Ejemplo n.º 16
0
 public override void RegisterCommands()
 {
     CommandsNext.RegisterCommands <DateBotCommands>();
     CommandsNext.RegisterCommands <SomeCommands>();
 }
Ejemplo n.º 17
0
        public override BaseHelpFormatter WithCommand(Command command)
        {
            if (command.Aliases?.Any() == true)
            {
                embed.AddField("Aliases:", string.Join(", ", command.Aliases.Select(Formatter.InlineCode)), false);
            }
            if (command.Overloads?.Any() == true)
            {
                var sb = new StringBuilder();
                embed.AddField(command.Name + ':', $"``_{command.Name}``: {command.Description}");

                foreach (var ovl in command.Overloads.OrderByDescending(x => x.Priority))
                {
                    foreach (var arg in ovl.Arguments)
                    {
                        sb.Append(arg.IsOptional || arg.IsCatchAll ? " [" : " <").Append(arg.Name).Append(" (").Append(CommandsNext.GetUserFriendlyTypeName(arg.Type)).Append("): ").Append(arg.Description ?? "No description provided.").Append(arg.IsCatchAll ? "..." : "").Append(arg.IsOptional || arg.IsCatchAll ? ']' : '>');
                    }

                    if (sb.Length != 0)
                    {
                        embed.AddField("Arguments:", sb.ToString().Trim(), false);
                    }
                }
            }
            return(this);
        }
Ejemplo n.º 18
0
        public override BaseHelpFormatter WithCommand(Command command)
        {
            _specificCommand = command;

            _embedBuilder.WithDescription($"{Formatter.InlineCode(prefix + command.Name)}: {command.Description ?? "No description provided."}");

            if (command is CommandGroup cgroup && cgroup.IsExecutableWithoutSubcommands)
            {
                _embedBuilder.WithDescription($"{_embedBuilder.Description}\n\nThis group can be executed as a standalone command.");
            }

            if (command.Aliases?.Any() == true)
            {
                _embedBuilder.AddField("Aliases", string.Join(", ", command.Aliases.Select(Formatter.InlineCode)), false);
            }

            if (command.Overloads?.Any() == true)
            {
                var sb = new StringBuilder();

                foreach (var ovl in command.Overloads.OrderByDescending(x => x.Priority))
                {
                    sb.Append('`').Append(prefix + command.QualifiedName);

                    if (ovl.Arguments.Any())
                    {
                        foreach (var arg in ovl.Arguments)
                        {
                            sb.Append(arg.IsOptional || arg.IsCatchAll ? " [" : " <").Append(arg.Name).Append(arg.IsCatchAll ? "..." : "").Append(arg.IsOptional || arg.IsCatchAll ? ']' : '>');
                        }

                        sb.Append("`\n");

                        foreach (var arg in ovl.Arguments)
                        {
                            sb.Append('`').Append("├ ").Append(arg.Name).Append(" (").Append(CommandsNext.GetUserFriendlyTypeName(arg.Type)).Append(")`: ").Append(arg.Description ?? "No description provided.").Append('\n');
                        }
                    }
                    else
                    {
                        sb.Append(" <none>`");
                    }

                    sb.Append('\n');
                }

                _embedBuilder.AddField("Arguments", sb.ToString().Trim(), false);
            }

            if (command.ExecutionChecks.Any())
            {
                _embedBuilder.AddField("Requires permissions", string.Join(", ", command.ExecutionChecks.Select(c => c.Translate())));
            }

            if (command.CustomAttributes.OfType <ExampleAttribute>().Any())
            {
                var examples = command.CustomAttributes.OfType <ExampleAttribute>().Select(e => e.ExampleText).ToList();
                _embedBuilder.AddField("Usage example(s)", string.Join("\n", examples.Select(e => $"{prefix}{e}")), false);
            }

            return(this);
        }
Ejemplo n.º 19
0
 public override void RegisterCommands()
 {
     CommandsNext.RegisterCommands <DummyCommands>();
 }