Exemplo n.º 1
0
        private void ConfigureCommands(ConfigJson config)
        {
            Client.Logger.LogInformation(Program.BotEventId, $"Setting up commands...");
            var ccfg = new CommandsNextConfiguration()
            {
                StringPrefixes      = config.CommandPrefix,
                CaseSensitive       = false,
                EnableDms           = true,
                EnableMentionPrefix = true
            };

            Commands = Client.UseCommandsNext(ccfg);

            // Add event callbacks
            Commands.CommandExecuted += StaticEvents.Commands_CommandExecuted;
            Commands.CommandErrored  += StaticEvents.Commands_CommandErrored;

            // Register commands
            Commands.RegisterCommands <Bunnies>();
            Commands.RegisterCommands <Commands.Utilities>();
            Commands.RegisterCommands <Games>();
            Commands.RegisterCommands <Searches>();
            Commands.RegisterCommands <Counters>();
            Commands.RegisterCommands <Help>();

            // Set custom helpformatter
            Commands.SetHelpFormatter <HelpFormatter>();
        }
Exemplo n.º 2
0
        private static async Task MainAsync()
        {
            discord = new DiscordClient(new DiscordConfiguration {
                Token           = "",
                TokenType       = TokenType.Bot,
                MinimumLogLevel = LogLevel.Information,
                Intents         = DiscordIntents.GuildMembers | DiscordIntents.AllUnprivileged
            });

            CommandsNextExtension commands = discord.UseCommandsNext(new CommandsNextConfiguration()
            {
                StringPrefixes = new[] { "." }
            });

            discord.Ready            += EventHandlers.Discord_Ready;
            discord.GuildMemberAdded += EventHandlers.Discord_GuildMemberAdded;
            discord.MessageCreated   += EventHandlers.Discord_MessageCreated;
            commands.CommandErrored  += EventHandlers.Commands_CommandErrored;

            commands.SetHelpFormatter <CustomHelpFormatter>();
            commands.RegisterCommands(Assembly.GetExecutingAssembly());

            await discord.ConnectAsync();

            await Task.Delay(-1);
        }
Exemplo n.º 3
0
        public Bot()
        {
            _oddity            = new OddityCore();
            _diagnosticService = new DiagnosticService();

            _oddity.Timeout                 = new TimeSpan(0, 0, 2);
            _oddity.OnRequestSend          += Oddity_OnRequestSend;
            _oddity.OnResponseReceive      += Oddity_OnResponseReceive;
            _oddity.OnDeserializationError += Oddity_OnDeserializationError;

            Client              = new DiscordClient(GetClientConfiguration());
            CacheService        = new CacheService();
            LogExecutedCommands = true;

            Client.Ready          += Client_Ready;
            Client.Heartbeated    += Client_Heartbeat;
            Client.GuildCreated   += Client_GuildCreated;
            Client.GuildDeleted   += Client_GuildDeleted;
            Client.ClientErrored  += Client_ClientError;
            Client.SocketErrored  += Client_SocketError;
            Client.SocketClosed   += Client_SocketClosed;
            Client.Resumed        += Client_Resumed;
            Client.MessageCreated += Client_MessageCreated;

            _commands = Client.UseCommandsNext(GetCommandsConfiguration());
            _commands.CommandExecuted += Commands_CommandExecuted;
            _commands.CommandErrored  += Commands_CommandError;
            _commands.SetHelpFormatter <CustomHelpFormatter>();

            RegisterCommands();
        }
Exemplo n.º 4
0
        }                                                                  //Commands Handler
        public async Task RunAsync()
        {
            #region Using the .json file
            var json = string.Empty;

            using (var fs = File.OpenRead("config.json"))
                using (var sr = new StreamReader(fs, new UTF8Encoding(false)))
                    json = await sr.ReadToEndAsync().ConfigureAwait(false);

            var configJson = JsonConvert.DeserializeObject <ConfigJson>(json);
            #endregion

            #region Bot Configuration
            var config = new DiscordConfiguration
            {
                Token                 = configJson.Token,
                TokenType             = TokenType.Bot,
                AutoReconnect         = true,
                LogLevel              = LogLevel.Debug,
                UseInternalLogHandler = true
            };

            Client = new DiscordClient(config);
            #endregion

            #region Interactivity Configuration

            Client.UseInteractivity(new InteractivityConfiguration
            {
                PollBehaviour = PollBehaviour.KeepEmojis,
                Timeout       = TimeSpan.FromDays(1)
            });

            #endregion

            #region Command Configuration and Adding Them To The Available Commands
            var commandsConfig = new CommandsNextConfiguration
            {
                StringPrefixes      = new string[] { configJson.Prefix },
                EnableMentionPrefix = true,
                EnableDms           = true,
                EnableDefaultHelp   = true,
                DmHelp = false
            };

            Commands = Client.UseCommandsNext(commandsConfig);
            Commands.RegisterCommands <Test>();
            Commands.RegisterCommands <Moderation>();
            Commands.RegisterCommands <Interactive>();
            Commands.RegisterCommands <UserInfo>();
            Commands.RegisterCommands <Kingdom.Commands>();
            Commands.SetHelpFormatter <Vinex_Bot.Commands.Help>();

            #endregion

            await Client.ConnectAsync();

            await Task.Delay(-1);
        }
