Пример #1
0
        public async Task DoMath([Summary("Equation to solve")][Remainder] string math)
        {
            await Context.Channel.TriggerTypingAsync();

            _logger.LogInformation("{username}#{discriminator} executed math: {math} on {server}/{channel}",
                                   Context.User.Username, Context.User.Discriminator, math, Context.Guild?.Name ?? "DM", Context.Channel.Name);

            var dt = new DataTable();

            var message = await ReplyAsync(ImageLookupUtility.GetImageUrl("MATH_IMAGES"));

            try
            {
                var result = dt.Compute(math, null);
                await ReplyAsync($"Result: `{result}`");
            }
            catch (EvaluateException)
            {
                await ReplyAsync("Unable to evaluate");
            }
            catch (SyntaxErrorException)
            {
                await ReplyAsync("Syntax error");
            }
            await Task.Delay(2500);

            await message.DeleteAsync();
        }
Пример #2
0
        public async Task Quit([Summary("The image to display when the bot quits")] string imageUrl = null)
        {
            await Context.Channel.TriggerTypingAsync();

            _logger.LogInformation("{username}#{discriminator} invoked quit on {server}/{channel}",
                                   Context.User.Username, Context.User.Discriminator, Context.Guild?.Name ?? "DM", Context.Channel.Name);

            if (Context.User.Username != _settings.OwnerName || Context.User.Discriminator != _settings.OwnerDiscriminator)
            {
                await ReplyAsync("Sorry, only the bot's owner can make the bot quit!");

                return;
            }
            else
            {
                if (LavaLinkHelper.isLavaLinkRunning())
                {
                    await _lavaNode.DisconnectAsync();
                }

                IUserMessage message;
                await ReplyAsync("Please, no! I want to live! Noooo.....");

                if (imageUrl != null)
                {
                    // Delete the quit command so the image isn't shown twice
                    await Context.Message.DeleteAsync();
                }

                var memoryStream = await ImageHelper.FetchImage(imageUrl ?? ImageLookupUtility.GetImageUrl("QUIT_IMAGES"));

                if (memoryStream == null)
                {
                    await ReplyAsync("Quit Image could not be fetched! Bye anyway!");

                    ShowQuitMessageIfEnabled();
                    Program.ExitCleanly();
                }
                memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
                message = await Context.Channel.SendFileAsync(memoryStream, "quitimage.png");

                await Task.Delay(3000);

                await message.DeleteAsync();

                ShowQuitMessageIfEnabled();
                await _servers.SendLogsAsync(Context.Guild, "Bot quitting", $"{Context.User.Mention} has requested the bot to terminate.");

                await _client.StopAsync(); // Allow the client to cleanup

                Program.ExitCleanly();
            }
        }
Пример #3
0
        public async Task BroadCast([Summary("Broadcast message")][Remainder] string message)
        {
            await Context.Channel.TriggerTypingAsync();

            _logger.LogInformation("{username}#{discriminator} executed broadcast ({message}) on {server}/{channel}",
                                   Context.User.Username, Context.User.Discriminator, message, Context.Guild?.Name ?? "DM", Context.Channel.Name);

            var sent = 0;

            foreach (var guild in _client.Guilds)
            {
                //var server = await _servers.GetServer(guild);
                var server = await ServerHelper.GetOrAddServer(guild.Id, _serverRepository);

                if (server.LoggingChannel != 0)
                {
                    // Logging channel set
                    var channel = _client.GetChannel(server.LoggingChannel) as ISocketMessageChannel;
                    if (channel != null)
                    {
                        await channel.SendEmbedAsync("Owner Broadcast Message", $"Message: {message}", ColorHelper.GetColor(server), ImageLookupUtility.GetImageUrl("BROADCAST_IMAGES"));
                    }
                    sent++;
                }
                else
                {
                    // Logging channel not set
                    var owner        = guild.Owner as SocketUser;
                    var ownerChannel = await owner?.GetOrCreateDMChannelAsync();

                    if (ownerChannel != null)
                    {
                        //await ownerChannel.SendEmbedAsync("Owner Broadcast Message", $"Message: {message}\n" +
                        //    $"Set the logging channel with: {server.Prefix}logs channel {{channelMention}} to avoid DMs from the bot!", ColorHelper.GetColor(server), ImageLookupUtility.GetImageUrl("BROADCAST_IMAGES"));
                        EmbedBuilder builder = new EmbedBuilder();
                        builder.Title       = "Owner Broadcast Message";
                        builder.Description = $"Message: { message}\n" +
                                              $"Set the logging channel with: {server.Prefix}logs channel {{channelMention}} to avoid DMs from the bot!";
                        builder.Color        = ColorHelper.GetColor(server);
                        builder.ThumbnailUrl = ImageLookupUtility.GetImageUrl("BROADCAST_IMAGES");
                        builder.WithCurrentTimestamp();

                        await ownerChannel.SendMessageAsync(null, false, builder.Build());
                    }
                }
            }

            await _servers.SendLogsAsync(Context.Guild, "Broadcast Message Sent", $"{Context.User.Mention} sent a broadcast message: {message}", ImageLookupUtility.GetImageUrl("LOGGING_IMAGES"));

            await ReplyAsync($"Broadcast message has been sent to {sent} server out of {_client.Guilds.Count} ({_client.Guilds.Count - sent} do not have logging channel set!)");
        }
