Example #1
0
        public async Task ListAsync(CommandContext ctx)
        {
            IReadOnlyList <PrivilegedUser> privileged = await this.Service.GetAsync();

            var notFound = new List <PrivilegedUser>();
            var valid    = new List <DiscordUser>();

            foreach (PrivilegedUser pu in privileged)
            {
                try {
                    DiscordUser user = await ctx.Client.GetUserAsync(pu.UserId);

                    valid.Add(user);
                } catch (NotFoundException) {
                    LogExt.Debug(ctx, "Found 404 privileged user: {UserId}", pu.UserId);
                    notFound.Add(pu);
                }
            }

            if (!valid.Any())
            {
                throw new CommandFailedException(ctx, "cmd-err-choice-none");
            }

            await ctx.PaginateAsync(
                "str-priv",
                valid,
                user => user.ToString(),
                this.ModuleColor,
                10
                );

            LogExt.Information(ctx, "Removing {Count} not found privileged users", notFound.Count);
            await this.Service.RemoveAsync(notFound);
        }
        /// <summary>
        /// This method will return username from discord user string (example: from this: Member 377421711232204812; veso266#8329 (veso266))
        /// </summary>
        /// <param name="str"></param>
        /// <returns>Discord username (example: veso266#8329)</returns>
        public static string GetUsername(DiscordUser str)
        {
            string longUsername    = str.ToString();                                                 //377421711232204812; veso266#8329 (veso266)
            string shorterUsername = longUsername.Split(';')[1];                                     // veso266#8329 (veso266)
            string finalUsername   = shorterUsername.Substring(1, shorterUsername.IndexOf('(') - 2); //veso266#8329

            return(finalUsername);
        }
Example #3
0
        private Task BotUpdated(SocketSelfUser oldBot, SocketSelfUser newBot)
        {
            Formatter.GenerateLog(_logger, LogSeverity.Info, "Self", "Bot Updated - " + newBot.ToString());

            var botDetails = new DiscordUser(newBot);

            return(SendEvent("bot", "Update", "GMBot.Bot.Update", botDetails.ToString()));
        }
Example #4
0
        public static string GetNickname(DiscordUser author)
        {
            string authorString = author.ToString().Replace('_', ' ');
            string nickname     = string.Empty;

            for (int i = authorString.LastIndexOf('(') + 1; i < authorString.LastIndexOf(')'); i++)
            {
                nickname += authorString[i];
            }
            return(nickname);
        }
Example #5
0
        public async Task UnbanAsync(CommandContext ctx,
                                     [Description("User.")] DiscordUser user,
                                     [RemainingText, Description("Reason.")] string reason = null)
        {
            if (user.Id == ctx.User.Id)
            {
                throw new CommandFailedException("You can't unban yourself...");
            }

            await ctx.Guild.UnbanMemberAsync(user.Id, reason : ctx.BuildInvocationDetailsString(reason));

            await this.InformAsync(ctx, $"{ctx.Member.Mention} removed a ban for {user.ToString()}!");
        }
Example #6
0
        public async Task BanAsync(CommandContext ctx,
                                   [Description("desc-user")] DiscordUser user,
                                   [Description("desc-ban-msg-days-del")] int days,
                                   [RemainingText, Description("desc-rsn")] string?reason = null)
        {
            if (user == ctx.User)
            {
                throw new CommandFailedException(ctx, "cmd-err-self-action");
            }

            string name = user.ToString();
            await ctx.Guild.BanMemberAsync(user.Id, delete_message_days : days, reason : ctx.BuildInvocationDetailsString(reason));

            await ctx.ImpInfoAsync(this.ModuleColor, "fmt-ban", ctx.User.Mention, name, days);
        }