Exemplo n.º 5
0
        public async Task RunAsync()
        {
            var json = string.Empty;

            using (var fs = File.OpenRead("config.json"))
                using (var sr = new StreamReader(fs, new UTF8Encoding(false)))
                    json = await sr.ReadToEndAsync().ConfigureAwait(false);

            ConfigJson ConfigJson = JsonConvert.DeserializeObject <ConfigJson>(json);

            DiscordConfiguration config = new DiscordConfiguration
            {
                Token           = ConfigJson.Token,
                TokenType       = TokenType.Bot,
                AutoReconnect   = true,
                MinimumLogLevel = Microsoft.Extensions.Logging.LogLevel.Debug
            };

#pragma warning disable IDE0003
            this.Client = new DiscordClient(config);
#pragma warning restore IDE0003

            Client.Ready += OnClientReady;

            CommandsNextConfiguration commandsConfig = new CommandsNextConfiguration
            {
                StringPrefixes       = new string[] { ConfigJson.Prefix },
                EnableDms            = false,
                EnableMentionPrefix  = true,
                IgnoreExtraArguments = true,
            };

            Commands = Client.UseCommandsNext(commandsConfig);

            Commands.CommandErrored += CmdErroredHandler;
            Commands.SetHelpFormatter <CustomHelpFormatter>();

            // Basic:
            Commands.RegisterCommands <Basic>();
            // Economy:
            Commands.RegisterCommands <Balance>();
            Commands.RegisterCommands <Experience>();
            Commands.RegisterCommands <Leaderboards>();
            Commands.RegisterCommands <Transactions>();

            await Client.ConnectAsync();

            // Deserializes Transactions Hooks
            await Transactions.TransactionStartup(Client);

            // Create transaction hub object
            TransactionHub tHub = new TransactionHub();
            // Hook transaction event to method
            tHub.OnTransaction += async(transaction) => await Transactions.HandleTransactionAsync(transaction);

            await Task.Delay(-1);
        }
Exemplo n.º 6
0
    /// <summary>
    /// Start the discord bot
    /// </summary>
    /// <returns>A <see cref="Task"/> representing the result of the asynchronous operation.</returns>
    public async Task StartAsync()
    {
        var config = new DiscordConfiguration
        {
            Token                 = Environment.GetEnvironmentVariable("SCRUFFY_DISCORD_TOKEN"),
            TokenType             = TokenType.Bot,
            AutoReconnect         = true,
            Intents               = DiscordIntents.All,
            LogTimestampFormat    = "yyyy-MM-dd HH:mm:ss",
            ReconnectIndefinitely = true              // TODO Connection handling
        };

        _discordClient = new DiscordClient(config);

        _discordClient.UseInteractivity(new InteractivityConfiguration
        {
            Timeout = TimeSpan.FromMinutes(2)
        });

        GlobalServiceProvider.Current.AddSingleton(_discordClient);

        _prefixResolver = new PrefixResolvingService();
        GlobalServiceProvider.Current.AddSingleton(_prefixResolver);

        _administrationPermissionsValidationService = new AdministrationPermissionsValidationService();
        GlobalServiceProvider.Current.AddSingleton(_administrationPermissionsValidationService);

        GlobalServiceProvider.Current.AddSingleton(new DiscordStatusService(_discordClient));

#if RELEASE
        _messageImportService = new MessageImportService(_discordClient);
        GlobalServiceProvider.Current.AddSingleton(_messageImportService);
#endif

        _commands = _discordClient.UseCommandsNext(new CommandsNextConfiguration
        {
            PrefixResolver      = _prefixResolver.OnPrefixResolver,
            EnableDms           = true,
            EnableMentionPrefix = true,
            CaseSensitive       = false,
            DmHelp            = false,
            EnableDefaultHelp = false,
            Services          = GlobalServiceProvider.Current.GetServiceProvider()
        });

        _commands.SetHelpFormatter <HelpCommandFormatter>();

        _commands.RegisterCommands(Assembly.Load("Scruffy.Commands"));

        _errorHandler = new DiscordErrorHandler(_commands);

        await _discordClient.ConnectAsync().ConfigureAwait(false);
    }
Exemplo n.º 7
0
        public async Task RunAsync()
        {
            var json = string.Empty;

            using (var fs = File.OpenRead("config.json"))
                using (var sr = new StreamReader(fs, new UTF8Encoding(false)))
                    json = await sr.ReadToEndAsync().ConfigureAwait(false);

            var configJson = JsonConvert.DeserializeObject <Configjson>(json);

            var config = new DiscordConfiguration
            {
                Token                = configJson.Token,
                TokenType            = TokenType.Bot,
                AutoReconnect        = true,
                MinimumLogLevel      = LogLevel.Debug,
                UseRelativeRatelimit = true,
            };

            Client = new DiscordClient(config);

            Client.Ready += Client_Ready;

            Client.UseInteractivity(new InteractivityConfiguration {
                Timeout = TimeSpan.FromMinutes(1)
            });

            var commandsConfig = new CommandsNextConfiguration
            {
                StringPrefixes      = new string[] { configJson.Prefix },
                EnableMentionPrefix = true,
                EnableDms           = false,
                DmHelp = false,
            };

            Commands = Client.UseCommandsNext(commandsConfig);

            Commands.RegisterCommands <FunCommands>();
            Commands.RegisterCommands <MathCommands>();
            Commands.RegisterCommands <SpecialCommands>();

            Commands.SetHelpFormatter <CustomHelpFormatter>();

            await Client.ConnectAsync();

            await Task.Delay(-1);
        }
