public async Task StartAsync(CancellationToken cancellationToken)
        {
            Console.WriteLine("start async");
            using var scope = _serviceProvider.CreateScope();
            try
            {
                var dbContext  = scope.ServiceProvider.GetRequiredService <CoreDbContext>();
                var timeout    = 5;
                var tries      = 0;
                var canConnect = false;
                while (!canConnect)
                {
                    if (tries > timeout)
                    {
                        _logging.Fatal("Failed to contact DB, exiting application");
                        Environment.ExitCode = 1;
                        //_lifetime.StopApplication();
                        break;
                    }

                    _logging.Info($"Attempting to contact database: Attempt {tries}");
                    try
                    {
                        canConnect = await dbContext.Database.CanConnectAsync(cancellationToken);
                    }
                    catch (Exception e)
                    {
                        _logging.Info($"Cannot Connect: {e.Message}");
                    }

                    tries++;
                }

                _logging.Info("Contacted Database Successfully!");

                await dbContext.Database.MigrateAsync(cancellationToken);

                _logging.Info("Database migrated successfully.");
            }
            catch (Exception e)
            {
                _logging.Fatal($"Database migration failed: {e.Message}");
                _logging.Fatal(e.StackTrace);
                Environment.ExitCode = 1;
                //_lifetime.StopApplication();
            }
        }
예제 #2
0
 public JailCommands(InteractivityService interactivity, IGuildConfigRepository repo, IJailSettingsRepository jailSettings, ILoggingService logging, DiscordSocketClient client, IJailDataRepository jailData, UnjailService unjail)
 {
     _interactivity = interactivity;
     _repo          = repo;
     _jailSettings  = jailSettings;
     _jailData      = jailData;
     _unjail        = unjail;
     _logging       = new SourcedLoggingService(logging, "Jail");
     _client        = client.Rest;
     _logging.Info("Jail commands setup");
 }
예제 #3
0
        private async Task <bool> SetupJail()
        {
            var modelResult = await CheckStaffAndRetrieveModel();

            if (modelResult.IsFailure())
            {
                return(false);
            }

            _logging.Info(
                $"{Context.User.Username}#{Context.User.Discriminator} in Guild {Context.Guild.Name}({Context.Guild.Id}) calling Setup Jail...");
            await SendChannelMessage(
                $"**Setting up jail config...** (Called by {MentionUtils.MentionUser(Context.User.Id)})");

            var task =
                from shouldLog in GetShouldJailBeLogged()
                from rolesChanged in GetJailRoles()
                from logChannel in GetJailLogChannel()
                select new JailConfigModel(Context.Guild.Id, shouldLog, logChannel, rolesChanged);
            var res = await task;

            if (res.IsFailure())
            {
                return(false);
            }
            var model = res.Get();

            if ((await _jailSettings.StoreJailConfig(model)).IsFailure())
            {
                return(false);
            }
            await SendChannelMessage(embed : model.CreateJailCommandEmbed());

            _logging.Info("Successfully completed jail setup");
            return(true);
        }
예제 #4
0
        public async Task Jail(string target)
        {
            _logging.Verbose("Jail function called");
            var modelResult = await CheckStaffAndRetrieveModel();

            if (modelResult.IsFailure())
            {
                return;
            }
            _logging.Info($"{Context.User.Username}#{Context.User.Discriminator} in Guild {Context.Guild.Name}({Context.Guild.Id}) calling Jail...");

            var configRes = await _jailSettings.GetJailConfig(Context.Guild.Id);

            if (configRes.IsFailure())
            {
                return;
            }
            var config = configRes.Get();

            var userRes = await GetTarget(target);

            if (userRes.IsFailure())
            {
                return;
            }
            var user = userRes.Get();

            var updateEvent = await user.EditRoles(MapRoles(Context.Guild, user)(config.Roles));

            await SendChannelMessage(
                $"> **User {MentionUtils.MentionUser(user.Id)} has been jailed.** (Done by {MentionUtils.MentionUser(Context.User.Id)})");

            await _jailData.Store(Context.Guild.Id, updateEvent.ToModel());

            await SetJailDetails(updateEvent, config.LogChannel);
        }
예제 #5
0
        public async Task InstallCommandsAsync(IServiceProvider services)
        {
            _provider = services;
            _logging.Info("Initialising Commands...");
            // Hook the MessageReceived event into our command handler
            _client.MessageReceived += HandleCommandAsync;

            // Here we discover all of the command modules in the entry
            // assembly and load them. Starting from Discord.NET 2.0, a
            // service provider is required to be passed into the
            // module registration method to inject the
            // required dependencies.
            //
            // If you do not use Dependency Injection, pass null.
            // See Dependency Injection guide for more information.
            await _commands.AddModulesAsync(assembly : Assembly.GetEntryAssembly(),
                                            services : services);
        }
        private async Task <bool> SetupRR()
        {
            var modelResult = await CheckStaffAndRetrieveModel();

            if (modelResult.IsFailure())
            {
                return(false);
            }

            _logging.Info($"{Context.User.Username}#{Context.User.Discriminator} in Guild {Context.Guild.Name}({Context.Guild.Id}) calling Setup RR...");
            await SendChannelMessage(
                $"**Setting up reaction role...** (Called by {MentionUtils.MentionUser(Context.User.Id)})");

            var rrId   = Guid.NewGuid();
            var result =
                from name in GetRRName()
                from channel in GetRRChannel()
                from shouldRemove in GetShouldRRBeRemoved()
                from shouldLog in GetShouldRRBeLogged()
                from shouldSave in GetShouldRRBeSaved()
                select new ReactionRoleModel
                (
                    name: name,
                    channelId: channel,
                    guildId: Context.Guild.Id,
                    messageId: 0,
                    rule: new ReactionRuleModel(new ReactionRoleConfig(shouldRemove, shouldLog, shouldSave, rrId, name))
                );

            var rr = await result;

            if (rr.IsFailure())
            {
                return(false);
            }
            var rrModel = rr.Get();

            return(await ManageRR(rrModel, "created Reaction Role"));
        }