Пример #4
0
        public async Task NoteShow([Summary("The name of the note to show")][Remainder] string name)
        {
            await Context.Channel.TriggerTypingAsync();

            _logger.LogInformation("{username}#{discriminator} executed note show ({name}) on {server}/{channel}",
                                   Context.User.Username, Context.User.Discriminator, name, Context.Guild?.Name ?? "DM", Context.Channel.Name);

            var user = await _userService.GetUser(Context.User);

            var notes      = (await _noteRepository.GetNotesByUserId(user.UserId))?.ToList();
            var noteToShow = notes?.Where(x => x.Name.ToLowerInvariant() == name.ToLowerInvariant()).SingleOrDefault();

            if (noteToShow == null)
            {
                await ReplyAsync($"Note `{name}` could not be found!");

                return;
            }

            await Context.Channel.SendEmbedAsync($"{noteToShow.Name}", $"{noteToShow.Text}", await _serverService.GetServer(Context.Guild), ImageLookupUtility.GetImageUrl("NOTE_IMAGES"));

            //await ReplyAsync(noteToShow.Text);
        }
Пример #5
0
        public async Task Ban(
            [Summary("The user to ban")] SocketGuildUser user,
            [Summary("The number of days of the banned user's messages to purge")] int days,
            [Summary("Reason for the ban")][Remainder] string reason = null)
        {
            await Context.Channel.TriggerTypingAsync();

            if (user == null)
            {
                await ReplyAsync("Please provide a user to ban!");
            }

            _logger.LogInformation("{user}#{discriminator} banned {user} in {channel} on {server}",
                                   Context.User.Username, Context.User.Discriminator, user.Username, Context.Channel.Name, Context.Guild?.Name ?? "DM");

            await Context.Channel.SendEmbedAsync("Ban Hammer", $"{user.Mention} has been banned for *{(reason ?? "no reason")}*",
                                                 ColorHelper.GetColor(await _servers.GetServer(Context.Guild)), ImageLookupUtility.GetImageUrl("BAN_IMAGES"));

            await _servers.SendLogsAsync(Context.Guild, "Banned", $"{Context.User.Mention} has banned {user.Mention} and deleted the past {days} day of their messages!");

            await user.BanAsync(days, reason);
        }