Example #7
0
        private static string ParseNickname(DiscordUser author)
        {
            string result = string.Empty;

            try
            {
                string authorString = author.ToString().Replace('_', ' ');
                string nickname     = string.Empty;
                for (int i = authorString.LastIndexOf('(') + 1; i < authorString.LastIndexOf(')'); i++)
                {
                    nickname += authorString[i];
                }
                result = nickname;
            }
            catch (Exception)
            {
                result = "UNKNOWN";
            }
            return(result);
        }
            public async Task ListAsync(CommandContext ctx)
            {
                List <DatabasePrivilegedUser> privileged;

                using (DatabaseContext db = this.Database.CreateContext())
                    privileged = await db.PrivilegedUsers.ToListAsync();

                var valid = new List <DiscordUser>();

                foreach (DatabasePrivilegedUser usr in privileged)
                {
                    try {
                        DiscordUser user = await ctx.Client.GetUserAsync(usr.UserId);

                        valid.Add(user);
                    } catch (NotFoundException) {
                        this.Shared.LogProvider.Log(LogLevel.Debug, $"Removed 404 privileged user with ID {usr.UserId}");
                        using (DatabaseContext db = this.Database.CreateContext()) {
                            db.PrivilegedUsers.Remove(new DatabasePrivilegedUser {
                                UserIdDb = usr.UserIdDb
                            });
                            await db.SaveChangesAsync();
                        }
                    }
                }

                if (!valid.Any())
                {
                    throw new CommandFailedException("No privileged users registered!");
                }

                await ctx.SendCollectionInPagesAsync(
                    "Privileged users",
                    valid,
                    user => user.ToString(),
                    this.ModuleColor,
                    10
                    );
            }
Example #9
0
            public async Task ListAsync(CommandContext ctx)
            {
                List <DatabaseBlockedUser> blocked;

                using (DatabaseContext db = this.Database.CreateContext())
                    blocked = await db.BlockedUsers.ToListAsync();

                var lines = new List <string>();

                foreach (DatabaseBlockedUser usr in blocked)
                {
                    try {
                        DiscordUser user = await ctx.Client.GetUserAsync(usr.UserId);

                        lines.Add($"{user.ToString()} ({Formatter.Italic(usr.Reason ?? "No reason provided.")})");
                    } catch (NotFoundException) {
                        this.Shared.LogProvider.Log(LogLevel.Debug, $"Removed 404 blocked user with ID {usr.UserId}");
                        using (DatabaseContext db = this.Database.CreateContext()) {
                            db.BlockedUsers.Remove(new DatabaseBlockedUser {
                                UserIdDb = usr.UserIdDb
                            });
                            await db.SaveChangesAsync();
                        }
                    }
                }

                if (!lines.Any())
                {
                    throw new CommandFailedException("No blocked users registered!");
                }

                await ctx.SendCollectionInPagesAsync(
                    "Blocked users (in database):",
                    lines,
                    line => line,
                    this.ModuleColor,
                    5
                    );
            }
Example #10
0
            public async Task WaifuClaimerAffinity([Remainder] IUser u = null)
            {
                if (u?.Id == Context.User.Id)
                {
                    await ReplyErrorLocalized("waifu_egomaniac").ConfigureAwait(false);

                    return;
                }
                DiscordUser oldAff     = null;
                var         sucess     = false;
                var         cooldown   = false;
                var         difference = TimeSpan.Zero;

                using (var uow = DbHandler.UnitOfWork())
                {
                    var w      = uow.Waifus.ByWaifuUserId(Context.User.Id);
                    var newAff = u == null ? null : uow.DiscordUsers.GetOrCreate(u);
                    var now    = DateTime.UtcNow;
                    if (w?.Affinity?.UserId == u?.Id)
                    {
                    }
                    else if (affinityCooldowns.AddOrUpdate(Context.User.Id,
                                                           now,
                                                           (key, old) => ((difference = now.Subtract(old)) > _affinityLimit) ? now : old) != now)
                    {
                        cooldown = true;
                    }
                    else if (w == null)
                    {
                        var thisUser = uow.DiscordUsers.GetOrCreate(Context.User);
                        uow.Waifus.Add(new WaifuInfo()
                        {
                            Affinity = newAff,
                            Waifu    = thisUser,
                            Price    = 1,
                            Claimer  = null
                        });
                        sucess = true;

                        uow._context.WaifuUpdates.Add(new WaifuUpdate()
                        {
                            User       = thisUser,
                            Old        = null,
                            New        = newAff,
                            UpdateType = WaifuUpdateType.AffinityChanged
                        });
                    }
                    else
                    {
                        if (w.Affinity != null)
                        {
                            oldAff = w.Affinity;
                        }
                        w.Affinity = newAff;
                        sucess     = true;

                        uow._context.WaifuUpdates.Add(new WaifuUpdate()
                        {
                            User       = w.Waifu,
                            Old        = oldAff,
                            New        = newAff,
                            UpdateType = WaifuUpdateType.AffinityChanged
                        });
                    }

                    await uow.CompleteAsync().ConfigureAwait(false);
                }
                if (!sucess)
                {
                    if (cooldown)
                    {
                        var remaining = _affinityLimit.Subtract(difference);
                        await ReplyErrorLocalized("waifu_affinity_cooldown",
                                                  Format.Bold(((int)remaining.TotalHours).ToString()),
                                                  Format.Bold(remaining.Minutes.ToString())).ConfigureAwait(false);
                    }
                    else
                    {
                        await ReplyErrorLocalized("waifu_affinity_already").ConfigureAwait(false);
                    }
                    return;
                }
                if (u == null)
                {
                    await ReplyConfirmLocalized("waifu_affinity_reset").ConfigureAwait(false);
                }
                else if (oldAff == null)
                {
                    await ReplyConfirmLocalized("waifu_affinity_set", Format.Bold(u.ToString())).ConfigureAwait(false);
                }
                else
                {
                    await ReplyConfirmLocalized("waifu_affinity_changed", Format.Bold(oldAff.ToString()), Format.Bold(u.ToString())).ConfigureAwait(false);
                }
            }
