Example #1
0
        private async Task LogMessageAsync(SocketGuildChannel channel, IMessage message)
        {
            if (message.Content.IsEmotikunEmote())
            {
                return;
            }

            using (var db = new Database.GuildConfigContext(_config))
            {
                var config = await db.GetCachedGuildFullConfigAsync(channel.Guild.Id);

                if (config == null)
                {
                    return;
                }

                var ch = channel.Guild.GetTextChannel(config.LogChannel);
                if (ch == null)
                {
                    return;
                }

                await ch.SendMessageAsync("", embed : BuildMessage(message));
            }
        }
Example #2
0
        public Profile(DiscordSocketClient client, ShindenClient shClient, ImageProcessing img, ILogger logger, IConfig config)
        {
            _shClient = shClient;
            _client   = client;
            _logger   = logger;
            _config   = config;
            _img      = img;

            _timer = new Timer(async _ =>
            {
                try
                {
                    using (var db = new Database.UserContext(_config))
                    {
                        using (var dbg = new Database.GuildConfigContext(_config))
                        {
                            await CyclicCheckAsync(db, dbg);
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.Log($"in profile check: {ex}");
                }
            },
                               null,
                               TimeSpan.FromMinutes(1),
                               TimeSpan.FromMinutes(1));
        }
Example #3
0
        private async Task CyclicCheckAsync(Database.UserContext context, Database.GuildConfigContext guildContext)
        {
            var subs = context.TimeStatuses.AsNoTracking().FromCache(new[] { "users" }).Where(x => x.Type.IsSubType());

            foreach (var sub in subs)
            {
                if (sub.IsActive())
                {
                    continue;
                }

                var guild = _client.GetGuild(sub.Guild);
                switch (sub.Type)
                {
                case StatusType.Globals:
                    var guildConfig = await guildContext.GetCachedGuildFullConfigAsync(sub.Guild);
                    await RemoveRoleAsync(guild, guildConfig?.GlobalEmotesRole ?? 0, sub.UserId);

                    break;

                case StatusType.Color:
                    await RomoveUserColorAsync(guild.GetUser(sub.UserId));

                    break;

                default:
                    break;
                }
            }
        }
Example #4
0
        public async Task SendHelpAsync([Summary("nazwa polecenia(opcjonalne)")][Remainder] string command = null)
        {
            if (command != null)
            {
                try
                {
                    string prefix = _config.Get().Prefix;
                    if (Context.Guild != null)
                    {
                        using (var db = new Database.GuildConfigContext(_config))
                        {
                            var gConfig = await db.GetCachedGuildFullConfigAsync(Context.Guild.Id);

                            if (gConfig?.Prefix != null)
                            {
                                prefix = gConfig.Prefix;
                            }
                        }
                    }

                    await ReplyAsync(_helper.GiveHelpAboutPrivateCmd("Debug", command, prefix));
                }
                catch (Exception ex)
                {
                    await ReplyAsync("", embed : ex.Message.ToEmbedMessage(EMType.Error).Build());
                }

                return;
            }

            await ReplyAsync(_helper.GivePrivateHelp("Debug"));
        }
Example #5
0
        public async Task RemovePersonAsync([Summary("użytkownik")] SocketGuildUser user, [Summary("nazwa krainy(opcjonalne)")][Remainder] string name = null)
        {
            using (var db = new Database.GuildConfigContext(Config))
            {
                var config = await db.GetCachedGuildFullConfigAsync(Context.Guild.Id);

                var land = _manager.DetermineLand(config.Lands, Context.User as SocketGuildUser, name);
                if (land == null)
                {
                    await ReplyAsync("", embed : "Nie zarządzasz żadną krainą.".ToEmbedMessage(EMType.Error).Build());

                    return;
                }

                var role = Context.Guild.GetRole(land.Underling);
                if (role == null)
                {
                    await ReplyAsync("", embed : "Nie odnaleziono roli członka!".ToEmbedMessage(EMType.Error).Build());

                    return;
                }

                if (user.Roles.Contains(role))
                {
                    await user.RemoveRoleAsync(role);
                }

                await ReplyAsync("", embed : $"{user.Mention} odchodzi z `{land.Name}`.".ToEmbedMessage(EMType.Success).Build());
            }
        }
Example #6
0
        public async override Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
        {
            var user = context.User as SocketGuildUser;

            if (user == null)
            {
                return(PreconditionResult.FromError($"To polecenie działa tylko z poziomu serwera."));
            }

            await Task.CompletedTask;

            var config = (IConfig)services.GetService(typeof(IConfig));

            using (var db = new Database.GuildConfigContext(config))
            {
                var gConfig = await db.GetCachedGuildFullConfigAsync(context.Guild.Id);

                if (gConfig == null)
                {
                    return(CheckUser(user));
                }

                var role = context.Guild.GetRole(gConfig.AdminRole);
                if (role == null)
                {
                    return(CheckUser(user));
                }

                if (user.Roles.Any(x => x.Id == role.Id))
                {
                    return(PreconditionResult.FromSuccess());
                }
                return(CheckUser(user));
            }
        }
Example #7
0
        public async Task AddGlobalEmotesAsync()
        {
            var user = Context.User as SocketGuildUser;

            if (user == null)
            {
                return;
            }

            using (var db = new Database.UserContext(Config))
            {
                var botuser = await db.GetUserOrCreateAsync(user.Id);

                if (botuser.TcCnt < 4000)
                {
                    await ReplyAsync("", embed : $"{user.Mention} nie posiadasz wystarczającej liczby TC!".ToEmbedMessage(EMType.Error).Build());

                    return;
                }

                using (var cdb = new Database.GuildConfigContext(Config))
                {
                    var gConfig = await cdb.GetCachedGuildFullConfigAsync(Context.Guild.Id);

                    var gRole = Context.Guild.GetRole(gConfig.GlobalEmotesRole);
                    if (gRole == null)
                    {
                        await ReplyAsync("", embed : "Serwer nie ma ustawionej roli globalnych emotek.".ToEmbedMessage(EMType.Bot).Build());

                        return;
                    }

                    var global = botuser.TimeStatuses.FirstOrDefault(x => x.Type == Database.Models.StatusType.Globals && x.Guild == Context.Guild.Id);
                    if (global == null)
                    {
                        global = new Database.Models.TimeStatus
                        {
                            Type   = StatusType.Globals,
                            Guild  = Context.Guild.Id,
                            EndsAt = DateTime.Now,
                        };
                        botuser.TimeStatuses.Add(global);
                    }

                    if (!user.Roles.Contains(gRole))
                    {
                        await user.AddRoleAsync(gRole);
                    }

                    global.EndsAt  = global.EndsAt.AddMonths(1);
                    botuser.TcCnt -= 4000;
                }

                await db.SaveChangesAsync();

                QueryCacheManager.ExpireTag(new string[] { $"user-{botuser.Id}", "users" });

                await ReplyAsync("", embed : $"{user.Mention} wykupił miesiąc globalnych emotek!".ToEmbedMessage(EMType.Success).Build());
            }
        }
Example #8
0
        private async Task LogMessageAsync(SocketGuildChannel channel, IMessage oldMessage, IMessage newMessage = null)
        {
            if (oldMessage.Content.IsEmotikunEmote() && newMessage == null)
            {
                return;
            }

            using (var db = new Database.GuildConfigContext(_config))
            {
                var config = await db.GetCachedGuildFullConfigAsync(channel.Guild.Id);

                if (config == null)
                {
                    return;
                }

                var ch = channel.Guild.GetTextChannel(config.LogChannel);
                if (ch == null)
                {
                    return;
                }

                var jump = (newMessage == null) ? "" : $"{newMessage.GetJumpUrl()}";
                await ch.SendMessageAsync(jump, embed : BuildMessage(oldMessage, newMessage));
            }
        }
Example #9
0
        public async Task AddRoleAsync([Summary("nazwa roli z wypisz role")] string name)
        {
            var user = Context.User as SocketGuildUser;

            if (user == null)
            {
                return;
            }

            using (var db = new Database.GuildConfigContext(Config))
            {
                var config = await db.GetCachedGuildFullConfigAsync(Context.Guild.Id);

                var selfRole = config.SelfRoles.FirstOrDefault(x => x.Name == name);
                var gRole    = Context.Guild.GetRole(selfRole?.Role ?? 0);

                if (gRole == null)
                {
                    await ReplyAsync("", embed : $"Nie odnaleziono roli `{name}`".ToEmbedMessage(EMType.Error).Build());

                    return;
                }

                if (!user.Roles.Contains(gRole))
                {
                    await user.AddRoleAsync(gRole);
                }

                await ReplyAsync("", embed : $"{user.Mention} przyznano role: `{name}`".ToEmbedMessage(EMType.Success).Build());
            }
        }
Example #10
0
        private async Task UserLeftAsync(SocketGuildUser user)
        {
            if (user.IsBot || user.IsWebhook)
            {
                return;
            }

            if (!_config.Get().BlacklistedGuilds.Any(x => x == user.Guild.Id))
            {
                using (var db = new Database.GuildConfigContext(_config))
                {
                    var config = await db.GetCachedGuildFullConfigAsync(user.Guild.Id);

                    if (config?.GoodbyeMessage == null)
                    {
                        return;
                    }
                    if (config.GoodbyeMessage == "off")
                    {
                        return;
                    }

                    await SendMessageAsync(ReplaceTags(user, config.GoodbyeMessage), user.Guild.GetTextChannel(config.GreetingChannel));
                }
            }

            var thisUser = _client.Guilds.FirstOrDefault(x => x.Id == user.Id);

            if (thisUser != null)
            {
                return;
            }

            var moveTask = new Task(() =>
            {
                using (var db = new Database.UserContext(_config))
                {
                    var duser = db.GetUserOrCreateAsync(user.Id).Result;
                    var fakeu = db.GetUserOrCreateAsync(1).Result;

                    foreach (var card in duser.GameDeck.Cards)
                    {
                        card.InCage = false;
                        card.TagList.Clear();
                        card.LastIdOwner = user.Id;
                        fakeu.GameDeck.Cards.Add(card);
                    }

                    duser.GameDeck.Cards.Clear();
                    db.Users.Remove(duser);

                    db.SaveChanges();

                    QueryCacheManager.ExpireTag(new string[] { "users" });
                }
            });

            await _executor.TryAdd(new Executable("delete user", moveTask), TimeSpan.FromSeconds(1));
        }
Example #11
0
        public async Task GiveMuteAsync()
        {
            var user = Context.User as SocketGuildUser;

            if (user == null)
            {
                return;
            }

            using (var db = new Database.GuildConfigContext(Config))
            {
                var config = await db.GetCachedGuildFullConfigAsync(Context.Guild.Id);

                if (config == null)
                {
                    await ReplyAsync("", embed : "Serwer nie jest poprawnie skonfigurowany.".ToEmbedMessage(EMType.Bot).Build());

                    return;
                }

                var notifChannel = Context.Guild.GetTextChannel(config.NotificationChannel);
                var userRole     = Context.Guild.GetRole(config.UserRole);
                var muteRole     = Context.Guild.GetRole(config.MuteRole);

                if (muteRole == null)
                {
                    await ReplyAsync("", embed : "Rola wyciszająca nie jest ustawiona.".ToEmbedMessage(EMType.Bot).Build());

                    return;
                }

                if (user.Roles.Contains(muteRole))
                {
                    await ReplyAsync("", embed : $"{user.Mention} już jest wyciszony.".ToEmbedMessage(EMType.Error).Build());

                    return;
                }

                var session = new AcceptSession(user, null, Context.Client.CurrentUser);
                await _session.KillSessionIfExistAsync(session);

                var msg = await ReplyAsync("", embed : $"{user.Mention} na pewno chcesz muta?".ToEmbedMessage(EMType.Error).Build());

                await msg.AddReactionsAsync(session.StartReactions);

                session.Actions = new AcceptMute(Config)
                {
                    NotifChannel = notifChannel,
                    Moderation   = _moderation,
                    MuteRole     = muteRole,
                    UserRole     = userRole,
                    Message      = msg,
                    User         = user,
                };
                session.Message = msg;

                await _session.TryAddSession(session);
            }
        }
Example #12
0
        private async Task HandleMessageAsync(SocketMessage message)
        {
            var msg = message as SocketUserMessage;

            if (msg == null)
            {
                return;
            }

            if (msg.Author.IsBot || msg.Author.IsWebhook)
            {
                return;
            }

            var user = msg.Author as SocketGuildUser;

            if (user == null)
            {
                return;
            }

            if (_config.Get().BlacklistedGuilds.Any(x => x == user.Guild.Id))
            {
                return;
            }

            using (var db = new Database.GuildConfigContext(_config))
            {
                var config = await db.GetCachedGuildFullConfigAsync(user.Guild.Id);

                if (config == null)
                {
                    return;
                }

                var noExp = config.ChannelsWithoutExp.Any(x => x.Channel == msg.Channel.Id);
                if (!noExp)
                {
                    HandleUserAsync(msg);
                }

                var sch = user.Guild.GetTextChannel(config.WaifuConfig.SpawnChannel);
                var tch = user.Guild.GetTextChannel(config.WaifuConfig.TrashSpawnChannel);
                if (sch != null && tch != null)
                {
                    string mention = "";
                    var    wRole   = user.Guild.GetRole(config.WaifuRole);
                    if (wRole != null)
                    {
                        mention = wRole.Mention;
                    }

                    HandleGuildAsync(sch, tch, config.SafariLimit, mention, noExp);
                }
            }
        }
Example #13
0
        private async Task HandleMessageAsync(SocketMessage message)
        {
            if (message.Author.IsBot || message.Author.IsWebhook)
            {
                return;
            }

            var user = message.Author as SocketGuildUser;

            if (user == null)
            {
                return;
            }

            bool calculateExp = true;

            using (var db = new Database.GuildConfigContext(_config))
            {
                var config = await db.GetCachedGuildFullConfigAsync(user.Guild.Id);

                if (config != null)
                {
                    var role = user.Guild.GetRole(config.UserRole);
                    if (role != null)
                    {
                        if (!user.Roles.Contains(role))
                        {
                            return;
                        }
                    }

                    if (config.ChannelsWithoutExp != null)
                    {
                        if (config.ChannelsWithoutExp.Any(x => x.Channel == message.Channel.Id))
                        {
                            calculateExp = false;
                        }
                    }
                }
            }

            if (!_messages.Any(x => x.Key == user.Id))
            {
                using (var db = new Database.UserContext(_config))
                {
                    if (!db.Users.Any(x => x.Id == user.Id))
                    {
                        var task = CreateUserTask(user);
                        await _executor.TryAdd(new Executable("add user", task), TimeSpan.FromSeconds(1));
                    }
                }
            }

            CountMessage(user.Id, message.Content.IsCommand(_config.Get().Prefix));
            CalculateExpAndCreateTask(user, message, calculateExp);
        }
Example #14
0
        private async Task CyclicCheckPenalties(Database.ManagmentContext db)
        {
            foreach (var penalty in await db.GetCachedFullPenalties())
            {
                var guild = _client.GetGuild(penalty.Guild);
                if (guild == null)
                {
                    continue;
                }

                var user = guild.GetUser(penalty.User);
                if (user != null)
                {
                    using (var conf = new Database.GuildConfigContext(_config))
                    {
                        var gconfig = await conf.GetCachedGuildFullConfigAsync(guild.Id);

                        var muteModRole = guild.GetRole(gconfig.ModMuteRole);
                        var muteRole    = guild.GetRole(gconfig.MuteRole);

                        if ((DateTime.Now - penalty.StartDate).TotalHours < penalty.DurationInHours)
                        {
                            var muteMod = penalty.Roles.Any(x => gconfig.ModeratorRoles.Any(z => z.Role == x.Role)) ? muteModRole : null;
                            _ = Task.Run(async() => { await MuteUserGuildAsync(user, muteRole, penalty.Roles, muteMod); });
                            continue;
                        }

                        if (penalty.Type == PenaltyType.Mute)
                        {
                            await UnmuteUserGuildAsync(user, muteRole, muteModRole, penalty.Roles);
                            await RemovePenaltyFromDb(db, penalty);
                        }
                    }
                }
                else
                {
                    if ((DateTime.Now - penalty.StartDate).TotalHours > penalty.DurationInHours)
                    {
                        if (penalty.Type == PenaltyType.Ban)
                        {
                            var ban = await guild.GetBanAsync(penalty.User);

                            if (ban != null)
                            {
                                await guild.RemoveBanAsync(penalty.User);
                            }
                        }
                        await RemovePenaltyFromDb(db, penalty);
                    }
                }
            }
        }
Example #15
0
        private async Task UserJoinedAsync(SocketGuildUser user)
        {
            if (user.IsBot || user.IsWebhook)
            {
                return;
            }

            if (_config.Get().BlacklistedGuilds.Any(x => x == user.Guild.Id))
            {
                return;
            }

            using (var db = new Database.GuildConfigContext(_config))
            {
                var config = await db.GetCachedGuildFullConfigAsync(user.Guild.Id);

                if (config?.WelcomeMessage == null)
                {
                    return;
                }
                if (config.WelcomeMessage == "off")
                {
                    return;
                }

                await SendMessageAsync(ReplaceTags(user, config.WelcomeMessage), user.Guild.GetTextChannel(config.GreetingChannel));

                if (config?.WelcomeMessagePW == null)
                {
                    return;
                }
                if (config.WelcomeMessagePW == "off")
                {
                    return;
                }

                try
                {
                    var pw = await user.GetOrCreateDMChannelAsync();

                    await pw.SendMessageAsync(ReplaceTags(user, config.WelcomeMessagePW));

                    await pw.CloseAsync();
                }
                catch (Exception ex)
                {
                    _logger.Log($"Greeting: {ex}");
                }
            }
        }
Example #16
0
        public async override Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
        {
            var user = context.User as SocketGuildUser;

            if (user == null)
            {
                return(PreconditionResult.FromSuccess());
            }

            await Task.CompletedTask;

            var config = (IConfig)services.GetService(typeof(IConfig));

            using (var db = new Database.GuildConfigContext(config))
            {
                var gConfig = await db.GetCachedGuildFullConfigAsync(context.Guild.Id);

                if (gConfig == null)
                {
                    return(PreconditionResult.FromSuccess());
                }

                if (gConfig.CommandChannels != null)
                {
                    if (gConfig.CommandChannels.Any(x => x.Channel == context.Channel.Id))
                    {
                        return(PreconditionResult.FromSuccess());
                    }

                    if (user.GuildPermissions.Administrator)
                    {
                        return(PreconditionResult.FromSuccess());
                    }

                    if (gConfig?.WaifuConfig?.CommandChannels != null)
                    {
                        if (gConfig.WaifuConfig.CommandChannels.Any(x => x.Channel == context.Channel.Id))
                        {
                            return(PreconditionResult.FromSuccess());
                        }
                    }

                    var channel = await context.Guild.GetTextChannelAsync(gConfig.CommandChannels.First().Channel);

                    return(PreconditionResult.FromError($"To polecenie działa na kanale {channel?.Mention}"));
                }
                return(PreconditionResult.FromSuccess());
            }
        }
Example #17
0
        private async Task HandleMessageAsync(SocketMessage message)
        {
            var msg = message as SocketUserMessage;

            if (msg == null)
            {
                return;
            }

            if (msg.Author.IsBot || msg.Author.IsWebhook)
            {
                return;
            }

            var user = msg.Author as SocketGuildUser;

            if (user == null)
            {
                return;
            }

            using (var db = new Database.GuildConfigContext(_config))
            {
                var config = await db.GetCachedGuildFullConfigAsync(user.Guild.Id);

                if (config == null)
                {
                    return;
                }

                if (config.ChannelsWithoutExp.Any(x => x.Channel == msg.Channel.Id))
                {
                    return;
                }

                HandleUserAsync(msg);

                var sch = user.Guild.GetTextChannel(config.WaifuConfig.SpawnChannel);
                var tch = user.Guild.GetTextChannel(config.WaifuConfig.TrashSpawnChannel);
                if (sch == null || tch == null)
                {
                    return;
                }

                HandleGuildAsync(sch, tch, config.SafariLimit);
            }
        }
Example #18
0
        public static async Task <GuildOptions> GetGuildConfigOrCreateAsync(this Database.GuildConfigContext context, ulong guildId)
        {
            var config = await context.Guilds.Include(x => x.ChannelsWithoutExp).Include(x => x.ChannelsWithoutSupervision).Include(x => x.CommandChannels).Include(x => x.SelfRoles)
                         .Include(x => x.Lands).Include(x => x.ModeratorRoles).Include(x => x.RolesPerLevel).Include(x => x.WaifuConfig).ThenInclude(x => x.CommandChannels).Include(x => x.Raports)
                         .Include(x => x.WaifuConfig).ThenInclude(x => x.FightChannels).FirstOrDefaultAsync(x => x.Id == guildId);

            if (config == null)
            {
                config = new GuildOptions
                {
                    Id          = guildId,
                    SafariLimit = 50
                };
                await context.Guilds.AddAsync(config);
            }
            return(config);
        }
Example #19
0
        public async Task ShowPeopleAsync([Summary("nazwa krainy(opcjonalne)")][Remainder] string name = null)
        {
            using (var db = new Database.GuildConfigContext(Config))
            {
                var config = await db.GetCachedGuildFullConfigAsync(Context.Guild.Id);

                var land = _manager.DetermineLand(config.Lands, Context.User as SocketGuildUser, name);
                if (land == null)
                {
                    await ReplyAsync("", embed : "Nie zarządzasz żadną krainą.".ToEmbedMessage(EMType.Error).Build());

                    return;
                }

                await ReplyAsync("", embed : _manager.GetMembersList(land, Context.Guild).Build());
            }
        }
Example #20
0
        public async Task GiveHelpAsync([Summary("nazwa polecenia(opcjonalne)")][Remainder] string command = null)
        {
            var gUser = Context.User as SocketGuildUser;

            if (gUser == null)
            {
                return;
            }

            if (command != null)
            {
                try
                {
                    bool admin = false;
                    bool dev   = false;

                    string prefix = _config.Get().Prefix;
                    if (Context.Guild != null)
                    {
                        using (var db = new Database.GuildConfigContext(_config))
                        {
                            var gConfig = await db.GetCachedGuildFullConfigAsync(Context.Guild.Id);

                            if (gConfig?.Prefix != null)
                            {
                                prefix = gConfig.Prefix;
                            }

                            admin = (gUser.Roles.Any(x => x.Id == gConfig?.AdminRole) || gUser.GuildPermissions.Administrator);
                            dev   = _config.Get().Dev.Any(x => x == gUser.Id);
                        }
                    }

                    await ReplyAsync(_helper.GiveHelpAboutPublicCmd(command, prefix, admin, dev));
                }
                catch (Exception ex)
                {
                    await ReplyAsync("", embed : ex.Message.ToEmbedMessage(EMType.Error).Build());
                }

                return;
            }

            await ReplyAsync(_helper.GivePublicHelp());
        }
Example #21
0
        private async Task BotLeftGuildAsync(SocketGuild guild)
        {
            using (var db = new Database.GuildConfigContext(_config))
            {
                var gConfig = await db.GetGuildConfigOrCreateAsync(guild.Id);

                db.Guilds.Remove(gConfig);

                var stats = db.TimeStatuses.Where(x => x.Guild == guild.Id).ToList();
                db.TimeStatuses.RemoveRange(stats);

                await db.SaveChangesAsync();
            }

            using (var db = new Database.ManagmentContext(_config))
            {
                var mute = db.Penalties.Where(x => x.Guild == guild.Id).ToList();
                db.Penalties.RemoveRange(mute);

                await db.SaveChangesAsync();
            }
        }
Example #22
0
        public async Task ShowRolesAsync()
        {
            using (var db = new Database.GuildConfigContext(Config))
            {
                var config = await db.GetCachedGuildFullConfigAsync(Context.Guild.Id);

                if (config.SelfRoles.Count < 1)
                {
                    await ReplyAsync("", embed : "Nie odnaleziono roli.".ToEmbedMessage(EMType.Error).Build());

                    return;
                }

                string stringRole = "";
                foreach (var selfRole in config.SelfRoles)
                {
                    var gRole = Context.Guild.GetRole(selfRole?.Role ?? 0);
                    stringRole += $" `{selfRole.Name}` ";
                }

                await ReplyAsync($"**Dostępne role:**\n{stringRole}\n\nUżyj `s.przyznaj role [nazwa]` aby dodać lub `s.zdejmij role [nazwa]` odebrać sobie role.");
            }
        }
Example #23
0
        private async Task UserLeftAsync(SocketGuildUser user)
        {
            if (user.IsBot || user.IsWebhook)
            {
                return;
            }

            using (var db = new Database.GuildConfigContext(_config))
            {
                var config = await db.GetCachedGuildFullConfigAsync(user.Guild.Id);

                if (config?.GoodbyeMessage == null)
                {
                    return;
                }
                if (config.GoodbyeMessage == "off")
                {
                    return;
                }

                await SendMessageAsync(ReplaceTags(user, config.GoodbyeMessage), user.Guild.GetTextChannel(config.GreetingChannel));
            }
        }
Example #24
0
        private Task CreateTask(SocketGuildUser user, ISocketMessageChannel channel, long exp, ulong messages, ulong commands, ulong characters)
        {
            return(new Task(() =>
            {
                using (var db = new Database.UserContext(_config))
                {
                    var usr = db.GetUserOrCreateAsync(user.Id).Result;
                    if (usr == null)
                    {
                        return;
                    }

                    if ((DateTime.Now - usr.MeasureDate.AddMonths(1)).TotalSeconds > 1)
                    {
                        usr.MeasureDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
                        usr.MessagesCntAtDate = usr.MessagesCnt;
                        usr.CharacterCntFromDate = characters;
                    }
                    else
                    {
                        usr.CharacterCntFromDate += characters;
                    }

                    usr.ExpCnt += exp;
                    usr.MessagesCnt += messages;
                    usr.CommandsCnt += commands;

                    var newLevel = CalculateLevel(usr.ExpCnt);
                    if (newLevel != usr.Level)
                    {
                        usr.Level = newLevel;
                        _ = Task.Run(async() => { await NotifyAboutLevelAsync(user, channel, newLevel); });
                    }

                    _ = Task.Run(async() =>
                    {
                        using (var dbc = new Database.GuildConfigContext(_config))
                        {
                            var config = await dbc.GetCachedGuildFullConfigAsync(user.Guild.Id);
                            if (config == null)
                            {
                                return;
                            }

                            foreach (var lvlRole in config.RolesPerLevel)
                            {
                                var role = user.Guild.GetRole(lvlRole.Role);
                                if (role == null)
                                {
                                    continue;
                                }

                                bool hasRole = user.Roles.Any(x => x.Id == role.Id);
                                if (newLevel >= (long)lvlRole.Level)
                                {
                                    if (!hasRole)
                                    {
                                        await user.AddRoleAsync(role);
                                    }
                                }
                                else if (hasRole)
                                {
                                    await user.RemoveRoleAsync(role);
                                }
                            }
                        }
                    });

                    db.SaveChanges();
                }
            }));
        }
Example #25
0
        public async Task ToggleColorRoleAsync([Summary("kolor z listy(brak - lista)")] FColor color = FColor.None, [Summary("waluta(SC/TC)")] SCurrency currency = SCurrency.Tc)
        {
            var user = Context.User as SocketGuildUser;

            if (user == null)
            {
                return;
            }

            if (color == FColor.None)
            {
                using (var img = _profile.GetColorList(currency))
                {
                    await Context.Channel.SendFileAsync(img, "list.png");

                    return;
                }
            }

            using (var db = new Database.UserContext(Config))
            {
                var botuser = await db.GetUserOrCreateAsync(user.Id);

                var points = currency == SCurrency.Tc ? botuser.TcCnt : botuser.ScCnt;
                if (points < color.Price(currency))
                {
                    await ReplyAsync("", embed : $"{user.Mention} nie posiadasz wystarczającej liczby {currency.ToString().ToUpper()}!".ToEmbedMessage(EMType.Error).Build());

                    return;
                }

                var colort = botuser.TimeStatuses.FirstOrDefault(x => x.Type == Database.Models.StatusType.Color && x.Guild == Context.Guild.Id);
                if (colort == null)
                {
                    colort = new Database.Models.TimeStatus
                    {
                        Type   = Database.Models.StatusType.Color,
                        Guild  = Context.Guild.Id,
                        EndsAt = DateTime.Now,
                    };
                    botuser.TimeStatuses.Add(colort);
                }

                await _profile.RomoveUserColorAsync(user);

                if (color == FColor.CleanColor)
                {
                    colort.EndsAt = DateTime.Now;
                }
                else
                {
                    using (var cdb = new Database.GuildConfigContext(Config))
                    {
                        var gConfig = await cdb.GetCachedGuildFullConfigAsync(Context.Guild.Id);

                        if (!await _profile.SetUserColorAsync(user, gConfig.AdminRole, color))
                        {
                            await ReplyAsync("", embed : $"Coś poszło nie tak!".ToEmbedMessage(EMType.Error).Build());

                            return;
                        }

                        colort.EndsAt = colort.EndsAt.AddMonths(1);

                        if (currency == SCurrency.Tc)
                        {
                            botuser.TcCnt -= color.Price(currency);
                        }
                        else
                        {
                            botuser.ScCnt -= color.Price(currency);
                        }
                    }
                }

                await db.SaveChangesAsync();

                QueryCacheManager.ExpireTag(new string[] { $"user-{botuser.Id}", "users" });

                await ReplyAsync("", embed : $"{user.Mention} wykupił kolor!".ToEmbedMessage(EMType.Success).Build());
            }
        }
Example #26
0
        public async Task ReportUserAsync([Summary("id wiadomości")] ulong messageId, [Summary("powód")][Remainder] string reason)
        {
            using (var db = new Database.GuildConfigContext(Config))
            {
                var config = await db.GetCachedGuildFullConfigAsync(Context.Guild.Id);

                if (config == null)
                {
                    await ReplyAsync("", embed : "Serwer nie jest jeszcze skonfigurowany.".ToEmbedMessage(EMType.Bot).Build());

                    return;
                }

                var raportCh = Context.Guild.GetTextChannel(config.RaportChannel);
                if (raportCh == null)
                {
                    await ReplyAsync("", embed : "Serwer nie ma skonfigurowanych raportów.".ToEmbedMessage(EMType.Bot).Build());

                    return;
                }

                await Context.Message.DeleteAsync();

                var repMsg = await Context.Channel.GetMessageAsync(messageId);

                if (repMsg == null)
                {
                    await ReplyAsync("", embed : "Nie odnaleziono wiadomości.".ToEmbedMessage(EMType.Error).Build());

                    return;
                }

                if (repMsg.Author.IsBot || repMsg.Author.IsWebhook)
                {
                    await ReplyAsync("", embed : "Raportować bota? Bez sensu.".ToEmbedMessage(EMType.Bot).Build());

                    return;
                }

                if ((DateTime.Now - repMsg.CreatedAt.DateTime.ToLocalTime()).TotalHours > 3)
                {
                    await ReplyAsync("", embed : "Można raportować tylko wiadomośći, które nie są starsze jak 3h.".ToEmbedMessage(EMType.Bot).Build());

                    return;
                }

                if (repMsg.Author.Id == Context.User.Id)
                {
                    var user = Context.User as SocketGuildUser;
                    if (user == null)
                    {
                        return;
                    }

                    var notifChannel = Context.Guild.GetTextChannel(config.NotificationChannel);
                    var userRole     = Context.Guild.GetRole(config.UserRole);
                    var muteRole     = Context.Guild.GetRole(config.MuteRole);

                    if (muteRole == null)
                    {
                        await ReplyAsync("", embed : "Rola wyciszająca nie jest ustawiona.".ToEmbedMessage(EMType.Bot).Build());

                        return;
                    }

                    if (user.Roles.Contains(muteRole))
                    {
                        await ReplyAsync("", embed : $"{user.Mention} już jest wyciszony.".ToEmbedMessage(EMType.Error).Build());

                        return;
                    }

                    var session = new AcceptSession(user, null, Context.Client.CurrentUser);
                    await _session.KillSessionIfExistAsync(session);

                    var msg = await ReplyAsync("", embed : $"{user.Mention} raportujesz samego siebie? Może pomoge! Na pewno chcesz muta?".ToEmbedMessage(EMType.Error).Build());

                    await msg.AddReactionsAsync(session.StartReactions);

                    session.Actions = new AcceptMute(Config)
                    {
                        NotifChannel = notifChannel,
                        Moderation   = _moderation,
                        MuteRole     = muteRole,
                        UserRole     = userRole,
                        Message      = msg,
                        User         = user,
                    };
                    session.Message = msg;

                    await _session.TryAddSession(session);

                    return;
                }

                await ReplyAsync("", embed : "Wysłano zgłoszenie.".ToEmbedMessage(EMType.Success).Build());

                string userName = $"{Context.User.Username}({Context.User.Id})";
                var    sendMsg  = await raportCh.SendMessageAsync($"{repMsg.GetJumpUrl()}", embed : "prep".ToEmbedMessage().Build());

                try
                {
                    await sendMsg.ModifyAsync(x => x.Embed = _helper.BuildRaportInfo(repMsg, userName, reason, sendMsg.Id));

                    var rConfig = await db.GetGuildConfigOrCreateAsync(Context.Guild.Id);

                    rConfig.Raports.Add(new Database.Models.Configuration.Raport {
                        User = repMsg.Author.Id, Message = sendMsg.Id
                    });
                    await db.SaveChangesAsync();
                }
                catch (Exception ex)
                {
                    _logger.Log($"in raport: {ex}");
                    await sendMsg.DeleteAsync();
                }
            }
        }
Example #27
0
 public static async Task <GuildOptions> GetCachedGuildFullConfigAsync(this Database.GuildConfigContext context, ulong guildId)
 {
     return((await context.Guilds.Include(x => x.ChannelsWithoutExp).Include(x => x.ChannelsWithoutSupervision).Include(x => x.CommandChannels).Include(x => x.SelfRoles)
             .Include(x => x.Lands).Include(x => x.ModeratorRoles).Include(x => x.RolesPerLevel).Include(x => x.WaifuConfig).ThenInclude(x => x.CommandChannels).Include(x => x.Raports)
             .Include(x => x.WaifuConfig).ThenInclude(x => x.FightChannels).AsNoTracking().FromCacheAsync(new string[] { $"config-{guildId}" })).FirstOrDefault(x => x.Id == guildId));
 }
Example #28
0
        public async Task TransferCardAsync([Summary("id użytkownika")] ulong id, [Summary("liczba kart")] uint count, [Summary("czas w minutach")] uint duration = 5)
        {
            var emote = new Emoji("🎰");
            var time  = DateTime.Now.AddMinutes(duration);

            var mention = "";

            using (var db = new Database.GuildConfigContext(_config))
            {
                var config = await db.GetCachedGuildFullConfigAsync(Context.Guild.Id);

                if (config != null)
                {
                    var wRole = Context.Guild.GetRole(config.WaifuRole);
                    if (wRole != null)
                    {
                        mention = wRole.Mention;
                    }
                }
            }

            var msg = await ReplyAsync(mention, embed : $"Loteria kart. Zareaguj {emote} aby wziąć udział.\n\nKoniec `{time.ToShortTimeString()}:{time.Second.ToString("00")}`".ToEmbedMessage(EMType.Bot).Build());

            await msg.AddReactionAsync(emote);

            await Task.Delay(TimeSpan.FromMinutes(duration));

            await msg.RemoveReactionAsync(emote, Context.Client.CurrentUser);

            var reactions = await msg.GetReactionUsersAsync(emote, 300).FlattenAsync();

            var users = reactions.ToList();

            IUser winner = null;

            using (var db = new Database.UserContext(_config))
            {
                var watch = Stopwatch.StartNew();
                while (winner == null)
                {
                    if (watch.ElapsedMilliseconds > 60000)
                    {
                        throw new Exception("Timeout");
                    }

                    if (users.Count < 1)
                    {
                        await msg.ModifyAsync(x => x.Embed = "Na loterie nie stawił się żaden użytkownik!".ToEmbedMessage(EMType.Error).Build());

                        return;
                    }

                    var selected = Services.Fun.GetOneRandomFrom(users);
                    var dUser    = await db.GetCachedFullUserAsync(selected.Id);

                    if (dUser != null)
                    {
                        if (!dUser.IsBlacklisted)
                        {
                            winner = selected;
                        }
                    }
                    else
                    {
                        users.Remove(selected);
                    }
                }
            }

            var exe = new Executable("lotery", new Task(async() =>
            {
                using (var db = new Database.UserContext(Config))
                {
                    var user = await db.GetUserOrCreateAsync(id);
                    if (user == null)
                    {
                        await msg.ModifyAsync(x => x.Embed = "Nie odnaleziono kart do rozdania!".ToEmbedMessage(EMType.Error).Build());
                        return;
                    }

                    var loteryCards = user.GameDeck.Cards.ToList();
                    if (loteryCards.Count < 1)
                    {
                        await msg.ModifyAsync(x => x.Embed = "Nie odnaleziono kart do rozdania!".ToEmbedMessage(EMType.Error).Build());
                        return;
                    }

                    var winnerUser = await db.GetUserOrCreateAsync(winner.Id);
                    if (winnerUser == null)
                    {
                        await msg.ModifyAsync(x => x.Embed = "Nie odnaleziono docelowego użytkownika!".ToEmbedMessage(EMType.Error).Build());
                        return;
                    }

                    int counter  = 0;
                    var cardsIds = new List <string>();
                    foreach (var thisCard in loteryCards)
                    {
                        cardsIds.Add(thisCard.GetString(false, false, true));

                        thisCard.Active = false;
                        thisCard.InCage = false;
                        thisCard.TagList.Clear();

                        user.GameDeck.Cards.Remove(thisCard);
                        winnerUser.GameDeck.Cards.Add(thisCard);

                        winnerUser.GameDeck.RemoveCharacterFromWishList(thisCard.Character);
                        winnerUser.GameDeck.RemoveCardFromWishList(thisCard.Id);

                        if (++counter == count)
                        {
                            break;
                        }
                    }

                    await db.SaveChangesAsync();

                    QueryCacheManager.ExpireTag(new string[] { $"user-{Context.User.Id}", "users", $"user-{id}" });

                    await msg.ModifyAsync(x => x.Embed = $"Loterie wygrywa {winner.Mention}.\nOtrzymuje: {string.Join("\n", cardsIds)}".TrimToLength(2000).ToEmbedMessage(EMType.Success).Build());
                }
            }));

            await _executor.TryAdd(exe, TimeSpan.FromSeconds(1));

            await msg.RemoveAllReactionsAsync();
        }
Example #29
0
        private async Task Analize(SocketGuildUser user, SocketUserMessage message)
        {
            using (var db = new Database.GuildConfigContext(_config))
            {
                var gConfig = await db.GetCachedGuildFullConfigAsync(user.Guild.Id);

                if (gConfig == null)
                {
                    return;
                }

                if (!gConfig.Supervision)
                {
                    return;
                }

                if (!_guilds.Any(x => x.Key == user.Guild.Id))
                {
                    _guilds.Add(user.Guild.Id, new Dictionary <ulong, SupervisorEntity>());
                    return;
                }

                var guild          = _guilds[user.Guild.Id];
                var messageContent = GetMessageContent(message);
                if (!guild.Any(x => x.Key == user.Id))
                {
                    guild.Add(user.Id, new SupervisorEntity(messageContent));
                    return;
                }

                var susspect = guild[user.Id];
                if (!susspect.IsValid())
                {
                    susspect = new SupervisorEntity(messageContent);
                    return;
                }

                var thisMessage = susspect.Get(messageContent);
                if (!thisMessage.IsValid())
                {
                    thisMessage = new SupervisorMessage(messageContent);
                }

                if (gConfig.AdminRole != 0)
                {
                    if (user.Roles.Any(x => x.Id == gConfig.AdminRole))
                    {
                        return;
                    }
                }

                if (gConfig.ChannelsWithoutSupervision.Any(x => x.Channel == message.Channel.Id))
                {
                    return;
                }

                var muteRole     = user.Guild.GetRole(gConfig.MuteRole);
                var userRole     = user.Guild.GetRole(gConfig.UserRole);
                var notifChannel = user.Guild.GetTextChannel(gConfig.NotificationChannel);

                bool hasRole = user.Roles.Any(x => x.Id == gConfig.UserRole || x.Id == gConfig.MuteRole) || gConfig.UserRole == 0;
                var  action  = MakeDecision(messageContent, susspect.Inc(), thisMessage.Inc(), hasRole);
                await MakeActionAsync(action, user, message, userRole, muteRole, notifChannel);
            }
        }
Example #30
0
        private async Task HandleMessageAsync(SocketMessage message)
        {
            var msg = message as SocketUserMessage;

            if (msg == null)
            {
                return;
            }

            if (msg.Author.IsBot || msg.Author.IsWebhook)
            {
                return;
            }

            var user = msg.Author as SocketGuildUser;

            if (user == null)
            {
                return;
            }

            if (_config.Get().BlacklistedGuilds.Any(x => x == user.Guild.Id))
            {
                return;
            }

            using (var db = new Database.GuildConfigContext(_config))
            {
                var gConfig = await db.GetCachedGuildFullConfigAsync(user.Guild.Id);

                if (gConfig == null)
                {
                    return;
                }

                if (!gConfig.ChaosMode)
                {
                    return;
                }
            }

            if (Fun.TakeATry(3))
            {
                var notChangedUsers = user.Guild.Users.Where(x => !x.IsBot && x.Id != user.Id && !_changed.Any(c => c == x.Id)).ToList();
                if (notChangedUsers.Count < 2)
                {
                    return;
                }

                if (_changed.Any(x => x == user.Id))
                {
                    user = Fun.GetOneRandomFrom(notChangedUsers);
                    notChangedUsers.Remove(user);
                }

                var user2 = Fun.GetOneRandomFrom(notChangedUsers);

                var user1Nickname = user.Nickname ?? user.Username;
                var user2Nickname = user2.Nickname ?? user2.Username;

                await user.ModifyAsync(x => x.Nickname = user2Nickname);

                _changed.Add(user.Id);

                await user2.ModifyAsync(x => x.Nickname = user1Nickname);

                _changed.Add(user2.Id);
            }
        }