示例#1
0
        public static CommandMap CreateFromAssembly(Assembly assembly = null)
        {
            CommandMap map = new CommandMap();

            map.RegisterAttributeCommands(assembly);
            return(map);
        }
示例#2
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();
        }
示例#3
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();
        }
示例#4
0
文件: Program.cs 项目: hlinkad/Miki
        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;
        }
示例#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();
        }