Пример #1
0
        public async Task RunAsync()
        {
            var json = string.Empty;

            using (var fs = File.OpenRead("config.json"))
                using (var sr = new StreamReader(fs, new UTF8Encoding(false)))
                    json = await sr.ReadToEndAsync().ConfigureAwait(false);


            var configJson = JsonConvert.DeserializeObject <ConfigJson>(json);

            var config = new DiscordConfiguration
            {
                Token           = configJson.Token,
                TokenType       = TokenType.Bot,
                AutoReconnect   = true,
                MinimumLogLevel = LogLevel.Debug,
                //UseInternalLogHandler = true
            };

            Client = new DiscordClient(config);

            Client.Ready += OnClientReady;

            Client.UseInteractivity(new InteractivityConfiguration
            {
                Timeout = TimeSpan.FromMinutes(2)
            });

            var commandsConfig = new CommandsNextConfiguration
            {
                StringPrefixes      = new string[] { configJson.Prefix },
                EnableDms           = false,
                EnableMentionPrefix = true,
                DmHelp = true,
            };

            Commands = Client.UseCommandsNext(commandsConfig);

            Commands.RegisterCommands <ListOfCommands>();

            await Client.ConnectAsync();

            await Task.Delay(-1);
        }
Пример #2
0
 public static void AddCommands(this CommandsNextExtension commands)
 {
     commands.RegisterCommands <RouletteCommand>();
     commands.RegisterCommands <CoinflipCommand>();
     commands.RegisterCommands <SlotsCommand>();
     commands.RegisterCommands <CreditsCommand>();
     commands.RegisterCommands <GlobalTopCommand>();
     commands.RegisterCommands <HourlyRewardCommand>();
     commands.RegisterCommands <DailyRewardCommand>();
     commands.RegisterCommands <CooldownCommand>();
     commands.RegisterCommands <WorkRewardCommand>();
     commands.RegisterCommands <GamesHistoryCommand>();
     commands.RegisterCommands <ShowProfileCommand>();
     commands.RegisterCommands <VoteRewardCommand>();
     commands.RegisterCommands <AboutCommand>();
     commands.RegisterCommands <CollectDropCommand>();
     commands.RegisterCommands <CountDEBUGCommand>();
 }
Пример #3
0
        private static async Task ChecksFailedError(CommandsNextExtension c, CommandErrorEventArgs e)
        {
            if (e.Exception is not ChecksFailedException checksFailed)
            {
                return;
            }

            IReadOnlyList <CheckBaseAttribute> failedChecks = checksFailed.FailedChecks;

            if (!failedChecks.Any())
            {
                return;
            }

            await e.Context.RespondAsync($"You can't use `{e.Command.QualifiedName}` because of the following reason(s):\n - {DetermineMessage(failedChecks, e.Context)}.");

            e.Handled = true;
        }
Пример #4
0
        private void RegisterCommands()
        {
            var commandsNextConfiguration = new CommandsNextConfiguration
            {
                StringPrefixes = SettingsService.Instance.Cfg.Prefixes,
            };

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

            // Registering OnCommandError method for the CommandErrored event
            _commands.CommandErrored += OnCommandError;
        }
Пример #5
0
        public static CommandsNextExtension RegisterAllCommandModules(this CommandsNextExtension cmdExt)
        {
            var cmdModules = GetAllCommandModules();

            foreach (var cmdModule in cmdModules)
            {
                try
                {
                    cmdExt.RegisterCommands(cmdModule);
                }
                catch (Exception e)
                {
                    //Ignored
                }
            }

            return(cmdExt);
        }
Пример #6
0
        private async Task Commands_CommandErrored(CommandsNextExtension sender, CommandErrorEventArgs e)
        {
            e.Context.Client.Logger.LogError(BotEventId, $"{e.Context.User.Username} tried executing '{e.Command?.QualifiedName ?? "<unknown command>"}' but it errored: {e.Exception.GetType()}: {e.Exception.Message ?? "<no message>"}", DateTime.Now);

            if (e.Exception is ChecksFailedException exception)
            {
                var emoji = DiscordEmoji.FromName(e.Context.Client, ":no_entry:");

                var embed = new DiscordEmbedBuilder
                {
                    Title       = "Access denied",
                    Description = $"{emoji} Sorry {e.Context.User.Username}, You do not have the permissions required to execute this command.",
                    Color       = new DiscordColor(0xFF0000)
                };

                await e.Context.RespondAsync("", embed : embed);
            }
        }