Пример #6
0
        private async Task Unmute([Summary("The user to unmute")] SocketGuildUser user)
        {
            var role = (Context.Guild as IGuild).Roles.FirstOrDefault(x => x.Name == "Muted");

            if (role == null)
            {
                await Context.Channel.SendEmbedAsync("Not Muted", "This person has not been muted!", await _servers.GetEmbedColor(Context.Guild.Id), ImageLookupUtility.GetImageUrl("ERROR_IMAGES"));

                return;
            }

            if (role.Position > Context.Guild.CurrentUser.Hierarchy)
            {
                await Context.Channel.SendEmbedAsync("Invalid permissions", "the muted role has a higher position than the bot!",
                                                     await _servers.GetEmbedColor(Context.Guild.Id), ImageLookupUtility.GetImageUrl("ERROR_IMAGES"));

                return;
            }

            if (!user.Roles.Contains(role))
            {
                await Context.Channel.SendEmbedAsync("Not Muted", "This person has not been muted!",
                                                     await _servers.GetEmbedColor(Context.Guild.Id), ImageLookupUtility.GetImageUrl("ERROR_IMAGES"));

                return;
            }

            await user.RemoveRoleAsync(role);

            await Context.Channel.SendEmbedAsync($"Unmuted {user.Username}", "Succesfully unmuted the user",
                                                 await _servers.GetEmbedColor(Context.Guild.Id), ImageLookupUtility.GetImageUrl("UNMUTE_IMAGES"));

            await _servers.SendLogsAsync(Context.Guild, "Un-muted", $"{Context.User.Mention} unmuted {user.Mention}");

            _logger.LogInformation("{user} unmuted {target} in {server}", Context.User.Username, user.Username, Context.Guild.Name);
        }
Пример #7
0
        public async Task Mute([Summary("The user to mute")] SocketGuildUser user,
                               [Summary("Number of minutes to mute for")] int minutes      = 5,
                               [Summary("The reason for muting")][Remainder] string reason = null)
        {
            await Context.Channel.TriggerTypingAsync();

            if (user.Hierarchy > Context.Guild.CurrentUser.Hierarchy)
            {
                await Context.Channel.SendEmbedAsync("Invalid User", "That user has a higher position than the bot!",
                                                     await _servers.GetEmbedColor(Context.Guild.Id), ImageLookupUtility.GetImageUrl("ERROR_IMAGES"));

                return;
            }

            // Check for muted role, attempt to create it if it doesn't exist
            var role = (Context.Guild as IGuild).Roles.FirstOrDefault(x => x.Name == "Muted");

            if (role == null)
            {
                role = await Context.Guild.CreateRoleAsync("Muted", new GuildPermissions(sendMessages : false), null, false, null);
            }

            if (role.Position > Context.Guild.CurrentUser.Hierarchy)
            {
                await Context.Channel.SendEmbedAsync("Invalid permissions", "the muted role has a higher position than the bot!",
                                                     await _servers.GetEmbedColor(Context.Guild.Id), ImageLookupUtility.GetImageUrl("ERROR_IMAGES"));

                return;
            }

            if (user.Roles.Contains(role))
            {
                await Context.Channel.SendEmbedAsync("Already Muted", "That user is already muted!",
                                                     await _servers.GetEmbedColor(Context.Guild.Id), ImageLookupUtility.GetImageUrl("ERROR_IMAGES"));

                return;
            }

            await role.ModifyAsync(x => x.Position = Context.Guild.CurrentUser.Hierarchy);

            foreach (var channel in Context.Guild.Channels)
            {
                if (!channel.GetPermissionOverwrite(role).HasValue || channel.GetPermissionOverwrite(role).Value.SendMessages == PermValue.Allow)
                {
                    await channel.AddPermissionOverwriteAsync(role, new OverwritePermissions(sendMessages : PermValue.Deny));
                }
            }

            MuteHandler.AddMute(new Mute {
                Guild = Context.Guild, User = user, End = DateTime.Now + TimeSpan.FromMinutes(minutes), Role = role
            });
            await user.AddRoleAsync(role);

            await Context.Channel.SendEmbedAsync($"Muted {user.Username}", $"Duration: {minutes} minutes\nReason: {reason ?? "None"}",
                                                 await _servers.GetEmbedColor(Context.Guild.Id), ImageLookupUtility.GetImageUrl("MUTE_IMAGES"));

            await _servers.SendLogsAsync(Context.Guild, "Muted", $"{Context.User.Mention} muted {user.Mention}");

            _logger.LogInformation("{user} muted {target} in {server}", Context.User.Username, user.Username, Context.Guild.Name);
        }
