Ejemplo n.º 1
0
        public void LoadDiscord()
        {
            WebhookManager.Listen("webhooks");
            WebhookManager.OnEvent += (eventArgs) => new Task(() => Console.WriteLine("[webhook] " + eventArgs.auth_code));

            bot = new Bot(Global.Config.AmountShards, new DiscordSocketConfig()
            {
                ShardId           = Global.Config.ShardId,
                TotalShards       = Global.Config.ShardCount,
                ConnectionTimeout = 100000,
                LargeThreshold    = 250,
            }, new ClientInformation()
            {
                Name       = "Miki",
                Version    = "0.6.2",
                ShardCount = Global.Config.ShardCount,
                DatabaseConnectionString = Global.Config.ConnString,
            });

            EventSystem eventSystem = new EventSystem(new EventSystemConfig()
            {
                Developers        = Global.Config.DeveloperIds,
                ErrorEmbedBuilder = new EmbedBuilder().WithTitle($"🚫 Something went wrong!").WithColor(new Color(1.0f, 0.0f, 0.0f))
            });

            bot.Attach(eventSystem);

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

            commandMap.Install(eventSystem, bot);

            var handler = new SimpleCommandHandler(commandMap);

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

            var sessionHandler = new SessionBasedCommandHandler();
            var messageHandler = new MessageListener();

            eventSystem.AddCommandHandler(sessionHandler);
            eventSystem.AddCommandHandler(messageHandler);
            eventSystem.AddCommandHandler(handler);

            if (!string.IsNullOrWhiteSpace(Global.Config.SharpRavenKey))
            {
                Global.ravenClient = new SharpRaven.RavenClient(Global.Config.SharpRavenKey);
            }

            bot.Client.MessageReceived += Bot_MessageReceived;

            bot.Client.JoinedGuild += Client_JoinedGuild;
            bot.Client.LeftGuild   += Client_LeftGuild;
            bot.Client.UserUpdated += Client_UserUpdated;

            bot.Client.ShardConnected    += Bot_OnShardConnect;
            bot.Client.ShardDisconnected += Bot_OnShardDisconnect;
        }
Ejemplo n.º 2
0
        public async Task StartBlackjack(EventContext e, int bet)
        {
            using (var context = new MikiContext())
            {
                User user = await context.Users.FindAsync(e.Author.Id.ToDbLong());

                await user.AddCurrencyAsync(-bet, e.Channel);

                await context.SaveChangesAsync();
            }

            BlackjackManager bm = new BlackjackManager();

            IDiscordMessage message = await bm.CreateEmbed(e)
                                      .ToEmbed()
                                      .SendToChannel(e.Channel);

            Framework.Events.CommandMap map = new Framework.Events.CommandMap();
            SimpleCommandHandler        c   = new SimpleCommandHandler(map);

            c.AddPrefix("");
            c.AddCommand(new CommandEvent("hit")
                         .Default(async(ec) => await OnBlackjackHit(ec, bm, message, bet)));
            c.AddCommand(new CommandEvent("stand")
                         .SetAliases("knock", "stay", "stop")
                         .Default(async(ec) => await OnBlackjackHold(ec, bm, message, bet)));

            e.EventSystem.GetCommandHandler <SessionBasedCommandHandler>().AddSession(
                new CommandSession()
            {
                UserId = e.Author.Id, ChannelId = e.Channel.Id
            }, c, new TimeSpan(1, 0, 0));
        }
