Beispiel #1
0
        private static async Task Main()
        {
            Program p = new Program();

            var appBuilder = new MikiAppBuilder();

            await p.LoadServicesAsync(appBuilder);

            MikiApp app = appBuilder.Build();

            await p.LoadDiscord(app);

            p.LoadLocales();

            for (int i = 0; i < Global.Config.MessageWorkerCount; i++)
            {
                MessageBucket.AddWorker();
            }

            using (var c = new MikiContext())
            {
                List <User> bannedUsers = await c.Users.Where(x => x.Banned).ToListAsync();

                foreach (var u in bannedUsers)
                {
                    app.GetService <EventSystem>().MessageFilter
                    .Get <UserFilter>().Users.Add(u.Id.FromDbLong());
                }
            }

            await Task.Delay(-1);
        }
Beispiel #2
0
        public AccountsModule(
            MikiApp app,
            Config config,
            IDiscordClient discordClient,
            AccountService accountsService,
            AchievementService achievementService,
            AchievementEvents achievementEvents,
            TransactionEvents transactionEvents)
        {
            this.app = app;
            this.achievementService = achievementService;
            this.discordClient      = discordClient;
            if (!string.IsNullOrWhiteSpace(config.ImageApiUrl))
            {
                client = new HttpClient(config.ImageApiUrl);
            }
            else
            {
                Log.Warning("Image API can not be loaded in AccountsModule");
            }

            discordClient.Events.MessageCreate.SubscribeTask(OnMessageCreateAsync);

            accountsService.OnLocalLevelUp          += OnUserLevelUpAsync;
            accountsService.OnLocalLevelUp          += OnLevelUpAchievementsAsync;
            transactionEvents.OnTransactionComplete += CheckCurrencyAchievementUnlocksAsync;

            achievementEvents.OnAchievementUnlocked
            .SubscribeTask(SendAchievementNotificationAsync);
            achievementEvents.OnAchievementUnlocked
            .SubscribeTask(CheckAchievementUnlocksAsync);
        }
Beispiel #3
0
        /**
         * -u   = user's name
         * -um  = user's mention
         * -s   = server's name
         * -o   = owner's nickname
         * -sc  = server count
         * -now = current time
         * -uc  = user count
         */

        public LoggingModule(MikiApp app, IDiscordClient client, ISentryClient sentryClient = null)
        {
            this.app                  = app;
            this.sentryClient         = sentryClient;
            client.GuildMemberCreate += OnClientOnGuildMemberCreateAsync;
            client.GuildMemberDelete += OnClientOnGuildMemberDeleteAsync;
        }
Beispiel #4
0
        /**
         * -u   = user's name
         * -um  = user's mention
         * -s   = server's name
         * -o   = owner's nickname
         * -sc  = server count
         * -now = current time
         * -uc  = user count
         */

        public LoggingModule(MikiApp app, IDiscordClient client, ISentryClient sentryClient = null)
        {
            this.app          = app;
            this.sentryClient = sentryClient;
            client.Events.GuildMemberCreate.SubscribeTask(OnClientOnGuildMemberCreateAsync);
            client.Events.GuildMemberDelete.SubscribeTask(OnClientOnGuildMemberDeleteAsync);
        }
        public AchievementManager(MikiApp bot)
        {
            this.bot = bot;

            AccountManager.Instance.OnLocalLevelUp += async(u, c, l) =>
            {
                using (var db = new MikiContext())
                {
                    if (await provider.IsEnabled(MikiApp.Instance.GetService <ICacheClient>(), db, c.Id))
                    {
                        LevelPacket p = new LevelPacket()
                        {
                            discordUser    = await(c as IDiscordGuildChannel).GetUserAsync(u.Id),
                            discordChannel = c,
                            level          = l,
                        };
                        await OnLevelGained?.Invoke(p);
                    }
                }
            };

            AccountManager.Instance.OnTransactionMade += async(msg, u1, u2, amount) =>
            {
                using (var db = new MikiContext())
                {
                    if (await provider.IsEnabled(MikiApp.Instance.GetService <ICacheClient>(), db, msg.ChannelId))
                    {
                        TransactionPacket p = new TransactionPacket()
                        {
                            discordUser    = msg.Author,
                            discordChannel = await msg.GetChannelAsync(),
                            giver          = u1,
                            receiver       = u2,
                            amount         = amount
                        };

                        await OnTransaction?.Invoke(p);
                    }
                }
            };

            bot.GetService <EventSystem>().GetCommandHandler <SimpleCommandHandler>().OnMessageProcessed += async(e, m, t) =>
            {
                CommandPacket p = new CommandPacket()
                {
                    discordUser    = m.Author,
                    discordChannel = await m.GetChannelAsync(),
                    message        = m,
                    command        = e,
                    success        = true
                };
                await OnCommandUsed?.Invoke(p);
            };
        }
