Beispiel #1
0
        public Task UserBanned(IUser user, IGuild guild)
        {
            var _ = Task.Run(async() =>
            {
                try
                {
                    if (user.IsBot)
                    {
                        return;
                    }

                    if ((IsToggled(guild)) == false)
                    {
                        return;
                    }

                    Discord.ITextChannel channel = await GetChannel(guild, "UserBannedChannel");
                    if (channel == null)
                    {
                        return;
                    }

                    var banReason = guild.GetBanAsync(user.Id).Result.Reason;

                    var embed = new EmbedBuilder();

                    embed.WithTitle($"🔨 User Banned | {user.Username}#{user.Discriminator}")
                    .WithColor(Color.Red)
                    .WithDescription($"{user.Mention} | ``{user.Id}``")
                    .WithFooter($"user_banned user_banlog {user.Id}")
                    .WithCurrentTimestamp();

                    if (banReason == null)
                    {
                        embed.AddField("Reason", "No Reason Provided");
                    }
                    else
                    {
                        embed.AddField("Reason", banReason);
                    }

                    if (Uri.IsWellFormedUriString(user.GetAvatarUrl(), UriKind.Absolute))
                    {
                        embed.WithThumbnailUrl(user.GetAvatarUrl());
                    }

                    await channel.SendMessageAsync("", false, embed.Build());
                }
                catch (Exception ex)
                {
                    Log.Error("Error with the user banned event handler: " + ex);
                    return;
                }
            });

            return(Task.CompletedTask);
        }
Beispiel #2
0
        public Task UserLeft(IGuildUser user)
        {
            var _ = Task.Run(async() =>
            {
                try
                {
                    if (user.IsBot)
                    {
                        return;
                    }

                    await _userRoleRetentionService.LogUserRoles(user);

                    if ((IsToggled(user.Guild)) == false)
                    {
                        return;
                    }

                    Discord.ITextChannel channel = await GetChannel(user.Guild, "UserLeftChannel");
                    if (channel == null)
                    {
                        return;
                    }

                    var embed = new EmbedBuilder();
                    embed.WithTitle($"❌ User Left | {user.Username}#{user.Discriminator}")
                    .WithColor(Color.Red)
                    .WithDescription($"{user.Mention} | ``{user.Id}``");
                    if (user.JoinedAt != null)
                    {
                        DateTimeOffset userJoined = ((DateTimeOffset)user.JoinedAt);
                        TimeSpan interval         = DateTime.UtcNow - userJoined.DateTime;
                        string day_word           = interval.Days == 1 ? "day" : "days";
                        embed.AddField("Joined Server", userJoined.ToString("ddd, dd MMM yyyy"), true);
                        embed.AddField("Time at Server", $"{interval.Days} {day_word}", true);
                    }
                    embed.WithFooter($"user_leave user_joinlog {user.Id}")
                    .WithCurrentTimestamp();

                    if (Uri.IsWellFormedUriString(user.GetAvatarUrl(), UriKind.Absolute))
                    {
                        embed.WithThumbnailUrl(user.GetAvatarUrl());
                    }

                    await channel.SendMessageAsync("", false, embed.Build());
                }
                catch (Exception ex)
                {
                    Log.Error("Error with the user left event handler: " + ex);
                    return;
                }
            });

            return(Task.CompletedTask);
        }
Beispiel #3
0
        public Task UserJoined(IGuildUser user)
        {
            var _ = Task.Run(async() =>
            {
                try
                {
                    await CheckUserAutoban(user); // check if the user is to be automatically banned on join

                    if (user.IsBot)
                    {
                        return;
                    }

                    await _raidProtectionService.CheckForExcessiveJoins(user.Guild);
                    await _userRoleRetentionService.RestoreUserRoles(user);

                    if ((IsToggled(user.Guild)) == false)
                    {
                        return;
                    }

                    Discord.ITextChannel channel = await GetChannel(user.Guild, "UserJoinedChannel");
                    if (channel == null)
                    {
                        return;
                    }


                    var embed = new EmbedBuilder();

                    embed.WithTitle($"✅ User Joined | {user.Username}#{user.Discriminator}")
                    .WithColor(Color.Green)
                    .WithDescription($"{user.Mention} | ``{user.Id}``")
                    .AddField("Joined Server", user.JoinedAt?.ToString("ddd, dd MMM yyyy"), true)
                    .AddField("Joined Discord", user.CreatedAt.ToString("ddd, dd MMM yyyy"), true)
                    .WithFooter($"user_join user_joinlog {user.Id}")
                    .WithCurrentTimestamp();

                    if (Uri.IsWellFormedUriString(user.GetAvatarUrl(), UriKind.Absolute))
                    {
                        embed.WithThumbnailUrl(user.GetAvatarUrl());
                    }

                    await channel.SendMessageAsync("", false, embed.Build());
                }
                catch (Exception ex)
                {
                    Log.Error("Error with the user joined event handler: " + ex);
                    return;
                }
            });

            return(Task.CompletedTask);
        }