Ejemplo n.º 3
0
        public async Task BuyMarriageSlotAsync(EventContext e)
        {
            using (var context = new MikiContext())
            {
                User user = await User.GetAsync(context, e.Author);

                int  limit     = 10;
                bool isDonator = await user.IsDonatorAsync(context);

                if (isDonator)
                {
                    limit += 5;
                }

                EmbedBuilder embed = new EmbedBuilder();

                if (user.MarriageSlots >= limit)
                {
                    embed.Description = $"For now, **{limit} slots** is the max. sorry :(";

                    if (limit == 10 && !isDonator)
                    {
                        embed.AddField("Pro tip!", "Donators get 5 more slots!")
                        .SetFooter("Check `>donate` for more information!", "");
                    }

                    embed.Color = new Color(1f, 0.6f, 0.4f);
                    embed.ToEmbed().QueueToChannel(e.Channel);
                    return;
                }

                int costForUpgrade = (user.MarriageSlots - 4) * 2500;

                embed.Description = $"Do you want to buy a Marriage slot for **{costForUpgrade}**?\n\nType `yes` to confirm.";
                embed.Color       = new Color(0.4f, 0.6f, 1f);

                SimpleCommandHandler commandHandler = new SimpleCommandHandler(new CommandMap());
                commandHandler.AddPrefix("");
                commandHandler.AddCommand(new CommandEvent("yes")
                                          .Default(async(cx) => await ConfirmBuyMarriageSlot(cx, costForUpgrade)));

                e.EventSystem.GetCommandHandler <SessionBasedCommandHandler>().AddSession(e.CreateSession(), commandHandler, new TimeSpan(0, 0, 20));

                embed.ToEmbed().QueueToChannel(e.Channel);
            }
        }
Ejemplo n.º 4
0
        public async Task LoadDiscord()
        {
            bot = new Bot(Global.Config.AmountShards, new DiscordSocketConfig()
            {
                ShardId           = Global.Config.ShardId,
                TotalShards       = Global.Config.ShardCount,
                ConnectionTimeout = 100000,
                LargeThreshold    = 250,
            }, new ClientInformation()
            {
                Name       = "Miki",
                Version    = "0.6.2",
                ShardCount = Global.Config.ShardCount,
                DatabaseConnectionString = Global.Config.ConnString,
            });

            EventSystem eventSystem = new EventSystem(new EventSystemConfig()
            {
                Developers        = Global.Config.DeveloperIds,
                ErrorEmbedBuilder = new EmbedBuilder().WithTitle($"🚫 Something went wrong!").WithColor(new Color(1.0f, 0.0f, 0.0f))
            });

            bot.Attach(eventSystem);
            ConfigurationManager mg = new ConfigurationManager();

            var commandMap = new CommandMap();

            commandMap.OnModuleLoaded += (module) =>
            {
                mg.RegisterType(module.GetReflectedInstance());
            };
            commandMap.RegisterAttributeCommands();
            commandMap.Install(eventSystem, bot);

            var handler = new SimpleCommandHandler(commandMap);

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

            var sessionHandler = new SessionBasedCommandHandler();
            var messageHandler = new MessageListener();

            eventSystem.AddCommandHandler(sessionHandler);
            eventSystem.AddCommandHandler(messageHandler);
            eventSystem.AddCommandHandler(handler);

            foreach (var x in mg.Containers)
            {
                Console.WriteLine(x.Type.Name);
                foreach (var y in x.ConfigurableItems)
                {
                    Console.WriteLine($"=> {y.Type.Name} : {y.Type.PropertyType} = {y.GetValue<object>().ToString()}");
                }
            }

            Console.WriteLine("---- loading config.json ----\nVALUES CHANGED TO:");

            await mg.ImportAsync(new JsonSerializationProvider(), "./testexport.json");

            foreach (var x in mg.Containers)
            {
                Console.WriteLine(x.Type.Name);
                foreach (var y in x.ConfigurableItems)
                {
                    Console.WriteLine($"=> {y.Type.Name} : {y.Type.PropertyType} = {y.GetValue<object>().ToString()}");
                }
            }

            if (!string.IsNullOrWhiteSpace(Global.Config.SharpRavenKey))
            {
                Global.ravenClient = new SharpRaven.RavenClient(Global.Config.SharpRavenKey);
            }

            bot.Client.MessageReceived += Bot_MessageReceived;

            bot.Client.JoinedGuild += Client_JoinedGuild;
            bot.Client.LeftGuild   += Client_LeftGuild;
            bot.Client.UserUpdated += Client_UserUpdated;

            bot.Client.ShardConnected    += Bot_OnShardConnect;
            bot.Client.ShardDisconnected += Bot_OnShardDisconnect;
        }
