Beispiel #1
0
        private async Task MemberUpdatedAsync(MemberUpdatedEventArgs args)
        {
            var oldMember = args.OldMember;
            var newMember = args.NewMember;

            // we care only about the mute role
            if (oldMember.Roles.Count == newMember.Roles.Count)
            {
                return;
            }

            using var scope = RiasBot.CreateScope();
            var db      = scope.ServiceProvider.GetRequiredService <RiasDbContext>();
            var guildDb = await db.Guilds.FirstOrDefaultAsync(x => x.GuildId == newMember.Guild.Id);

            if (guildDb is null)
            {
                return;
            }

            var userGuildDb = await db.GuildUsers.FirstOrDefaultAsync(x => x.GuildId == newMember.Guild.Id && x.UserId == newMember.Id);

            if (userGuildDb is null)
            {
                return;
            }

            userGuildDb.IsMuted = newMember.Roles.FirstOrDefault(x => x.Key == guildDb.MuteRoleId).Value != null;
            await db.SaveChangesAsync();
        }
Beispiel #2
0
        public async Task LeaveGuildAsync(string name)
        {
            var guild = ulong.TryParse(name, out var guildId)
                ? RiasBot.GetGuild(guildId)
                : RiasBot.Client.ShardClients
                        .SelectMany(x => x.Value.Guilds)
                        .FirstOrDefault(x => string.Equals(x.Value.Name, name)).Value;

            if (guild is null)
            {
                await ReplyErrorAsync(Localization.BotGuildNotFound);

                return;
            }

            var embed = new DiscordEmbedBuilder
            {
                Color       = RiasUtilities.ConfirmColor,
                Description = GetText(Localization.BotLeftGuild, guild.Name)
            }.AddField(GetText(Localization.CommonId), guild.Id.ToString(), true).AddField(GetText(Localization.CommonMembers), guild.MemberCount.ToString(), true);

            await ReplyAsync(embed);

            await guild.LeaveAsync();
        }
Beispiel #3
0
        /// <summary>
        /// Gets the user's currency.
        /// </summary>
        public async Task <int> GetUserCurrencyAsync(ulong userId)
        {
            using var scope = RiasBot.CreateScope();
            var db = scope.ServiceProvider.GetRequiredService <RiasDbContext>();

            return((await db.Users.FirstOrDefaultAsync(x => x.UserId == userId))?.Currency ?? 0);
        }
        public async Task <int> RemoveUserCurrencyAsync(Snowflake userId, int currency)
        {
            using var scope = RiasBot.CreateScope();
            var db     = scope.ServiceProvider.GetRequiredService <RiasDbContext>();
            var userDb = await db.Users.FirstOrDefaultAsync(x => x.UserId == userId);

            if (userDb == null)
            {
                return(0);
            }

            var currencyTaken = currency;

            if (currency > userDb.Currency)
            {
                currencyTaken   = userDb.Currency;
                userDb.Currency = 0;
            }
            else
            {
                userDb.Currency -= currency;
            }

            await db.SaveChangesAsync();

            return(currencyTaken);
        }