Beispiel #4
0
        private async Task LogErrorInDiscordChannel(IResult result, SocketMessage originalMessage)
        {
            FloofDataContext _floofDb = new FloofDataContext();

            var userMsg = originalMessage as SocketUserMessage; // the original command
            var channel = userMsg.Channel as ITextChannel;      // the channel of the original command

            if (channel == null)
            {
                return;
            }

            var serverConfig = _floofDb.ErrorLoggingConfigs.Find(channel.GuildId); // no db result

            if (serverConfig == null)
            {
                return;
            }

            if ((!serverConfig.IsOn) || (serverConfig.ChannelId == null)) // not configured or disabled
            {
                return;
            }

            Discord.ITextChannel errorLoggingChannel = await channel.Guild.GetTextChannelAsync((ulong)serverConfig.ChannelId); // can return null if channel invalid

            if (errorLoggingChannel == null)
            {
                return;
            }


            Embed embed = generateErrorEmbed(userMsg.Author, result, userMsg);
            await errorLoggingChannel.SendMessageAsync("", false, embed);

            return;
        }
        public Task GuildMemberUpdated(SocketGuildUser before, SocketGuildUser after)
        {
            var _ = Task.Run(async() =>
            {
                try
                {
                    if (before == null || after == null) // empty user params
                    {
                        return;
                    }

                    if (after.IsBot)
                    {
                        return;
                    }

                    var user = after as SocketGuildUser;

                    if ((IsToggled(user.Guild) == false)) // turned off
                    {
                        return;
                    }

                    Discord.ITextChannel channel = await GetChannel(user.Guild, "MemberUpdatesChannel");
                    if (channel == null) // no log channel set
                    {
                        return;
                    }

                    var embed = new EmbedBuilder();

                    if (before.Username != after.Username)
                    {
                        embed.WithTitle($"👥 Username Changed | {user.Username}#{user.Discriminator}")
                        .WithColor(Color.Purple)
                        .WithDescription($"{user.Mention} | ``{user.Id}``")
                        .AddField("Old Username", user.Username, true)
                        .AddField("New Name", user.Username, true)
                        .WithFooter($"user_username_change user_namelog {user.Id}")
                        .WithCurrentTimestamp();

                        if (Uri.IsWellFormedUriString(user.GetAvatarUrl(), UriKind.Absolute))
                        {
                            embed.WithThumbnailUrl(user.GetAvatarUrl());
                        }

                        bool hasBadWord = _wordFilterService.hasFilteredWord(new FloofDataContext(), after.Username, channel.Guild.Id);
                        if (hasBadWord)
                        {
                            await _nicknameAlertService.HandleBadNickname(user, user.Guild);
                        }
                    }
                    else if (before.Nickname != after.Nickname)
                    {
                        embed.WithTitle($"👥 Nickname Changed | {user.Username}#{user.Discriminator}")
                        .WithColor(Color.Purple)
                        .WithDescription($"{user.Mention} | ``{user.Id}``")
                        .WithFooter($"user_nickname_change user_namelog {user.Id}")
                        .WithCurrentTimestamp();

                        if (before.Nickname != null && after.Nickname != null) // changing nickname
                        {
                            embed.AddField("Old Nickname", before.Nickname, true);
                            embed.AddField("New Nickname", user.Nickname, true);
                        }
                        else if (after.Nickname == null) // removed their nickname
                        {
                            embed.AddField("Old Nickname", before.Nickname, true);
                        }
                        else // new nickname, didnt have one before
                        {
                            embed.AddField("New Nickname", user.Nickname, true);
                        }

                        if (Uri.IsWellFormedUriString(user.GetAvatarUrl(), UriKind.Absolute))
                        {
                            embed.WithThumbnailUrl(user.GetAvatarUrl());
                        }
                        if (after.Nickname != null)
                        {
                            bool hasBadWord = _wordFilterService.hasFilteredWord(new FloofDataContext(), after.Nickname, channel.Guild.Id);
                            if (hasBadWord)
                            {
                                await _nicknameAlertService.HandleBadNickname(user, user.Guild);
                            }
                        }
                    }
                    else if (before.AvatarId != after.AvatarId)
                    {
                        embed.WithTitle($"🖼️ Avatar Changed | {user.Username}#{user.Discriminator}")
                        .WithColor(Color.Purple)
                        .WithDescription($"{user.Mention} | ``{user.Id}``")
                        .WithFooter($"user_avatar_change {user.Id}")
                        .WithCurrentTimestamp();
                        if (Uri.IsWellFormedUriString(before.GetAvatarUrl(), UriKind.Absolute))
                        {
                            embed.WithThumbnailUrl(before.GetAvatarUrl());
                        }
                        if (Uri.IsWellFormedUriString(after.GetAvatarUrl(), UriKind.Absolute))
                        {
                            embed.WithImageUrl(after.GetAvatarUrl());
                        }
                    }
                    else if (before.Roles.Count != after.Roles.Count)
                    {
                        List <SocketRole> beforeRoles    = new List <SocketRole>(before.Roles);
                        List <SocketRole> afterRoles     = new List <SocketRole>(after.Roles);
                        List <SocketRole> roleDifference = new List <SocketRole>();

                        if (before.Roles.Count > after.Roles.Count) // roles removed
                        {
                            roleDifference = beforeRoles.Except(afterRoles).ToList();
                            embed.WithTitle($"❗ Roles Removed | {user.Username}#{user.Discriminator}")
                            .WithColor(Color.Orange)
                            .WithDescription($"{user.Mention} | ``{user.Id}``")
                            .WithFooter($"user_roles_removed user_rolelog {user.Id}")
                            .WithCurrentTimestamp();

                            foreach (SocketRole role in roleDifference)
                            {
                                embed.AddField("Role Removed", role);
                            }

                            if (Uri.IsWellFormedUriString(user.GetAvatarUrl(), UriKind.Absolute))
                            {
                                embed.WithThumbnailUrl(user.GetAvatarUrl());
                            }
                        }
                        else if (before.Roles.Count < after.Roles.Count) // roles added
                        {
                            roleDifference = afterRoles.Except(beforeRoles).ToList();
                            embed.WithTitle($"❗ Roles Added | {user.Username}#{user.Discriminator}")
                            .WithColor(Color.Orange)
                            .WithDescription($"{user.Mention} | ``{user.Id}``")
                            .WithFooter($"user_roles_added user_rolelog {user.Id}")
                            .WithCurrentTimestamp();
                            foreach (SocketRole role in roleDifference)
                            {
                                embed.AddField("Role Added", role);
                            }
                            if (Uri.IsWellFormedUriString(user.GetAvatarUrl(), UriKind.Absolute))
                            {
                                embed.WithThumbnailUrl(user.GetAvatarUrl());
                            }
                        }
                    }
                    else
                    {
                        return;
                    }
                    await channel.SendMessageAsync("", false, embed.Build());
                }
                catch (Exception ex)
                {
                    Log.Error("Error with the guild member updated event handler: " + ex);
                    return;
                }
            });

            return(Task.CompletedTask);
        }
        public Task MessageDeleted(Cacheable <IMessage, ulong> before, ISocketMessageChannel chan)
        {
            var _ = Task.Run(async() =>
            {
                try
                {
                    // deal with empty message
                    var message = (before.HasValue ? before.Value : null) as IUserMessage;
                    if (message == null)
                    {
                        return;
                    }

                    if (message.Author.IsBot)
                    {
                        return;
                    }

                    var channel = chan as ITextChannel; // channel null, dm message?
                    if (channel == null)
                    {
                        return;
                    }

                    if ((IsToggled(channel.Guild)) == false) // not toggled on
                    {
                        return;
                    }


                    Discord.ITextChannel logChannel = await GetChannel(channel.Guild, "MessageDeletedChannel");
                    if (logChannel == null)
                    {
                        return;
                    }

                    var embed = new EmbedBuilder();

                    embed.WithTitle($"⚠️ Message Deleted | {message.Author.Username}#{message.Author.Discriminator}")
                    .WithColor(Color.Gold)
                    .WithDescription($"{message.Author.Mention} ({message.Author.Id}) has had their message deleted in {channel.Mention}!")
                    .AddField("Content", message.Content)
                    .WithCurrentTimestamp()
                    .WithFooter($"user_message_deleted user_messagelog {message.Author.Id}");

                    if (Uri.IsWellFormedUriString(message.Author.GetAvatarUrl(), UriKind.Absolute))
                    {
                        embed.WithThumbnailUrl(message.Author.GetAvatarUrl());
                    }

                    await logChannel.SendMessageAsync("", false, embed.Build());
                }
                catch (Exception ex)
                {
                    Log.Error("Error with the message deleted event handler: " + ex);
                    return;
                }
            });

            return(Task.CompletedTask);
        }
        public Task MessageUpdated(Cacheable <IMessage, ulong> before, SocketMessage after, ISocketMessageChannel chan)
        {
            var _ = Task.Run(async() =>
            {
                try
                {
                    // deal with empty message
                    var messageBefore = (before.HasValue ? before.Value : null) as IUserMessage;
                    if (messageBefore == null)
                    {
                        return;
                    }

                    if (after.Author.IsBot)
                    {
                        return;
                    }

                    var channel = chan as ITextChannel; // channel null, dm message?
                    if (channel == null)
                    {
                        return;
                    }

                    if (messageBefore.Content == after.Content) // no change
                    {
                        return;
                    }

                    if ((IsToggled(channel.Guild)) == false) // not toggled on
                    {
                        return;
                    }

                    Discord.ITextChannel logChannel = await GetChannel(channel.Guild, "MessageUpdatedChannel");
                    if (logChannel == null)
                    {
                        return;
                    }

                    var embed = new EmbedBuilder();

                    embed.WithTitle($"⚠️ Message Edited | {after.Author.Username}#{after.Author.Discriminator}")
                    .WithColor(Color.DarkGrey)
                    .WithDescription($"{after.Author.Mention} ({after.Author.Id}) has edited their message in {channel.Mention}!")
                    .AddField("Before", messageBefore.Content, true)
                    .AddField("After", after.Content, true)
                    .WithCurrentTimestamp()
                    .WithFooter($"user_message_edited user_messagelog {after.Author.Id}");

                    if (Uri.IsWellFormedUriString(after.Author.GetAvatarUrl(), UriKind.Absolute))
                    {
                        embed.WithThumbnailUrl(after.Author.GetAvatarUrl());
                    }

                    await logChannel.SendMessageAsync("", false, embed.Build());

                    bool hasBadWord = _wordFilterService.hasFilteredWord(new FloofDataContext(), after.Content, channel.Guild.Id, channel.Id);
                    if (hasBadWord)
                    {
                        await HandleBadMessage(after.Author, after);
                    }
                }
                catch (Exception ex)
                {
                    Log.Error("Error with the message updated event handler: " + ex);
                    return;
                }
            });

            return(Task.CompletedTask);
        }
