Ejemplo n.º 1
0
        public async Task <CreateHomeWorkReminderResponse> SaveReminderInDB(CreateHomeWorkReminderRequest data)
        {
            if (data == null)
            {
                return(null);
            }
            var result = new CreateHomeWorkReminderResponse()
            {
                Result = false
            };
            var reminder = await _context.UserHomeWorkReminder.FirstOrDefaultAsync(uhwr => uhwr.HomeWorkId == data.HomeWorkId && uhwr.UserId == data.UserId && uhwr.DateTimeSend == data.DateOfReminder.Ticks);

            if (reminder != null)
            {
                if (reminder.DateTimeSend.CompareTo(data.DateOfReminder.Ticks) != 0 && data.DateOfReminder.CompareTo(DateTime.Now) > 0)
                {
                    reminder.DateTimeSend = data.DateOfReminder.Ticks;
                    try
                    {
                        _context.UserHomeWorkReminder.Update(reminder);
                        await _context.SaveChangesAsync();
                    }
                    catch (Exception ex)
                    {
                        _logger.LogException(ex);
                    }
                }
                result.Id = reminder.Id;
            }
            else
            {
                try
                {
                    var addedReminder = new UserHomeWorkReminder {
                        HomeWorkId = data.HomeWorkId, UserId = data.UserId, DateTimeSend = data.DateOfReminder.Ticks
                    };
                    await _context.UserHomeWorkReminder.AddAsync(addedReminder);

                    await _context.SaveChangesAsync();

                    result.Result = true;
                    result.Id     = addedReminder.Id;
                }
                catch (Exception ex)
                {
                    _logger.LogException(ex);
                }
            }
            return(result);
        }