Beispiel #5
0
        private async Task PledgeReceivedAsync(string data)
        {
            try
            {
                var pledgeData = JsonConvert.DeserializeObject <JToken>(data);
                var userId     = pledgeData !.Value <ulong>("discord_id");

                using var scope = RiasBot.CreateScope();
                var db        = scope.ServiceProvider.GetRequiredService <RiasDbContext>();
                var patreonDb = await db.Patreon.FirstOrDefaultAsync(x => x.UserId == userId);

                if (patreonDb is null)
                {
                    Log.Error("Couldn't take the patreon data from the database for user {UserId}", userId);
                    return;
                }

                var reward = pledgeData.Value <int>("reward") * 5;
                var userDb = await db.GetOrAddAsync(x => x.UserId == userId, () => new UserEntity { UserId = userId });

                userDb.Currency += reward;

                patreonDb.Checked = true;
                await db.SaveChangesAsync();

                Log.Information("Patreon discord user with ID {UserId} was rewarded with {Reward} hearts", userId, reward);
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Exception on receiving a pledge");
            }
        }
        public async Task <bool> CheckColorAsync(CachedUser user, Color color, int?tier = null)
        {
            if (Credentials.PatreonConfig is null)
            {
                return(true);
            }

            if (user.Id == Credentials.MasterId)
            {
                return(true);
            }

            if (_colors.Any(x => x == color))
            {
                return(true);
            }

            if (tier.HasValue)
            {
                return(tier.Value >= PatreonService.ProfileColorTier);
            }

            using var scope = RiasBot.CreateScope();
            var db = scope.ServiceProvider.GetRequiredService <RiasDbContext>();

            tier = (await db.Patreon.FirstOrDefaultAsync(x => x.UserId == user.Id))?.Tier ?? 0;
            return(tier >= PatreonService.ProfileColorTier);
        }
        public int GetUserCurrency(Snowflake userId)
        {
            using var scope = RiasBot.CreateScope();
            var db = scope.ServiceProvider.GetRequiredService <RiasDbContext>();

            return(db.Users.FirstOrDefault(x => x.UserId == userId)?.Currency ?? 0);
        }
Beispiel #8
0
        private async Task CheckVotesAsync()
        {
            using var scope = RiasBot.CreateScope();
            var db    = scope.ServiceProvider.GetRequiredService <RiasDbContext>();
            var votes = await db.Votes.Where(x => !x.Checked).ToListAsync();

            foreach (var vote in votes)
            {
                var userDb = await db.GetOrAddAsync(x => x.UserId == vote.UserId, () => new UsersEntity { UserId = vote.UserId });

                if (userDb.IsBlacklisted)
                {
                    db.Remove(vote);
                    Log.Information($"Vote discord user with ID {vote.UserId} is blacklisted, it was removed from the votes database table");
                    continue;
                }

                var reward = vote.IsWeekend ? 50 : 25;
                userDb.Currency += reward;

                vote.Checked = true;
                Log.Information($"Vote discord user with ID {vote.UserId} was rewarded with {reward} hearts");
            }

            await db.SaveChangesAsync();
        }
Beispiel #9
0
        public async Task AddAssignableRoleAsync(CachedMember member)
        {
            var currentMember = member.Guild.CurrentMember;

            if (!currentMember.Permissions.ManageRoles)
            {
                return;
            }

            if (member.Roles.Count > 1)
            {
                return;
            }

            using var scope = RiasBot.CreateScope();
            var db      = scope.ServiceProvider.GetRequiredService <RiasDbContext>();
            var guildDb = await db.Guilds.FirstOrDefaultAsync(x => x.GuildId == member.Guild.Id);

            if (guildDb is null)
            {
                return;
            }

            var aar = member.Guild.GetRole(guildDb.AutoAssignableRoleId);

            if (aar is null)
            {
                return;
            }

            if (currentMember.CheckRoleHierarchy(aar) > 0 && !aar.IsManaged && member.GetRole(aar.Id) is null)
            {
                await member.GrantRoleAsync(aar.Id);
            }
        }
Beispiel #10
0
        public RiasService(IServiceProvider serviceProvider)
        {
            RiasBot       = serviceProvider.GetRequiredService <RiasBot>();
            Configuration = serviceProvider.GetRequiredService <Configuration>();
            Localization  = serviceProvider.GetRequiredService <Localization>();

            _serviceProvider = serviceProvider;
        }
        public async Task AddUserCurrencyAsync(Snowflake userId, int currency)
        {
            using var scope = RiasBot.CreateScope();
            var db     = scope.ServiceProvider.GetRequiredService <RiasDbContext>();
            var userDb = await db.GetOrAddAsync(x => x.UserId == userId, () => new UsersEntity { UserId = userId });

            userDb.Currency += currency;
            await db.SaveChangesAsync();
        }