Пример #8
0
        public async Task Prefix([Summary("The prefix to use to address the bot")] string prefix = null)
        {
            await Context.Channel.TriggerTypingAsync();

            var myPrefix = await _servers.GetGuildPrefix(Context.Guild.Id);

            if (prefix == null)
            {
                await Context.Channel.SendEmbedAsync("Prefix", $"My Prefix is {myPrefix}",
                                                     await _servers.GetEmbedColor(Context.Guild.Id), ImageLookupUtility.GetImageUrl("PREFIX_IMAGES"));

                return;
            }

            if (prefix.Length > _prefixMaxLength)
            {
                await Context.Channel.SendEmbedAsync("Invalid Prefix", $"Prefix must be less than {_prefixMaxLength} characters.",
                                                     await _servers.GetEmbedColor(Context.Guild.Id), ImageLookupUtility.GetImageUrl("PREFIX_IMAGES"));

                return;
            }

            await _servers.ModifyGuildPrefix(Context.Guild.Id, prefix);

            await Context.Channel.SendEmbedAsync("Prefix Modified", $"The prefix has been modified to `{prefix}`.",
                                                 await _servers.GetEmbedColor(Context.Guild.Id), ImageLookupUtility.GetImageUrl("PREFIX_IMAGES"));

            await _servers.SendLogsAsync(Context.Guild, "Prefix adjusted", $"{Context.User.Mention} modifed the prefix to {prefix}");

            _logger.LogInformation("{user}#{discriminator} changed the prefix for {server} to '{prefix}'",
                                   Context.User.Username, Context.User.Discriminator, Context.Guild.Name, prefix);
        }
Пример #9
0
        public async Task Purge([Summary("The number of message to purge")] int amount)
        {
            await Context.Channel.TriggerTypingAsync();

            var messages = await Context.Channel.GetMessagesAsync(amount + 1).FlattenAsync();

            await(Context.Channel as SocketTextChannel).DeleteMessagesAsync(messages);

            var message = await Context.Channel.SendEmbedAsync("Purge Successful", $"{messages.Count()} messages deleted successfuly!",
                                                               await _servers.GetEmbedColor(Context.Guild.Id), ImageLookupUtility.GetImageUrl("PURGE_IMAGES"));

            await Task.Delay(3000);

            await message.DeleteAsync();

            await _servers.SendLogsAsync(Context.Guild, "Messages Purged", $"{Context.User.Mention} purged {messages.Count()} messages in {Context.Channel}");

            _logger.LogInformation("{user}#{discriminator} purged {number} messages in {channel} on {server}",
                                   Context.User.Username, Context.User.Discriminator, amount, Context.Channel.Name, Context.Guild.Name);
        }
Пример #10
0
        public async Task Invite()
        {
            await Context.Channel.TriggerTypingAsync();

            _logger.LogInformation("{username}#{discriminator} executed uptime: on {server}/{channel}",
                                   Context.User.Username, Context.User.Discriminator, Context.Guild?.Name ?? "DM", Context.Channel.Name);

            await Context.Channel.SendEmbedAsync("Invite Link", $"Follow the link to invite {_settings.BotName}!\n{_settings.InviteLink}",
                                                 ColorHelper.GetColor(await _servers.GetServer(Context.Guild)), ImageLookupUtility.GetImageUrl("INVITE_IMAGES"));

            //await ReplyAsync(_settings.InviteLink);
        }
Пример #11
0
        public async Task Unban([Summary("Id of the user to unban")] ulong userId)
        {
            await Context.Channel.TriggerTypingAsync();

            _logger.LogInformation("{user}#{discriminator} unbanned {userId} in {channel} on {server}",
                                   Context.User.Username, Context.User.Discriminator, userId, Context.Channel.Name, Context.Guild.Name);

            await Context.Channel.SendEmbedAsync("Un-Banned", $"{userId} has been un-banned",
                                                 ColorHelper.GetColor(await _servers.GetServer(Context.Guild)), ImageLookupUtility.GetImageUrl("UNBAN_IMAGES"));

            await _servers.SendLogsAsync(Context.Guild, "Un-Banned", $"{Context.User.Mention} has un-banned userId: {userId}");

            await Context.Guild.RemoveBanAsync(userId);
        }