Example #11
0
            public async Task WaifuClaimerAffinity([Remainder] IGuildUser u = null)
            {
                if (u?.Id == Context.User.Id)
                {
                    await ReplyErrorLocalized("waifu_egomaniac").ConfigureAwait(false);

                    return;
                }
                DiscordUser oldAff    = null;
                var         sucess    = false;
                TimeSpan?   remaining = null;

                using (var uow = _db.UnitOfWork)
                {
                    var w      = uow.Waifus.ByWaifuUserId(Context.User.Id);
                    var newAff = u == null ? null : uow.DiscordUsers.GetOrCreate(u);
                    var now    = DateTime.UtcNow;
                    if (w?.Affinity?.UserId == u?.Id)
                    {
                    }
                    else if (!_cache.TryAddAffinityCooldown(Context.User.Id, out remaining))
                    {
                    }
                    else if (w == null)
                    {
                        var thisUser = uow.DiscordUsers.GetOrCreate(Context.User);
                        uow.Waifus.Add(new WaifuInfo()
                        {
                            Affinity = newAff,
                            Waifu    = thisUser,
                            Price    = 1,
                            Claimer  = null
                        });
                        sucess = true;

                        uow._context.WaifuUpdates.Add(new WaifuUpdate()
                        {
                            User       = thisUser,
                            Old        = null,
                            New        = newAff,
                            UpdateType = WaifuUpdateType.AffinityChanged
                        });
                    }
                    else
                    {
                        if (w.Affinity != null)
                        {
                            oldAff = w.Affinity;
                        }
                        w.Affinity = newAff;
                        sucess     = true;

                        uow._context.WaifuUpdates.Add(new WaifuUpdate()
                        {
                            User       = w.Waifu,
                            Old        = oldAff,
                            New        = newAff,
                            UpdateType = WaifuUpdateType.AffinityChanged
                        });
                    }

                    await uow.CompleteAsync().ConfigureAwait(false);
                }
                if (!sucess)
                {
                    if (remaining != null)
                    {
                        await ReplyErrorLocalized("waifu_affinity_cooldown",
                                                  Format.Bold(((int)remaining?.TotalHours).ToString()),
                                                  Format.Bold(remaining?.Minutes.ToString())).ConfigureAwait(false);
                    }
                    else
                    {
                        await ReplyErrorLocalized("waifu_affinity_already").ConfigureAwait(false);
                    }
                    return;
                }
                if (u == null)
                {
                    await ReplyConfirmLocalized("waifu_affinity_reset").ConfigureAwait(false);
                }
                else if (oldAff == null)
                {
                    await ReplyConfirmLocalized("waifu_affinity_set", Format.Bold(u.ToString())).ConfigureAwait(false);
                }
                else
                {
                    await ReplyConfirmLocalized("waifu_affinity_changed", Format.Bold(oldAff.ToString()), Format.Bold(u.ToString())).ConfigureAwait(false);
                }
            }
Example #12
0
        public async Task UnbanAsync(CommandContext ctx,
                                     [Description("ID.")] ulong id,
                                     [RemainingText, Description("Reason.")] string reason = null)
        {
            if (id == ctx.User.Id)
            {
                throw new CommandFailedException("You can't unban yourself...");
            }

            DiscordUser u = await ctx.Client.GetUserAsync(id);

            await ctx.Guild.UnbanMemberAsync(id, reason : ctx.BuildInvocationDetailsString(reason));

            await this.InformAsync(ctx, $"{Formatter.Bold(ctx.User.Username)} removed an ID ban for {Formatter.Bold(u.ToString())}!");
        }