Beispiel #12
0
        public async Task HelpAsync()
        {
            var embed = new LocalEmbedBuilder
            {
                Color  = RiasUtilities.ConfirmColor,
                Author = new LocalEmbedAuthorBuilder
                {
                    Name    = GetText(Localization.HelpTitle, RiasBot.CurrentUser.Name, Rias.Version),
                    IconUrl = RiasBot.CurrentUser.GetAvatarUrl()
                },
                Footer = new LocalEmbedFooterBuilder().WithText("© 2018-2020 Copyright: Koneko#0001")
            };

            embed.WithDescription(GetText(Localization.HelpInfo, Context.Prefix));

            var          links     = new StringBuilder();
            const string delimiter = " • ";

            if (!string.IsNullOrEmpty(Credentials.OwnerServerInvite))
            {
                var ownerServer = RiasBot.GetGuild(Credentials.OwnerServerId);
                links.Append(delimiter)
                .Append(GetText(Localization.HelpSupportServer, ownerServer.Name, Credentials.OwnerServerInvite))
                .Append("\n");
            }

            if (links.Length > 0)
            {
                links.Append(delimiter);
            }
            if (!string.IsNullOrEmpty(Credentials.Invite))
            {
                links.Append(GetText(Localization.HelpInviteMe, Credentials.Invite)).Append("\n");
            }

            if (links.Length > 0)
            {
                links.Append(delimiter);
            }
            if (!string.IsNullOrEmpty(Credentials.Website))
            {
                links.Append(GetText(Localization.HelpWebsite, Credentials.Website)).Append("\n");
            }

            if (links.Length > 0)
            {
                links.Append(delimiter);
            }
            if (!string.IsNullOrEmpty(Credentials.Patreon))
            {
                links.Append(GetText(Localization.HelpDonate, Credentials.Patreon)).Append("\n");
            }

            embed.AddField(GetText(Localization.HelpLinks), links.ToString());
            await ReplyAsync(embed);
        }
Beispiel #13
0
        public RiasModule(IServiceProvider serviceProvider)
        {
            RiasBot       = serviceProvider.GetRequiredService <RiasBot>();
            Configuration = serviceProvider.GetRequiredService <Configuration>();
            Localization  = serviceProvider.GetRequiredService <Localization>();

            _httpClient = new Lazy <HttpClient>(() => serviceProvider.GetRequiredService <IHttpClientFactory>().CreateClient());

            _scope    = serviceProvider.CreateScope();
            DbContext = _scope.ServiceProvider.GetRequiredService <RiasDbContext>();
        }
Beispiel #14
0
        private async Task MemberLeftAsync(MemberLeftEventArgs args)
        {
            if (RiasBot.CurrentUser != null && args.User.Id == RiasBot.CurrentUser.Id)
            {
                return;
            }

            using var scope = RiasBot.CreateScope();
            var db      = scope.ServiceProvider.GetRequiredService <RiasDbContext>();
            var guildDb = await db.Guilds.FirstOrDefaultAsync(g => g.GuildId == args.Guild.Id);

            await SendByeMessageAsync(guildDb, args.User, args.Guild);
        }
Beispiel #15
0
        private async Task DisableByeAsync(CachedGuild guild)
        {
            using var scope = RiasBot.CreateScope();
            var db      = scope.ServiceProvider.GetRequiredService <RiasDbContext>();
            var guildDb = await db.Guilds.FirstOrDefaultAsync(x => x.GuildId == guild.Id);

            if (guildDb is null)
            {
                return;
            }

            guildDb.ByeNotification = false;
            await db.SaveChangesAsync();
        }