예제 #7
0
        private async Task <bool> SetupRR()
        {
            var modelResult = await CheckStaffAndRetrieveModel();

            if (modelResult.IsFailure())
            {
                return(false);
            }

            _logging.Info($"{Context.User.Username}#{Context.User.Discriminator} in Guild {Context.Guild.Name}({Context.Guild.Id}) calling Setup Linked RR...");
            await SendChannelMessage(
                $"**Setting up linked reaction role...** (Called by {MentionUtils.MentionUser(Context.User.Id)})");

            //TODO List all the options
            var result =
                from name in GetRRName()
                from channel in GetRRChannel()
                from shouldRemove in GetShouldRRBeRemoved()
                from shouldLog in GetShouldRRBeLogged()
                from rrId in GetRRStorageKey()
                select new ReactionRoleModel
                (
                    name: name,
                    channelId: channel,
                    guildId: Context.Guild.Id,
                    messageId: 0,
                    rule: new ReverseRuleModel(new ReactionRoleConfig(shouldRemove, shouldLog, false, rrId, name))
                );

            var rr = await result;

            if (rr.IsFailure())
            {
                return(false);
            }
            var rrModel = rr.Get();

            var emoteTask = GetEmote();
            var emoteRes  = await emoteTask;

            if (emoteRes.IsFailure())
            {
                return(false);
            }
            var emote = emoteRes.Get();

            rrModel = rrModel.WithEmoteLinked(emote.Name);

            var res =
                from title in GetRRTitle()
                from content in GetRRContent()
                select CreateReactionRoleMessageEmbed(title, content);

            var embedRes = await res;

            if (embedRes.IsFailure())
            {
                return(false);
            }

            var embed = embedRes.Get();

            _logging.Info("Created embed!");

            var msg = await Context.Guild.GetTextChannel(rrModel.ChannelId).SendMessageAsync(embed: embed);

            rrModel = rrModel with {
                MessageId = msg.Id
            };

            _logging.Info("Sent Message!");

            await msg.AddReactionAsync(emote);

            _rrService.UpsertReactionMessage(rrModel);
            await _rrRepo.AddOrUpdateReactionRole(rrModel);

            _logging.Info("Successfully completed Linked RR setup!");
            await SendChannelMessage(
                $"> **Sucessfully completed Linked Reaction Role setup!**");

            return(true);
        }
    }
예제 #8
0
        public async Task SetupGuildConfig()
        {
            var modelResult = await CheckStaffAndRetrieveModel();

            if (modelResult.IsFailure())
            {
                return;
            }
            var model = modelResult.Get();

            _logging.Info($"{Context.User.Username}#{Context.User.Discriminator} in Guild {Context.Guild.Name}({Context.Guild.Id}) calling Setup...");
            await SendChannelMessage(
                $"**Setting up bot...** (Called by {MentionUtils.MentionUser(Context.User.Id)})");
            await SendChannelMessage(
                "**What is the logging channel?**");

            ulong channel = 0;
            var   result  = await _interactivity.NextMessageAsync(CheckUserAndChannelForMessage(message =>
                                                                                                MentionUtils.TryParseChannel(message.Content, out channel)));

            if (!result.IsSuccess)
            {
                _logging.Error("Setup command timed out...");
                return;
            }

            await SendChannelMessage(
                $"**Set logging channel as {MentionUtils.MentionChannel(channel)}...**");
            await SendChannelMessage(
                $"**What are the staff roles? (Type `skip` to skip)**");

            IEnumerable <ulong> roles = new List <ulong>();

            result = await _interactivity.NextMessageAsync(CheckUserAndChannelForMessage(message =>
            {
                try
                {
                    if (message.Content == "skip")
                    {
                        return(true);
                    }

                    _logging.Verbose($"Roles: {message.Content}");
                    roles = message.MentionedRoles.Select(x => x.Id);
                }
                catch (Exception)
                {
                    _logging.Verbose("Role parsing error!");
                    return(false);
                }

                return(true);
            }));

            if (!result.IsSuccess)
            {
                _logging.Error("Setup command timed out...");
                return;
            }

            var guildConfig = new GuildConfigModel(Context.Guild.Id, channel, roles.ToImmutableHashSet());
            await _repo.StoreGuildConfig(guildConfig);

            _logging.Info("Successfully completed setup!");
            await SendChannelMessage(
                $"**Sucessfully completed setup!**");
            await SendChannelMessage(embed : CreateConfigInfoEmbedLog(guildConfig));
        }