Beispiel #8
0
        public async Task sendModMail([Summary("Message Content")][Remainder] string content = "")
        {
            try
            {
                if (string.IsNullOrEmpty(content))
                {
                    EmbedBuilder b;
                    b = new EmbedBuilder()
                    {
                        Description = $"Usage: `modmail [message]`",
                        Color       = Color.Magenta
                    };
                    await Context.Message.Author.SendMessageAsync("", false, b.Build());
                }

                // get values
                ModMail serverConfig         = _floofDb.ModMails.Find(SERVER_ID);
                IGuild  guild                = Context.Client.GetGuild(SERVER_ID);                             // can return null
                Discord.ITextChannel channel = await guild.GetTextChannelAsync((ulong)serverConfig.ChannelId); // can return null

                IRole role = null;

                if (!Context.User.MutualGuilds.Contains(guild)) // the modmail server is not a mutual server
                {
                    return;
                }

                if (serverConfig == null || serverConfig.IsEnabled == false || guild == null || channel == null) // not configured
                {
                    await Context.Channel.SendMessageAsync("Modmail is not configured on this server.");

                    return;
                }

                if (serverConfig.ModRoleId != null)
                {
                    role = guild.GetRole((ulong)serverConfig.ModRoleId); // can return null
                }

                if (content.Length > 500)
                {
                    await Context.Message.Author.SendMessageAsync("Mod mail content cannot exceed 500 characters");

                    return;
                }

                // form embed
                SocketUser   sender  = Context.Message.Author;
                EmbedBuilder builder = new EmbedBuilder()
                {
                    Title       = "⚠️ | MOD MAIL ALERT!",
                    Description = $"Modmail from: {sender.Mention} ({sender.Username}#{sender.Discriminator})",
                    Color       = Discord.Color.Gold
                };
                builder.WithCurrentTimestamp();
                builder.AddField("Message Content", $"```{content}```");
                string messageContent = (role == null) ? "Mod mail" : role.Mention; // role id can be set in database but deleted from server
                await Context.Channel.SendMessageAsync("Alerting all mods!");

                await channel.SendMessageAsync(messageContent, false, builder.Build());
            }
            catch (Exception ex)
            {
                await Context.Channel.SendMessageAsync(ex.ToString());

                return;
            }
        }