Пример #7
0
        public Bot(Config _config)
        {
            config = _config;

            if (config.BotProxyEnabled)
            {
                _proxy             = new WebProxy(config.BotProxyAddress);
                _proxy.Credentials = new NetworkCredential(config.BotProxyUsername, config.BotProxyPassword);;
            }

            MainAsync(config.Token).ConfigureAwait(false).GetAwaiter().GetResult();
            commands = client.UseCommandsNext(new CommandsNextConfiguration
            {
                StringPrefixes = new string[] { config.Prefix }
            });
            commands.RegisterCommands <MyCommands>();
            commands.SetHelpFormatter <HelpFormatter>();
        }
Пример #8
0
        public async Task RunAsync()
        {
            DiscordConfiguration config = new DiscordConfiguration
            {
                Token = // Insert personal token here.
#if DEBUG
                        ReadFromJson("debug"),
#else                                               // Using this format to switch between the live bot and a bot used for debugging.
                        ReadFromJson("release"),
#endif
                TokenType             = TokenType.Bot,
                AutoReconnect         = true,
                LogLevel              = LogLevel.Debug,
                UseInternalLogHandler = true
            };

            Client = new DiscordClient(config);

            Client.Ready += OnClientReady;

            CommandsNextConfiguration commandsConfig = new CommandsNextConfiguration
            {
                StringPrefixes      = new[] { "!", "?", "." }, // Can be changed to fit user liking.
                EnableDms           = false,
                EnableMentionPrefix = true,
                DmHelp = true
            };

            Client.UseInteractivity(new InteractivityConfiguration
            {
                Timeout = TimeSpan.FromMinutes(2) // Can be tuned to user liking. 2 = 2 minutes.
            });

            Commands = Client.UseCommandsNext(commandsConfig);

            Commands.RegisterCommands <CommandsClass>();
            Commands.RegisterCommands <TicTacToe>();
            Commands.RegisterCommands <LogServersOnline>();
            Commands.RegisterCommands <TrackScores>();

            await Client.ConnectAsync();

            await Task.Delay(-1);
        }
Пример #9
0
        internal Bot(IServiceProvider serviceProvider,
                     BotConfiguration botConfiguration)
        {
            _serviceProvider  = serviceProvider;
            _botConfiguration = botConfiguration;

            var discordConfig = new DiscordConfiguration
            {
                Token    = _botConfiguration.DiscordToken,
                LogLevel = LogLevel.Debug,
                UseInternalLogHandler = false,
                ReconnectIndefinitely = true
            };

            _discordClient = new DiscordClient(discordConfig);

            var interactivityConfig = new InteractivityConfiguration {
                PaginationBehaviour = PaginationBehaviour.Ignore
            };

            _discordClient.UseInteractivity(interactivityConfig);

            var commandsConfig = new CommandsNextConfiguration
            {
                StringPrefixes      = new[] { COMMAND_PREFIX },
                Services            = serviceProvider,
                CaseSensitive       = false,
                EnableMentionPrefix = false
            };

            _commandsNextConfig = commandsConfig;
            _commands           = _discordClient.UseCommandsNext(commandsConfig);
            _commands.RegisterCommands(Assembly.GetExecutingAssembly());
            _commands.SetHelpFormatter <HelpFormatter>();

            _discordClient.DebugLogger.LogMessageReceived += OnLogMessageReceived;
            _discordClient.GuildCreated       += OnGuildAvailable;
            _discordClient.GuildDeleted       += OnGuildDeleted;
            _discordClient.GuildMemberAdded   += OnGuildMemberAdded;
            _discordClient.GuildMemberRemoved += OnGuildMemberRemoved;
            _discordClient.Ready += _ => Task.FromResult(_clientIsReady = true);

            _commands.CommandErrored += OnCommandError;
        }
