Пример #1
0
        private static void MiscellaneousActionsCallback(object _)
        {
            var client = _ as DiscordClient;

            try {
                List <DatabaseBirthday> todayBirthdays;
                using (DatabaseContext db = GlobalDatabaseContextBuilder.CreateContext()) {
                    todayBirthdays = db.Birthdays
                                     .Where(b => b.Date.Month == DateTime.Now.Month && b.Date.Day == DateTime.Now.Day && b.LastUpdateYear < DateTime.Now.Year)
                                     .ToList();
                }
                foreach (DatabaseBirthday birthday in todayBirthdays)
                {
                    DiscordChannel channel = SharedData.AsyncExecutor.Execute(client.GetChannelAsync(birthday.ChannelId));
                    DiscordUser    user    = SharedData.AsyncExecutor.Execute(client.GetUserAsync(birthday.UserId));
                    SharedData.AsyncExecutor.Execute(channel.SendMessageAsync(user.Mention, embed: new DiscordEmbedBuilder {
                        Description = $"{StaticDiscordEmoji.Tada} Happy birthday, {user.Mention}! {StaticDiscordEmoji.Cake}",
                        Color       = DiscordColor.Aquamarine
                    }));

                    using (DatabaseContext db = GlobalDatabaseContextBuilder.CreateContext()) {
                        birthday.LastUpdateYear = DateTime.Now.Year;
                        db.Birthdays.Update(birthday);
                        db.SaveChanges();
                    }
                }

                using (DatabaseContext db = GlobalDatabaseContextBuilder.CreateContext()) {
                    db.Database.ExecuteSqlCommand("UPDATE gf.bank_accounts SET balance = GREATEST(CEILING(1.0015 * balance), 10);");
                    db.SaveChanges();
                }
            } catch (Exception e) {
                SharedData.LogProvider.Log(LogLevel.Error, e);
            }
        }
Пример #2
0
 private static void DatabaseSyncCallback(object _)
 {
     try {
         using (DatabaseContext db = GlobalDatabaseContextBuilder.CreateContext()) {
             foreach ((ulong uid, int count) in SharedData.MessageCount)
             {
                 DatabaseMessageCount msgcount = db.MessageCount.Find((long)uid);
                 if (msgcount is null)
                 {
                     db.MessageCount.Add(new DatabaseMessageCount {
                         MessageCount = count,
                         UserId       = uid
                     });
                 }
                 else
                 {
                     if (count != msgcount.MessageCount)
                     {
                         msgcount.MessageCount = count;
                         db.MessageCount.Update(msgcount);
                     }
                 }
             }
             db.SaveChanges();
         }
     } catch (Exception e) {
         SharedData.LogProvider.Log(LogLevel.Error, e);
     }
 }
Пример #3
0
        private static void BotActivityCallback(object _)
        {
            if (!SharedData.StatusRotationEnabled)
            {
                return;
            }

            var client = _ as DiscordClient;

            try {
                DatabaseBotStatus status;
                using (DatabaseContext db = GlobalDatabaseContextBuilder.CreateContext())
                    status = db.BotStatuses.Shuffle().FirstOrDefault();

                var activity = new DiscordActivity(status?.Status ?? "@TheGodfather help", status?.Activity ?? ActivityType.Playing);

                SharedData.AsyncExecutor.Execute(client.UpdateStatusAsync(activity));
            } catch (Exception e) {
                SharedData.LogProvider.Log(LogLevel.Error, e);
            }
        }