Exemplo n.º 8
0
        public async Task RunBotAsync()
        {
            var config = new ConfigurationBuilder()
                         .AddJsonFile("appsettings.json", false, true)
                         .Build();
            Discord discord = new Discord();

            config.GetSection("Discord").Bind(discord);
            var services = ConfigureService(config);
            var cfg      = new DiscordConfiguration
            {
                Token           = discord.DiscordToken,
                TokenType       = TokenType.Bot,
                AutoReconnect   = true,
                MinimumLogLevel = LogLevel.Debug
            };

            Client                 = new DiscordClient(cfg);
            Client.Ready          += ClientReady;
            Client.GuildAvailable += ClientGuildAvailable;
            Client.ClientErrored  += ClientErrored;
            Client.UseInteractivity(new InteractivityConfiguration
            {
                PaginationBehaviour = PaginationBehaviour.Ignore,
                Timeout             = TimeSpan.FromMinutes(5)
            });
            var ccfg = new CommandsNextConfiguration
            {
                StringPrefixes      = new[] { discord.Prefix },
                EnableDms           = true,
                EnableMentionPrefix = true,
                Services            = services
            };

            Commands = Client.UseCommandsNext(ccfg);
            Commands.CommandExecuted += CommandExecute;
            Commands.CommandErrored  += CommandErrored;
            Commands.RegisterCommands <ItemCommand>();
            Commands.RegisterCommands <OperatorCommand>();
            Commands.RegisterCommands <RecruitCommand>();
            Commands.RegisterCommands <TipCommand>();
            Commands.SetHelpFormatter <HelpFormatter>();
            await Client.ConnectAsync();

            await Task.Delay(-1);
        }
Exemplo n.º 9
0
        public Bot(Config _config)
        {
            config = _config;

            if (config.BotProxyEnabled)
            {
                _proxy             = new WebProxy(config.BotProxyAddress);
                _proxy.Credentials = new NetworkCredential(config.BotProxyUsername, config.BotProxyPassword);;
            }

            MainAsync(config.Token).ConfigureAwait(false).GetAwaiter().GetResult();
            commands = client.UseCommandsNext(new CommandsNextConfiguration
            {
                StringPrefixes = new string[] { config.Prefix }
            });
            commands.RegisterCommands <MyCommands>();
            commands.SetHelpFormatter <HelpFormatter>();
        }
Exemplo n.º 10
0
        internal Bot(IServiceProvider serviceProvider,
                     BotConfiguration botConfiguration)
        {
            _serviceProvider  = serviceProvider;
            _botConfiguration = botConfiguration;

            var discordConfig = new DiscordConfiguration
            {
                Token    = _botConfiguration.DiscordToken,
                LogLevel = LogLevel.Debug,
                UseInternalLogHandler = false,
                ReconnectIndefinitely = true
            };

            _discordClient = new DiscordClient(discordConfig);

            var interactivityConfig = new InteractivityConfiguration {
                PaginationBehaviour = PaginationBehaviour.Ignore
            };

            _discordClient.UseInteractivity(interactivityConfig);

            var commandsConfig = new CommandsNextConfiguration
            {
                StringPrefixes      = new[] { COMMAND_PREFIX },
                Services            = serviceProvider,
                CaseSensitive       = false,
                EnableMentionPrefix = false
            };

            _commandsNextConfig = commandsConfig;
            _commands           = _discordClient.UseCommandsNext(commandsConfig);
            _commands.RegisterCommands(Assembly.GetExecutingAssembly());
            _commands.SetHelpFormatter <HelpFormatter>();

            _discordClient.DebugLogger.LogMessageReceived += OnLogMessageReceived;
            _discordClient.GuildCreated       += OnGuildAvailable;
            _discordClient.GuildDeleted       += OnGuildDeleted;
            _discordClient.GuildMemberAdded   += OnGuildMemberAdded;
            _discordClient.GuildMemberRemoved += OnGuildMemberRemoved;
            _discordClient.Ready += _ => Task.FromResult(_clientIsReady = true);

            _commands.CommandErrored += OnCommandError;
        }
Exemplo n.º 11
0
        private static async Task MainAsync()
        {
            var data = new Global().DefaultDatabase();

            _yone = new DiscordClient(new DiscordConfiguration
            {
                Token                 = data.botToken,
                TokenType             = TokenType.Bot,
                UseInternalLogHandler = true,
                AutomaticGuildSync    = true,
                AutoReconnect         = true
            });
            _commands = _yone.UseCommandsNext(new CommandsNextConfiguration
            {
                PrefixResolver       = GetPrefixPositionAsync,
                EnableMentionPrefix  = true,
                EnableDms            = false,
                CaseSensitive        = false,
                IgnoreExtraArguments = true
            });
            _yone.UseInteractivity(new InteractivityConfiguration
            {
                PaginationBehavior = 0,
                PaginationTimeout  = TimeSpan.FromMinutes(5.0),
                Timeout            = TimeSpan.FromMinutes(2.0)
            });
            var msc = new VoiceNextConfiguration
            {
                VoiceApplication = VoiceApplication.Music
            };


            var dspExtended = _yone.UseDspExtended();

            _commands.SetHelpFormatter <Help.DefaultHelpFormatter>();
            _commands.RegisterCommands(Assembly.GetExecutingAssembly());

            dspExtended.RegisterAssembly(Assembly.GetExecutingAssembly());

            _yone.UseVoiceNext(msc);
            await _yone.ConnectAsync();

            await Task.Delay(-1);
        }
Exemplo n.º 12
0
 public static void RegisterAll(this CommandsNextExtension client)
 {
     client.RegisterCommands <Administration>();
     client.RegisterCommands <ImageBoards>();
     client.RegisterCommands <Japan>();
     client.RegisterCommands <Language>();
     client.RegisterCommands <LocalStats>();
     client.RegisterCommands <Math>();
     client.RegisterCommands <Minigames>();
     client.RegisterCommands <Misc>();
     client.RegisterCommands <Money>();
     client.RegisterCommands <PublicStats>();
     client.RegisterCommands <Quotes>();
     client.RegisterCommands <ReactionRoles>();
     client.RegisterConverter(new BoardConv());
     client.RegisterConverter(new BooruConv());
     client.RegisterConverter(new CurrencyConv());
     client.RegisterConverter(new DiscordNamedColorConverter());
     client.RegisterConverter(new DoujinEnumConv());
     client.RegisterConverter(new HashTypeConv());
     client.RegisterConverter(new RpsOptionConv());
     client.SetHelpFormatter <HelpFormatter>();
 }