Пример #12
0
        public async Task YouTube([Summary("What to search YT for")][Remainder] string query = null)
        {
            await Context.Channel.TriggerTypingAsync();

            _logger.LogInformation("{username}#{discriminator} executed youtube ({query}) on {server}/{channel}",
                                   Context.User.Username, Context.User.Discriminator, query, Context.Guild?.Name ?? "DM", Context.Channel.Name);

            var embedColor = ColorHelper.GetColor(await _servers.GetServer(Context.Guild));

            if (query == null)
            {
                await Context.Channel.SendEmbedAsync("Bad Request", "You didn't tell me what to search for!", embedColor);

                return;
            }

            var url = "https://www.youtube.com/results?search_query=" + HttpUtility.UrlEncode(query);
            await Context.Channel.SendEmbedAsync("YouTube Results", $"I searched youtube for you:\n{url}", embedColor, ImageLookupUtility.GetImageUrl("SEARCH_IMAGES"));
        }
Пример #13
0
        private async Task OnCommandExecuted(Optional <CommandInfo> command, ICommandContext context, IResult result)
        {
            if (_apiService.ApiIsEnabled)
            {
                if (command.IsSpecified)
                {
                    var commandItem = new CommandItemCreateDto
                    {
                        Guild = new GuildCreateDto {
                            GuildId = context.Guild?.Id ?? 0, GuildName = context.Guild?.Name ?? "DM"
                        },
                        Channel = new ChannelCreateDto {
                            ChannelId = context.Channel.Id, ChannelName = context.Channel.Name
                        },
                        Name      = command.Value.Name,
                        Module    = command.Value.Module.Name,
                        Message   = context.Message.Content,
                        Succesful = result.IsSuccess,
                        Date      = DateTimeOffset.UtcNow,
                        User      = new UserCreateDto {
                            UserId = context.User.Id, UserName = context.User.Username
                        }
                    };

                    try
                    {
                        await _apiService.CommandItemApi.SaveCommandItem(commandItem);
                    }
                    catch (Exception e)
                    {
                        _logger.LogWarning(e, "An exception occured while trying to contact the API");
                    }
                }
            }

            if (result.Error == CommandError.UnknownCommand)
            {
                //TODO make this optional/a setting
                Task.Run(async() =>
                {
                    _logger.LogDebug("{user} attempted to use an unknown command ({command}) on {server}/{channel}",
                                     context.User.Username, context.Message.Content, context.Guild?.Name ?? "DM", context.Channel);

                    var badCommandMessage = await context.Channel.SendMessageAsync(ImageLookupUtility.GetImageUrl("BADCOMMAND_IMAGES"));
                    await Task.Delay(3500);
                    await badCommandMessage.DeleteAsync();
                });

                return;
            }

            if (!result.IsSuccess)
            {
                _logger.LogError("Error Occured for command {command}: {error} in {server}/{channel}",
                                 context.Message.Content, result.Error, context.Guild?.Name ?? "DM", context.Channel);

                Console.WriteLine($"The following error occured: {result.Error}");

                await context.Channel.SendMessageAsync($"The following error occured: {result.ErrorReason}");
            }
        }
