Exemplo n.º 1
0
        private async Task InstallCommandsAsync()
        {
            try
            {
                if (_client is DiscordSocketClient socketClient)
                {
                    // Hook the MessageReceived event into our command handler
                    socketClient.MessageReceived += HandleCommandAsync;
                }

                //Exception and Post Execution handling
                _commands.Log             += ExceptionLogging.Log;
                _commands.CommandExecuted += CommandExecuted;

                //Adds custom type readers
                _commands.AddTypeReader(typeof(Emoji), new EmojiTypeReader());
                _commands.AddTypeReader(typeof(UserRef), new UserRefTypeReader());
                _commands.AddTypeReader(typeof(IUser), new BetterUserTypeReader());
                _commands.AddTypeReader(typeof(TimeSpan), new TimeSpanTypeReader(), true);

                // See Dependency Injection guide for more information.
                await _commands.AddModulesAsync(assembly : Assembly.GetAssembly(typeof(MainClass)),
                                                services : services);

                //await new LogMessage(LogSeverity.Info, "CMDs", "Commands set up").Log();
            }
            catch (Exception e)
            {
                await new LogMessage(LogSeverity.Critical, "CMDs", "Commands set up failed", e).Log();
            }
        }
Exemplo n.º 2
0
 public void AddTypeReaders()
 {
     _service.AddTypeReader <Emoji>(new EmojiTypeReader());
     _service.AddTypeReader <AccountOption>(new AccountOptionTypeReader());
     _service.AddTypeReader <object>(new ObjectTypeReader());
     _service.AddTypeReader <WidgetType>(new WidgetTypeTypeReader());
 }
Exemplo n.º 3
0
 public async Task InitializeAsync()
 {
     _commands.AddTypeReader <Event>(new EventTypeReader());
     _commands.AddTypeReader <EventRole>(new EventRoleTypeReader());
     // Register modules that are public and inherit ModuleBase<T>.
     await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _services);
 }
Exemplo n.º 4
0
        public async Task Init()
        {
            _commands.AddTypeReader <PKSystem>(new PKSystemTypeReader());
            _commands.AddTypeReader <PKMember>(new PKMemberTypeReader());
            _commands.CommandExecuted += CommandExecuted;
            await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _services);

            _client.ShardReady += ShardReady;
            _client.Log        += FrameworkLog;

            _client.MessageReceived += (msg) =>
            {
                // _client.CurrentUser will be null if we've connected *some* shards but not shard #0 yet
                // This will cause an error in WebhookCacheService so we just workaround and don't process any messages
                // until we properly connect. TODO: can we do this without chucking away a bunch of messages?
                if (_client.CurrentUser == null)
                {
                    return(Task.CompletedTask);
                }

                return(HandleEvent(s => s.AddMessageBreadcrumb(msg), eh => eh.HandleMessage(msg)));
            };
            _client.ReactionAdded       += (msg, channel, reaction) => HandleEvent(s => s.AddReactionAddedBreadcrumb(msg, channel, reaction), eh => eh.HandleReactionAdded(msg, channel, reaction));
            _client.MessageDeleted      += (msg, channel) => HandleEvent(s => s.AddMessageDeleteBreadcrumb(msg, channel), eh => eh.HandleMessageDeleted(msg, channel));
            _client.MessagesBulkDeleted += (msgs, channel) => HandleEvent(s => s.AddMessageBulkDeleteBreadcrumb(msgs, channel), eh => eh.HandleMessagesBulkDelete(msgs, channel));
        }
Exemplo n.º 5
0
        public async Task MainAsync()
        {
            await _client.LoginAsync(TokenType.Bot, Environment.GetEnvironmentVariable("DiscordToken"), true);

            await _client.StartAsync();

            //waits until the client is ready before using it
            _client.Ready += async() =>
            {
                _commands.AddTypeReader(typeof(Reminder), new ReminderTypeReader());
                _commands.AddTypeReader(typeof(DateTime), new DateTimeTypeReader());
                await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _provider);

                //Checks if the bot is the beta bot or not
                //If the bot is beta it will not connect to twitch
                if (_client.CurrentUser.Id == MainBotId)
                {
                    _provider.GetRequiredService <TwitchAPIService>();
                }


                //setting status
                IActivity game = new Game("Pushing the smoke...", ActivityType.Playing, ActivityProperties.None, null);
                await _client.SetActivityAsync(game);
            };



            //block the main task from closing
            await Task.Delay(Timeout.Infinite);
        }