Ejemplo n.º 5
0
        public async Task LoadDiscord()
        {
            StackExchangeCachePool pool = new StackExchangeCachePool(
                new ProtobufSerializer(),
                ConfigurationOptions.Parse(Global.Config.RedisConnectionString)
                );


            var client = new DistributedGateway(new MessageClientConfiguration
            {
                ConnectionString = new Uri(Global.Config.RabbitUrl.ToString()),
                QueueName        = "gateway",
                ExchangeName     = "consumer",
                ConsumerAutoAck  = false,
                PrefetchCount    = 25
            });

            Global.Client = new Framework.Bot(client, pool, new ClientInformation()
            {
                Name       = "Miki",
                Version    = "0.7",
                ShardCount = Global.Config.ShardCount,
                DatabaseConnectionString = Global.Config.ConnString,
                Token = Global.Config.Token,
                DatabaseContextFactory = () => new MikiContext()
            });

            (Global.Client.Client.ApiClient as DiscordApiClient).HttpClient.OnRequestComplete += (method, uri) =>
            {
                Log.Debug(method + " " + uri);
                DogStatsd.Histogram("discord.http.requests", uri, 1, new string[] { $"http_method:{method}" });
            };

            new BasicCacheStage().Initialize(Global.Client.CacheClient);

            EventSystem eventSystem = new EventSystem(new EventSystemConfig()
            {
                Developers = Global.Config.DeveloperIds,
            });

            eventSystem.OnError += async(ex, context) =>
            {
                if (ex is BotException botEx)
                {
                    Utils.ErrorEmbedResource(context, botEx.Resource)
                    .ToEmbed().QueueToChannel(context.Channel);
                }
                else
                {
                    Log.Error(ex);
                    await Global.ravenClient.CaptureAsync(new SentryEvent(ex));
                }
            };

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

            Global.Client.Attach(eventSystem);
            ConfigurationManager mg = new ConfigurationManager();

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

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

            var handler = new SimpleCommandHandler(pool, commandMap);

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

            var sessionHandler = new SessionBasedCommandHandler(pool);
            var messageHandler = new MessageListener(pool);

            eventSystem.AddCommandHandler(sessionHandler);
            eventSystem.AddCommandHandler(messageHandler);
            eventSystem.AddCommandHandler(handler);

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

            string configFile = Environment.CurrentDirectory + Config.MikiConfigurationFile;

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

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

            if (!string.IsNullOrWhiteSpace(Global.Config.SharpRavenKey))
            {
                Global.ravenClient = new SharpRaven.RavenClient(Global.Config.SharpRavenKey);
            }

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

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

            Global.Client.Client.MessageCreate += Bot_MessageReceived;

            Global.Client.Client.GuildJoin  += Client_JoinedGuild;
            Global.Client.Client.GuildLeave += Client_LeftGuild;
            Global.Client.Client.UserUpdate += Client_UserUpdated;

            await Global.Client.StartAsync();
        }