Exemplo n.º 13
0
        private async void Connect()
        {
            var connectionConfig = new DiscordConfiguration
            {
                Token         = SettingsLoader.SettingsContainer.Token,
                TokenType     = TokenType.Bot,
                AutoReconnect = true,
                Intents       = DiscordIntents.All
            };

            DiscordClient = new DiscordClient(connectionConfig);

            _messageResponseService = new MessageResponseService();

            var commandsConfig = new CommandsNextConfiguration
            {
                StringPrefixes       = new [] { SettingsLoader.SettingsContainer.Prefix },
                EnableDms            = false,
                EnableMentionPrefix  = true,
                CaseSensitive        = false,
                IgnoreExtraArguments = true,
                Services             = BuildDependencies()
            };

            _commands = DiscordClient.UseCommandsNext(commandsConfig);
            _commands.SetHelpFormatter <CustomHelpFormatter>();
            _commands.CommandExecuted += Commands_CommandExecuted;
            _commands.CommandErrored  += Commands_CommandErrored;

            DiscordClient.MessageCreated       += DiscordClient_MessageCreatedAsync;
            DiscordClient.MessageUpdated       += DiscordClient_MessageUpdatedAsync;
            DiscordClient.MessageReactionAdded += DiscordClient_MessageReactionAddedAsync;
            DiscordClient.GuildMemberAdded     += DiscordClient_UserJoinedAsync;
            DiscordClient.MessageCreated       += DiscordClient_MessageCreated;

            await DiscordClient.ConnectAsync();
        }
Exemplo n.º 14
0
        public ModuloComandos(CommandsNextConfiguration ccfg, DiscordClient client)
        {
            Comandos = client.UseCommandsNext(ccfg);
            Comandos.CommandExecuted += ComandoExecutado;
            Comandos.CommandErrored  += ComandoAconteceuErro;
            Comandos.SetHelpFormatter <IAjudaComando>();

            Comandos.RegisterCommands <ComandoAjuda>();
            Comandos.RegisterCommands <ComandoConvite>();
            Comandos.RegisterCommands <ComandoInfo>();
            Comandos.RegisterCommands <ComandoVotar>();
            Comandos.RegisterCommands <ComandoUsuario>();
            Comandos.RegisterCommands <ComandoAdm>();
            Comandos.RegisterCommands <ComandoPrefixo>();

            Comandos.RegisterCommands <TopComando>();

            Comandos.RegisterCommands <ComandoStatus>();
            Comandos.RegisterCommands <ComandoProficiencia>();
            Comandos.RegisterCommands <ComandoAtribuir>();
            Comandos.RegisterCommands <ComandoLocal>();
            Comandos.RegisterCommands <ComandoExplorar>();
            Comandos.RegisterCommands <ComandoAtacar>();
            Comandos.RegisterCommands <ComandoMochila>();
            Comandos.RegisterCommands <ComandoMinerar>();
            Comandos.RegisterCommands <ComandoCortar>();
            Comandos.RegisterCommands <ComandoExaminar>();
            Comandos.RegisterCommands <ComandoViajar>();
            Comandos.RegisterCommands <ComandoMercado>();
            Comandos.RegisterCommands <ComandoItemUsar>();
            Comandos.RegisterCommands <ComandoItemComprar>();
            Comandos.RegisterCommands <ComandoItemVender>();
            //Comandos.RegisterCommands<ComandoItemEquipar>();
            //Comandos.RegisterCommands<ComandoItemDesequipar>();
            //Comandos.RegisterCommands<DesequiparComando>();
            //Comandos.RegisterCommands<ReceitaComando>();
        }
Exemplo n.º 15
0
        internal async Task RunAsync(Configuration configuration, int shardId, int shardCount, string dbPath)
        {
            LogLevel level;

            switch (configuration.LogLevel.ToLower())
            {
            case "debug":
                level = LogLevel.Debug;
                break;

            case "warning":
                level = LogLevel.Warning;
                break;

            case "error":
                level = LogLevel.Error;
                break;

            case "critical":
                level = LogLevel.Critical;
                break;

            default:
                level = LogLevel.Info;
                break;
            }

            client = new DiscordClient(new DiscordConfiguration
            {
                AutoReconnect         = true,
                LogLevel              = level,
                Token                 = configuration.Token,
                TokenType             = TokenType.Bot,
                ShardCount            = shardCount,
                ShardId               = shardId,
                UseInternalLogHandler = true
            });

            Events.supportGuildId = configuration.SupportId;

            client.Ready          += Events.OnClientReady;
            client.Resumed        += Events.OnClientResumed;
            client.ClientErrored  += Events.OnClientError;
            client.SocketErrored  += Events.OnClientSocketError;
            client.GuildAvailable += Events.OnGuildJoin;
            client.GuildCreated   += Events.OnGuildJoin;
            client.GuildDeleted   += Events.OnGuildLeave;

            client.MessageCreated += AFK.AFKMessageHandler;

            client.MessageReactionAdded        += Starboard.ReactionAddHandler;
            client.MessageReactionRemoved      += Starboard.ReactionRemoveHandler;
            client.MessageReactionRemovedEmoji += Starboard.ReactionRemoveEmojiHandler;
            client.MessageReactionsCleared     += Starboard.ReactionRemoveAllHandler;

            commands = client.UseCommandsNext(new CommandsNextConfiguration
            {
                CaseSensitive        = true,
                EnableDefaultHelp    = true,
                EnableDms            = true,
                EnableMentionPrefix  = true,
                IgnoreExtraArguments = true,
                StringPrefixes       = configuration.Prefixes,
            });

            commands.SetHelpFormatter <Help>();

            commands.CommandExecuted += Events.OnCommandExecute;
            commands.CommandErrored  += Events.OnCommandError;

            commands.RegisterCommands <Fun>();
            commands.RegisterCommands <Info>();
            commands.RegisterCommands <Moderation>();
            commands.RegisterCommands <NSFW>();
            commands.RegisterCommands <Owner>();
            commands.RegisterCommands <Search>();
            //commands.RegisterCommands<Settings>();

            client.UseInteractivity(new InteractivityConfiguration
            {
                PaginationBehaviour = PaginationBehaviour.Ignore,
                PaginationDeletion  = PaginationDeletion.DeleteEmojis,
                PollBehaviour       = PollBehaviour.DeleteEmojis
            });

            IMDb.InitializeWithKey(configuration.OMDb);
            Managers.Google.InitializeService(configuration.Google.Key, configuration.Google.Cx);

            await Spotify.AuthorizeAsync(configuration.Spotify.ID, configuration.Spotify.Secret, client.DebugLogger);

            await Database.ConnectAsync(dbPath, client.DebugLogger);

            garbage = new GarbageCollection();

            AppDomain.CurrentDomain.ProcessExit += new EventHandler((s, e) => HandleProcessQuit().GetAwaiter().GetResult());

            Emojis.Initialize(configuration.Emojis.Success,
                              configuration.Emojis.Warning,
                              configuration.Emojis.Error,
                              configuration.Emojis.Online,
                              configuration.Emojis.Idle,
                              configuration.Emojis.DoNotDisturb,
                              configuration.Emojis.Offline);

            await client.ConnectAsync(new DiscordActivity(configuration.Status.Name, configuration.Status.Type));

            await Task.Delay(-1);
        }
Exemplo n.º 16
0
        private async Task Login()
        {
            _logger.Information("Initializing the client setup...");
            var activity = new DiscordActivity("ur mom is pretty gae", ActivityType.Custom);

            _client = new DiscordShardedClient(new DiscordConfiguration
            {
                Token                   = _token,
                TokenType               = TokenType.Bot,
                DateTimeFormat          = "dd-MM-yyyy HH:mm",
                AutoReconnect           = true,
                MessageCacheSize        = 4096,
                ReconnectIndefinitely   = true,
                HttpTimeout             = Timeout.InfiniteTimeSpan,
                GatewayCompressionLevel = GatewayCompressionLevel.Payload
            });

            _logger.Information("Successfully setup the client.");
            _logger.Information("Setting up all configurations...");

            var ccfg = new CommandsNextConfiguration
            {
                Services            = _serviceProvider,
                PrefixResolver      = PrefixResolverAsync,
                EnableMentionPrefix = false,
                EnableDms           = true,
                DmHelp            = true,
                EnableDefaultHelp = true
            };

            _logger.Information("Commands configuration setup done.");

            var icfg = new InteractivityConfiguration
            {
                PollBehaviour = PollBehaviour.KeepEmojis,
                Timeout       = TimeSpan.FromMinutes(2)
            };

            _logger.Information("Interactivity configuration setup done.");
            _logger.Information("Connecting all shards...");
            await _client.StartAsync().ConfigureAwait(true);

            await _client.UpdateStatusAsync(activity, UserStatus.Online).ConfigureAwait(true);

            _logger.Information("Setting up client event handler...");
            _clientEventHandler = new ClientEventHandler(_client, _logger, _redis, _reactionListener);

            foreach (var shard in _client.ShardClients.Values)
            {
                _logger.Information($"Applying configs to shard {shard.ShardId}...");
                _cnext = shard.UseCommandsNext(ccfg);
                _cnext.RegisterCommands(Assembly.GetEntryAssembly());
                _cnext.SetHelpFormatter <HelpFormatter>();
                shard.UseInteractivity(icfg);
                _logger.Information($"Settings up command event handler for the shard {shard.ShardId}...");
                _commandEventHandler = new CommandEventHandler(_cnext, _logger);
                _logger.Information($"Setup for shard {shard.ShardId} done.");
                await shard.InitializeAsync();
            }

            foreach (var cNextRegisteredCommand in _cnext.RegisteredCommands)
            {
                _logger.Information($"{cNextRegisteredCommand.Value} is registered!");
            }
        }