Exemplo n.º 6
0
        public async Task MainAsync()
        {
            _config = new ConfigurationBuilder()
                      .SetBasePath(AppContext.BaseDirectory)
                      .AddJsonFile(path: "config.json")
                      .Build();

            _services = new ServiceCollection()
                        .AddSingleton(_config)
                        .AddSingleton <DiscordSocketClient>()
                        .AddSingleton <InteractivityService>()
                        .AddSingleton <MessageQueue>()
                        .AddSingleton <CommandHandler>()
                        .AddSingleton <CommandService>()
                        .AddSingleton <GuildSettings>()
                        .AddSingleton <Logger>()
                        .BuildServiceProvider();

            _client      = _services.GetRequiredService <DiscordSocketClient>();
            _client.Log += _services.GetRequiredService <Logger>().Log;

            await _client.LoginAsync(TokenType.Bot, _config["token"]);

            await _client.StartAsync();

            commandService      = _services.GetRequiredService <CommandService>();
            commandService.Log += _services.GetRequiredService <Logger>().Log;
            commandService.AddTypeReader(typeof(List <string[]>), new JsonTypeReader <List <string[]> >());
            commandService.AddTypeReader(typeof(List <EditData>), new JsonTypeReader <List <EditData> >());
            handler = _services.GetRequiredService <CommandHandler>();
            await handler.InstallCommandsAsync();

            // Block this task until the program is closed.
            await Task.Delay(-1);
        }
Exemplo n.º 7
0
        public async Task InstallCommandsAsync()
        {
            // Hook the MessageReceived event into our command handler
            _client.MessageReceived += HandleCommandAsync;

            _client.MessageDeleted  += _client_MessageDeleted;
            _client.MessageUpdated  += _client_MessageUpdated;
            _client.ReactionAdded   += _client_ReactionAdded;
            _client.ReactionRemoved += _client_ReactionRemoved;

            _commands.AddTypeReader(typeof(System.Numerics.BigInteger), new BigIntegerTypeReader());
            _commands.AddTypeReader(typeof(IEmote), new EmojiTypereader());

            // Here we discover all of the command modules in the entry
            // assembly and load them. Starting from Discord.NET 2.0, a
            // service provider is required to be passed into the
            // module registration method to inject the
            // required dependencies.
            //
            // If you do not use Dependency Injection, pass null.
            // See Dependency Injection guide for more information.

            await _commands.AddModuleAsync <BasicModule>(null);

            await _commands.AddModuleAsync <ListSortModule>(null);

            await _commands.AddModuleAsync <BotServerManagmentModule>(null);

            await _commands.AddModuleAsync <MiscCommandsModlue>(null);

            await _commands.AddModuleAsync <ReminderModule>(null);

            //await _commands.AddModulesAsync(assembly: Assembly.GetEntryAssembly(),
            //                                services: null);
        }
Exemplo n.º 8
0
        public async Task StartClient()
        {
            if (string.IsNullOrWhiteSpace(_botOptions.Token))
            {
                throw new Exception("Your token is missing or configured incorrectly.");
            }

            await _discord.LoginAsync(TokenType.Bot, _botOptions.Token);

            await _discord.StartAsync();

            await _discord.SetActivityAsync(new Game($"{_botOptions.Prefix}help", ActivityType.Listening));

            _commandService.AddTypeReader(typeof(decimal), new DecimalTypeReader(), true);
            _commandService.AddTypeReader(typeof(Fraction), new FractionTypeReader());

            await _commandService.AddModulesAsync(Assembly.GetEntryAssembly(), _provider);

            await CheckModuleFlags();

            if (!_commandService.Modules.Any())
            {
                throw new Exception("There are no modules enabled.");
            }
        }