Пример #10
0
        private static async Task MainAsync()
        {
            var data = new Global().DefaultDatabase();

            _yone = new DiscordClient(new DiscordConfiguration
            {
                Token                 = data.botToken,
                TokenType             = TokenType.Bot,
                UseInternalLogHandler = true,
                AutomaticGuildSync    = true,
                AutoReconnect         = true
            });
            _commands = _yone.UseCommandsNext(new CommandsNextConfiguration
            {
                PrefixResolver       = GetPrefixPositionAsync,
                EnableMentionPrefix  = true,
                EnableDms            = false,
                CaseSensitive        = false,
                IgnoreExtraArguments = true
            });
            _yone.UseInteractivity(new InteractivityConfiguration
            {
                PaginationBehavior = 0,
                PaginationTimeout  = TimeSpan.FromMinutes(5.0),
                Timeout            = TimeSpan.FromMinutes(2.0)
            });
            var msc = new VoiceNextConfiguration
            {
                VoiceApplication = VoiceApplication.Music
            };


            var dspExtended = _yone.UseDspExtended();

            _commands.SetHelpFormatter <Help.DefaultHelpFormatter>();
            _commands.RegisterCommands(Assembly.GetExecutingAssembly());

            dspExtended.RegisterAssembly(Assembly.GetExecutingAssembly());

            _yone.UseVoiceNext(msc);
            await _yone.ConnectAsync();

            await Task.Delay(-1);
        }
Пример #11
0
        /// <summary>
        /// Starts or stops discord
        /// </summary>
        /// <returns>The built task</returns>
        public async Task StartStopDiscord()
        {
            try
            {
                if (!IsRunning)
                {
                    IsRunning = true;
                    Logger.Log("Connecting to Discord...", LogLevel.Info);
                    await _client.ConnectAsync();

                    await Task.Delay(1000);

                    await _client.UpdateStatusAsync(new DiscordActivity(
                                                        $"{_client.CurrentApplication.Owners.First().Username}",
                                                        ActivityType.Watching));

                    Logger.Log($"Successfully connected to Discord on {_client.Guilds.Count} Servers:\n\t{string.Join("\n\t", _client.Guilds.Values)}", LogLevel.Info);
                }
                else
                {
                    IsRunning = false;
                    Logger.Log("Disconnecting from Discord...", LogLevel.Info);
                    await Dispose();

                    _client = new DiscordClient(new DiscordConfiguration
                    {
                        Token = Config.Instance.Token
                    });
                    _commandsNext = _client.UseCommandsNext(new CommandsNextConfiguration
                    {
                        EnableDms      = false,
                        StringPrefixes = new List <string> {
                            Config.Instance.Prefix
                        }
                    });
                    Logger.Log("Successfully disconnected", LogLevel.Info);
                }
            }
            catch (Exception e)
            {
                Logger.Log($"Error logging into Discord: {e.Message}", LogLevel.Error);
            }
        }
Пример #12
0
        public async Task RunAsync()
        {
            var json = string.Empty;

            using (var fs = File.OpenRead("config.json"))
                using (var sr = new StreamReader(fs, new UTF8Encoding(false)))
                    json = await sr.ReadToEndAsync().ConfigureAwait(false);

            var configJson = JsonConvert.DeserializeObject <ConfigJson>(json);

            var config = new DiscordConfiguration
            {
                Token                 = configJson.Token,
                TokenType             = TokenType.Bot,
                AutoReconnect         = true,
                LogLevel              = LogLevel.Debug,
                UseInternalLogHandler = true
            };

            Client = new DiscordClient(config);

            Client.Ready += OnClientReady;

            Client.UseInteractivity(new InteractivityConfiguration
            {
            });

            var commandsConfig = new CommandsNextConfiguration
            {
                StringPrefixes       = new string[] { configJson.Prefix },
                EnableMentionPrefix  = true,
                EnableDms            = true,
                IgnoreExtraArguments = true,
                CaseSensitive        = false
            };

            Commands = Client.UseCommandsNext(commandsConfig);
            Commands.RegisterCommands <SheetManager>();
            Commands.RegisterCommands <RoleplayManager>();
            await Client.ConnectAsync();

            await Task.Delay(-1);
        }
