public async Task InitializeAsync(Func <Task> OnReady, string token, int timeToRun, EventWaitHandle waitHandle)
        {
            _waitHandle = waitHandle;
            Log.LogInformation("InitializeAsync");

            StartTimer(timeToRun);

            await RemoveAllCommandsAsync();

            var serviceCollection = new ServiceCollection().AddSingleton(Client).AddSingleton(Commands);

            Client.MessageReceived += OnMessageReceived;
            foreach (var ass in _assemblyFactory.GetAssemblies().ToList())
            {
                var assembly = Assembly.LoadFile(ass);
                var innerServiceCollection = new ServiceCollection().AddSingleton(Client).AddSingleton(Commands);
                assembly.GetTypes()
                .Where(t => t.GetCustomAttribute <DiscordCommandAttribute>(true) is DiscordCommandAttribute).ToList()
                .ForEach(s =>
                {
                    Log.LogInformation($"Found Command Class: {s.Name}");
                    innerServiceCollection = innerServiceCollection.AddSingleton(s);
                    serviceCollection      = serviceCollection.AddSingleton(s);
                });

                await Commands.AddModulesAsync(assembly, innerServiceCollection.BuildServiceProvider());
            }
            Client.Ready += OnReady;
            Services      = serviceCollection.BuildServiceProvider();

            await Client.LoginAsync(TokenType.Bot, token);

            await Client.StartAsync();
        }
Beispiel #2
0
 public async Task InstallCommands()
 {
     // Hook the MessageReceived Event into our Command Handler
     Client.MessageReceived += HandleCommand;
     // Discover all of the commands in this assembly and load them.
     await Commands.AddModulesAsync(Assembly.GetAssembly(typeof(Commands.Info)));
 }
Beispiel #3
0
        public async Task InitAsync()
        {
            await Commands.AddModulesAsync(Assembly.GetEntryAssembly(), Services);

            foreach (var command in Commands.Commands)
            {
                Logger.Information($"Command {command.Name} was loaded.");
            }
        }
Beispiel #4
0
        private async Task DnDMainAsync()
        {
            await MainAsync(Token);

            await Commands.AddModulesAsync(typeof(Program).Assembly, null);

            Client.MessageReceived += Client_MessageReceived;
            Client.Ready           += Client_Ready;
            await Task.Delay(-1);
        }
Beispiel #5
0
 public void Initialize()
 {
     // Pass the service provider to the second parameter of
     // AddModulesAsync to inject dependencies to all modules
     // that may require them.
     Commands.AddModulesAsync(
         assembly: Assembly.GetEntryAssembly(),
         services: Services);
     Client.MessageReceived += HandleCommandAsync;
 }
Beispiel #6
0
        private async Task MainAsync()
        {
            await MainAsync(ApiAccessKeys.MiniGamesKey);

            await Commands.AddModulesAsync(typeof(Program).Assembly, null);

            Client.MessageReceived += Client_MessageRecieved;
            Client.Ready           += Client_Ready;
            await Task.Delay(-1);
        }
Beispiel #7
0
        public async Task Run()
        {
            Client.MessageReceived += HandleCommandAsync;
            await Commands.AddModulesAsync(Assembly.GetEntryAssembly(), Services).ConfigureAwait(false);

            await Client.LoginAsync(TokenType.Bot, Token).ConfigureAwait(false);

            await Client.StartAsync().ConfigureAwait(false);

            await Task.Delay(-1).ConfigureAwait(false);
        }
Beispiel #8
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(Config.Discord.Token))
            {
                throw new ConfigException("Missing bot token in config.");
            }

            await Client.LoginAsync(TokenType.Bot, Config.Discord.Token).ConfigureAwait(false);

            await Client.StartAsync().ConfigureAwait(false);

            await SetActivity(Config.Discord.Activity).ConfigureAwait(false);

            await Commands.AddModulesAsync(Assembly.GetEntryAssembly(), Services).ConfigureAwait(false);
        }
Beispiel #9
0
        public async Task StartAsync(ServiceProvider services, ServiceCollection serviceCollection)
        {
            Services          = services;
            ServiceCollection = serviceCollection;
            string discordToken = Config["tokens:discord"];                 // Get the discord token from the config file

            if (string.IsNullOrWhiteSpace(discordToken))
            {
                throw new Exception("Please enter your bot's token into the `Config.json` file found in the applications root directory.");
            }

            await Client.LoginAsync(TokenType.Bot, discordToken);                 // Login to discord

            await Client.StartAsync();                                            // Connect to the websocket

            Client.Connected += OnDiscordConnected;

            await Commands.AddModulesAsync(Assembly.GetEntryAssembly(), services);                 // Load commands and modules into the command service
        }