Exemplo n.º 9
0
        private async Task StartAsync(params string[] args)
        {
            _client = new DiscordSocketClient(new DiscordSocketConfig {
                LogLevel = LogSeverity.Info
            });

            var serv = InstallServices();

            serv.GetRequiredService <ReliabilityService>();
            serv.GetRequiredService <CommandHandlerService>();
            serv.GetRequiredService <InviteService>();

            await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), serv);

            _commands.AddTypeReader <RLPlaylist>(new RLPlatformTypeReader());
            _commands.AddTypeReader <RLRegion>(new RLRegionTypeReader());
            _commands.AddTypeReader <RLPlaylist>(new RLPlaylistTypeReader());

            _client.Log   += Log;
            _commands.Log += Log;

            await _client.LoginAsync(TokenType.Bot, ConfigurationManager.AppSettings["TOKEN"]);

            await _client.StartAsync();

            await _client.SetGameAsync(ConfigurationManager.AppSettings["GAME"]);

            await Task.Delay(-1).ConfigureAwait(false);
        }
Exemplo n.º 10
0
        //Adds modules and services
        public override async Task InitializeAsync(CancellationToken cancellationToken)
        {
            //Adds custom type readers
            _commands.AddTypeReader(typeof(IUser), new ExtendedUserTypeReader());
            _commands.AddTypeReader(typeof(IRole), new ExtendedRoleTypeReader());

            await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _services);
        }
Exemplo n.º 11
0
        protected override async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            _client.MessageReceived += HandleCommandAsync;

            _command.AddTypeReader(typeof(PointType), new PointTypeTypeReader());
            _command.AddTypeReader(typeof(AccountItem), new AccountItemTypeReader());
            await _command.AddModulesAsync(Assembly.GetEntryAssembly(), _provider);
        }
Exemplo n.º 12
0
        //Adds modules and services
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            //Adds custom type readers
            _commandService.AddTypeReader(typeof(IUser), new ExtendedUserTypeReader());
            _commandService.AddTypeReader(typeof(IRole), new ExtendedRoleTypeReader());

            await _commandService.AddModulesAsync(Assembly.GetEntryAssembly(), _services);
        }
        public async Task InitializeAsync(IServiceProvider provider)
        {
            _provider = provider;
            _commands.AddTypeReader <ModuleInfo>(new ModuleInfoTypeReader());
            _commands.AddTypeReader <CommandInfo>(new CommandInfoTypeReader());

            await _commands.AddModulesAsync(Assembly.GetEntryAssembly());
        }
 public async Task Initialize()
 {
     _client.MessageReceived   += HandleCommand;
     _client.MessageUpdated    += MessageUpdated;
     _commands.CommandExecuted += CommandExecuted;
     _commands.AddTypeReader <CodeSnippet>(new CodeSnippetTypeReader());
     _commands.AddTypeReader <Size>(new SizeTypeReader());
     await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _services);
 }
        public async Task InstallCommandsAsync()
        {
            _client.MessageReceived += HandleCommandAsync;

            _commands.AddTypeReader(typeof(bool), new TypeReaders.BooleanTypeReader());
            _commands.AddTypeReader(typeof(int), new TypeReaders.IntegerTypeReader());

            await _commands.AddModulesAsync(assembly : Assembly.GetEntryAssembly(), services : null);
        }
Exemplo n.º 16
0
        public async Task InitializeAsync(IServiceProvider provider)
        {
            _provider = provider;
            _commands.AddTypeReader <IMentionable>(new MentionableTypeReader(), true);
            _commands.AddTypeReader <Guid>(new GuidTypeReader(), true);
            using var scope = _provider.CreateScope();
            await _commands.AddModulesAsync(Assembly.GetExecutingAssembly(), scope.ServiceProvider);

            // Add additional initialization code here...
        }
Exemplo n.º 17
0
        /// <summary>
        /// Installs the commands and subscribes to MessageReceived event.
        /// </summary>
        public async Task InstallCommandsAsync()
        {
            _commands.AddTypeReader(typeof(Globals.SkillType), new Addons.SkillTypeReader());
            _commands.AddTypeReader(typeof(Globals.SpecialType), new Addons.SpecialTypeReader());

            await _commands.AddModulesAsync(
                assembly : Assembly.GetEntryAssembly(),
                services : _services);

            _client.MessageReceived   += HandleCommandAsync;
            _commands.CommandExecuted += OnCommandExecutedAsync;
        }