Пример #13
0
        public static async Task Main(string[] args)
        {
            var discordConfig = Config.AppSetting.GetSection("DiscordSettings");

            _discord = new DiscordClient(new DiscordConfiguration
            {
                Token           = discordConfig["token"],
                TokenType       = TokenType.Bot,
                MinimumLogLevel = LogLevel.Debug,
            });

            _commands = _discord.UseCommandsNext(new CommandsNextConfiguration
            {
                EnableDms           = true,
                EnableMentionPrefix = true,
                StringPrefixes      = new [] { discordConfig["prefix"] },
            });

            _discord.UseInteractivity(new InteractivityConfiguration
            {
            });

            var slash = _discord.UseSlashCommands();

            slash.RegisterCommands <XbpsSlashCommands>(323558395414183936);
            slash.RegisterCommands <LevelCommands>(323558395414183936);
            slash.RegisterCommands <ModerationCommands>(323558395414183936);
            slash.RegisterCommands <MiscCommands>(323558395414183936);


            await _discord.ConnectAsync();

            _discord.Ready += (sender, eventArgs) =>
            {
                _ = Task.Run(UpdateStatus);
                return(Task.CompletedTask);
            };


            LevelingSystem.Init(_discord);
            DiscordLogger.Init(_discord);
            await Task.Delay(-1);
        }
Пример #14
0
        // this instantiates the container class and the client
        public Bot(string token)
        {
            // create config from the supplied token
            var cfg = new DiscordConfiguration
            {
                Token     = token,               // use the supplied token
                TokenType = TokenType.Bot,       // log in as a bot
                Intents   = DiscordIntents.AllUnprivileged
                            | DiscordIntents.GuildMembers,
                AutoReconnect   = true,          // reconnect automatically
                MinimumLogLevel = LogLevel.Debug,
            };

            // initialize the client
            this.Client = new DiscordClient(cfg);

            var ccfg = new CommandsNextConfiguration
            {
                // let's use a string prefix
                StringPrefixes = new[] { "." },

                // enable responding in direct messages
                EnableDms = true,

                // enable mentioning the bot as a command prefix
                EnableMentionPrefix = true
            };

            // and hook them up
            this.Commands = this.Client.UseCommandsNext(ccfg);

            // let's hook some command events, so we know what's
            // going on
            this.Commands.CommandExecuted += this.Commands_CommandExecuted;
            this.Commands.CommandErrored  += this.Commands_CommandErrored;

            // up next, let's register our commands
            this.Commands.RegisterCommands <CommandsGame>();
            this.Commands.RegisterCommands <CommandsPlayer>();

            // set up our custom help formatter
            this.Commands.SetHelpFormatter <SimpleHelpFormatter>();
        }
Пример #15
0
 // Registers all command modules
 static void RegisterCommands(ref CommandsNextExtension commands)
 {
     // Register commands
     commands.RegisterCommands <Prefixes>();
     commands.RegisterCommands <Meta>();
     commands.RegisterCommands <Rename>();
     commands.RegisterCommands <Delete>();
     commands.RegisterCommands <Say>();
     commands.RegisterCommands <MediaGenCommands>();
     commands.RegisterCommands <Anon>();
     commands.RegisterCommands <Avatar>();
     commands.RegisterCommands <ReactionPins>();
     commands.RegisterCommands <Spoil>();
     //commands.RegisterCommands<Commands.Utilities>();
     // Execute onStart scripts to register events
     Anon.OnStart(commands.Client, Configuration);
     ReactionPins.OnStart(commands.Client, Configuration);
     MediaGenCommands.OnStart(commands.Client, Configuration);
 }
Пример #16
0
        private async Task Commands_CommandErrored(CommandsNextExtension ext, CommandErrorEventArgs e)
        {
            if (e.Exception is ChecksFailedException)
            {
                var emoji = DiscordEmoji.FromName(e.Context.Client, ":no_entry:");
                await e.Context.RespondAsync($"{emoji} Access denied!");
            }
            else if (e.Exception is CommandNotFoundException)
            {
                Console.WriteLine(e.Exception.Message);
            }
            else
            {
                Console.WriteLine(e.Exception.Message);
                Console.WriteLine(e.Exception.StackTrace);

                await e.Context.RespondAsync(e.Exception.Message);
            }
        }