Beispiel #10
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(ConfigurationService.Token))
            {
                throw new ConfigException("Missing bot token in config.");
            }

            await Client.LoginAsync(TokenType.Bot, ConfigurationService.Token);

            await Client.StartAsync();

            BotState.AppInfo = await Client.GetApplicationInfoAsync();

            Commands.AddTypeReader <JObject>(new JObjectTypeReader());
            Commands.AddTypeReader <GroupCommandMatch>(new GroupCommandMatchTypeReader());
            Commands.AddTypeReader <MathSession>(new MathSessionTypeReader());
            Commands.AddTypeReader <GlobalConfigItems>(new GlobalConfigItemTypeReader());

            using var scope = Services.CreateScope();
            await Commands.AddModulesAsync(Assembly.GetEntryAssembly(), scope.ServiceProvider);
        }
Beispiel #11
0
        private async Task MtgMainAsync()
        {
            Console.WriteLine(ConsoleWriteOverride.AddTimeStamp("Loading Filters."));
            LegalityDictionary.LoadLegalityDict();

            //var aTimer = new Timer(1800000); //thirty minutes in milliseconds
            //aTimer.BeginInit();
            //aTimer.Elapsed += OnTimedEvent;
            //aTimer.EndInit();
            //aTimer.Start();
            var logRepository = LogManager.GetRepository(typeof(Program).Assembly);

            XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));
            await MainAsync(Token);

            await Commands.AddModulesAsync(typeof(Program).Assembly, null);

            Client.MessageReceived += Client_MessageRecieved;
            Client.Ready           += Client_Ready;

            //Thread.Sleep(10000); //10 seconds, sleeps a different thread from the bot so that it can finish loading before we begin.
            //new MTGMoversShakersOutput().DetermineDelivery(Client);
            await Task.Delay(-1);
        }
Beispiel #12
0
 public async Task RegisterCommandsAsync()
 {
     Client.MessageReceived += HandleCommandAsync;
     await Commands.AddModulesAsync(Assembly.GetEntryAssembly(), Services);
 }
Beispiel #13
0
 private async Task InstallCommands()
 {
     Client.MessageReceived += HandleCommand;
     await Commands.AddModulesAsync(Assembly.GetEntryAssembly(), null);
 }
Beispiel #14
0
 public async Task InstallCommands()
 {
     await Commands.AddModulesAsync(Assembly.GetEntryAssembly());
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="NinjaCatDiscordClient"/> class.
        /// </summary>
        public NinjaCatDiscordClient() : base(new DiscordSocketConfig() { TotalShards = Constants.ShardCount })
        {
            // Write startup messages.
            LogInfo($"{Constants.AppName} on {RuntimeInformation.FrameworkDescription} has started.");
            LogInfo($"===============================================================");

            // Listen for events.
            Log += (message) => {
                // Log the output.
                LogInfo(message.ToString());
                return(Task.CompletedTask);
            };

            // Get latest post URL, if there is one.
            if (File.Exists(Constants.LatestPostFileName))
            {
                CurrentUrl = File.ReadAllText(Constants.LatestPostFileName);
            }

            if (File.Exists(Constants.SettingsFileName))
            {
                Settings = JsonConvert.DeserializeObject <NinjaCatSettings>(File.ReadAllText(Constants.SettingsFileName));
            }
            else
            {
                Settings = new NinjaCatSettings();
            }

            // Initialize commands.
            Commands.AddModulesAsync(Assembly.GetEntryAssembly(), null).Wait();

            // Listen for messages.
            MessageReceived += async(message) => {
                var msg = message as SocketUserMessage;
                if (msg == null)
                {
                    return;
                }

                // Keeps track of where the command begins.
                var pos = 0;

                // Attempt to parse a command. Silently ignore unknown commanads.
                if (msg.HasStringPrefixLower(Constants.CommandPrefix, ref pos))
                {
                    var result = await Commands.ExecuteAsync(new NinjaCatCommandContext(this, msg), msg.Content.Substring(pos), null);

                    if (!result.IsSuccess)
                    {
                        if (result.Error == CommandError.UnknownCommand)
                        {
                            return;
                        }

                        await msg.Channel.TriggerTypingAsync();

                        await Task.Delay(TimeSpan.FromSeconds(0.5));

                        await msg.Channel.SendMessageAsync($"I'm sorry, but something happened. Error: {result.ErrorReason}\n\nIf there are spaces in a parameter, make sure to surround it with quotes.");
                    }
                    return;
                }
            };
        }
 public async Task ImportCommandsAsync(Assembly assembly)
 {
     await Commands.AddModulesAsync(assembly, _host.Services);
 }