Exemplo n.º 18
0
		/// <summary>
		/// Install all the modules and sets up for command handling
		/// </summary>
		/// <returns></returns>
		public async Task SetupCommandHandlingAsync()
		{
			//Add our custom type readers
			_commands.AddTypeReader(typeof(string[]), new StringArrayTypeReader());
			_commands.AddTypeReader(typeof(SocketGuildUser[]), new GuildUserArrayTypeReader());
			_commands.AddTypeReader(typeof(Emoji), new EmojiTypeReader());

			//Add our modules and setup the module manager so other classes can access module info
			await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _services);
			DiscordModuleManager.SetupModuleManager(_commands);

			_client.MessageReceived += HandleMessage;
		}
Exemplo n.º 19
0
#pragma warning restore CA2211 // Non-constant fields should not be visible

        public CommandHandler(
            DiscordSocketClient discord,
            CommandService commands,
            IServiceProvider provider,
            GitHubService git,
            LoggingService logging,
            InteractiveService interactiveService,
            HttpClient client)
        {
            _discord     = discord;
            _commands    = commands;
            _provider    = provider;
            _git         = git;
            _logging     = logging;
            _interactive = interactiveService;
            _client      = client;

            _discord.MessageReceived       += Discord_MessageReceived; // Bind MessageReceived event
            _discord.JoinedGuild           += Discord_JoinedGuild;     // Bind JoinedGuild event
            _discord.UserVoiceStateUpdated += Discord_UserVoiceStateUpdated;
            _discord.ReactionAdded         += Discord_ReactionAdded;
            _discord.ReactionRemoved       += Discord_ReactionRemoved;
            _discord.UserJoined            += Discord_UserJoined;
            _discord.Ready += async() =>
            {
                await LoggingService.OnLogAsync(new LogMessage(LogSeverity.Info, "Discord", $"Logged in as: {_discord.CurrentUser.Username}"));

                _ = Task.Run(async() =>
                {
                    var msg = new HttpRequestMessage(HttpMethod.Get, "https://api.github.com/repos/D3LT4PL/DygModBot/commits?per_page=1");
                    msg.Headers.UserAgent.ParseAdd("DygModBot by D3LT4PL/1.0");
                    var resp   = await _client.SendAsync(msg);
                    var header = resp.Headers.GetValues("link").First();
                    var amount = int.Parse(new Regex("&page=([0-9]*)>; rel=\"last\"").Match(header).Groups[1].Value);

                    IActivity activity = new Game($"Build nr {amount}");
                    await _discord.SetActivityAsync(activity);
                    await _discord.SetStatusAsync(UserStatus.DoNotDisturb);
                    FinishedInit = true;
                    await Task.Delay(TimeSpan.FromMinutes(1));
                    await _discord.SetActivityAsync(new Game("db!new | db!oc | DM me"));
                    await _discord.SetStatusAsync(UserStatus.Online);
                });
            };

            _commands.AddTypeReader <object>(new ObjectTypeReader());
            _commands.AddTypeReader <Uri>(new UriTypeReader());
            _commands.AddTypeReader <TimeSpan>(new CustomTimeSpanTypeReader(), true);
            _commands.AddTypeReader <IEmote>(new IEmoteTypeReader());
            _commands.AddTypeReader <IMessage>(new IMessageTypeReader());
        }
Exemplo n.º 20
0
        public CommandHandlingService(IServiceProvider services)
        {
            _commands = services.GetRequiredService <CommandService>();
            _discord  = services.GetRequiredService <DiscordShardedClient>();
            _services = services;

            _commands.CommandExecuted += CommandExecutedAsync;
            _commands.Log             += LogAsync;
            _discord.MessageReceived  += MessageReceivedAsync;

            // Add TypeReaders
            _commands.AddTypeReader(typeof(ILiveBotUser), new LiveBotUserTypeReader());
            _commands.AddTypeReader(typeof(bool), new EnhancedBoolTypeReader());
        }