Пример #17
0
        public static void RegisterPlugin(Plugin plugin, CommandsNextExtension extension)
        {
            Logger.Info($"Registering '{plugin.Name}' from {plugin.Author}");

            Type[] assemblyTypes = plugin.GetType().Assembly.GetTypes();
            Type   commandClass  = assemblyTypes.FirstOrDefault(t => t.CustomAttributes.Any(a => a.AttributeType == typeof(CommandClass)));

            if (commandClass == null)
            {
                Logger.Warn($"{plugin.Name} doesn't have a main command class");
                return;
            }

            extension.RegisterCommands(commandClass);

            plugin.OnPluginRegistered();

            Logger.Info($"Registered plugin '{plugin.Name}'");
        }
Пример #18
0
        public async Task Start()
        {
            var json = string.Empty;

            using (var fs = File.OpenRead("config.json"))
                using (var sr = new StreamReader(fs, new UTF8Encoding(false)))
                    json = await sr.ReadToEndAsync().ConfigureAwait(false);

            var configJson = JsonConvert.DeserializeObject <ConfigJson>(json);

            var config = new DiscordConfiguration
            {
                Token           = configJson.Token,
                TokenType       = TokenType.Bot,
                AutoReconnect   = true,
                MinimumLogLevel = LogLevel.Debug
            };

            Client = new DiscordClient(config);

            Client.Ready += OnClientReady;

            Client.MessageReactionAdded   += OnReactionAdded;
            Client.MessageReactionRemoved += OnReactionRemoved;


            var commandsConfig = new CommandsNextConfiguration
            {
                StringPrefixes      = new string[] { configJson.Prefix },
                EnableMentionPrefix = true,
                EnableDms           = false,
                DmHelp            = true,
                EnableDefaultHelp = true,
            };

            Commands = Client.UseCommandsNext(commandsConfig);

            Commands.RegisterCommands <ChatCommands>();

            await Client.ConnectAsync();

            await Task.Delay(-1);
        }
Пример #19
0
        public async Task RunAsync()
        {
            var json = "";

            using (var fs = File.OpenRead("config.json"))
                using (var sr = new StreamReader(fs, new UTF8Encoding(false)))
                    json = await sr.ReadToEndAsync().ConfigureAwait(false);

            var configJson = JsonConvert.DeserializeObject <ConfigJSON>(json);

            var config = new DiscordConfiguration
            {
                //Token = configJson.Token,
                Token                 = "",
                TokenType             = TokenType.Bot,
                AutoReconnect         = true,
                LogLevel              = LogLevel.Debug,
                UseInternalLogHandler = true
            };

            Client = new DiscordClient(config);

            Client.Ready += OnClientReady;

            var commandsConfig = new CommandsNextConfiguration
            {
                StringPrefixes      = new string[] { configJson.Prefix },
                EnableMentionPrefix = true,
                EnableDms           = false
            };

            Commands = Client.UseCommandsNext(commandsConfig);

            Commands.RegisterCommands <FunCommands>();
            Commands.RegisterCommands <ReminderCommands>();
            Commands.RegisterCommands <PrankCommands>();
            Commands.RegisterCommands <WeatherCommand>();


            await Client.ConnectAsync();

            await Task.Delay(-1);
        }
Пример #20
0
        public async Task RunAsync()
        {
            var root = Environment.GetEnvironmentVariable("WEBROOT_PATH");

            Console.Write($"ENVIRONMENT: WEBROOT_PATH: {root}");
            var path = Path.Combine(root, "config.json");
            var json = string.Empty;

            using (var fs = File.OpenRead("config.json"))
                using (var sr = new StreamReader(fs, new UTF8Encoding(false)))
                    json = await sr.ReadToEndAsync().ConfigureAwait(false);

            var configJson = JsonConvert.DeserializeObject <ConfigJson>(json);

            var config = new DiscordConfiguration
            {
                Token           = configJson.Token,
                TokenType       = TokenType.Bot,
                AutoReconnect   = true,
                MinimumLogLevel = LogLevel.Debug,
            };

            Client = new DiscordClient(config);

            Client.Ready += OnClientReady;

            var commandsConfig = new CommandsNextConfiguration
            {
                StringPrefixes      = new string[] { configJson.Prefix },
                EnableMentionPrefix = true,
                EnableDms           = false,
                DmHelp = true
            };

            Commands = Client.UseCommandsNext(commandsConfig);
            Commands.RegisterCommands <BasicCommands>();
            Commands.RegisterCommands <GetURLCommands>();

            await Client.ConnectAsync();

            await Task.Delay(-1);
        }