Пример #14
0
        public async Task HelpCommand([Summary("The command to get help with")][Remainder] string command = null)
        {
            if (command != null)
            {
                var cmd = _commandService.Commands.Where(x => x.Name.ToLowerInvariant() == command.ToLowerInvariant() || x.Aliases.Contains(command.ToLowerInvariant())).SingleOrDefault();
                if (cmd == null)
                {
                    await ReplyAsync($"No such command: `{command}`!");

                    return;
                }

                var helpEmbed = new EmbedBuilder();
                if (cmd.Name != null)
                {
                    helpEmbed.WithTitle($"Command: {cmd.Name}");
                }

                var aliases = string.Empty;
                for (int i = 0; i < cmd.Aliases.Count; i++)
                {
                    aliases += $"{cmd.Aliases[i]}";
                    if (i != cmd.Aliases.Count - 1)
                    {
                        aliases += ", ";
                    }
                }
                helpEmbed.AddField("Aliasese", aliases);
                helpEmbed.AddField("Summary", cmd.Summary);

                var parameters = string.Empty;
                if (cmd.Parameters.Count > 0)
                {
                    for (int i = 0; i < cmd.Parameters.Count; i++)
                    {
                        parameters += $"`{cmd.Parameters[i]}`";

                        if (!string.IsNullOrWhiteSpace(cmd.Parameters[i].Summary))
                        {
                            parameters += $" ({cmd.Parameters[i].Summary})";
                        }

                        if (i != cmd.Parameters.Count - 1)
                        {
                            parameters += ", ";
                        }
                    }
                }
                if (!string.IsNullOrEmpty(parameters))
                {
                    helpEmbed.AddField("Parameters", parameters);
                }
                helpEmbed.WithThumbnailUrl(ImageLookupUtility.GetImageUrl("HELP_IMAGES"));

                await ReplyAsync(null, false, helpEmbed.Build());

                return;
            }


            // Changing pages seems a little broken when DMing the bot, TODO: Look into later
            string prefix = string.Empty;

            if (Context.Guild != null)
            {
                prefix = await _servers.GetGuildPrefix(Context.Guild.Id);
            }

            List <string> pages = new List <string>();

            foreach (var module in _commandService.Modules)
            {
                if (module.Name.EndsWith("Hidden"))
                {
                    continue;
                }
                string page = $"Command Module: ***{module.Name}***\n";
                foreach (var cmd in module.Commands)
                {
                    page += $"`{prefix}";
                    if (module.Group != null)
                    {
                        page += $"{module.Group} ";
                    }
                    page += $"{cmd.Name}` - {cmd.Summary ?? "No description provided"}\n";
                }
                pages.Add(page);
            }

            await PagedReplyAsync(pages);

            _logger.LogInformation("{username}#{discriminator} executed help on {server}/{channel}",
                                   Context.User.Username, Context.User.Discriminator, Context.Guild?.Name ?? "DM", Context.Channel.Name);
        }
Пример #15
0
        public async Task Warn([Summary("The user to warn")] SocketGuildUser user, [Summary("The reason for the warning")][Remainder] string reason = "No Reason Provided")
        {
            await Context.Channel.TriggerTypingAsync();

            _logger.LogInformation("{user}#{discriminator} warned {user} for {reason} in {channel} on {server}",
                                   Context.User.Username, Context.User.Discriminator, user.Username, reason, Context.Channel.Name, Context.Guild?.Name ?? "DM");

            if (user.Id == _client.CurrentUser.Id)
            {
                await ReplyAsync("Nice try, but I am immune from warnings!");

                return;
            }

            if (user.Id == Context.User.Id)
            {
                await ReplyAsync("Lol, you are warning yourself!");
            }

            var server = await ServerHelper.GetOrAddServer(Context.Guild.Id, _serverRepository);

            var userDb = await UserHelper.GetOrAddUser(user, _userRepository);

            var warning = new Warning
            {
                UserId   = userDb.Id,
                ServerId = server.Id,
                Text     = reason
            };
            await _warningRepository.AddAsync(warning);

            var warn = await _warningRepository.GetUsersWarnings(server, userDb);

            var wAction = await _warningRepository.GetWarningAction(server);

            if (wAction == null)
            {
                wAction = new WarnAction
                {
                    Action          = WarningAction.NoAction,
                    ActionThreshold = 1
                };
                await ReplyAsync($"{Context.User.Mention}: NOTE! The warning action has not been set!");
            }

            await Context.Channel.SendEmbedAsync("You have been warned!", $"{user.Mention} you have been warned for: `{reason}`!\n" +
                                                 $"This is warning #`{warn.Count()}` of `{wAction.ActionThreshold}`\n" +
                                                 $"The action is set to: { Enum.GetName(typeof(WarningAction), wAction.Action)}",
                                                 ColorHelper.GetColor(server));

            if (warn.Count() >= wAction.ActionThreshold)
            {
                var message = $"The maximum number of warnings has been reached, because of the warn action ";
                switch (wAction.Action)
                {
                case WarningAction.NoAction:
                    message += "nothing happens.";
                    break;

                case WarningAction.Kick:
                    message += $"{user.Username} has been kicked.";
                    await user.KickAsync("Maximum Warnings Reached!");

                    break;

                case WarningAction.Ban:
                    message += $"{user.Username} has been banned.";
                    await user.BanAsync(0, "Maximum Warnings Reached!");

                    break;

                default:
                    message += "default switch statement :(";
                    break;
                }

                await ReplyAsync(message);
            }
            await _servers.SendLogsAsync(Context.Guild, $"User Warned", $"{Context.User.Mention} warned {user.Username} for: {reason}", ImageLookupUtility.GetImageUrl("LOGGING_IMAGES"));
        }