Beispiel #6
0
 public AccountsModule(Module m, MikiApp app)
 {
     if (!string.IsNullOrWhiteSpace(Global.Config.MikiApiKey) &&
         !string.IsNullOrWhiteSpace(Global.Config.ImageApiUrl))
     {
         client = new RestClient(Global.Config.ImageApiUrl)
                  .AddHeader("Authorization", Global.Config.MikiApiKey);
     }
     else
     {
         Log.Warning("Image API can not be loaded in AccountsModule");
     }
 }
        public CustomCommandsModule(MikiApp app)
        {
            var pipeline = new CommandPipelineBuilder(app.Services)
                           .UseStage(new CorePipelineStage())
                           .UsePrefixes()
                           .UseStage(new FetchDataStage())
                           .UseArgumentPack()
                           .UseStage(new CustomCommandsHandler())
                           .Build();

            app.Services.GetService <IDiscordClient>()
            .MessageCreate += async(e) => await pipeline.ExecuteAsync(e);
        }
Beispiel #8
0
 public DonatorModule(Module m, MikiApp b)
 {
     if (!string.IsNullOrWhiteSpace(Global.Config.ImageApiUrl) &&
         !string.IsNullOrWhiteSpace(Global.Config.MikiApiKey))
     {
         client = new RestClient(Global.Config.ImageApiUrl)
                  .AddHeader("Authorization", Global.Config.MikiApiKey);
     }
     else
     {
         m.Enabled = false;
         Log.Warning("Disabled Donator module due to missing configuration parameters for MikiAPI.");
     }
 }
Beispiel #9
0
        public SchedulerService(MikiApp app, IExtendedCacheClient cacheClient, ISentryClient sentryClient)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            this.app          = app;
            this.cacheClient  = cacheClient;
            this.sentryClient = sentryClient;
            taskCallbacks     = new Dictionary <string, Func <IContext, string, Task> >();
            cancellationToken = new CancellationTokenSource();
            workerTask        = RunWorkerAsync(cancellationToken.Token).ConfigureAwait(false);
        }
Beispiel #10
0
        public FunModule(MikiApp bot)
        {
            var config = bot.Services.GetService <Config>();

            if (!string.IsNullOrWhiteSpace(config.ImageApiUrl))
            {
                imageClient = new HttpClient(config.ImageApiUrl);
            }

            if (!string.IsNullOrWhiteSpace(config.DanbooruCredentials))
            {
                imgurClient = new ImgurClient(config.DanbooruCredentials);
            }
        }