Пример #21
0
        public async Task RunAsync()
        {
            var json = string.Empty;

            using (var fs = File.OpenRead("config.json"))
                using (var sr = new StreamReader(fs, new UTF8Encoding(false)))
                    json = await sr.ReadToEndAsync().ConfigureAwait(false);

            var ConfigJson = JsonConvert.DeserializeObject <ConfigJson>(json);


            var config = new DiscordConfiguration
            {
                Token         = ConfigJson.Token,
                TokenType     = TokenType.Bot,
                AutoReconnect = true
                                // MinimumLogLevel = Log,
                                //useInternal = true
            };

            Client = new DiscordClient(config);

            //Client.Ready += OnClientReady;

            var commandsConfig = new CommandsNextConfiguration
            {
                StringPrefixes      = new String[] { ConfigJson.Prefix },
                EnableDms           = false,
                EnableMentionPrefix = true,
                DmHelp = true,
            };

            // Register Commands Below

            Commands = Client.UseCommandsNext(commandsConfig);

            Commands.RegisterCommands <FunCommands>();

            await Client.ConnectAsync();

            await Task.Delay(-1);
        }
Пример #22
0
        private void InitConfiguration(IServiceProvider services, IServiceScopeFactory scopeFactory)
        {
            var json = string.Empty;

            using (var fs = File.OpenRead("config.json"))
            {
                using (var sr = new StreamReader(fs, new UTF8Encoding(false)))
                {
                    json = sr.ReadToEnd();
                }
            }

            var configJson = JsonConvert.DeserializeObject <ConfigJson>(json);

            var config = new DiscordConfiguration
            {
                Token           = configJson.Token,
                TokenType       = TokenType.Bot,
                AutoReconnect   = true,
                MinimumLogLevel = Microsoft.Extensions.Logging.LogLevel.Debug
            };

            Client = new DiscordClient(config);

            Client.Ready += Client_Ready;

            Client.UseInteractivity(new InteractivityConfiguration
            {
                Timeout = TimeSpan.FromSeconds(30)
            });

            var commandsConfig = new CommandsNextConfiguration
            {
                StringPrefixes       = configJson.Prefixes,
                EnableDms            = false,
                EnableMentionPrefix  = true,
                IgnoreExtraArguments = true,
                Services             = services
            };

            Commands = Client.UseCommandsNext(commandsConfig);
        }
        public async Task RunAsync()
        {
            var json = string.Empty;

            using (var fs = File.OpenRead(@"C:\Users\seyda\source\repos\FoxexBot\FoxexBot\config.json"))
                using (var sr = new StreamReader(fs, new UTF8Encoding(false)))
                    json = await sr.ReadToEndAsync().ConfigureAwait(false);

            var configJson = JsonConvert.DeserializeObject <ConfigJson>(json);

            var config = new DiscordConfiguration
            {
                Token         = configJson.Token,
                TokenType     = TokenType.Bot,
                AutoReconnect = true,
            };

            Client        = new DiscordClient(config);
            Client.Ready += Client_Ready;

            Client.UseInteractivity(new DSharpPlus.Interactivity.InteractivityConfiguration
            {
                Timeout = TimeSpan.FromMinutes(1)
            });

            var commandsConfig = new CommandsNextConfiguration
            {
                StringPrefixes      = new string[] { configJson.Prefix },
                EnableMentionPrefix = true,
                EnableDms           = false,
                EnableDefaultHelp   = false
            };

            Commands = Client.UseCommandsNext(commandsConfig);
            Commands.RegisterCommands <FoxexBot.Commands.KurCommand>();
            Commands.RegisterCommands <FoxexBot.Commands.YardımCommand>();
            Commands.RegisterCommands <FoxexBot.Commands.FunCommands>();
            Commands.RegisterCommands <FoxexBot.Commands.ModerationCommands>();
            await Client.ConnectAsync();

            await Task.Delay(-1);
        }