Exemplo n.º 21
0
        public CommandHandlingService(IServiceProvider services)
        {
            _commands = services.GetRequiredService<CommandService>();
            _discord = services.GetRequiredService<DiscordSocketClient>();
            _services = services;
            _random = new Random();

            _commands.AddTypeReader(typeof(BuffType), new BuffTypeReader());
            _commands.AddTypeReader(typeof(DateTime), new DateTimeReader(), true);
            _commands.AddTypeReader(typeof(AlertAction), new AlertActionReader());

            _commands.CommandExecuted += CommandExecutedAsync;
            _discord.MessageReceived += MessageReceivedAsync;
        }
Exemplo n.º 22
0
        public CommandHandlingService(CommandService commands, DiscordSocketClient discord, IServiceProvider provider, IConfiguration config, ILogger <CommandHandlingService> log)
        {
            _commands = commands;
            _discord  = discord;
            _provider = provider;
            _config   = config;
            _logger   = log;

            _commands.CommandExecuted += CommandExecutedAsync;
            _discord.MessageReceived  += MessageReceivedAsync;

            _commands.AddTypeReader <IGuild>(new GuildTypeReader <SocketGuild>());
            _commands.AddTypeReader <Uri>(new UriTypeReader());
        }
Exemplo n.º 23
0
        public async Task InitialiseAsync()
        {
            _client.MessageReceived   += HandleCommandAsync;
            _client.ChannelDestroyed  += OnChannelDestroyedAsync;
            _commands.CommandExecuted += OnCommandExecutedAsync;
            _client.ReactionAdded     += Client_ReactionAdded;

            _commands.AddTypeReader <Item>(new ItemTypeReader());
            _commands.AddTypeReader <MarbleBotUser>(new MarbleBotUserTypeReader());
            _commands.AddTypeReader <Weapon>(new WeaponTypeReader());

            await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _services).ConfigureAwait(false);

            await _client.SetGameAsync("for mb/help!", type : ActivityType.Watching);
        }
Exemplo n.º 24
0
        public static async Task <CommandService> InstallCommands(DiscordSocketClient client, IServiceProvider services)
        {
            // Hook the MessageReceived Event into our Command Handler
            var commands = new CommandService();

            commands.Log           += Log;
            client.MessageReceived += msg => HandleCommand(client, services, commands, msg);
            // Discover all of the commands in this assembly and load them.
            commands.AddTypeReader(typeof(IUser), new MainGuildUserTypeReader <IUser>());
            commands.AddTypeReader(typeof(IGuildUser), new MainGuildUserTypeReader <IGuildUser>());
            commands.AddTypeReader <IGupUser>(new MainGuildUserTypeReader <IGupUser>(GupUser.BehaviorOverrides), true);
            await commands.AddModulesAsync(Assembly.GetEntryAssembly(), services);

            return(commands);
        }
Exemplo n.º 25
0
        public async Task InitializeAsync()
        {
            _commandService.AddTypeReader(typeof(MiunieUser), new MiunieUserTypeReader(_convertor));

            _discord.Client.MessageReceived += HandleCommandAsync;
            _ = await _commandService.AddModulesAsync(Assembly.GetExecutingAssembly(), _services);
        }
Exemplo n.º 26
0
        public async Task StartAsync()
        {
            string discordToken = _config.DiscordToken;

            if (string.IsNullOrWhiteSpace(discordToken))
            {
                throw new Exception("Please enter a valid bot's token.");
            }

            await _discord.LoginAsync(TokenType.Bot, discordToken);

            await _discord.StartAsync();

            _commands.AddTypeReader <List <string> >(new ListOfStringTypeReader());

            await _commands.AddModuleAsync(typeof(CoinModule), _provider);

            await _commands.AddModuleAsync(typeof(CoinWarModule), _provider);

            await _commands.AddModuleAsync(typeof(PollModule), _provider);

            await _commands.AddModuleAsync(typeof(MafiaModule), _provider);

            await _commands.AddModuleAsync(typeof(InfoModule), _provider);

            await _commands.AddModuleAsync(typeof(BetModule), _provider);

            await _commands.AddModuleAsync(typeof(AwardModule), _provider);
        }