Beispiel #11
0
        private static async Task Main(string[] args)
        {
            Program p = new Program();

            if (args.Length > 0)
            {
                if (args.Any(x => x.ToLowerInvariant() == "--migrate" && x.ToLowerInvariant() == "-m"))
                {
                    await new MikiDbContextFactory().CreateDbContext(new string[] { }).Database.MigrateAsync();
                    return;
                }
            }

            var appBuilder = new MikiAppBuilder();

            await p.LoadServicesAsync(appBuilder);

            MikiApp app = appBuilder.Build();

            await p.LoadDiscord(app);

            p.LoadLocales();

            for (int i = 0; i < Global.Config.MessageWorkerCount; i++)
            {
                MessageBucket.AddWorker();
            }

            using (var scope = app.Services.CreateScope())
            {
                var context = scope.ServiceProvider
                              .GetService <MikiDbContext>();

                List <IsBanned> bannedUsers = await context.IsBanned
                                              .Where(x => x.ExpirationDate > DateTime.UtcNow)
                                              .ToListAsync();

                foreach (var u in bannedUsers)
                {
                    app.GetService <EventSystem>().MessageFilter
                    .Get <UserFilter>().Users.Add(u.UserId.FromDbLong());
                }
            }

            await Task.Delay(-1);
        }
Beispiel #12
0
        public AccountService(
            MikiApp app, IDiscordClient client, ISentryClient sentryClient, ICacheClient cache)
        {
            if (client == null)
            {
                throw new InvalidOperationException();
            }

            this.app          = app;
            this.sentryClient = sentryClient;
            this.cache        = cache;

            client.GuildMemberCreate += this.Client_UserJoinedAsync;
            client.MessageCreate     += this.CheckAsync;

            experienceLock = new SemaphoreSlim(1, 1);
        }
Beispiel #13
0
        public GeneralModule(Module m, MikiApp b)
        {
            //EventSystem.Instance.AddCommandDoneEvent(x =>
            //{
            //	x.Name = "--count-commands";
            //	x.processEvent = async (msg, e, success, t) =>
            //	{
            //		if (success)
            //		{
            //			using (var context = new MikiContext())
            //			{
            //				User user = await User.GetAsync(context, msg.Author);
            //				CommandUsage u = await CommandUsage.GetAsync(context, msg.Author.Id.ToDbLong(), e.Name);

            //				u.Amount++;
            //				user.Total_Commands++;

            //				await CommandUsage.UpdateCacheAsync(user.Id, e.Name, u);
            //				await context.SaveChangesAsync();
            //			}
            //		}
            //	};
            //});
        }
Beispiel #14
0
 public ServerCountModule(Module m, MikiApp b)
 {
     m.JoinedGuild = OnUpdateGuilds;
     m.LeftGuild   = OnUpdateGuilds;
     //	countLib = new CountLib(ConnectionString);
 }
Beispiel #15
0
 public CustomCommandsModule(Module mod, MikiApp app)
 {
     app.GetService <EventSystem>().AddCommandHandler(new CustomCommandsHandler());
 }
Beispiel #16
0
 public InternalModule(Module module, MikiApp bot)
 {
 }
Beispiel #17
0
        public async Task LoadDiscord(MikiApp app)
        {
            var cache   = app.GetService <IExtendedCacheClient>();
            var gateway = app.GetService <IGateway>();

            new BasicCacheStage().Initialize(gateway, cache);

            var         config      = app.GetService <ConfigurationManager>();
            EventSystem eventSystem = app.GetService <EventSystem>();
            {
                app.Discord.MessageCreate += eventSystem.OnMessageReceivedAsync;

                eventSystem.OnError += async(ex, context) =>
                {
                    if (ex is LocalizedException botEx)
                    {
                        await Utils.ErrorEmbedResource(context, botEx.LocaleResource)
                        .ToEmbed().QueueToChannelAsync(context.Channel);
                    }
                    else
                    {
                        Log.Error(ex);
                        await app.GetService <RavenClient>().CaptureAsync(new SentryEvent(ex));
                    }
                };

                eventSystem.MessageFilter.AddFilter(new BotFilter());
                eventSystem.MessageFilter.AddFilter(new UserFilter());

                var commandMap = new Framework.Events.CommandMap();

                commandMap.OnModuleLoaded += (module) =>
                {
                    config.RegisterType(module.GetReflectedInstance().GetType(), module.GetReflectedInstance());
                };

                var handler = new SimpleCommandHandler(cache, commandMap);

                handler.AddPrefix(">", true, true);
                handler.AddPrefix("miki.");

                handler.OnMessageProcessed += async(cmd, msg, time) =>
                {
                    await Task.Yield();

                    Log.Message($"{cmd.Name} processed in {time}ms");
                };

                eventSystem.AddCommandHandler(handler);

                commandMap.RegisterAttributeCommands();
                commandMap.Install(eventSystem);
            }

            string configFile = Environment.CurrentDirectory + Config.MikiConfigurationFile;

            if (File.Exists(configFile))
            {
                await config.ImportAsync(
                    new JsonSerializationProvider(),
                    configFile
                    );
            }

            await config.ExportAsync(
                new JsonSerializationProvider(),
                configFile
                );

            app.Discord.MessageCreate += Bot_MessageReceived;

            app.Discord.GuildJoin  += Client_JoinedGuild;
            app.Discord.GuildLeave += Client_LeftGuild;
            app.Discord.UserUpdate += Client_UserUpdated;

            await gateway.StartAsync();
        }