Пример #16
0
        public async Task WarnAction([Summary("Action: none, kick or ban")] string action = null,
                                     [Summary("The number of warnings before the action is performed")] int maxWarns = -1)
        {
            await Context.Channel.TriggerTypingAsync();

            _logger.LogInformation("{user}#{discriminator} invoked warnaction ({action}, {maxWarns}) messages in {channel} on {server}",
                                   Context.User.Username, Context.User.Discriminator, action, maxWarns, Context.Channel.Name, Context.Guild?.Name ?? "DM");

            var server = await _serverRepository.GetByServerId(Context.Guild.Id);

            if (server == null)
            {
                server = new Server {
                    GuildId = Context.Guild.Id
                };
                await _serverRepository.AddAsync(server);
            }

            if (action == null && maxWarns < 0)
            {
                var wAction = await _warningRepository.GetWarningAction(server);

                if (wAction == null)
                {
                    await ReplyAsync("The warn action has not been set.");

                    return;
                }
                await Context.Channel.SendEmbedAsync("Warn Action", $"The warn action is set to: `{ Enum.GetName(typeof(WarningAction), wAction.Action)}`. The threshold is: `{wAction.ActionThreshold}`",
                                                     ColorHelper.GetColor(server));

                return;
            }

            var        message    = $"Warn action set to `{action.ToLowerInvariant()}`, Max Warnings { maxWarns} by {Context.User.Mention}";
            bool       valid      = false;
            WarnAction warnAction = null;

            if (action.ToLowerInvariant() == "none" && maxWarns > 0)
            {
                valid      = true;
                warnAction = new WarnAction
                {
                    ServerId        = server.Id,
                    Action          = WarningAction.NoAction,
                    ActionThreshold = maxWarns
                };
            }
            else if (action.ToLowerInvariant() == "kick" && maxWarns > 0)
            {
                valid      = true;
                warnAction = new WarnAction
                {
                    ServerId        = server.Id,
                    Action          = WarningAction.Kick,
                    ActionThreshold = maxWarns
                };
            }
            else if (action.ToLowerInvariant() == "ban" && maxWarns > 0)
            {
                valid      = true;
                warnAction = new WarnAction
                {
                    ServerId        = server.Id,
                    Action          = WarningAction.Ban,
                    ActionThreshold = maxWarns
                };
            }

            if (valid)
            {
                await _warningRepository.SetWarnAction(warnAction);

                await _servers.SendLogsAsync(Context.Guild, $"Warn Action Set", message, ImageLookupUtility.GetImageUrl("LOGGING_IMAGES"));

                await Context.Channel.SendEmbedAsync("Warn Action Set", $"Warn action set to: `{action.ToLowerInvariant()}`. Threshold set to: `{maxWarns}`",
                                                     ColorHelper.GetColor(server));
            }
            else
            {
                await ReplyAsync("Please provide a valid option: `none`, `kick`, `ban` and positive maximum warnings.");
            }
        }
Пример #17
0
        public async Task Kick([Summary("user to kick")] SocketGuildUser user = null)
        {
            await Context.Channel.TriggerTypingAsync();

            if (user == null)
            {
                await ReplyAsync("Please specify the user the kick");

                return;
            }

            await user.KickAsync();

            await Context.Channel.SendEmbedAsync("Kicked", $"{user.Mention} was kicked to the curb!",
                                                 ColorHelper.GetColor(await _servers.GetServer(Context.Guild)), ImageLookupUtility.GetImageUrl("KICK_IMAGES"));

            await _servers.SendLogsAsync(Context.Guild, "User kicked", $"{Context.User.Mention} kicked {user.Mention}.");

            _logger.LogInformation("{user}#{discriminator} kicked {user} messages in {channel} on {server}",
                                   Context.User.Username, Context.User.Discriminator, user.Username, Context.Channel.Name, Context.Guild.Name);
        }