Example #13
0
        public async Task TempBanAsync(CommandContext ctx,
                                       [Description("User (doesn't have to be a member).")] DiscordUser user,
                                       [Description("Time span.")] TimeSpan timespan,
                                       [RemainingText, Description("Reason.")] string reason = null)
        {
            if (user.Id == ctx.User.Id)
            {
                throw new CommandFailedException("You can't ban yourself.");
            }

            await ctx.Guild.BanMemberAsync(user.Id, 0, ctx.BuildInvocationDetailsString(reason));

            DateTime until = DateTime.UtcNow + timespan;

            await this.InformAsync(ctx, $"{Formatter.Bold(ctx.User.Username)} BANNED {Formatter.Bold(user.ToString())} until {Formatter.Bold(until.ToLongTimeString())} UTC!");

            var task = new UnbanTaskInfo(ctx.Guild.Id, user.Id, until);
            await SavedTaskExecutor.ScheduleAsync(this.Shared, this.Database, (DiscordClientImpl)ctx.Client, task);
        }
Example #14
0
        public async Task TempBanAsync(CommandContext ctx,
                                       [Description("User (doesn't have to be a member).")] DiscordUser user,
                                       [Description("Time span.")] TimeSpan timespan,
                                       [RemainingText, Description("Reason.")] string reason = null)
        {
            if (user.Id == ctx.User.Id)
            {
                throw new CommandFailedException("You can't ban yourself.");
            }

            if (timespan.TotalMinutes < 1 || timespan.TotalDays > 31)
            {
                throw new InvalidCommandUsageException("Given time period cannot be lower than 1 minute or greater than 1 month");
            }

            await ctx.Guild.BanMemberAsync(user.Id, 0, ctx.BuildInvocationDetailsString(reason));

            DateTime until = DateTime.UtcNow + timespan;

            await this.InformAsync(ctx, $"{ctx.Member.Mention} {Formatter.Bold("BANNED")} {user.ToString()} for {Formatter.Bold(timespan.Humanize(4, minUnit: TimeUnit.Second))}!");

            var task = new UnbanTaskInfo(ctx.Guild.Id, user.Id, until);
            await SavedTaskExecutor.ScheduleAsync(this.Shared, this.Database, ctx.Client, task);
        }
        public static async Task ChannelUpdateEventHandlerAsync(TheGodfatherShard shard, ChannelUpdateEventArgs e)
        {
            if (e.ChannelBefore.Position != e.ChannelAfter.Position)
            {
                return;
            }

            DiscordChannel logchn = shard.SharedData.GetLogChannelForGuild(shard.Client, e.Guild);

            if (logchn == null)
            {
                return;
            }

            if (await shard.DatabaseService.IsExemptedAsync(e.Guild.Id, e.ChannelAfter.Id, EntityType.Channel))
            {
                return;
            }

            DiscordEmbedBuilder  emb   = FormEmbedBuilder(EventOrigin.Channel, "Channel updated");
            DiscordAuditLogEntry entry = await e.Guild.GetFirstAuditLogEntryAsync(AuditLogActionType.ChannelUpdate);

            if (entry != null && entry is DiscordAuditLogChannelEntry centry)       // Regular update
            {
                emb.WithDescription(centry.Target.ToString());
                emb.AddField("User responsible", centry.UserResponsible?.Mention ?? _unknown, inline: true);
                if (centry.BitrateChange != null)
                {
                    emb.AddField("Bitrate changed to", centry.BitrateChange.After.ToString(), inline: true);
                }
                if (centry.NameChange != null)
                {
                    emb.AddField("Name changed to", centry.NameChange.After, inline: true);
                }
                if (centry.NsfwChange != null)
                {
                    emb.AddField("NSFW flag changed to", centry.NsfwChange.After.Value.ToString(), inline: true);
                }
                if (centry.OverwriteChange != null)
                {
                    emb.AddField("Permissions overwrites changed", $"{centry.OverwriteChange.After.Count} overwrites after changes");
                }
                if (centry.TopicChange != null)
                {
                    string ptopic = Formatter.BlockCode(Formatter.Sanitize(string.IsNullOrWhiteSpace(centry.TopicChange.Before) ? " " : centry.TopicChange.Before));
                    string ctopic = Formatter.BlockCode(Formatter.Sanitize(string.IsNullOrWhiteSpace(centry.TopicChange.After) ? " " : centry.TopicChange.After));
                    emb.AddField("Topic changed", $"From:{ptopic}\nTo:{ctopic}");
                }
                if (centry.TypeChange != null)
                {
                    emb.AddField("Type changed to", centry.TypeChange.After.Value.ToString());
                }
                if (!string.IsNullOrWhiteSpace(centry.Reason))
                {
                    emb.AddField("Reason", centry.Reason);
                }
                emb.WithFooter($"At {centry.CreationTimestamp.ToUniversalTime().ToString()} UTC", centry.UserResponsible.AvatarUrl);
            }
            else        // Overwrite update
            {
                AuditLogActionType type;
                if (e.ChannelBefore.PermissionOverwrites.Count > e.ChannelAfter.PermissionOverwrites.Count)
                {
                    type  = AuditLogActionType.OverwriteCreate;
                    entry = await e.Guild.GetFirstAuditLogEntryAsync(AuditLogActionType.OverwriteCreate);
                }
                else if (e.ChannelBefore.PermissionOverwrites.Count < e.ChannelAfter.PermissionOverwrites.Count)
                {
                    type  = AuditLogActionType.OverwriteDelete;
                    entry = await e.Guild.GetFirstAuditLogEntryAsync(AuditLogActionType.OverwriteDelete);
                }
                else
                {
                    if (e.ChannelBefore.PermissionOverwrites.Zip(e.ChannelAfter.PermissionOverwrites, (o1, o2) => o1.Allowed != o1.Allowed && o2.Denied != o2.Denied).Any())
                    {
                        type  = AuditLogActionType.OverwriteUpdate;
                        entry = await e.Guild.GetFirstAuditLogEntryAsync(AuditLogActionType.OverwriteUpdate);
                    }
                    else
                    {
                        type  = AuditLogActionType.ChannelUpdate;
                        entry = await e.Guild.GetFirstAuditLogEntryAsync(AuditLogActionType.ChannelUpdate);
                    }
                }

                if (entry != null && entry is DiscordAuditLogOverwriteEntry owentry)
                {
                    emb.WithDescription($"{owentry.Channel.ToString()} ({type})");
                    emb.AddField("User responsible", owentry.UserResponsible?.Mention ?? _unknown, inline: true);

                    DiscordUser member = null;
                    DiscordRole role   = null;

                    try {
                        bool isMemberUpdated = owentry.Target.Type.HasFlag(OverwriteType.Member);
                        if (isMemberUpdated)
                        {
                            member = await e.Client.GetUserAsync(owentry.Target.Id);
                        }
                        else
                        {
                            role = e.Guild.GetRole(owentry.Target.Id);
                        }
                        emb.AddField("Target", isMemberUpdated ? member.ToString() : role.ToString(), inline: true);
                        if (owentry.AllowChange != null)
                        {
                            emb.AddField("Allowed", $"{owentry.Target.Allowed.ToPermissionString() ?? _unknown}", inline: true);
                        }
                        if (owentry.DenyChange != null)
                        {
                            emb.AddField("Denied", $"{owentry.Target.Denied.ToPermissionString() ?? _unknown}", inline: true);
                        }
                    } catch {
                        emb.AddField("Target ID", owentry.Target.Id.ToString(), inline: true);
                    }

                    if (!string.IsNullOrWhiteSpace(owentry.Reason))
                    {
                        emb.AddField("Reason", owentry.Reason);
                    }
                    emb.WithFooter(owentry.CreationTimestamp.ToUtcTimestamp(), owentry.UserResponsible.AvatarUrl);
                }
                else
                {
                    return;
                }
            }

            await logchn.SendMessageAsync(embed : emb.Build());
        }
Example #16
0
        public async Task BanIDAsync(CommandContext ctx,
                                     [Description("ID.")] ulong id,
                                     [RemainingText, Description("Reason.")] string reason = null)
        {
            if (id == ctx.User.Id)
            {
                throw new CommandFailedException("You can't ban yourself.");
            }

            DiscordUser u = await ctx.Client.GetUserAsync(id);

            await ctx.Guild.BanMemberAsync(u.Id, delete_message_days : 7, reason : ctx.BuildInvocationDetailsString(reason));

            await this.InformAsync(ctx, $"{ctx.Member.Mention} {Formatter.Bold("BANNED")} {u.ToString()}!");
        }