Beispiel #9
0
        public Task UserUpdated(SocketUser before, SocketUser userAfter)
        {
            var _ = Task.Run(async() =>
            {
                try
                {
                    if (!(userAfter is SocketGuildUser after))
                    {
                        return;
                    }

                    if (before == null || after == null) // empty user params
                    {
                        return;
                    }

                    if (after.IsBot)
                    {
                        return;
                    }

                    if (IsToggled(after.Guild) == false) // turned off
                    {
                        return;
                    }

                    Discord.ITextChannel channel = await GetChannel(after.Guild, "MemberUpdatesChannel");
                    if (channel == null) // no log channel set
                    {
                        return;
                    }

                    var embed = new EmbedBuilder();

                    if (before.Username != after.Username)
                    {
                        embed.WithTitle($"👥 Username Changed | {after.Username}#{after.Discriminator}")
                        .WithColor(Color.Purple)
                        .WithDescription($"{after.Mention} | ``{after.Id}``")
                        .AddField("Old Username", before.Username, true)
                        .AddField("New Name", after.Username, true)
                        .WithFooter($"user_username_change user_namelog {after.Id}")
                        .WithCurrentTimestamp();

                        if (Uri.IsWellFormedUriString(after.GetAvatarUrl(), UriKind.Absolute))
                        {
                            embed.WithThumbnailUrl(after.GetAvatarUrl());
                        }

                        bool hasBadWord = _wordFilterService.hasFilteredWord(new FloofDataContext(), after.Username, channel.Guild.Id);
                        if (hasBadWord)
                        {
                            await _nicknameAlertService.HandleBadNickname(after, after.Guild);
                        }
                    }
                    else if (before.AvatarId != after.AvatarId)
                    {
                        embed.WithTitle($"🖼️ Avatar Changed | {after.Username}#{after.Discriminator}")
                        .WithColor(Color.Purple)
                        .WithDescription($"{after.Mention} | ``{after.Id}``")
                        .WithFooter($"user_avatar_change {after.Id}")
                        .WithCurrentTimestamp();
                        if (Uri.IsWellFormedUriString(before.GetAvatarUrl(), UriKind.Absolute))
                        {
                            embed.WithThumbnailUrl(before.GetAvatarUrl());
                        }
                        if (Uri.IsWellFormedUriString(after.GetAvatarUrl(), UriKind.Absolute))
                        {
                            embed.WithImageUrl(after.GetAvatarUrl());
                        }
                    }
                    else
                    {
                        return;
                    }
                    await channel.SendMessageAsync("", false, embed.Build());
                }
                catch (Exception ex)
                {
                    Log.Error("Error with the user updated event handler: " + ex);
                    return;
                }
            });

            return(Task.CompletedTask);
        }