Beispiel #16
0
        public async Task HelpAsync()
        {
            var embed = new DiscordEmbedBuilder()
                        .WithColor(RiasUtilities.ConfirmColor)
                        .WithAuthor(GetText(Localization.HelpTitle, RiasBot.CurrentUser !.Username, RiasBot.Version), RiasBot.CurrentUser.GetAvatarUrl(ImageFormat.Auto))
                        .WithFooter(GetText(Localization.HelpFooter))
                        .WithDescription(GetText(Localization.HelpInfo, Context.Prefix));

            var          links     = new StringBuilder();
            const string delimiter = " • ";

            if (!string.IsNullOrEmpty(Configuration.OwnerServerInvite))
            {
                var ownerServer = RiasBot.GetGuild(Configuration.OwnerServerId);
                links.Append(delimiter)
                .Append(GetText(Localization.HelpSupportServer, ownerServer !.Name, Configuration.OwnerServerInvite))
                .AppendLine();
            }

            if (links.Length > 0)
            {
                links.Append(delimiter);
            }
            if (!string.IsNullOrEmpty(Configuration.Invite))
            {
                links.Append(GetText(Localization.HelpInviteMe, Configuration.Invite)).AppendLine();
            }

            if (links.Length > 0)
            {
                links.Append(delimiter);
            }
            if (!string.IsNullOrEmpty(Configuration.Website))
            {
                links.Append(GetText(Localization.HelpWebsite, Configuration.Website)).AppendLine();
            }

            if (links.Length > 0)
            {
                links.Append(delimiter);
            }
            if (!string.IsNullOrEmpty(Configuration.Patreon))
            {
                links.Append(GetText(Localization.HelpDonate, Configuration.Patreon)).AppendLine();
            }

            embed.AddField(GetText(Localization.HelpLinks), links.ToString());
            await ReplyAsync(embed);
        }
Beispiel #17
0
        private async Task MemberJoinedAsync(MemberJoinedEventArgs args)
        {
            var member = args.Member;

            if (RiasBot.CurrentUser != null && member.Id == RiasBot.CurrentUser.Id)
            {
                return;
            }

            await RunTaskAsync(AddAssignableRoleAsync(member));

            using var scope = RiasBot.CreateScope();
            var db      = scope.ServiceProvider.GetRequiredService <RiasDbContext>();
            var guildDb = await db.Guilds.FirstOrDefaultAsync(g => g.GuildId == member.Guild.Id);

            await SendGreetMessageAsync(guildDb, member);

            var currentUser = member.Guild.CurrentMember;

            if (!currentUser.Permissions.ManageRoles)
            {
                return;
            }

            var userGuildDb = await db.GuildUsers.FirstOrDefaultAsync(x => x.GuildId == member.Guild.Id && x.UserId == member.Id);

            if (userGuildDb is null)
            {
                return;
            }
            if (!userGuildDb.IsMuted)
            {
                return;
            }

            var role = member.Guild.GetRole(guildDb?.MuteRoleId ?? 0)
                       ?? member.Guild.Roles.FirstOrDefault(x => string.Equals(x.Value.Name, MuteService.MuteRole)).Value;

            if (role != null)
            {
                await member.GrantRoleAsync(role.Id);
            }
            else
            {
                userGuildDb.IsMuted = false;
                await db.SaveChangesAsync();
            }
        }
Beispiel #18
0
        /// <summary>
        /// Remove currency from the user and returns the new currency.
        /// </summary>
        public async Task <int> RemoveUserCurrencyAsync(ulong userId, int currency)
        {
            using var scope = RiasBot.CreateScope();
            var db     = scope.ServiceProvider.GetRequiredService <RiasDbContext>();
            var userDb = await db.Users.FirstOrDefaultAsync(x => x.UserId == userId);

            if (userDb == null)
            {
                return(0);
            }

            userDb.Currency -= Math.Min(currency, userDb.Currency);
            await db.SaveChangesAsync();

            return(userDb.Currency);
        }