Ejemplo n.º 2
0
        async Task CheckUser(SocketGuildUser user)
        {
            using (var con = new BotDBContext())
            {
                var userInDb = await con.UsersPlayers.Include(u => u.User).Where(u => u.User.DiscordId == user.Id).Include(p => p.Players).ThenInclude(m => m.Matches).FirstOrDefaultAsync();

                if (userInDb != null)
                {
                    Console.WriteLine("UserCheck");
                    foreach (var player in userInDb.Players)
                    {
                        var playerRep = new PlayerRepository();
                        await playerRep.GetPlayerById(player.PubgID);

                        await playerRep.LoadMatches();

                        foreach (var playerMatch in playerRep.Player.Matches.OrderByDescending(d => d.Match.CreatedAt))
                        {
                            if (playerMatch.Match.CreatedAt > DateTime.Now.AddHours(-Config.Instance.WatchRecentHours))
                            {
                                if (!con.Notifications.Any(m => m.MatchID == playerMatch.MatchId && m.UserId == user.Id))
                                {
                                    if (playerMatch.Match.GetParticipantsMatchStats(playerRep.Player.Name).WinPlace < Config.Instance.WinPlace)
                                    {
                                        var participants = playerMatch.Match.GetMyTeam(playerRep.Player.Name);
                                        Console.WriteLine($"Message Sent to {user.Id} | {user.Username} {playerMatch.MatchId} at {DateTime.Now}");

                                        await Discord.UserExtensions.SendMessageAsync(user, embed : EmbedHelper.GetParticipantsStats(participants, playerMatch.Match));

                                        con.Notifications.Add(new Model.Notification()
                                        {
                                            UserId = user.Id, MatchID = playerMatch.MatchId
                                        });
                                        await con.SaveChangesAsync();

                                        player.Matches.Add(new Model.Match()
                                        {
                                            MatchId = playerMatch.MatchId
                                        });
                                        con.UsersPlayers.Update(userInDb);
                                        await con.SaveChangesAsync();
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 3
0
        private async Task ProcessUsers(SocketGuild guild)
        {
            foreach (SocketGuildUser user in guild.Users)
            {
                if (guild.Users.Count > 100)
                {
                    return;
                }

                using (BotDBContext DBContext = DBFactory.Create <BotDBContext>())
                {
                    DBContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
                    var userObj    = new DiscordUser(user.Id.ToString(), (short)user.DiscriminatorValue, user.Username, user.GetAvatarUrl(ImageFormat.Gif), user.CreatedAt, user.IsBot);
                    var userRecord = await DBContext.Users.FindAsync(userObj.Id);

                    if (userRecord == null)
                    {
                        ConsoleEx.WriteColoredLine(LogSeverity.Verbose, ConsoleTextFormat.TimeAndText, "Adding new User ", ConsoleColor.Cyan, user.Username + $"#{userObj.Discriminator}", ConsoleColor.Gray, " to the database.");
                        await DBContext.AddAsync(userObj);
                    }
                    else
                    {
                        DBContext.DetachLocal(userObj, userObj.Id);
                    }

                    await DBContext.SaveChangesAsync();
                }
            }
        }
Ejemplo n.º 4
0
        public async Task <PrefixResponseData> TryRemovePrefix(IGuild guild, IUser user, string prefix)
        {
            if (PrefixDictionary.ContainsKey(guild.Id.ToString()))
            {
                List <DiscordCustomPrefix> customPrefixBag = PrefixDictionary.GetValue(guild.Id.ToString());
                if (customPrefixBag == null || customPrefixBag.Count == 0)
                {
                    return(new PrefixResponseData(false, "No custom prefixes exist on the current guild."));
                }
                else
                {
                    using (BotDBContext DBContext = Provider.GetService <DBContextFactory>().Create <BotDBContext>())
                    {
                        foreach (DiscordCustomPrefix prefixObj in customPrefixBag)
                        {
                            if (prefixObj.Prefix == prefix && user.Id.ToString() == prefixObj.CreatorId)
                            {
                                PrefixDictionary.GetValue(guild.Id.ToString()).Remove(prefixObj);
                                DBContext.DiscordCustomPrefixes.Remove(prefixObj);
                                await DBContext.SaveChangesAsync();

                                return(new PrefixResponseData(true, "Successfully removed the specified prefix from this guild."));
                            }
                        }
                    }
                }
            }
            else
            {
                return(new PrefixResponseData(false, $"Unable to remove the specified prefix, it does not exist in this guild."));
            }

            return(new PrefixResponseData(false, $"Unable to remove the specified prefix from the guild for an unknown reason."));
        }
Ejemplo n.º 5
0
        private async Task ProcessGuilds()
        {
            using (BotDBContext DBContext = DBFactory.Create <BotDBContext>())
            {
                DBContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
                foreach (SocketGuild guild in Client.Guilds)
                {
                    var guildObj    = new DiscordGuild(guild.Id, guild.Name, guild.OwnerId, guild.CreatedAt, guild.IconUrl, guild.SplashUrl);
                    var guildRecord = await DBContext.Guilds.FindAsync(guildObj.Id);

                    if (guildRecord == null)
                    {
                        ConsoleEx.WriteColoredLine(LogSeverity.Verbose, ConsoleTextFormat.TimeAndText, "Adding new Guild ", ConsoleColor.Cyan, guild.Name, ConsoleColor.Gray, " to the database.");
                        await DBContext.AddAsync(guildObj);
                    }
                    else
                    {
                        DBContext.DetachLocal(guildObj, guildObj.Id);
                    }

                    await DBContext.SaveChangesAsync();

                    await ProcessTextChannels(guild);
                    await ProcessUsers(guild);
                }
            }
        }
Ejemplo n.º 6
0
        public async Task <CreateHomeWorkResponse> SaveHomeworkInDB(CreateHomeWorkRequest data)
        {
            _logger.LogInformation("SaveHomeworkInDB begin");
            if (data == null)
            {
                return(null);
            }
            var result = new CreateHomeWorkResponse()
            {
                Result = false
            };

            if (await _context.HomeWork.FirstOrDefaultAsync(u => u.Title == data.Title && u.DateOfReadyness == data.DateOfReadyness.Ticks) != null)
            {
                _logger.LogInformation("dublicate");
                return(result);
            }
            try
            {
                await _context.HomeWork.AddAsync(new HomeWork { Title = data.Title, DateOfReadyness = data.DateOfReadyness.Ticks });

                await _context.SaveChangesAsync();

                result.Result = true;
                return(result);
            }
            catch (Exception ex)
            {
                _logger.LogException(ex);
                return(result);
            }
        }
Ejemplo n.º 7
0
        private async Task SendComicsAsync(Subscription subscriptionType)
        {
            using (var db = new BotDBContext())
            {
                var clients = (from c in db.Clients
                               join sub in db.Subscriptions on c.Subscription equals sub.Id
                               where sub.SubsctiptionType == (int)subscriptionType
                               select c.ChatId
                               ).Distinct();

                MessageToSend message = (subscriptionType == Subscription.Oglaf) ? GetOglafPicture() : GetXKCDPicture();

                foreach (var client in clients)
                {
                    var lastPostedKey = (from cli in db.Clients
                                         join sub in db.Subscriptions on cli.Subscription equals sub.Id
                                         where cli.ChatId == client && sub.SubsctiptionType == (int)subscriptionType
                                         orderby sub.Id descending
                                         select new
                    {
                        LTK = sub.LastPostedKey,
                        SUBID = sub.Id
                    }
                                         ).First();

                    if (message.Title.Equals(lastPostedKey.LTK))
                    {
                        continue;
                    }

                    DatabaseInteractions.Subscription subToUpdate = db.Subscriptions.Where(x => x.Id == lastPostedKey.SUBID).First();
                    string newHash = message.Title;
                    subToUpdate.LastPostedKey = newHash;
                    db.Update(subToUpdate);
                    //db.Subscriptions.Where(x => x.Id == lastPostedKey.SUBID).First().LastPostedKey = message.Title.GetHashCode().ToString();

                    try
                    {
                        await _bot.SendTextMessageAsync(client, message.Title.ToUpper());

                        await _bot.SendTextMessageAsync(client, message.SubTitle);

                        await _bot.SendPhotoAsync(client, new InputOnlineFile(message.Image));
                    }
                    catch (ChatNotFoundException e)
                    {
                        TraceError.Info(e.Message);
                        var clientsRecords = db.Clients.Where(c => c.ChatId == client).ToList();
                        TraceError.Info("Client Recs to remove: " + string.Join(",", clientsRecords.Select(c => c.ChatId)));
                        var subscriptionsToRemove = db.Subscriptions.Where(x => clientsRecords.Select(o => o.Subscription).Contains(x.Id));
                        TraceError.Info("Subscription Recs to remove: " + string.Join(",", subscriptionsToRemove.Select(s => s.SubsctiptionType.ToString())));
                        db.Subscriptions.RemoveRange(subscriptionsToRemove);
                        db.Clients.RemoveRange(clientsRecords);
                    }
                }
                await db.SaveChangesAsync();
            }
        }
Ejemplo n.º 8
0
        public async Task RemoveWatch([Remainder] string playersName = null)
        {
            if (playersName == null)
            {
                await ReplyAsync(Strings.PlayerNameRequired);

                return;
            }
            var playerRep = new PlayerRepository();
            await playerRep.GetPlayerByName(playersName);

            if (playerRep.Player == null)
            {
                await ReplyAsync(Strings.PlayerNotFound);

                return;
            }


            using (var context = new BotDBContext())
            {
                var user = await context.Users.FirstOrDefaultAsync(u => u.DiscordId == Context.User.Id);

                if (user == null) //It is a new User
                {
                    await ReplyAsync(Strings.YouHaveNoWatches);

                    return;
                }
                else
                {
                    var usersPlayers = await context.UsersPlayers.Where(u => u.UserID == user.ID).Include(p => p.Players).FirstOrDefaultAsync();

                    if (usersPlayers == null)
                    {
                        await ReplyAsync(Strings.PlayerIsNotInYourWatch);

                        return;
                    }
                    var players      = usersPlayers.Players.ToList();
                    var playerInList = players.FirstOrDefault(p => p.PubgID == playerRep.Player.Id);
                    if (playerInList != null)
                    {
                        players.Remove(playerInList);
                    }

                    usersPlayers.Players = players;
                    context.UsersPlayers.Update(usersPlayers);
                    await context.SaveChangesAsync();
                    await ReplyAsync(Strings.WatchRemovedSuccess);
                }
            }
        }
Ejemplo n.º 9
0
        public async Task <bool> AddSalutation(EmbedSalutation salutation)
        {
            if (await SalutationExists(salutation.GuildId, salutation.OnJoin))
            {
                return(false);
            }

            using (BotDBContext DBContext = DBFactory.Create <BotDBContext>())
            {
                await DBContext.DiscordSalutationMessages.AddAsync(new DiscordSalutationMessage(salutation.GuildId, salutation.Message, salutation.OnJoin, true, salutation.EmbedColor, salutation.ImgUrl));

                await DBContext.SaveChangesAsync();

                return(true);
            }
        }
Ejemplo n.º 10
0
 public async Task DeleteTag([Summary("The tag name.")] string name)
 {
     using (BotDBContext DBContext = DBFactory.Create <BotDBContext>())
     {
         ChannelTag selectedTag = DBContext.ChannelTags.Where(x => x.ChannelId == Context.Channel.Id.ToString() && x.Name.ToLower() == name.ToLower() && x.OwnerId == Context.User.Id.ToString()).FirstOrDefault();
         if (selectedTag != null)
         {
             DBContext.ChannelTags.Remove(selectedTag);
             await DBContext.SaveChangesAsync();
             await ReplyAsync("", embed : EmbedService.MakeFailFeedbackEmbed($"The tag {name.Bold()} has been deleted."));
         }
         else
         {
             await ReplyAsync("", embed : EmbedService.MakeFailFeedbackEmbed("The specified tag either doesn't exist or you don't own it."));
         }
     }
 }
Ejemplo n.º 11
0
        public async Task <bool> RemoveSalutation(string guildId, bool onJoin)
        {
            if (!(await SalutationExists(guildId, onJoin)))
            {
                return(false);
            }

            using (BotDBContext DBContext = DBFactory.Create <BotDBContext>())
            {
                var msg = await DBContext.DiscordSalutationMessages.FindAsync(guildId, onJoin);

                DBContext.DiscordSalutationMessages.Remove(msg);
                await DBContext.SaveChangesAsync();

                return(true);
            }
        }
Ejemplo n.º 12
0
        public async Task <bool> AddSalutation(TextSalutation salutation)
        {
            if (await SalutationExists(salutation.GuildId, salutation.OnJoin))
            {
                return(false);
            }

            using (BotDBContext DBContext = DBFactory.Create <BotDBContext>())
            {
                await DBContext.DiscordSalutationMessages.AddAsync(new DiscordSalutationMessage(salutation.GuildId, salutation.Message, salutation.OnJoin, false, new byte[3] {
                    0, 0, 0
                }, null));

                await DBContext.SaveChangesAsync();

                return(true);
            }
        }
Ejemplo n.º 13
0
        public async Task MakeTag([Summary("The name of the Tag.")] string name, [Summary("The content of the tag.")][Remainder] string content)
        {
            using (BotDBContext DBContext = DBFactory.Create <BotDBContext>())
            {
                var tagExists = DBContext.ChannelTags.Where(x => x.ChannelId == Context.Channel.Id.ToString()).FirstOrDefault(x => x.Name.ToLower() == name.ToLower());
                if (tagExists == null)
                {
                    ChannelTag channelTag = new ChannelTag(name, content, Context.Channel.Id.ToString(), Context.User.Id.ToString(), DateTime.Now);
                    await DBContext.AddAsync(channelTag);

                    await DBContext.SaveChangesAsync();
                    await ReplyAsync("", embed : EmbedService.MakeSuccessFeedbackEmbed($"You have successfully attached the tag {name} to this channel."));
                }
                else
                {
                    await ReplyAsync("", embed : EmbedService.MakeFailFeedbackEmbed("A tag already exists in this channel with that name."));
                }
            }
        }
Ejemplo n.º 14
0
 public async Task <PrefixResponseData> ClearGuildPrefixes(IGuild guild)
 {
     if (!PrefixDictionary.ContainsKey(guild.Id.ToString()))
     {
         return(new PrefixResponseData(false, "The current guild does not have any custom prefixes at the moment."));
     }
     else
     {
         int items = PrefixDictionary.GetValue(guild.Id.ToString()).Count;
         using (BotDBContext DBContext = Provider.GetService <DBContextFactory>().Create <BotDBContext>())
         {
             DBContext.DiscordCustomPrefixes.RemoveRange(PrefixDictionary.GetValue(guild.Id.ToString()).ToList());
             await DBContext.SaveChangesAsync();
         }
         List <DiscordCustomPrefix> newBag = new List <DiscordCustomPrefix>();
         PrefixDictionary[guild.Id.ToString()] = newBag;
         return(new PrefixResponseData(true, $"Cleared {items.ToString().Number()} custom prefixes from the current guild."));
     }
 }
Ejemplo n.º 15
0
        public async Task <PrefixResponseData> TryAddPrefix(IGuild guild, IUser user, string prefix)
        {
            var resp = CanAddPrefix(guild, user, prefix);

            if (!resp.WasSuccess)
            {
                return(new PrefixResponseData(false, resp.Message));
            }

            using (BotDBContext DBContext = Provider.GetService <DBContextFactory>().Create <BotDBContext>())
            {
                var newPrefix = new DiscordCustomPrefix(guild.Id.ToString(), user.Id.ToString(), prefix, "0", DateTime.Now);
                PrefixDictionary.GetValue(guild.Id.ToString()).Add(newPrefix);
                await DBContext.DiscordCustomPrefixes.AddAsync(newPrefix);

                await DBContext.SaveChangesAsync();

                return(new PrefixResponseData(true, $"Successfully added new server prefix to {guild.Name}"));
            }
        }
Ejemplo n.º 16
0
        async Task LogAction(ICommandContext context)
        {
            using (var con = new BotDBContext())
            {
                var userInDb = con.Users.FirstOrDefault(u => u.DiscordId == context.User.Id);
                if (userInDb == null)
                {
                    userInDb = new Model.User()
                    {
                        DiscordId = context.User.Id, Name = context.User.Username, UserTag = context.User.Discriminator
                    };
                }
                Console.WriteLine($"User {context.User.Username} requested {context.Message.Content} ***** at {DateTime.Now.ToShortDateString()}");

                await con.Logs.AddAsync(new Model.Log()
                {
                    Date = DateTime.Now, Content = context.Message.Content, User = userInDb
                });

                await con.SaveChangesAsync();
            }
        }
Ejemplo n.º 17
0
        private async Task ProcessTextChannels(SocketGuild guild)
        {
            using (BotDBContext DBContext = DBFactory.Create <BotDBContext>())
            {
                foreach (SocketTextChannel textChannel in guild.TextChannels)
                {
                    DBContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
                    var channelObj    = new DiscordTextChannel(textChannel.Id.ToString(), guild.Id.ToString(), textChannel.Name, textChannel.Topic, textChannel.CreatedAt, ((textChannel as ISocketPrivateChannel) != null));
                    var channelRecord = await DBContext.TextChannels.FindAsync(channelObj.Id);

                    if (channelRecord == null)
                    {
                        ConsoleEx.WriteColoredLine(LogSeverity.Verbose, ConsoleTextFormat.TimeAndText, "Adding new Text Channel ", ConsoleColor.Cyan, textChannel.Name, ConsoleColor.Gray, " to the database.");
                        await DBContext.AddAsync(channelObj);
                    }
                    else
                    {
                        DBContext.DetachLocal(channelObj, channelObj.Id);
                    }

                    await DBContext.SaveChangesAsync();
                }
            }
        }
Ejemplo n.º 18
0
        public async Task AddWatch([Remainder] string playersName = null)
        {
            if (playersName == null)
            {
                await ReplyAsync(Strings.PlayerNameRequired);

                return;
            }
            var playerRep = new PlayerRepository();
            await playerRep.GetPlayerByName(playersName);

            if (playerRep.Player == null)
            {
                await ReplyAsync(Strings.PlayerNotFound);

                return;
            }

            using (var context = new BotDBContext())
            {
                var user = await context.Users.FirstOrDefaultAsync(u => u.DiscordId == Context.User.Id);

                if (user == null) //It is a new User
                {
                    var newUsersPlayer = new Model.UsersPlayers()
                    {
                        User = new Model.User()
                        {
                            DiscordId = Context.User.Id, Name = Context.User.Username
                        },
                        Players = new List <Model.Player>
                        {
                            new Model.Player()
                            {
                                PubgID = playerRep.Player.Id
                            }
                        }
                    };

                    await context.UsersPlayers.AddAsync(newUsersPlayer);

                    await context.SaveChangesAsync();
                    await ReplyAsync(Strings.PlayerAddedToWatch);
                }
                else
                {
                    var usersPlayers = await context.UsersPlayers.Where(u => u.UserID == user.ID).Include(p => p.Players).FirstOrDefaultAsync();

                    if (usersPlayers == null)
                    {
                        usersPlayers = new Model.UsersPlayers()
                        {
                            User = user, Players = new List <Model.Player>()
                        };
                    }
                    if (usersPlayers != null)
                    {
                        var playersList = usersPlayers.Players.ToList();
                        if (playersList.FirstOrDefault(a => a.PubgID == playerRep.Player.Id) == null)
                        {
                            playersList.Add(new Model.Player()
                            {
                                PubgID = playerRep.Player.Id
                            });
                            usersPlayers.Players = playersList;
                            context.Update(usersPlayers);
                            await context.SaveChangesAsync();
                            await ReplyAsync(Strings.PlayerAddedToWatch);
                        }
                        else
                        {
                            await ReplyAsync(Strings.PlayerIsAlreadySaved);
                        }
                    }
                }
            }
        }
Ejemplo n.º 19
0
        private void GameTracker()
        {
            Client.UserJoined += async(user) =>
            {
                using (BotDBContext DBContext = DBFactory.Create <BotDBContext>())
                {
                    DBContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
                    DiscordUser newDiscordUser = new DiscordUser(user.Id.ToString(), (short)user.DiscriminatorValue, user.Username, user.GetAvatarUrl(ImageFormat.Gif), user.CreatedAt, user.IsBot);
                    DiscordUser searchedUser   = DBContext.Users.FirstOrDefault(x => x.Id == user.Id.ToString());

                    if (searchedUser == null)
                    {
                        await DBContext.AddAsync(newDiscordUser);
                    }
                    else
                    {
                        DBContext.DetachLocal(newDiscordUser, user.Id.ToString());
                    }

                    await DBContext.SaveChangesAsync();
                }
            };

            Client.GuildAvailable += async(guild) =>
            {
                foreach (IGuildUser user in guild.Users)
                {
                    UserStatusTimes.TryAdd(user.Id, new StatusTime(user.Status, DateTime.UtcNow));
                    if (user.Game.HasValue)
                    {
                        UserGameTimes.TryAdd(user.Id, new GameTime(user.Game.Value.Name, DateTime.UtcNow));
                    }
                }
                await Task.CompletedTask;
            };

            Client.GuildMemberUpdated += async(oldUser, newUser) =>
            {
                try
                {
                    using (BotDBContext DBContext = DBFactory.Create <BotDBContext>())
                    {
                        DBContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
                        DiscordUser newDiscordUser = new DiscordUser(newUser.Id.ToString(), (short)newUser.DiscriminatorValue, newUser.Username, newUser.GetAvatarUrl(ImageFormat.Gif), newUser.CreatedAt, newUser.IsBot);
                        DiscordUser searchedUser   = await DBContext.Users.FindAsync(oldUser.Id.ToString());

                        if (searchedUser == null)
                        {
                            await DBContext.AddAsync(newDiscordUser);
                        }
                        else
                        {
                            DBContext.DetachLocal(newDiscordUser, newUser.Id.ToString());
                        }

                        await DBContext.SaveChangesAsync();

                        if (oldUser.Status != newUser.Status)
                        {
                            UserStatusTimes.TryUpdate(oldUser.Id, new StatusTime(newUser.Status, DateTime.UtcNow));
                        }

                        if (!oldUser.Game.HasValue && !newUser.Game.HasValue)
                        {
                            return;
                        }

                        if ((oldUser.Game.HasValue && newUser.Game.HasValue) && (oldUser.Game.Value.Name == newUser.Game.Value.Name))
                        {
                            return;
                        }

                        if (!oldUser.Game.HasValue && newUser.Game.HasValue)
                        {
                            UserGameTimes.TryUpdate(oldUser.Id, new GameTime(newUser.Game.Value.Name, DateTime.UtcNow));
                        }
                        else if (oldUser.Game.HasValue && UserGameTimes.ContainsKey(oldUser.Id))
                        {
                            TimeSpan timeDiff = DateTime.UtcNow - UserGameTimes.GetValue(oldUser.Id).TimeStarted;
                            int      minutes  = (int)timeDiff.TotalMinutes;
                            if (minutes == 0)
                            {
                                return;
                            }

                            using (BotDBContext innerContext = Provider.GetService <DBContextFactory>().Create <BotDBContext>())
                            {
                                DBContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
                                UserGameTimes.TryRemove(oldUser.Id, out _);
                                DiscordGameTime currentTime = await innerContext.GameTime.FindAsync(oldUser.Id.ToString(), oldUser.Game.Value.Name);

                                if (currentTime == null)
                                {
                                    await innerContext.GameTime.AddAsync(new DiscordGameTime(oldUser.Id.ToString(), oldUser.Game.Value.Name, minutes, DateTime.Now));
                                }
                                else
                                {
                                    currentTime.Minutes   += minutes;
                                    currentTime.LastPlayed = DateTime.Now;
                                }

                                if (newUser.Game.HasValue)
                                {
                                    UserGameTimes.TryUpdate(oldUser.Id, new GameTime(newUser.Game.Value.Name, DateTime.UtcNow));
                                }
                                await innerContext.SaveChangesAsync();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            };
        }
Ejemplo n.º 20
0
        private void GuildTracker()
        {
            Client.JoinedGuild += async(guild) =>
            {
                using (BotDBContext DBContext = DBFactory.Create <BotDBContext>())
                {
                    DBContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
                    var existingGuild = DBContext.Guilds.FromSql("SELECT * FROM Guilds WHERE Id = {0} LIMIT 1", guild.Id.ToString()).AsNoTracking().FirstOrDefault();
                    var newGuild      = new DiscordGuild(guild.Id, guild.Name, guild.OwnerId, guild.CreatedAt, guild.IconUrl, guild.SplashUrl);
                    if (existingGuild == null)
                    {
                        await DBContext.AddAsync(newGuild);

                        ConsoleEx.WriteColoredLine($"Joined new Guild $[[DarkCyan]]${guild.Name}$[[Gray]]$!");
                        foreach (ITextChannel channel in guild.TextChannels)
                        {
                            var newChannel = new DiscordTextChannel(channel.Id.ToString(), channel.GuildId.ToString(), channel.Name, channel.Topic, channel.CreatedAt, ((channel as ISocketPrivateChannel) != null));
                            ConsoleEx.WriteColoredLine($"Joined new Channel $[[DarkCyan]]${channel.Name}$[[Gray]]$ within the Guild $[[DarkCyan]]${guild.Name}$[[Gray]]$!");
                        }
                    }
                    else
                    {
                        DBContext.DetachLocal(newGuild, existingGuild.Id);
                        ConsoleEx.WriteColoredLine($"Joined existing Guild $[[DarkCyan]]${guild.Name}$[[Gray]]$, updating data.");
                        await ProcessTextChannels(guild);
                        await ProcessUsers(guild);
                    }
                    await DBContext.SaveChangesAsync();
                }
            };

            Client.GuildUpdated += async(oldGuild, newGuild) =>
            {
                using (BotDBContext DBContext = DBFactory.Create <BotDBContext>())
                {
                    DBContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
                    DiscordGuild foundGuild = DBContext.Guilds.FromSql("SELECT * FROM Guilds WHERE Id = {0} LIMIT 1", oldGuild.Id.ToString()).AsNoTracking().First();
                    var          addedGuild = new DiscordGuild(newGuild.Id, newGuild.Name, newGuild.OwnerId, newGuild.CreatedAt, newGuild.IconUrl, newGuild.SplashUrl);
                    if (foundGuild == null)
                    {
                        await DBContext.AddAsync(addedGuild);
                        await ProcessTextChannels(newGuild);
                        await ProcessUsers(newGuild);
                    }
                    else
                    {
                        DBContext.DetachLocal(addedGuild, oldGuild.Id.ToString());
                        ConsoleEx.WriteColoredLine($"Updating existing Guild $[[DarkCyan]]${oldGuild.Name}$[[Gray]]$, adjusting record.");
                    }
                    await DBContext.SaveChangesAsync();
                }
            };

            Client.ChannelCreated += async(channel) =>
            {
                ITextChannel textChannel = channel as ITextChannel;
                if (textChannel == null)
                {
                    return;
                }

                using (BotDBContext DBContext = DBFactory.Create <BotDBContext>())
                {
                    DBContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
                    var existingTextChannel = DBContext.TextChannels.FromSql("SELECT * FROM TextChannels WHERE Id = {0} LIMIT 1", channel.Id.ToString()).AsNoTracking().FirstOrDefault();
                    if (existingTextChannel == null)
                    {
                        var newChannel = new DiscordTextChannel(textChannel.Id.ToString(), textChannel.GuildId.ToString(), textChannel.Name, textChannel.Topic, textChannel.CreatedAt, ((textChannel as ISocketPrivateChannel) != null));
                        await DBContext.AddAsync(newChannel);

                        ConsoleEx.WriteColoredLine($"Added new TextChannel $[[DarkCyan]]${textChannel.Name}$[[Gray]]$!");
                    }
                    else
                    {
                        DBContext.DetachLocal(existingTextChannel, existingTextChannel.Id);
                        ConsoleEx.WriteColoredLine($"Channel already exists somehow, $[[DarkCyan]]${textChannel.Name}$[[Gray]]$, updating records.");
                    }
                    await DBContext.SaveChangesAsync();
                }
            };

            Client.ChannelUpdated += async(oldChan, newChan) =>
            {
                ITextChannel oldTextChannel = oldChan as ITextChannel;
                ITextChannel newTextChannel = newChan as ITextChannel;
                if (oldTextChannel == null || newTextChannel == null)
                {
                    return;
                }

                using (BotDBContext DBContext = DBFactory.Create <BotDBContext>())
                {
                    DBContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
                    var existingChannel = DBContext.TextChannels.FromSql("SELECT * FROM TextChannels WHERE Id = {0} LIMIT 1", oldChan.Id.ToString()).FirstOrDefault();

                    var newChannel = new DiscordTextChannel(newTextChannel.Id.ToString(), newTextChannel.GuildId.ToString(), newTextChannel.Name, newTextChannel.Topic, newTextChannel.CreatedAt, ((newTextChannel as ISocketPrivateChannel) != null));
                    if (existingChannel == null)
                    {
                        await DBContext.AddAsync(newChannel);

                        ConsoleEx.WriteColoredLine($"Added new TextChannel $[[DarkCyan]]${newTextChannel.Name}$[[Gray]]$ that $[[Red]]$should$[[Gray]]$ have existed!");
                    }
                    else
                    {
                        DBContext.DetachLocal(newChannel, newTextChannel.Id.ToString());
                        ConsoleEx.WriteColoredLine($"Updating existing TextChannel $[[DarkCyan]]${oldTextChannel.Name}$[[Gray]]$, adjusting record.");
                    }
                    await DBContext.SaveChangesAsync();
                }
            };
        }
Ejemplo n.º 21
0
        private void ReactionTracker()
        {
            try
            {
                Client.ReactionAdded += async(cachedMsg, msg, reaction) =>
                {
                    if (reaction.User.Value.IsBot)
                    {
                        return;
                    }

                    IMessage reactedMessage = await reaction.Channel.GetMessageAsync(cachedMsg.Id);

                    if (reaction.User.Value.Id == reactedMessage.Author.Id)
                    {
                        return;
                    }

                    DiscordReaction reactionObj;

                    if ((reaction.Emote as Emoji) == null)
                    {
                        reactionObj = new DiscordReaction(reaction.MessageId.ToString(), reaction.Channel.Id.ToString(), reactedMessage.Author.Id.ToString(), reaction.UserId.ToString(), (reaction.Emote as Emote).Id.ToString(), reaction.Emote.Name, DateTime.Now);
                    }
                    else
                    {
                        reactionObj = new DiscordReaction(reaction.MessageId.ToString(), reaction.Channel.Id.ToString(), reactedMessage.Author.Id.ToString(), reaction.UserId.ToString(), (reaction.Emote as Emoji).Name, DateTime.Now);
                    }

                    using (BotDBContext DBContext = DBFactory.Create <BotDBContext>())
                    {
                        DBContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
                        await DBContext.AddAsync(reactionObj);

                        await DBContext.SaveChangesAsync();
                    }
                };

                Client.ReactionRemoved += async(cachedMsg, msg, reaction) =>
                {
                    if (reaction.User.Value.IsBot)
                    {
                        return;
                    }

                    IMessage reactedMessage = await reaction.Channel.GetMessageAsync(cachedMsg.Id);

                    if (reaction.User.Value.Id == reactedMessage.Author.Id)
                    {
                        return;
                    }

                    using (BotDBContext DBContext = DBFactory.Create <BotDBContext>())
                    {
                        DBContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
                        DiscordReaction existingReaction = DBContext.Reactions.FirstOrDefault(x => x.ReceiverId == reactedMessage.Author.Id.ToString() && x.ReactorId == reaction.UserId.ToString() && x.ReactionName == reaction.Emote.Name && x.Id == reaction.MessageId.ToString());
                        if (existingReaction != null)
                        {
                            DBContext.Remove(existingReaction);
                        }

                        await DBContext.SaveChangesAsync();
                    }
                };

                Client.ReactionsCleared += async(msgCache, msgChannel) =>
                {
                    using (BotDBContext DBContext = DBFactory.Create <BotDBContext>())
                    {
                        DBContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
                        IUserMessage fetchedMsg = await msgCache.GetOrDownloadAsync();

                        DBContext.Reactions.RemoveRange(DBContext.Reactions.FromSql("SELECT * FROM Reactions WHERE Id = {0}", fetchedMsg.Id).AsNoTracking().ToList());
                        ConsoleEx.WriteColoredLine($"Reactions cleared from message ID($[[DarkCyan]]${fetchedMsg.Id}$[[Gray]]$.");
                        await DBContext.SaveChangesAsync();
                    }
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Ejemplo n.º 22
0
        private void MessageTracker()
        {
            try
            {
                Client.MessageReceived += async(msg) =>
                {
                    if (msg.Source == MessageSource.Webhook || msg.Source == MessageSource.System)
                    {
                        return;
                    }

                    if (msg.Content == "" && msg.Attachments.Count == 0)
                    {
                        return;
                    }

                    DiscordMessage           msgObj        = new DiscordMessage(msg.Id.ToString(), msg.Author.Id.ToString(), msg.Channel.Id.ToString(), msg.Content, DateTime.Now);
                    DiscordMessageAttachment attachmentObj = null;
                    using (BotDBContext DBContext = DBFactory.Create <BotDBContext>())
                    {
                        DBContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
                        if (msg.Attachments.Count > 0)
                        {
                            foreach (Attachment attachment in msg.Attachments)
                            {
                                using (BotDBContext innerContext = Provider.GetService <DBContextFactory>().Create <BotDBContext>())
                                {
                                    innerContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
                                    attachmentObj = new DiscordMessageAttachment(msgObj.Id, attachment.Url);
                                    await innerContext.Attachments.AddAsync(attachmentObj);

                                    await innerContext.SaveChangesAsync();

                                    //innerContext.GameTime.Include()
                                }
                            }
                        }

                        await DBContext.Messages.AddAsync(msgObj);

                        await DBContext.SaveChangesAsync();
                    }
                };

                Client.MessageUpdated += async(cachedMsg, msg, channel) =>
                {
                    using (BotDBContext DBContext = DBFactory.Create <BotDBContext>())
                    {
                        if (msg != null)
                        {
                            DiscordMessage msgObj = new DiscordMessage(msg.Id.ToString(), msg.Author.Id.ToString(), msg.Channel.Id.ToString(), msg.Content ?? "", DateTime.Now);
                            DBContext.DetachLocal <DiscordMessage>(msgObj, msg.Id.ToString());
                            await DBContext.SaveChangesAsync();

                            await Task.CompletedTask;
                        }
                    }
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }