Beispiel #1
0
        public async Task RunAsync()
        {
            var json  = string.Empty;
            var json1 = string.Empty;
            var json2 = string.Empty;

            using (var fs = File.OpenRead("AllTheLogin.json")) {
                using (var sr = new StreamReader(fs, new UTF8Encoding(false))) {
                    json = await sr.ReadToEndAsync().ConfigureAwait(false);
                }
            }
            using (var fs = File.OpenRead("AvatarHashes.json")) {
                using (var sr = new StreamReader(fs, new UTF8Encoding(false))) {
                    json1 = await sr.ReadToEndAsync().ConfigureAwait(false);
                }
            }
            using (var fs = File.OpenRead("AllTheStatus.json")) {
                using (var sr = new StreamReader(fs, new UTF8Encoding(false))) {
                    json2 = await sr.ReadToEndAsync().ConfigureAwait(false);
                }
            }

            loginJson  = JsonConvert.DeserializeObject <LoginInfo>(json);
            bigJson    = JsonConvert.DeserializeObject <AH>(json1);
            statusJson = JsonConvert.DeserializeObject <SS>(json2);

            ftpClient = new FtpClient(loginJson.hostName, 21, loginJson.userName, loginJson.passWord);

            var config0 = new DiscordConfiguration {
                Token         = loginJson.botToken,
                AutoReconnect = true,
                TokenType     = TokenType.Bot,
                Intents       = DiscordIntents.All
            };

            discord = new DiscordClient(config0);

            SlashCommandsExtension commands = discord.UseSlashCommands();

            commands.RegisterCommands <SVCommands>();

            avatarEmbed = new DiscordEmbedBuilder {
                Title = "Avatar Update!"
            };

            discord.GuildMemberUpdated += MemberUpdated;


            await discord.ConnectAsync();

            discord.Ready += BotReady;
            await Task.Delay(-1);
        }
Beispiel #2
0
        public async Task RunAsync()
        {
            ReadConfig.Read();
            var  varrepo = new VariableRepository(ReadConfig.Config.ConnectionString);
            bool result;

#if DEBUG
            result = varrepo.Read(3, out Variable prefix);             //get testPrefix if in designmode
#else
            result = varrepo.Read(2, out Variable prefix);             //otherwise get default prefix
#endif
            DiscordConfiguration config = new DiscordConfiguration
            {
                Token         = ReadConfig.Config.Token,
                TokenType     = TokenType.Bot,
                AutoReconnect = true,
#if DEBUG
                MinimumLogLevel = Microsoft.Extensions.Logging.LogLevel.Debug,
#endif
                Intents = DiscordIntents.All
            };

            Client = new DiscordClient(config);

            //Register client events
            Client.Ready += Events.OnClientReady;
            Client.GuildDownloadCompleted      += Events.Client_GuildDownloadCompleted;
            Client.MessageCreated              += Events.MessageCreated;
            Client.MessageUpdated              += Events.MessageUpdated;
            Client.MessageDeleted              += Events.MessageDeleted;
            Client.GuildMemberAdded            += Events.MemberAdded;
            Client.MessageReactionAdded        += Events.ReactionAdded;
            Client.MessageReactionRemoved      += Events.ReactionRemoved;
            Client.VoiceStateUpdated           += Events.VoiceStateUpdated;
            Client.ClientErrored               += Events.ClientErrored;
            Client.ComponentInteractionCreated += Events.ComponentTriggered;

            //Register client events for logging
            Client.GuildBanAdded       += Logger.BanAdded;
            Client.GuildBanRemoved     += Logger.BanRemoved;
            Client.GuildMemberUpdated  += Logger.MemberUpdated;
            Client.ChannelUpdated      += Logger.ChannelUpdated;
            Client.GuildRoleUpdated    += Logger.RoleUpdated;
            Client.MessageUpdated      += Logger.MessageEdited;
            Client.MessageDeleted      += Logger.MessageDeleted;
            Client.MessagesBulkDeleted += Logger.BulkMessagesDeleted;
            //Client.GuildEmojisUpdated += Logger.EmojiUpdated;
            Client.VoiceStateUpdated += Logger.VoiceUpdate;


            //Register timer events
            SystemService.Instance.WarnTimer.Elapsed += Events.TimerTick;

            //Register Logger events
            SystemService.Instance.Logger.RaiseLogEvent += Events.OnLog;

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

            CommandsNextConfiguration commandsConfig = new CommandsNextConfiguration
            {
                StringPrefixes      = new string[] { prefix.Value },
                EnableMentionPrefix = true
            };
            Commands = Client.UseCommandsNext(commandsConfig);

            //Register commands
            Commands.RegisterCommands <AuditCommands>();
            Commands.RegisterCommands <EmbedCommands>();
            Commands.RegisterCommands <InfoCommands>();
            Commands.RegisterCommands <LavalinkCommands>();
            Commands.RegisterCommands <ReactionCommands>();
            Commands.RegisterCommands <RuleCommands>();
            Commands.RegisterCommands <TechnicalCommands>();
            Commands.RegisterCommands <WarnCommands>();
            Commands.RegisterCommands <EventCommands>();

            //Register command events
            Commands.CommandErrored += Events.CommandErrored;

            SlashCommands = Client.UseSlashCommands();

            //Register interactions
            SlashCommands.RegisterCommands <WarnInteractions>(699555747591094344);

            //Register interaction events
            SlashCommands.ContextMenuErrored += Events.ContextMenuErrored;

            await Client.ConnectAsync();

            LavalinkNodeConnection lavaNode = null;
            lavaNode = await ConnectLavaNodeAsync();

            if (lavaNode != null)
            {
                //Register lava commands
                lavaNode.PlaybackFinished += Events.PlaybackFinished;
            }

            await Task.Delay(-1);
        }