Beispiel #19
0
        public async Task GlobalXpLeaderboardAsync(int page = 1)
        {
            page--;
            if (page < 0)
            {
                page = 0;
            }

            var membersXp = await DbContext.GetOrderedListAsync <UserEntity, int>(x => x.Xp, true);

            var xpLeaderboard = membersXp.Skip(page * 15)
                                .Take(15)
                                .ToList();

            if (xpLeaderboard.Count == 0)
            {
                await ReplyErrorAsync(Localization.XpLeaderboardEmpty);

                return;
            }

            var description = new StringBuilder();
            var index       = page * 15;

            foreach (var userDb in xpLeaderboard)
            {
                var user = await RiasBot.GetUserAsync(userDb.UserId);

                description.Append($"{++index}. **{user?.FullName()}**: " +
                                   $"`{GetText(Localization.XpLevelX, RiasUtilities.XpToLevel(userDb.Xp, XpService.XpThreshold))} " +
                                   $"({userDb.Xp} {GetText(Localization.XpXp).ToLowerInvariant()})`\n");
            }

            var embed = new DiscordEmbedBuilder
            {
                Color       = RiasUtilities.ConfirmColor,
                Title       = GetText(Localization.XpLeaderboard),
                Description = description.ToString(),
                Footer      = new DiscordEmbedBuilder.EmbedFooter
                {
                    IconUrl = Context.User.GetAvatarUrl(ImageFormat.Auto),
                    Text    = $"{Context.User.FullName()} • #{membersXp.FindIndex(x => x.UserId == Context.User.Id) + 1}"
                }
            };

            await ReplyAsync(embed);
        }
Beispiel #20
0
        private Task ShardReadyAsync(ShardReadyEventArgs e)
        {
            _shardsReady.AddOrUpdate(e.SessionId, true, (shardKey, value) => true);
            if (_shardsReady.Count == RiasBot.Shards.Count && _shardsReady.All(x => x.Value))
            {
                RiasBot.ShardReady -= ShardReadyAsync;
                Log.Information("All shards are connected");

                RiasBot.GetRequiredService <MuteService>();

                var reactionsService = RiasBot.GetRequiredService <ReactionsService>();
                reactionsService.WeebUserAgent = $"{RiasBot.CurrentUser.Name}/{Rias.Version}";
                reactionsService.AddWeebUserAgent();
            }

            return(Task.CompletedTask);
        }
Beispiel #21
0
            public async Task LeaderboardAsync(int page = 1)
            {
                page--;
                if (page < 0)
                {
                    page = 0;
                }

                var usersCurrency = await DbContext.GetOrderedListAsync <UserEntity, int>(x => x.Currency, true);

                var currencyLeaderboard = usersCurrency.Skip(page * 15)
                                          .Take(15)
                                          .ToList();

                if (currencyLeaderboard.Count == 0)
                {
                    await ReplyErrorAsync(Localization.GamblingLeaderboardNoUsers);

                    return;
                }

                var embed = new DiscordEmbedBuilder
                {
                    Color  = RiasUtilities.ConfirmColor,
                    Title  = GetText(Localization.GamblingCurrencyLeaderboard, Configuration.Currency),
                    Footer = new DiscordEmbedBuilder.EmbedFooter
                    {
                        IconUrl = Context.User.GetAvatarUrl(ImageFormat.Auto),
                        Text    = $"{Context.User.FullName()} • #{usersCurrency.FindIndex(x => x.UserId == Context.User.Id) + 1}"
                    }
                };

                var index = 0;

                foreach (var userCurrency in currencyLeaderboard)
                {
                    var user = await RiasBot.GetUserAsync(userCurrency.UserId);

                    embed.AddField($"#{++index + page * 15} {user?.FullName()}", $"{userCurrency.Currency} {Configuration.Currency}", true);
                }

                await ReplyAsync(embed);
            }