Exemplo n.º 17
0
        public async Task RunAsync()
        {
            Log.Logger = new LoggerConfiguration()
                         .WriteTo.Console()
                         .MinimumLevel.Debug()
                         .CreateLogger();

            var logFactory = new LoggerFactory().AddSerilog();
            var config     = new DiscordConfiguration
            {
                Token         = Configuration.Token,
                TokenType     = TokenType.Bot,
                AutoReconnect = true,
                LoggerFactory = logFactory,
                Intents       = DiscordIntents.All
            };

            Client = new DiscordClient(config);

            Client.Ready          += OnClientReady;
            Client.MessageCreated += OnMessage;

            Client.UseInteractivity(new InteractivityConfiguration
            {
                Timeout            = TimeSpan.FromMinutes(5),
                PollBehaviour      = PollBehaviour.KeepEmojis,
                PaginationDeletion = PaginationDeletion.DeleteMessage
            });

            Services = new ServiceCollection()
                       .AddDbContext <MUNContext>()
                       .AddSingleton(this)
                       .AddSingleton(Configuration)
                       .AddSingleton <Guilds>()
                       .AddSingleton <ProfanityFilterService>()
                       .AddSingleton <PollService>()
                       .BuildServiceProvider();

            var commandsConfig = new CommandsNextConfiguration
            {
                StringPrefixes      = new string[] { Configuration.Prefix },
                EnableMentionPrefix = true,
                EnableDms           = false,
                Services            = Services
            };

            Commands = Client.UseCommandsNext(commandsConfig);

            Commands.SetHelpFormatter <MUNHelp>();

            Commands.RegisterConverter(new ChitConverter());

            Commands.RegisterCommands <ConfigurationModule>();
            Commands.RegisterCommands <GeneralModule>();
            Commands.RegisterCommands <TimerModule>();
            Commands.RegisterCommands <ModerationModule>();
            Commands.RegisterCommands <CountryModule>();
            Commands.RegisterCommands <MotionModule>();
            Commands.RegisterCommands <PointsModule>();

            Commands.CommandErrored += OnError;

            await Client.ConnectAsync();

            await Task.Delay(-1);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Initialise the bot and keep it running
        /// </summary>
        public async Task Run()
        {
            // Set proper TLS settings
            ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

            // Check for a token
            string tokenPath = @"token.txt";

            if (!File.Exists(tokenPath))
            {
                Console.WriteLine("Please create a file called \"token.txt\" before running the bot!");
                Console.WriteLine("[Press any key to exit...]");
                Console.ReadKey();
                Environment.Exit(0);
            }
            Token = File.ReadAllText(tokenPath, Encoding.Default);

            // Get JSON config file
            Config.Init();

            // Initialise Discord client
            Client = new DiscordClient(new DiscordConfiguration()
            {
                AutoReconnect   = true,
                LargeThreshold  = 250,
                MinimumLogLevel = LogLevel.Information,
                Token           = Token,
                TokenType       = TokenType.Bot,
            });

            // Initialise events
            LogMessage($"DiscordWikiBot, version {Version}");

            // Get default locale
            Locale.Init();

            // Get site information and start linking bot
            LogMessage("Getting wiki site information");
            Linking.Init();

            // Methods for linking bot
            Client.MessageCreated += (s, e) =>
            {
                Task.Run(async() =>
                {
                    await Linking.Answer(s, e);
                });

                return(Task.CompletedTask);
            };
            Client.MessageUpdated += (s, e) =>
            {
                Task.Run(async() =>
                {
                    await Linking.Edit(s, e);
                });

                return(Task.CompletedTask);
            };
            Client.MessageDeleted      += Linking.Delete;
            Client.MessagesBulkDeleted += Linking.BulkDelete;

            // Start EventStreams
            if (Config.GetDomain() != null)
            {
                EventStreams.Init();
            }

            // Start Translatewiki fetches
            if (Config.GetTWChannel() != null && Config.GetTWLang() != null)
            {
                TranslateWiki.Init();
            }

            // Set some events for logging the information
            Client.Ready          += Client_Ready;
            Client.GuildAvailable += Client_GuildAvailable;
            Client.GuildCreated   += Client_GuildCreated;
            Client.GuildDeleted   += Client_GuildDeleted;
            Client.ClientErrored  += Client_ClientErrored;

            // Initialise commands
            LogMessage("Setting up commands");
            Commands = Client.UseCommandsNext(new CommandsNextConfiguration
            {
                StringPrefixes      = new[] { Config.GetValue("prefix") },
                EnableDms           = false,
                EnableMentionPrefix = true,
            });

            Commands.RegisterCommands <Pinging>();

            Commands.RegisterCommands <Configuring>();

            if (EventStreams.Enabled)
            {
                Commands.RegisterCommands <Streaming>();
            }

            // Set up custom formatter
            Commands.SetHelpFormatter <LocalisedHelpFormatter>();

            // Connect and start
            LogMessage("Connecting...");
            await Client.ConnectAsync();

            // Make sure not to close down automatically
            await CtrlC();
        }
Exemplo n.º 19
0
        public async Task RunAsync()
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .WriteTo.Console(theme: SystemConsoleTheme.Grayscale)
                         .CreateLogger();

            var logFactory = new LoggerFactory().AddSerilog();
            var config     = new DiscordConfiguration
            {
                Token           = configuration.Token,
                TokenType       = TokenType.Bot,
                AutoReconnect   = true,
                MinimumLogLevel = LogLevel.Debug,
                LoggerFactory   = logFactory,
                Intents         = DiscordIntents.All
            };

            Client = new DiscordClient(config);

            Client.Ready          += OnClientReady;
            Client.MessageCreated += OnMessage;

            Client.UseInteractivity(new InteractivityConfiguration
            {
                Timeout = TimeSpan.FromMinutes(5)
            });

            var services = new ServiceCollection()
                           .AddSingleton(this)
                           .AddDbContext <DisarisContext>()
                           .AddSingleton <Tags>()
                           .AddSingleton <HttpClient>()
                           .AddSingleton(configuration)
                           .BuildServiceProvider();


            var commandsConfig = new CommandsNextConfiguration
            {
                StringPrefixes      = new string[] { configuration.Prefix },
                EnableMentionPrefix = true,
                EnableDms           = false,
                Services            = services
            };

            Commands = Client.UseCommandsNext(commandsConfig);

            Commands.SetHelpFormatter <DisarisHelp>();

            Commands.CommandErrored += OnError;

            Commands.RegisterCommands <General>();
            Commands.RegisterCommands <TagModule>();
            Commands.RegisterCommands <AddModule>();
            Commands.RegisterCommands <Carbon>();
            Commands.RegisterCommands <DnD>();
            Commands.RegisterCommands <StatTracker>();
            Commands.RegisterCommands <RotationTracker>();

            await Client.ConnectAsync();

            await Task.Delay(-1);
        }
Exemplo n.º 20
0
        public async Task RunBotAsync()
        {
            var service = new BotServices();

            service.LoadBotConfiguration();

            Client = new DiscordClient(new DiscordConfiguration
            {
                Token                   = TokenHandler.Tokens.DiscordToken,
                TokenType               = TokenType.Bot,
                AutoReconnect           = true,
                LogLevel                = LogLevel.Info,
                UseInternalLogHandler   = false,
                GatewayCompressionLevel = GatewayCompressionLevel.Stream,
                LargeThreshold          = 250
            });
            Client.Ready         += Client_Ready;
            Client.ClientErrored += Client_ClientError;
            Client.DebugLogger.LogMessageReceived += Client_LogMessageHandler;
            Client.UseInteractivity(new InteractivityConfiguration
            {
                PaginationBehaviour = PaginationBehaviour.Ignore, // Default pagination behavior to just ignore the reactions
                Timeout             = TimeSpan.FromMinutes(2)     // Default pagination timeout to 2 minutes
            });

            Commands = Client.UseCommandsNext(new CommandsNextConfiguration
            {
                PrefixResolver      = PrefixResolverAsync, // Set the command prefix that will be used by the bot
                EnableDms           = false,               // Set the boolean for responding to direct messages
                EnableMentionPrefix = true,                // Set the boolean for mentioning the bot as a command prefix
                CaseSensitive       = false,
            });
            Commands.CommandExecuted += Commands_CommandExecuted;
            Commands.CommandErrored  += Commands_CommandErrored;
            Commands.RegisterCommands <BotModule>();
            Commands.RegisterCommands <ServerModule>();
            Commands.RegisterCommands <ChannelModule>();
            Commands.RegisterCommands <RoleModule>();
            Commands.RegisterCommands <UserModule>();
            //Commands.RegisterCommands<AmiiboModule>();
            //Commands.RegisterCommands<DictionaryModule>();
            //Commands.RegisterCommands<EmojiModule>();
            //Commands.RegisterCommands<GoodReadsModule>();
            //Commands.RegisterCommands<GoogleModule>();
            //Commands.RegisterCommands<ImgurModule>();
            //Commands.RegisterCommands<MathModule>();
            //Commands.RegisterCommands<MiscModule>();
            //Commands.RegisterCommands<NASAModule>();
            //Commands.RegisterCommands<OMDBModule>();
            //Commands.RegisterCommands<PokemonModule>();
            //Commands.RegisterCommands<PollModule>();
            //Commands.RegisterCommands<RedditModule>();
            //Commands.RegisterCommands<SimpsonsModule>();
            //Commands.RegisterCommands<SpeedrunModule>();
            //Commands.RegisterCommands<SteamModule>();
            //Commands.RegisterCommands<TeamFortressModule>();
            //Commands.RegisterCommands<TwitchModule>();
            //Commands.RegisterCommands<WikipediaModule>();
            //Commands.RegisterCommands<YouTubeModule>();
            Commands.RegisterCommands <YoutubeBotCommands>();
            Commands.SetHelpFormatter <HelpFormatter>();

            // Start the uptime counter
            Console.Title             = SharedData.Name + " (" + SharedData.Version + ")";
            SharedData.ProcessStarted = DateTime.Now;
            //await SteamService.UpdateSteamListAsync().ConfigureAwait(false);
            //await TeamFortressService.UpdateTF2SchemaAsync().ConfigureAwait(false);
            //await PokemonService.UpdatePokemonListAsync().ConfigureAwait(false);
            await Client.ConnectAsync().ConfigureAwait(false); // Connect and log into Discord

            await Task.Delay(-1).ConfigureAwait(false);        // Prevent the console window from closing
        }