Пример #24
0
        public static async Task RunAsync()
        {
            var json = string.Empty;

            using (var fs = File.OpenRead("config.json"))
                using (var sr = new StreamReader(fs, new UTF8Encoding(false)))
                    json = await sr.ReadToEndAsync().ConfigureAwait(false);

            config = JsonConvert.DeserializeObject <Config>(json);
            Console.WriteLine(json);

            var dConfig = new DiscordConfiguration
            {
                Token                 = config.Token,
                TokenType             = TokenType.Bot,
                AutoReconnect         = true,
                LogLevel              = LogLevel.Debug,
                UseInternalLogHandler = true
            };


            Client = new DiscordClient(dConfig);

            Client.Ready += OnClientReady;

            var commandsConfig = new CommandsNextConfiguration
            {
                StringPrefixes      = new string[] { config.Prefix },
                EnableMentionPrefix = true,
                EnableDms           = false,
                DmHelp = true
            };

            Commands = Client.UseCommandsNext(commandsConfig);

            Commands.RegisterCommands <Commands.Misc>();
            Commands.RegisterCommands <Commands.Main>();

            await Client.ConnectAsync();

            await Task.Delay(-1);
        }
Пример #25
0
        private async Task Commands_CommandErrored(CommandsNextExtension sender, CommandErrorEventArgs e)
        {
            e.Context.Client.Logger.LogError(
                $"{e.Context.User.Username} tried executing '{e.Command?.QualifiedName ?? "<unknown command>"}' but it errored: {e.Exception.GetType()}: {e.Exception.Message ?? "<no message>"}",
                DateTime.Now);

            if (e.Exception is ChecksFailedException)
            {
                var emoji = DiscordEmoji.FromName(e.Context.Client, ":no_entry:");

                var embed = new DiscordEmbedBuilder
                {
                    Title       = "Přístup zakázán",
                    Description =
                        $"{emoji} Na vykonání příkazu nemáte dostatečná práva. Pokud si myslíte že ano, kontaktujte svého MODa.",
                    Color = new DiscordColor(0xFF0000) // red
                };
                await e.Context.RespondAsync("", embed : embed);
            }
        }