Beispiel #18
0
        public AccountManager(MikiApp bot)
        {
            OnGlobalLevelUp += (a, e, l) =>
            {
                DogStatsd.Counter("levels.global", l, 1, new [] {
                    $"level:{l}"
                });
                return(Task.CompletedTask);
            };

            OnLocalLevelUp += async(a, e, l) =>
            {
                DogStatsd.Counter("levels.local", l, 1, new[] {
                    $"level:{l}"
                });

                var  guild   = await(e as IDiscordGuildChannel).GetGuildAsync();
                long guildId = guild.Id.ToDbLong();

                List <LevelRole> rolesObtained = new List <LevelRole>();

                using (var scope = MikiApp.Instance.Services.CreateScope())
                {
                    var context = scope.ServiceProvider.GetService <MikiDbContext>();
                    rolesObtained = await context.LevelRoles
                                    .Where(p => p.GuildId == guildId && p.RequiredLevel == l && p.Automatic)
                                    .ToListAsync();

                    var setting = (LevelNotificationsSetting)await Setting
                                  .GetAsync(context, e.Id, DatabaseSettingId.LevelUps);

                    if (setting == LevelNotificationsSetting.None)
                    {
                        return;
                    }

                    if (setting == LevelNotificationsSetting.RewardsOnly && rolesObtained.Count == 0)
                    {
                        return;
                    }

                    LocaleInstance instance = await Locale.GetLanguageInstanceAsync(context, e.Id);

                    EmbedBuilder embed = new EmbedBuilder()
                    {
                        Title       = instance.GetString("miki_accounts_level_up_header"),
                        Description = instance.GetString("miki_accounts_level_up_content", $"{a.Username}#{a.Discriminator}", l),
                        Color       = new Color(1, 0.7f, 0.2f)
                    };

                    if (rolesObtained.Count > 0)
                    {
                        var roles = await guild.GetRolesAsync();

                        var guildUser = await guild.GetMemberAsync(a.Id);

                        if (guildUser != null)
                        {
                            foreach (var role in rolesObtained)
                            {
                                var r = roles.FirstOrDefault(x => x.Id == (ulong)role.RoleId);

                                if (r != null)
                                {
                                    await guildUser.AddRoleAsync(r);
                                }
                            }
                        }

                        embed.AddInlineField("Rewards",
                                             string.Join("\n", rolesObtained.Select(x => $"New Role: **{roles.FirstOrDefault(z => z.Id.ToDbLong() == x.RoleId).Name}**")));
                    }

                    if (e is IDiscordTextChannel tc)
                    {
                        await embed.ToEmbed().QueueToChannelAsync(tc);
                    }
                }
            };

            //bot.Discord.Update += Client_GuildUpdated;
            bot.Discord.GuildMemberCreate += Client_UserJoined;
            bot.Discord.MessageCreate     += CheckAsync;
        }