Beispiel #3
0
        private async Task RestartBot(DiscordSettings previousSettings, DiscordSettings newSettings, HashSet <ulong> currentGuilds)
        {
            if (!string.IsNullOrEmpty(newSettings.BotToken))
            {
                if (!string.Equals(previousSettings.BotToken, newSettings.BotToken, StringComparison.OrdinalIgnoreCase))
                {
                    if (_client != null)
                    {
                        await _client.DisconnectAsync();

                        _client.Ready -= Connected;
                        _client.ComponentInteractionCreated -= DiscordComponentInteractionCreatedHandler;
                        _client.Dispose();
                    }

                    if (_slashCommands != null)
                    {
                        _slashCommands.SlashCommandErrored -= SlashCommandErrorHandler;
                    }

                    var config = new DiscordConfiguration()
                    {
                        Token                 = newSettings.BotToken,
                        TokenType             = TokenType.Bot,
                        AutoReconnect         = true,
                        MinimumLogLevel       = LogLevel.Warning,
                        Intents               = DiscordIntents.All,
                        ReconnectIndefinitely = true
                    };

                    _client = new DiscordClient(config);

                    _slashCommands = _client.UseSlashCommands(new SlashCommandsConfiguration
                    {
                        Services = new ServiceCollection()
                                   .AddSingleton <DiscordClient>(_client)
                                   .AddSingleton <ILogger>(_logger)
                                   .AddSingleton <DiscordSettingsProvider>(_discordSettingsProvider)
                                   .AddSingleton <MovieWorkflowFactory>(_movieWorkflowFactory)
                                   .AddSingleton <TvShowWorkflowFactory>(_tvShowWorkflowFactory)
                                   .BuildServiceProvider()
                    });

                    _slashCommands.SlashCommandErrored += SlashCommandErrorHandler;

                    _client.Ready += Connected;
                    _client.ComponentInteractionCreated += DiscordComponentInteractionCreatedHandler;

                    _currentGuilds = new HashSet <ulong>();
                    await _client.ConnectAsync();
                }

                if (_client != null)
                {
                    if (_client.Guilds.Any())
                    {
                        await ApplyBotConfigurationAsync(newSettings);

                        var prop = _slashCommands.GetType().GetProperty("_updateList", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                        prop.SetValue(_slashCommands, new List <KeyValuePair <ulong?, Type> >());

                        var slashCommandType = SlashCommandBuilder.Build(_logger, newSettings, _serviceProvider.Get <RadarrSettingsProvider>(), _serviceProvider.Get <SonarrSettingsProvider>(), _serviceProvider.Get <OverseerrSettingsProvider>());

                        if (newSettings.EnableRequestsThroughDirectMessages)
                        {
                            try { _slashCommands.RegisterCommands(slashCommandType); }
                            catch (System.Exception ex) { _logger.LogError(ex, "Error while registering global slash commands: " + ex.Message); }

                            foreach (var guildId in _client.Guilds.Keys)
                            {
                                try { _slashCommands.RegisterCommands <EmptySlashCommands>(guildId); }
                                catch (System.Exception ex) { _logger.LogError(ex, $"Error while emptying guild-specific slash commands for guid {guildId}: " + ex.Message); }
                            }
                        }
                        else
                        {
                            try { _slashCommands.RegisterCommands <EmptySlashCommands>(); }
                            catch (System.Exception ex) { _logger.LogError(ex, "Error while emptying global slash commands: " + ex.Message); }

                            foreach (var guildId in _client.Guilds.Keys)
                            {
                                try { _slashCommands.RegisterCommands(slashCommandType, guildId); }
                                catch (System.Exception ex) { _logger.LogError(ex, $"Error while registering guild-specific slash commands for guid {guildId}: " + ex.Message); }
                            }
                        }

                        await _slashCommands.RefreshCommands();

                        await Task.Delay(TimeSpan.FromMinutes(1));
                    }
                }
                else
                {
                    _logger.LogWarning("No Bot Token for Discord has been configured.");
                }
            }
        }