Beispiel #10
0
        /// <summary>
        /// Create a Text Channel using the name and roles provided
        /// </summary>
        public static async Task CreateChannel(CommandContext Context, string Channel, [Optional] List <Permissions> Roles, [Optional] string Description, [Optional] string Category, [Optional] int?Position)
        {
            await Task.Delay(1000);

            // Get the list of channels
            IReadOnlyCollection <IGuildChannel> channels = await Context.Guild.GetChannelsAsync();

            // Check if the channel exists
            bool exists = false;

            Discord.ITextChannel newchannel = null;
            foreach (var channelname in channels)
            {
                try
                {
                    if (channelname.Name.ToString().ToLower().Trim() == Channel.ToString().ToLower().Trim())
                    {
                        // If the channel exists exit
                        exists     = true;
                        newchannel = channelname as ITextChannel;
                        break;
                    }
                }
                catch { }
            }
            if (exists == false)
            {
                newchannel = await Context.Guild.CreateTextChannelAsync(Channel);
            }
            // Wait for Channel to Generate
            await Task.Delay(1000);

            if (newchannel != null)
            {
                // Check if roles were passed
                if (Roles != null)
                {
                    // Parse in the roles to add them to the channel
                    foreach (Permissions role in Roles)
                    {
                        // Before we go any further let's see if the role already exists
                        // If the role exists exit the task
                        foreach (Discord.IRole existingrole in Context.Guild.Roles)
                        {
                            // Compare the list of roles in the discord with the Role
                            if (existingrole.Name.ToLower().Trim() == role.Role.ToLower().Trim())
                            {
                                // Add the selected roles to the channel using inhert as its base
                                await newchannel.AddPermissionOverwriteAsync(existingrole, role.ChannelPermType);

                                break;
                            }
                        }
                    }
                    // Remove the everyone permission if it's not in the list
                    bool permfound = false;
                    foreach (Permissions perm in Roles)
                    {
                        if (perm.Role.ToLower().Contains("everyone") == true)
                        {
                            permfound = true;
                            break;
                        }
                    }
                    if (permfound == false)
                    {
                        foreach (Discord.IRole existingrole in Context.Guild.Roles)
                        {
                            // Compare the list of roles in the discord with the Role
                            if (existingrole.Name.ToLower() == "@everyone")
                            {
                                OverwritePermissions denypermissions = new OverwritePermissions(createInstantInvite: PermValue.Deny, manageChannel: PermValue.Deny, addReactions: PermValue.Deny, viewChannel: PermValue.Deny, sendMessages: PermValue.Deny, sendTTSMessages: PermValue.Deny, manageMessages: PermValue.Deny, embedLinks: PermValue.Deny, attachFiles: PermValue.Deny, readMessageHistory: PermValue.Deny, mentionEveryone: PermValue.Deny, useExternalEmojis: PermValue.Deny, connect: PermValue.Deny, speak: PermValue.Deny, muteMembers: PermValue.Deny, deafenMembers: PermValue.Deny, moveMembers: PermValue.Deny, useVoiceActivation: PermValue.Deny, manageRoles: PermValue.Deny, manageWebhooks: PermValue.Deny);
                                // Remove Everyones permissions
                                await newchannel.AddPermissionOverwriteAsync(existingrole, denypermissions);

                                break;
                            }
                        }
                    }
                }
                // Check if a description was passed, if it was update the description
                if (Description != null)
                {
                    // Modify the new channel created description
                    await newchannel.ModifyAsync(x =>
                    {
                        x.Topic = Description;
                    });
                }
                // Check if a category was passed
                if (Category != null)
                {
                    // Get the list of categories
                    IReadOnlyCollection <IGuildChannel> categories = await Context.Guild.GetCategoriesAsync();

                    ulong categoryId = 000000;
                    // Check if the category name matches the id if it does return the ID
                    foreach (var categoryname in categories)
                    {
                        if (categoryname.Name.ToLower().Trim() == Category.ToLower().Trim())
                        {
                            categoryId = categoryname.Id;
                            break;
                        }
                    }

                    // Add it to the category
                    await newchannel.ModifyAsync(x =>
                    {
                        x.CategoryId = categoryId;
                    });
                }
                // Check if a position was provided
                if (Position != null)
                {
                    // Update its position
                    await newchannel.ModifyAsync(x =>
                    {
                        x.Position = Position.Value;
                    });
                }
                if (Roles == null)
                {
                    await newchannel.SyncPermissionsAsync();
                }
            }
        }