Exemplo 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;
        }
Exemplo n.º 2
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;
        }
Exemplo n.º 3
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();
        }
Exemplo n.º 4
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;
        }
Exemplo n.º 5
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();
        }