Пример #26
0
        public static void RegisterConverters(this CommandsNextExtension cnext, Assembly?assembly = null)
        {
            assembly ??= Assembly.GetExecutingAssembly();

            Type argConvType = typeof(IArgumentConverter);
            IEnumerable <Type> converterTypes = assembly
                                                .GetTypes()
                                                .Where(t => argConvType.IsAssignableFrom(t) && !t.IsAbstract && !t.IsInterface)
            ;

            foreach (Type converterType in converterTypes)
            {
                try {
                    object?converterInstance = Activator.CreateInstance(converterType);
                    if (converterInstance is { })
                    {
                        cnext.RegisterConverter((dynamic)converterInstance);
                        Log.Debug("Registered converter: {Converter}", converterType.Name);
                    }
                } catch {
Пример #27
0
 static async Task HandleErrors(CommandsNextExtension ex, CommandErrorEventArgs er, DiscordClient client)
 {
     client.Logger.LogError(er.Exception.ToString());
     if (er.Exception is ModBot.UserError)
     {
         await er.Context.RespondAsync(embed : Embeds.Error
                                       .WithFooter($"Use {er.Context.Prefix}support to get an invite to the support server")
                                       .WithDescription(er.Exception.Message));
     }
     else if (er.Exception is ChecksFailedException)
     {
         foreach (var check in (er.Exception as ChecksFailedException).FailedChecks)
         {
             if (check is RequireUserPermissionsAttribute)
             {
                 await er.Context.RespondAsync(embed : Embeds.Error
                                               .WithFooter($"Use {er.Context.Prefix}support to get an invite to the support server")
                                               .WithDescription($"You need {(check as RequireUserPermissionsAttribute).Permissions.ToString()} to run that command."));
             }
             if (check is RequireBotPermissionsAttribute)
             {
                 await er.Context.RespondAsync(embed : Embeds.Error
                                               .WithFooter($"Use {er.Context.Prefix}support to get an invite to the support server")
                                               .WithDescription($"I need {(check as RequireBotPermissionsAttribute).Permissions.ToString()} to run that command."));
             }
         }
     }
     else if (er.Exception is System.ArgumentException)
     {
         await er.Context.RespondAsync(embed : Embeds.Error.WithTitle("Syntax Error").WithDescription($"Run `{er.Context.Prefix}help {er.Command.QualifiedName}` for more information."));
     }
     else if (er.Exception is CommandNotFoundException)
     {
     }
     else
     {
         await er.Context.RespondAsync(embed : Embeds.Error.WithTitle("Unhandled Error")
                                       .WithDescription($"Something has gone wrong.\n```{er.Exception.Message.Truncate(2000)}```")
                                       .WithFooter($"Use {er.Context.Prefix}support to get an invite to the support server"));
     }
 }
Пример #28
0
        static async Task MainAsync(string[] args)
        {
            var services = new ServiceCollection();

            services.AddTransient <PublicService>();
            services.AddTransient <ModeratorService>();
            services.AddTransient <TagRepository>(sp => new TagRepository(sp.GetService <GuildBotDbContext>()));
            services.AddSingleton <GuildBotDbContext>(provider =>
                                                      new GuildBotDbContext(ConfigurationProvider.GetAppSettings()["db"]));



            _client = new DiscordClient(new DiscordConfiguration()
            {
                Token         = ConfigurationProvider.GetAppSettings()["token"],
                TokenType     = TokenType.Bot,
                AutoReconnect = true
            });

            _commandsNext = _client.UseCommandsNext(new CommandsNextConfiguration()
            {
                StringPrefixes = new [] { "/" },
                CaseSensitive  = false,
                EnableDms      = true,
                DmHelp         = false,
                Services       = services.BuildServiceProvider()
            });

            _commandsNext.RegisterAllCommandModules();

            _client
            .HandleUserAdded()
            .HandleUserLeft();

            //Ensure database is created
            await _commandsNext.Services.GetService <GuildBotDbContext>().Database.EnsureCreatedAsync();

            await _client.ConnectAsync();

            await Task.Delay(-1);
        }
Пример #29
0
        public static void Main()
        {
            Console.Title = "CraftBot";

            SetupLogging();

            LogManager.GetCurrentClassLogger().Info("Starting");

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            LogManager.GetCurrentClassLogger().Info($"Set security protocol to {ServicePointManager.SecurityProtocol.ToString()}");

            CheckRequiredDirectories();
            LoadConfig();


            Client = new DiscordClient(new DiscordConfiguration()
            {
                AutoReconnect          = true,
                LogLevel               = DSharpPlus.LogLevel.Debug,
                Token                  = Config.Tokens["discord"],
                TokenType              = TokenType.Bot,
                UseInternalLogHandler  = false,
                WebSocketClientFactory = CompatibleWebSocket.GetWebSocketClient(),
            });

            Commands = Client.UseCommandsNext(new CommandsNextConfiguration()
            {
                StringPrefixes = Config.Triggers
            });

            Interactivity = Client.UseInteractivity(new InteractivityConfiguration());

            SetupEventHandlers();

            PluginLoader.LoadPlugins();
            PluginLoader.RegisterPlugins();

            RunAsync().GetAwaiter().GetResult();

            _ = Console.ReadLine();
        }
Пример #30
0
        public async Task RunAsync()
        {
            var json = string.Empty;

            using (var fs = File.OpenRead("config.json"))
                using (var sr = new StreamReader(fs, new UTF8Encoding(false)))
                    json = await sr.ReadToEndAsync().ConfigureAwait(false);

            var configJson = JsonConvert.DeserializeObject <ConfigJson>(json);

            var config = new DiscordConfiguration
            {
                Token           = configJson.Token,
                TokenType       = TokenType.Bot,
                AutoReconnect   = true,
                MinimumLogLevel = Microsoft.Extensions.Logging.LogLevel.Debug,
            };

            Client = new DiscordClient(config);

            Client.Ready += OnClientReady;

            var commandsConfig = new CommandsNextConfiguration
            {
                StringPrefixes      = new string[] { configJson.Prefix },
                EnableDms           = false,
                EnableMentionPrefix = true,
                DmHelp = true,
                IgnoreExtraArguments     = true,
                CaseSensitive            = false,
                UseDefaultCommandHandler = true,
            };

            Commands = Client.UseCommandsNext(commandsConfig);

            Commands.RegisterCommands <BiriBiriComands>();

            await Client.ConnectAsync();

            await Task.Delay(-1);
        }