Пример #4
0
        private static async Task RegisterPeriodicTasksAsync()
        {
            BotStatusUpdateTimer = new Timer(BotActivityCallback, Shards[0].Client, TimeSpan.FromSeconds(10), TimeSpan.FromMinutes(10));
            DatabaseSyncTimer    = new Timer(DatabaseSyncCallback, Shards[0].Client, TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(BotConfiguration.DatabaseSyncInterval));
            FeedCheckTimer       = new Timer(FeedCheckCallback, Shards[0].Client, TimeSpan.FromSeconds(BotConfiguration.FeedCheckStartDelay), TimeSpan.FromSeconds(BotConfiguration.FeedCheckInterval));
            MiscActionsTimer     = new Timer(MiscellaneousActionsCallback, Shards[0].Client, TimeSpan.FromSeconds(5), TimeSpan.FromHours(12));

            using (DatabaseContext db = GlobalDatabaseContextBuilder.CreateContext()) {
                await RegisterSavedTasksAsync(db.SavedTasks.ToDictionary <DatabaseSavedTask, int, SavedTaskInfo>(
                                                  t => t.Id,
                                                  t => {
                    switch (t.Type)
                    {
                    case SavedTaskType.Unban:
                        return(new UnbanTaskInfo(t.GuildId, t.UserId, t.ExecutionTime));

                    case SavedTaskType.Unmute:
                        return(new UnmuteTaskInfo(t.GuildId, t.UserId, t.RoleId, t.ExecutionTime));

                    default:
                        return(null);
                    }
                })
                                              );
                await RegisterRemindersAsync(db.Reminders.ToDictionary(
                                                 t => t.Id,
                                                 t => new SendMessageTaskInfo(t.ChannelId, t.UserId, t.Message, t.ExecutionTime, t.IsRepeating, t.RepeatInterval)
                                                 ));
            }


            async Task RegisterSavedTasksAsync(IReadOnlyDictionary <int, SavedTaskInfo> tasks)
            {
                int scheduled = 0, missed = 0;

                foreach ((int tid, SavedTaskInfo task) in tasks)
                {
                    if (await RegisterTaskAsync(tid, task))
                    {
                        scheduled++;
                    }
                    else
                    {
                        missed++;
                    }
                }
                SharedData.LogProvider.ElevatedLog(LogLevel.Info, $"Saved tasks: {scheduled} scheduled; {missed} missed.");
            }

            async Task RegisterRemindersAsync(IReadOnlyDictionary <int, SendMessageTaskInfo> reminders)
            {
                int scheduled = 0, missed = 0;

                foreach ((int tid, SendMessageTaskInfo task) in reminders)
                {
                    if (await RegisterTaskAsync(tid, task))
                    {
                        scheduled++;
                    }
                    else
                    {
                        missed++;
                    }
                }
                SharedData.LogProvider.ElevatedLog(LogLevel.Info, $"Reminders: {scheduled} scheduled; {missed} missed.");
            }

            async Task <bool> RegisterTaskAsync(int id, SavedTaskInfo tinfo)
            {
                var texec = new SavedTaskExecutor(id, Shards[0].Client, tinfo, SharedData, GlobalDatabaseContextBuilder);

                if (texec.TaskInfo.IsExecutionTimeReached)
                {
                    await texec.HandleMissedExecutionAsync();

                    return(false);
                }
                else
                {
                    texec.Schedule();
                    return(true);
                }
            }
        }