Ejemplo n.º 6
0
        public async Task LoadDiscord()
        {
            ConfigurationOptions options = new ConfigurationOptions();

            foreach (string s in Global.Config.RedisEndPoints)
            {
                options.EndPoints.Add(s);
            }

            if (!string.IsNullOrWhiteSpace(Global.Config.RedisPassword))
            {
                options.Password = Global.Config.RedisPassword;
            }

            StackExchangeCachePool pool = new StackExchangeCachePool(
                new ProtobufSerializer(),
                options
                );

            Global.Client = new Bot(Global.Config.AmountShards, pool, new ClientInformation()
            {
                Name       = "Miki",
                Version    = "0.6.2",
                ShardCount = Global.Config.ShardCount,
                DatabaseConnectionString = Global.Config.ConnString,
                Token = Global.Config.Token
            }, Global.Config.RabbitUrl.ToString());

            EventSystem eventSystem = new EventSystem(new EventSystemConfig()
            {
                Developers        = Global.Config.DeveloperIds,
                ErrorEmbedBuilder = new EmbedBuilder()
                                    .SetTitle($"🚫 Something went wrong!")
                                    .SetColor(new Color(1.0f, 0.0f, 0.0f))
            });

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

            Global.Client.Attach(eventSystem);
            ConfigurationManager mg = new ConfigurationManager();

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

            commandMap.OnModuleLoaded += (module) =>
            {
                mg.RegisterType(module.GetReflectedInstance());
            };

            var handler = new SimpleCommandHandler(commandMap);

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

            var sessionHandler = new SessionBasedCommandHandler();
            var messageHandler = new MessageListener();

            eventSystem.AddCommandHandler(sessionHandler);
            eventSystem.AddCommandHandler(messageHandler);
            eventSystem.AddCommandHandler(handler);

            commandMap.RegisterAttributeCommands();
            commandMap.Install(eventSystem, Global.Client);

            if (!string.IsNullOrWhiteSpace(Global.Config.SharpRavenKey))
            {
                Global.ravenClient = new SharpRaven.RavenClient(Global.Config.SharpRavenKey);
            }

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

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

            Global.Client.Client.MessageCreate += Bot_MessageReceived;;

            Global.Client.Client.GuildJoin  += Client_JoinedGuild;
            Global.Client.Client.GuildLeave += Client_LeftGuild;
            Global.Client.Client.UserUpdate += Client_UserUpdated;
        }
Ejemplo n.º 7
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();
        }
Ejemplo n.º 8
0
        public async Task LoadDiscord()
        {
            Global.ApiClient = new DiscordApiClient(Global.Config.Token, Global.RedisClient);

            if (Global.Config.SelfHosted)
            {
                //var gatewayConfig = GatewayConfiguration.Default();
                //gatewayConfig.ShardCount = 1;
                //gatewayConfig.ShardId = 0;
                //gatewayConfig.Token = Global.Config.Token;
                //gatewayConfig.ApiClient = Global.ApiClient;
                //gatewayConfig.WebSocketClient = new BasicWebSocketClient();
                //Global.Gateway = new CentralizedGatewayShard(gatewayConfig);
            }
            else
            {
                // For distributed systems
                _gateway = new DistributedGateway(new MessageClientConfiguration
                {
                    ConnectionString = new Uri(Global.Config.RabbitUrl.ToString()),
                    QueueName        = "gateway",
                    ExchangeName     = "consumer",
                    ConsumerAutoAck  = false,
                    PrefetchCount    = 25
                });
            }

            Global.Client = new MikiApplication(new ClientInformation()
            {
                ClientConfiguration = new DiscordClientConfigurations
                {
                    ApiClient   = Global.ApiClient,
                    CacheClient = Global.RedisClient,
                    Gateway     = _gateway
                },
                DatabaseContextFactory = () => new MikiContext()
            });

            var logging = new LoggingService();

            Global.Client.AddService(logging);

            new BasicCacheStage().Initialize(_gateway, Global.RedisClient);

            Global.ApiClient.RestClient.OnRequestComplete += (method, uri) =>
            {
                Log.Debug(method + " " + uri);
                DogStatsd.Histogram("discord.http.requests", uri, 1, new string[] { $"http_method:{method}" });
            };

            Global.CurrentUser = await Global.Client.Discord.GetCurrentUserAsync();

            EventSystem eventSystem = new EventSystem(new EventSystemConfig()
            {
                Developers = Global.Config.DeveloperIds,
            });

            eventSystem.OnError += async(ex, context) =>
            {
                if (ex is LocalizedException botEx)
                {
                    Utils.ErrorEmbedResource(context, botEx.LocaleResource)
                    .ToEmbed().QueueToChannel(context.Channel);
                }
                else
                {
                    Log.Error(ex);
                    await Global.ravenClient.CaptureAsync(new SentryEvent(ex));
                }
            };

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

            Global.Client.Attach(eventSystem);
            ConfigurationManager mg = new ConfigurationManager();

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

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

            var handler = new SimpleCommandHandler(Global.RedisClient, commandMap);

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

            var sessionHandler = new SessionBasedCommandHandler(Global.RedisClient);
            var messageHandler = new MessageListener(Global.RedisClient);

            eventSystem.AddCommandHandler(sessionHandler);
            eventSystem.AddCommandHandler(messageHandler);
            eventSystem.AddCommandHandler(handler);

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

            string configFile = Environment.CurrentDirectory + Config.MikiConfigurationFile;

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

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

            if (!string.IsNullOrWhiteSpace(Global.Config.SharpRavenKey))
            {
                Global.ravenClient = new SharpRaven.RavenClient(Global.Config.SharpRavenKey);
            }

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

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

            Global.Client.Discord.MessageCreate += Bot_MessageReceived;

            Global.Client.Discord.GuildJoin  += Client_JoinedGuild;
            Global.Client.Discord.GuildLeave += Client_LeftGuild;
            Global.Client.Discord.UserUpdate += Client_UserUpdated;

            await _gateway.StartAsync();
        }