Beispiel #22
0
        private async Task CheckPatronsAsync()
        {
            using var scope = RiasBot.CreateScope();
            var db      = scope.ServiceProvider.GetRequiredService <RiasDbContext>();
            var patrons = await db.Patreon.Where(x => x.PatronStatus == PatronStatus.ActivePatron && !x.Checked && x.Tier > 0)
                          .ToListAsync();

            foreach (var patron in patrons)
            {
                var reward = patron.AmountCents * 5;
                var userDb = await db.GetOrAddAsync(x => x.UserId == patron.UserId, () => new UserEntity { UserId = patron.UserId });

                userDb.Currency += reward;

                patron.Checked = true;
                Log.Information("Patreon discord user with ID {UserId} was rewarded with {Reward} hearts", patron.UserId, reward);
            }

            await db.SaveChangesAsync();
        }
Beispiel #23
0
        public async Task FindUserAsync([Remainder] string value)
        {
            DiscordUser?user = null;

            if (ulong.TryParse(value, out var userId))
            {
                user = await RiasBot.GetUserAsync(userId);

                if (user is null)
                {
                    await ReplyErrorAsync(Localization.AdministrationUserNotFound);

                    return;
                }
            }
            else
            {
                var index = value.LastIndexOf("#", StringComparison.Ordinal);
                if (index >= 0)
                {
                    user = RiasBot.Members.FirstOrDefault(x => string.Equals(x.Value.Username, value[..index]) &&
Beispiel #24
0
        private async Task SendPatronsAsync()
        {
            using var scope = RiasBot.CreateScope();
            var db      = scope.ServiceProvider.GetRequiredService <RiasDbContext>();
            var patrons = (await db.GetOrderedListAsync <PatreonEntity, int>(
                               x => x.PatronStatus == PatronStatus.ActivePatron && x.Tier > 0,
                               x => x.Tier,
                               true))
                          .Where(x => RiasBot.Members.ContainsKey(x.UserId))
                          .Select(x =>
            {
                var user = RiasBot.Members[x.UserId];
                return(new PatreonDiscordUser
                {
                    PatreonId = x.PatreonUserId,
                    DiscordId = x.UserId,
                    PatreonUsername = x.PatreonUserName,
                    DiscordUsername = user.Username,
                    DiscordDiscriminator = user.Discriminator,
                    DiscordAvatar = user.GetAvatarUrl(ImageFormat.Auto),
                    Tier = x.Tier
                });
            });

            try
            {
                var data = JsonConvert.SerializeObject(patrons, Formatting.Indented);
#if RIAS_GLOBAL
                await _httpClient !.PostAsync("https://rias.gg/api/patreon", new StringContent(data));
#elif DEBUG
                await _httpClient !.PostAsync("https://localhost/api/patreon", new StringContent(data));
#endif
            }
            catch
            {
                // ignored
            }
        }
Beispiel #25
0
            public MuteContext(RiasBot riasBot, ulong guildId, ulong moderatorId, ulong memberId, ulong channelId)
            {
                Guild    = riasBot.GetGuild(guildId);
                GuildId  = guildId;
                MemberId = memberId;

                if (Guild != null)
                {
                    if (Guild.Members.TryGetValue(moderatorId, out var moderator))
                    {
                        Moderator = moderator;
                    }

                    if (Guild.Members.TryGetValue(memberId, out var member))
                    {
                        Member = member;
                    }

                    SourceChannel = Guild.GetChannel(channelId);
                }

                SentByTimer = true;
            }
            public async Task ActivityAsync(string?type = null, [Remainder] string?name = null)
            {
                await Service.StopActivityRotationAsync();

                if (type is null || name is null)
                {
                    await RiasBot.SetPresenceAsync(null);
                    await ReplyConfirmationAsync(Localization.BotActivityRemoved);

                    return;
                }

                var activity = Service.GetActivity(name, type);

                if (activity.Type == ActivityType.Streaming)
                {
                    name = $"[{name}]({activity.Url})";
                }

                await RiasBot.SetPresenceAsync(activity);

                await ReplyConfirmationAsync(Localization.BotActivitySet, GetText(Localization.BotActivity(type.ToLower()), name.ToLowerInvariant()).ToLowerInvariant());
            }
Beispiel #27
0
        public async Task LeaveGuildAsync(string name)
        {
            var guild = Snowflake.TryParse(name, out var guildId)
                ? RiasBot.GetGuild(guildId)
                : RiasBot.Guilds.FirstOrDefault(x => string.Equals(x.Value.Name, name)).Value;

            if (guild is null)
            {
                await ReplyErrorAsync(Localization.BotGuildNotFound);

                return;
            }

            var embed = new LocalEmbedBuilder()
            {
                Color       = RiasUtilities.ConfirmColor,
                Description = GetText(Localization.BotLeftGuild, guild.Name)
            }.AddField(GetText(Localization.CommonId), guild.Id, true).AddField(GetText(Localization.CommonUsers), guild.MemberCount, true);

            await ReplyAsync(embed);

            await guild.LeaveAsync();
        }
Beispiel #28
0
        public async Task GlobalXpLeaderboardAsync(int page = 1)
        {
            page--;
            if (page < 0)
            {
                page = 0;
            }

            var xpLeaderboard = await DbContext.GetOrderedListAsync <UsersEntity, int>(x => x.Xp, true, (page * 15)..((page + 1) * 15));

            if (xpLeaderboard.Count == 0)
            {
                await ReplyErrorAsync(Localization.XpLeaderboardEmpty);

                return;
            }

            var embed = new LocalEmbedBuilder
            {
                Color = RiasUtilities.ConfirmColor,
                Title = GetText(Localization.XpLeaderboard)
            };

            var index = page * 15;

            foreach (var userDb in xpLeaderboard)
            {
                var user = (IUser)RiasBot.GetUser(userDb.UserId) ?? await RiasBot.GetUserAsync(userDb.UserId);

                embed.AddField($"{++index}. {user}",
                               $"{GetText(Localization.XpLevelX, RiasUtilities.XpToLevel(userDb.Xp, XpService.XpThreshold))} | {GetText(Localization.XpXp)} {userDb.Xp}",
                               true);
            }

            await ReplyAsync(embed);
        }
Beispiel #29
0
        private async Task PledgeReceivedAsync(string data)
        {
            var pledgeData = JsonConvert.DeserializeObject <PatreonPledge>(data);

            using var scope = RiasBot.CreateScope();
            var db        = scope.ServiceProvider.GetRequiredService <RiasDbContext>();
            var patreonDb = await db.Patreon.FirstOrDefaultAsync(x => x.UserId == pledgeData.DiscordId);

            if (patreonDb is null)
            {
                Log.Error($"Couldn't take the patreon data from the database for user {pledgeData.DiscordId}");
                return;
            }

            var reward = pledgeData.AmountCents * 5;
            var userDb = await db.GetOrAddAsync(x => x.UserId == pledgeData.DiscordId, () => new UsersEntity { UserId = pledgeData.DiscordId });

            userDb.Currency += reward;

            patreonDb.Checked = true;
            await db.SaveChangesAsync();

            Log.Information($"Patreon discord user with ID {patreonDb.UserId} was rewarded with {reward} hearts");
        }
Beispiel #30
0
        private async Task VoteReceivedAsync(string data)
        {
            var voteData = JsonConvert.DeserializeObject <Vote>(data);

            using var scope = RiasBot.CreateScope();
            var db     = scope.ServiceProvider.GetRequiredService <RiasDbContext>();
            var voteDb = await db.Votes.FirstOrDefaultAsync(x => x.UserId == voteData.UserId && !x.Checked);

            if (voteDb is null)
            {
                Log.Error($"Couldn't take the vote data from the database for user {voteData.UserId}");
                return;
            }

            var reward = voteDb.IsWeekend ? 50 : 25;
            var userDb = await db.GetOrAddAsync(x => x.UserId == voteData.UserId, () => new UsersEntity { UserId = voteData.UserId });

            userDb.Currency += reward;

            voteDb.Checked = true;
            await db.SaveChangesAsync();

            Log.Information($"Vote discord user with ID {voteDb.UserId} was rewarded with {reward} hearts");
        }