Exemplo n.º 21
0
        private async Task MainAsync()
        {
            // getting versions and assembly info
            SetBotVersionInfo();

            // init log channels
            _logChannels    = new List <DiscordChannel>();
            _lastLogChWrite = File.GetLastWriteTime("logchannels.txt");

            string json = await FileHandler.ReadJsonConfig();

            if (json.Length == 0)
            {
                return;
            }
            if (json == "default")
            {
                Console.ForegroundColor = ConsoleColor.DarkGreen;
                Console.WriteLine("Created default config file.\n" +
                                  "Now you need to get your discord bot token " +
                                  "and put it in config.json file.\n" +
                                  "Also make sure you set other parameters.");
                Console.ResetColor();
                return;
            }

            // setting up client
            var cfgjson = JsonSerializer.Deserialize <ConfigJson>(json);

            if (cfgjson == null)
            {
                return;
            }
            var cfg = new DiscordConfiguration
            {
                Token              = cfgjson.Token,
                TokenType          = TokenType.Bot,
                AutoReconnect      = true,
                MinimumLogLevel    = RuntimeInfo == "Debug" ? LogLevel.Debug : LogLevel.Information,
                MessageCacheSize   = 2048,
                LogTimestampFormat = "dd-MM-yyyy HH:mm:ss zzz"
            };

            // client init and event hooks
            _discord                         = new DiscordClient(cfg);
            _discord.Ready                  += Discord_Ready;
            _discord.GuildAvailable         += Discord_GuildAvailable;
            _discord.GuildUnavailable       += Discord_GuildUnavailable;
            _discord.GuildCreated           += Discord_GuildCreated;
            _discord.GuildDeleted           += Discord_GuildDeleted;
            _discord.ChannelDeleted         += Discord_ChannelDeleted;
            _discord.DmChannelDeleted       += Discord_DmChannelDeleted;
            _discord.GuildDownloadCompleted += Discord_GuildDownloadCompleted;
            _discord.ClientErrored          += Discord_ClientErrored;
            _discord.SocketClosed           += Discord_SocketClosed;
            _discord.Resumed                += Discord_Resumed;
            _discord.Heartbeated            += Discord_Heartbeated;

            // setting up interactivity
            var intcfg = new InteractivityConfiguration
            {
                Timeout            = TimeSpan.FromMinutes(cfgjson.ActTimeout),
                PaginationDeletion = PaginationDeletion.DeleteMessage,
                PollBehaviour      = PollBehaviour.KeepEmojis
            };

            _discord.UseInteractivity(intcfg);

            // setting up commands
            var cmdcfg = new CommandsNextConfiguration
            {
                StringPrefixes = new List <string> {
                    cfgjson.CommandPrefix
                },
                EnableDms           = cfgjson.DmsEnabled,
                EnableMentionPrefix = cfgjson.MentionEnabled,
                CaseSensitive       = cfgjson.CaseSensitive,
                EnableDefaultHelp   = true
            };

            // commands hooks and register
            _commands = _discord.UseCommandsNext(cmdcfg);
            _commands.CommandExecuted += Commands_CommandExecuted;
            _commands.CommandErrored  += Commands_CommandErrored;
            _commands.RegisterCommands <Commands.Commands>();
            _commands.RegisterCommands <LeetCommands>();
            _commands.RegisterCommands <Interactivities.Interactivities>();
            _commands.RegisterCommands <Administrative>();
            _commands.RegisterCommands <Cats>();
            _commands.RegisterCommands <DiceRolling>();
            _commands.RegisterCommands <CryptoAes>();
            _commands.RegisterCommands <CryptoRsa>();
            _commands.RegisterCommands <MathCommands>();
            _commands.RegisterCommands <StatusCommands>();
            _commands.RegisterCommands <VoiceCommands>();
            // adding math converter for custom type and name
            var mathopscvrt = new MathOperationConverter();

            _commands.RegisterConverter(mathopscvrt);
            _commands.RegisterUserFriendlyTypeName <MathOperation>("operator");

            // setting up and enabling voice
            var vcfg = new VoiceNextConfiguration
            {
                AudioFormat    = AudioFormat.Default,
                EnableIncoming = false
            };

            _discord.UseVoiceNext(vcfg);

            // setting custom help formatter
            _commands.SetHelpFormatter <HelpFormatter>();

            // init twitch live and youtube video monitors
            _ttvApIclid   = cfgjson.TwitchApiClid;
            _ttvApIsecret = cfgjson.TwitchApiSecret;
            _ytApIkey     = cfgjson.YoutubeApiKey;
            _tlm          = new TwitchLiveMonitor();
            _yvm          = new YoutubeVideoMonitor();

            // getting aes and rsa keys from config
            AesKey        = cfgjson.AesKey;
            AesIv         = cfgjson.AesIv;
            RsaPublicKey  = cfgjson.RsaPublicKey;
            RsaPrivateKey = cfgjson.RsaPrivateKey;

            // connecting discord
            try
            {
                await _discord.ConnectAsync();
            }
            catch (Exception e)
            {
                _discord.Logger.LogCritical($"{e.Message}");
                return;
            }

            await Task.Delay(-1);
        }
Exemplo n.º 22
0
        private async Task Login()
        {
            this.logger.Information("Initializing the client setup...");

            client = new DiscordShardedClient(new DiscordConfiguration
            {
                Token                   = config.Token,
                TokenType               = TokenType.Bot,
                LogTimestampFormat      = "dd-MM-yyyy HH:mm",
                AutoReconnect           = true,
                MessageCacheSize        = 4096,
                HttpTimeout             = Timeout.InfiniteTimeSpan,
                GatewayCompressionLevel = GatewayCompressionLevel.Stream
            });

            this.logger.Information("Successfully setup the client.");
            this.logger.Information("Setting up all configurations...");

            var ccfg = new CommandsNextConfiguration
            {
                Services            = serviceProvider,
                PrefixResolver      = PrefixResolverAsync,
                EnableMentionPrefix = true,
                EnableDms           = true,
                DmHelp                   = false,
                EnableDefaultHelp        = true,
                UseDefaultCommandHandler = true
            };

            this.logger.Information("Commands configuration setup done.");

            var icfg = new InteractivityConfiguration {
                PollBehaviour = PollBehaviour.KeepEmojis, Timeout = TimeSpan.FromMinutes(2)
            };

            this.logger.Information("Interactivity configuration setup done.");
            this.logger.Information("Connecting all shards...");
            await client.StartAsync()
            .ConfigureAwait(true);

            this.logger.Information("Setting up client event handler...");
            clientEventHandler = new ClientEventHandler(client, logger, redis, reactionService, logService);

            foreach (var shard in client.ShardClients.Values)
            {
                logger.Information($"Applying configs to shard {shard.ShardId}...");
                commandsNext = shard.UseCommandsNext(ccfg);
                commandsNext.RegisterCommands(typeof(Modules.Dummy).Assembly);
                commandsNext.SetHelpFormatter <HelpFormatter>();
                shard.UseInteractivity(icfg);
                this.logger.Information($"Settings up command event handler for the shard {shard.ShardId}...");
                commandEventHandler = new CommandEventHandler(commandsNext, logger);
                this.logger.Information($"Setup for shard {shard.ShardId} done.");
                await shard.InitializeAsync().ConfigureAwait(true);
            }

            foreach (var cNextRegisteredCommand in commandsNext.RegisteredCommands)
            {
                this.logger.Information($"{cNextRegisteredCommand.Value} is registered!");
            }
        }