Ejemplo n.º 9
0
        // TODO: probable rewrite at some point
        public async Task ValidateBet(EventContext e, Func <EventContext, int, Task> callback = null, int maxBet = 1000000)
        {
            ArgObject arg = e.Arguments.FirstOrDefault();

            if (arg != null)
            {
                const int noAskLimit = 10000;

                using (MikiContext context = new MikiContext())
                {
                    User user = await context.Users.FindAsync(e.Author.Id.ToDbLong());

                    if (user == null)
                    {
                        // TODO: add user null error
                        return;
                    }

                    string checkArg = arg.Argument;

                    if (int.TryParse(checkArg, out int bet))
                    {
                    }
                    else if (checkArg.ToLower() == "all" || checkArg == "*")
                    {
                        bet = user.Currency > maxBet ? maxBet : user.Currency;
                    }
                    else
                    {
                        e.ErrorEmbed(e.GetResource("miki_error_gambling_parse_error"))
                        .ToEmbed().QueueToChannel(e.Channel);
                        return;
                    }

                    if (bet < 1)
                    {
                        e.ErrorEmbed(e.GetResource("miki_error_gambling_zero_or_less"))
                        .ToEmbed().QueueToChannel(e.Channel);
                    }
                    else if (bet > user.Currency)
                    {
                        e.ErrorEmbed(e.GetResource("miki_mekos_insufficient"))
                        .ToEmbed().QueueToChannel(e.Channel);
                    }
                    else if (bet > maxBet)
                    {
                        e.ErrorEmbed($"you cannot bet more than {maxBet} mekos!")
                        .ToEmbed().QueueToChannel(e.Channel);
                        return;
                    }
                    else if (bet > noAskLimit)
                    {
                        IDiscordMessage confirmationMessage = null;

                        Framework.Events.CommandMap map = new Framework.Events.CommandMap();
                        map.AddCommand(new CommandEvent()
                        {
                            Name           = "yes",
                            ProcessCommand = async(ec) => {
                                await confirmationMessage.DeleteAsync();
                                await ValidateGlitch(ec, callback, bet);
                            }
                        });

                        SimpleCommandHandler commandHandler = new SimpleCommandHandler(map);
                        commandHandler.AddPrefix("");

                        e.EventSystem.GetCommandHandler <SessionBasedCommandHandler>()
                        .AddSession(new CommandSession {
                            ChannelId = e.Channel.Id, UserId = e.Author.Id
                        }, commandHandler, new TimeSpan(0, 2, 0));

                        EmbedBuilder embed = Utils.Embed;
                        embed.Description =
                            $"Are you sure you want to bet **{bet}**? You currently have `{user.Currency}` mekos.\n\nType `yes` to confirm.";
                        embed.Color         = new Color(0.4f, 0.6f, 1f);
                        confirmationMessage = await embed.ToEmbed().SendToChannel(e.Channel);
                    }
                    else
                    {
                        if (callback != null)
                        {
                            await callback(e, bet);
                        }
                    }
                }
            }
            else
            {
                e.ErrorEmbed(e.GetResource("miki_error_gambling_no_arg"))
                .ToEmbed().QueueToChannel(e.Channel);
            }
        }