Exemplo n.º 27
0
        public async Task InstallCommandsAsync()
        {
            // Hook the MessageReceived event into our command handler
            _client.MessageReceived += HandleCommandAsync;
            _client.MessageUpdated  += HandleUpdatedCommandAsync;
            //_client.ReactionAdded += HandleReactionAddedCommandAsync;

            _commands.AddTypeReader <YoutubeVideoUrl>(new YoutubeVideoUrlTypeReader());

            // Here we discover all of the command modules in the entry
            // assembly and load them. Starting from Discord.NET 2.0, a
            // service provider is required to be passed into the
            // module registration method to inject the
            // required dependencies.
            //
            // If you do not use Dependency Injection, pass null.
            // See Dependency Injection guide for more information.
            IEnumerable <ModuleInfo> modules = await _commands.AddModulesAsync(assembly : Assembly.GetEntryAssembly(),
                                                                               services : this.serviceProvider);

            StringBuilder sb   = new StringBuilder();
            StringBuilder help = new StringBuilder();

            sb.AppendLine(Program.APPLICATION_NAME);
            sb.AppendLine(Program.VERSION);
            sb.AppendLine("Discord Modules loaded:");
            help.AppendLine(Program.APPLICATION_NAME);
            help.AppendLine(Program.VERSION);
            foreach (ModuleInfo module in modules)
            {
                sb.AppendLine(module.Name);
                sb.AppendLine(module.Summary);
                sb.AppendLine("Commands: ");
                foreach (CommandInfo cmd in module.Commands)
                {
                    sb.AppendLine("    " + cmd.Name);
                    sb.AppendLine("    " + cmd.Summary);
                }
                sb.AppendLine("-----");

                //only print description from allowed module
                //in case you have some kind of hidden module like administration or debug
                if (module.Name == DiscordModule.MODULE_NAME)
                {
                    help.AppendLine("```");
                    help.AppendLine(module.Name);
                    help.AppendLine(module.Summary);
                    help.AppendLine("Commands: ");
                    foreach (CommandInfo cmd in module.Commands)
                    {
                        help.AppendLine("    " + cmd.Name + '\t' + cmd.Summary);
                    }
                    help.AppendLine("```");
                }
                DiscordModule.HELP_STRING = help.ToString();
            }
            logger.LogInformation(sb.ToString());

            var changeLogsRaw = File.ReadAllText("changelog.json");
        }
Exemplo n.º 28
0
        private IEnumerable <object> LoadTypeReaders(Assembly assembly)
        {
            Type[] allTypes;
            try
            {
                allTypes = assembly.GetTypes();
            }
            catch (ReflectionTypeLoadException ex)
            {
                Log.Warning(ex.LoaderExceptions[0], "Error getting types");
                return(Enumerable.Empty <object>());
            }
            var filteredTypes = allTypes
                                .Where(x => x.IsSubclassOf(typeof(TypeReader)) &&
                                       x.BaseType.GetGenericArguments().Length > 0 &&
                                       !x.IsAbstract);

            var toReturn = new List <object>();

            foreach (var ft in filteredTypes)
            {
                var x        = (TypeReader)Activator.CreateInstance(ft, Client, CommandService);
                var baseType = ft.BaseType;
                var typeArgs = baseType.GetGenericArguments();
                CommandService.AddTypeReader(typeArgs[0], x);
                toReturn.Add(x);
            }

            return(toReturn);
        }
Exemplo n.º 29
0
        public void Initialize()
        {
            _discord.MessageReceived  += HandleCommandAsync;
            _commands.CommandExecuted += OnCommandExecutedAsync;

            _commands.AddTypeReader <GuildUserProxy>(new GuildUserProxyTypeReader());
        }
Exemplo n.º 30
0
        public async Task StartAsync()
        {
            _discordClient.MessageReceived += OnMessageReceivedAsync;
            _commandService.AddTypeReader(typeof(int), new IntTypeReader());

            await _commandService.AddModulesAsync(Assembly.GetEntryAssembly(), _serviceProvider);
        }