Пример #5
0
        private static void LoadSharedDataFromDatabase()
        {
            Console.Write("\r[3/5] Loading data from database...               ");

            // Placing performance-sensitive data into memory, instead of it being read from the database
            ConcurrentHashSet <ulong> blockedChannels;
            ConcurrentHashSet <ulong> blockedUsers;
            ConcurrentDictionary <ulong, CachedGuildConfig>                  guildConfigurations;
            ConcurrentDictionary <ulong, ConcurrentHashSet <Filter> >        filters;
            ConcurrentDictionary <ulong, ConcurrentHashSet <TextReaction> >  treactions;
            ConcurrentDictionary <ulong, ConcurrentHashSet <EmojiReaction> > ereactions;
            ConcurrentDictionary <ulong, int> msgcount;

            using (DatabaseContext db = GlobalDatabaseContextBuilder.CreateContext()) {
                blockedChannels     = new ConcurrentHashSet <ulong>(db.BlockedChannels.Select(c => c.ChannelId));
                blockedUsers        = new ConcurrentHashSet <ulong>(db.BlockedUsers.Select(u => u.UserId));
                guildConfigurations = new ConcurrentDictionary <ulong, CachedGuildConfig>(db.GuildConfig.Select(
                                                                                              gcfg => new KeyValuePair <ulong, CachedGuildConfig>(gcfg.GuildId, new CachedGuildConfig {
                    AntispamSettings = new AntispamSettings {
                        Action      = gcfg.AntispamAction,
                        Enabled     = gcfg.AntispamEnabled,
                        Sensitivity = gcfg.AntispamSensitivity
                    },
                    Currency           = gcfg.Currency,
                    LinkfilterSettings = new LinkfilterSettings {
                        BlockBooterWebsites     = gcfg.LinkfilterBootersEnabled,
                        BlockDiscordInvites     = gcfg.LinkfilterDiscordInvitesEnabled,
                        BlockDisturbingWebsites = gcfg.LinkfilterDisturbingWebsitesEnabled,
                        BlockIpLoggingWebsites  = gcfg.LinkfilterIpLoggersEnabled,
                        BlockUrlShorteners      = gcfg.LinkfilterUrlShortenersEnabled,
                        Enabled = gcfg.LinkfilterEnabled
                    },
                    LogChannelId      = gcfg.LogChannelId,
                    Prefix            = gcfg.Prefix,
                    RatelimitSettings = new RatelimitSettings {
                        Action      = gcfg.RatelimitAction,
                        Enabled     = gcfg.RatelimitEnabled,
                        Sensitivity = gcfg.RatelimitSensitivity
                    },
                    ReactionResponse   = gcfg.ReactionResponse,
                    SuggestionsEnabled = gcfg.SuggestionsEnabled
                }
                                                                                                                                                  )));
                filters = new ConcurrentDictionary <ulong, ConcurrentHashSet <Filter> >(
                    db.Filters
                    .GroupBy(f => f.GuildId)
                    .ToDictionary(g => g.Key, g => new ConcurrentHashSet <Filter>(g.Select(f => new Filter(f.Id, f.Trigger))))
                    );
                msgcount = new ConcurrentDictionary <ulong, int>(
                    db.MessageCount
                    .GroupBy(ui => ui.UserId)
                    .ToDictionary(g => g.Key, g => g.First().MessageCount)
                    );
                treactions = new ConcurrentDictionary <ulong, ConcurrentHashSet <TextReaction> >(
                    db.TextReactions
                    .Include(t => t.DbTriggers)
                    .AsEnumerable()
                    .GroupBy(tr => tr.GuildId)
                    .ToDictionary(g => g.Key, g => new ConcurrentHashSet <TextReaction>(g.Select(tr => new TextReaction(tr.Id, tr.Triggers, tr.Response, true))))
                    );
                ereactions = new ConcurrentDictionary <ulong, ConcurrentHashSet <EmojiReaction> >(
                    db.EmojiReactions
                    .Include(t => t.DbTriggers)
                    .AsEnumerable()
                    .GroupBy(er => er.GuildId)
                    .ToDictionary(g => g.Key, g => new ConcurrentHashSet <EmojiReaction>(g.Select(er => new EmojiReaction(er.Id, er.Triggers, er.Reaction, true))))
                    );
            }

            var logger = new Logger(BotConfiguration);

            foreach (Logger.SpecialLoggingRule rule in BotConfiguration.SpecialLoggerRules)
            {
                logger.ApplySpecialLoggingRule(rule);
            }

            SharedData = new SharedData {
                BlockedChannels     = blockedChannels,
                BlockedUsers        = blockedUsers,
                BotConfiguration    = BotConfiguration,
                MainLoopCts         = new CancellationTokenSource(),
                EmojiReactions      = ereactions,
                Filters             = filters,
                GuildConfigurations = guildConfigurations,
                LogProvider         = logger,
                MessageCount        = msgcount,
                TextReactions       = treactions,
                UptimeInformation   = new UptimeInformation(Process.GetCurrentProcess().StartTime)
            };
        }