예제 #1
0
        void OnSettingsClosed(object sender, EventArgs e)
        {
            DiscordSettings settings = (DiscordSettings)sender;

            SetToken(settings.BotToken);
            chatchannel = settings.ChatChannel;
        }
예제 #2
0
        private async Task <Response> SaveDiscordNotifications()
        {
            var settings = this.BindAndValidate <DiscordNotificationSettings>();

            if (!ModelValidationResult.IsValid)
            {
                return(Response.AsJson(ModelValidationResult.SendJsonError()));
            }

            var result = await DiscordSettings.SaveSettingsAsync(settings);

            if (settings.Enabled)
            {
                NotificationService.Subscribe(new DiscordNotification(DiscordApi, DiscordSettings));
            }
            else
            {
                NotificationService.UnSubscribe(new DiscordNotification(DiscordApi, DiscordSettings));
            }

            Log.Info("Saved discord settings, result: {0}", result);
            return(Response.AsJson(result
                ? new JsonResponseModel {
                Result = true, Message = "Successfully Updated the Settings for Discord Notifications!"
            }
                : new JsonResponseModel {
                Result = false, Message = "Could not update the settings, take a look at the logs."
            }));
        }
예제 #3
0
 public CommandHandler(DiscordSocketClient client, CommandService commands, IServiceProvider serviceProvider, IOptions <DiscordSettings> options)
 {
     _client          = client;
     _commands        = commands;
     _serviceProvider = serviceProvider;
     _options         = options.Value;
 }
예제 #4
0
        private async Task MainAsync()
        {
            LoggerSetup.SetupLog();

            _client   = new DiscordSocketClient();
            _commands = new CommandService();

            var configBuilder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("appsettings.json", false, true);
            var configuration = configBuilder.Build();

            await InstallCommandsAsync(configuration);

            _logger = LogManager.GetCurrentClassLogger();

            _client.Log += Log;

            var discordSettings = new DiscordSettings();

            configuration.Bind("Discord", discordSettings);

            await _client.LoginAsync(Discord.TokenType.Bot, discordSettings.Token);

            await _client.StartAsync();

            var chronoGgService = _services.GetService <ChronoGgService>();
            await chronoGgService.StartService();

            var mehService = _services.GetRequiredService <MehService>();
            await mehService.StartService();

            _logger.Debug("Bot running at {0}", DateTime.Now);

            await Task.Delay(-1);
        }
예제 #5
0
 public RequestrrModuleBase(DiscordSocketClient discord, SocketCommandContext commandContext, DiscordSettingsProvider discordSettingsProvider)
 {
     _discord                = discord;
     Context                 = commandContext;
     _discordSettings        = discordSettingsProvider.Provide();
     _discord.ReactionAdded += HandleReactionAsync;
 }
예제 #6
0
 public DiscordService(CommandHandlingService commandHandlingService, DiscordSocketClient client, IOptions <DiscordSettings> discordSettings, IServiceProvider serviceProvider, ILogger <DiscordService> logger)
 {
     _commandHandlingService = commandHandlingService;
     _client          = client;
     _logger          = logger;
     _discordSettings = discordSettings.Value;
 }
 /// <summary>
 /// Instantiates a new instance of the <see cref="ModerationBackgroundService"/> class.
 /// </summary>
 /// <param name="sp">The service provider.</param>
 /// <param name="logger">The logger.</param>
 /// <param name="colourPalette">The colour palette.</param>
 /// <param name="discordSettings">The Discord settings.</param>
 public ModerationBackgroundService(IServiceProvider sp, ILogger <ModerationBackgroundService> logger, IColourPalette colourPalette, DiscordSettings discordSettings)
 {
     _sp              = sp;
     _logger          = logger;
     _colourPalette   = colourPalette;
     _discordSettings = discordSettings;
 }
예제 #8
0
        private void TryToStart()
        {
            var token = Config["Token"].ToString();

            if (token == "")
            {
                PrintError("Discord token is not setup!");
                return;
            }
            var settings = new DiscordSettings {
                ApiToken = token
            };

            _client.Connect(settings);
            _status.Activities = new List <DiscordActivity>
            {
                _activity
            };
            var updateInterval = float.Parse(Config["UpdateInterval"].ToString());

            timer.Every(updateInterval, () =>
            {
                _activity.Name = string.Format(Config["Status"].ToString(), server.Players, server.MaxPlayers);
                _activity.Type = ActivityType.Game;
                _client?.Bot?.UpdateStatus(_status);
            });
        }
예제 #9
0
        public ChatClientsSettings Provide()
        {
            dynamic settings = SettingsFile.Read();

            var discordSettings = new DiscordSettings
            {
                BotToken          = (string)settings.ChatClients.Discord.BotToken,
                ClientId          = (string)settings.ChatClients.Discord.ClientId,
                StatusMessage     = (string)settings.ChatClients.Discord.StatusMessage,
                MonitoredChannels = settings.ChatClients.Discord.MonitoredChannels.ToObject <string[]>(),
                TvShowRoles       = settings.ChatClients.Discord.TvShowRoles.ToObject <string[]>(),
                MovieRoles        = settings.ChatClients.Discord.MovieRoles.ToObject <string[]>(),
                EnableRequestsThroughDirectMessages = (bool)settings.ChatClients.Discord.EnableRequestsThroughDirectMessages,
                AutomaticallyNotifyRequesters       = (bool)settings.ChatClients.Discord.AutomaticallyNotifyRequesters,
                NotificationMode     = (string)settings.ChatClients.Discord.NotificationMode,
                NotificationChannels = settings.ChatClients.Discord.NotificationChannels.ToObject <string[]>(),
                AutomaticallyPurgeCommandMessages = (bool)settings.ChatClients.Discord.AutomaticallyPurgeCommandMessages,
            };

            return(new ChatClientsSettings
            {
                Discord = discordSettings,
                Language = settings.ChatClients.Language,
            });
        }
예제 #10
0
        private async Task ApplyBotConfigurationAsync(DiscordSettings discordSettings)
        {
            await _client.SetGameAsync(discordSettings.StatusMessage);

            _moduleInfo = await _commandService.CreateModuleAsync(string.Empty, x =>
            {
                x.AddCommand("ping", async(commandContext, noidea, serviceProvider, commandInfo) =>
                {
                    using (var command = new DiscordPingWorkFlow((SocketCommandContext)commandContext, _client, serviceProvider.Get <DiscordSettingsProvider>()))
                    {
                        await command.HandlePingAsync();
                    }
                }, c => c.WithName("ping").WithRunMode(RunMode.Async));

                x.AddCommand("help", async(commandContext, noidea, serviceProvider, commandInfo) =>
                {
                    using (var command = new DiscordHelpWorkFlow((SocketCommandContext)commandContext, _client, serviceProvider.Get <DiscordSettingsProvider>()))
                    {
                        await command.HandleHelpAsync();
                    }
                }, c => c.WithName("help").WithRunMode(RunMode.Async));

                if (discordSettings.MovieDownloadClient != DownloadClient.Disabled)
                {
                    x.AddCommand(discordSettings.MovieCommand, async(commandContext, message, serviceProvider, commandInfo) =>
                    {
                        using (var command = new DiscordMovieRequestingWorkFlow(
                                   (SocketCommandContext)commandContext,
                                   _client,
                                   GetMovieClient <IMovieSearcher>(discordSettings),
                                   GetMovieClient <IMovieRequester>(discordSettings),
                                   serviceProvider.Get <DiscordSettingsProvider>(),
                                   _movieNotificationRequestRepository))
                        {
                            await command.HandleMovieRequestAsync(message[0].ToString());
                        }
                    }, c => c.WithName("movie").WithSummary($"The correct usage of this command is: ```{discordSettings.CommandPrefix}{discordSettings.MovieCommand} name of movie```").WithRunMode(RunMode.Async).AddParameter <string>("movieName", p => p.WithIsRemainder(true).WithIsOptional(false)));
                }

                if (discordSettings.TvShowDownloadClient != DownloadClient.Disabled)
                {
                    x.AddCommand(discordSettings.TvShowCommand, async(commandContext, message, serviceProvider, commandInfo) =>
                    {
                        using (var command = new DiscordTvShowsRequestingWorkFlow(
                                   (SocketCommandContext)commandContext,
                                   _client,
                                   GetTvShowClient <ITvShowSearcher>(discordSettings),
                                   GetTvShowClient <ITvShowRequester>(discordSettings),
                                   serviceProvider.Get <DiscordSettingsProvider>(),
                                   _tvShowNotificationRequestRepository))
                        {
                            await command.HandleTvShowRequestAsync(message[0].ToString());
                        }
                    }, c => c.WithName("tv").WithSummary($"The correct usage of this command is: ```{discordSettings.CommandPrefix}{discordSettings.TvShowCommand} name of tv show```").WithRunMode(RunMode.Async).AddParameter <string>("tvShowName", p => p.WithIsRemainder(true).WithIsOptional(false)));
                }
            });
        }
예제 #11
0
        public async void Start()
        {
            _commandService = new CommandService(new CommandServiceConfig
            {
                CaseSensitiveCommands = false,
            });

            _client            = new DiscordSocketClient();
            _client.Log       += LogAsync;
            _client.Connected += Connected;
            _commandService.CommandExecuted += CommandExecutedAsync;
            _client.MessageReceived         += MessageReceivedAsync;

            Task.Run(async() =>
            {
                while (true)
                {
                    try
                    {
                        var newSettings = _discordSettingsProvider.Provide();
                        var mustRestart = false;

                        try
                        {
                            if (_client.ConnectionState == ConnectionState.Connected)
                            {
                                mustRestart = string.IsNullOrEmpty(_client.CurrentUser.Username);
                            }
                        }
                        catch
                        {
                            mustRestart = true;
                        }

                        if (mustRestart)
                        {
                            _logger.LogWarning("Restarting bot due to incorrect automatic reconnection.");
                        }

                        if (!_currentSettings.Equals(newSettings) || mustRestart || _client.ConnectionState == ConnectionState.Disconnected)
                        {
                            _logger.LogWarning("Bot configuration changed/not connected to Discord: restarting bot");
                            _currentSettings = newSettings;
                            await RestartBot(newSettings);
                            _logger.LogWarning("Bot has been restarted.");
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, "Error while restarting the bot: " + ex.Message);
                    }

                    await Task.Delay(5000);
                }
            });
        }
 /// <summary>
 /// Instantiates a new instance of <see cref="GuildCreatedResponder"/>.
 /// </summary>
 /// <param name="guildApi">The guild API.</param>
 /// <param name="discordSettings">The Discord settings.</param>
 /// <param name="logger">The logger.</param>
 public GuildCreatedResponder(
     IDiscordRestGuildAPI guildApi,
     DiscordSettings discordSettings,
     ILogger <GuildCreatedResponder> logger
     )
 {
     _guildApi        = guildApi;
     _discordSettings = discordSettings;
     _logger          = logger;
 }
 public Handler(
     MemberBotContext context,
     DiscordSettings config,
     ITcpCommunicationService tcpCommunicationService
     )
 {
     _context = context;
     _config  = config;
     _tcpCommunicationService = tcpCommunicationService;
 }
예제 #14
0
 public ApplicationsModule(
     ILogger <ApplicationsModule> logger,
     IMediator mediator,
     DiscordSettings config
     )
 {
     _logger   = logger;
     _mediator = mediator;
     _config   = config;
 }
예제 #15
0
        public DatabaseStorage(DiscordSettings discordSettings, ILogger <DatabaseStorage> logger)
        {
            var storagePath = discordSettings.StoragePath ?? new FileInfo(new Uri(Assembly.GetEntryAssembly() !.GetName() !.CodeBase !).AbsolutePath).Directory !.FullName;
            var builder     = new SqliteConnectionStringBuilder
            {
                DataSource = Path.Combine(storagePath, "polaris.db")
            };

            _connectionString = builder.ToString();
            _logger           = logger ?? throw new ArgumentNullException(nameof(logger));
        }
예제 #16
0
 public DiscordBotService
 (
     IDiscordClient discordClient,
     DiscordSettings settings,
     ILogger logger
 )
 {
     _discordClient = discordClient;
     this._settings = settings;
     _logger        = logger;
 }
        public WonderlandClient(DiscordSocketClient client, CommandHandler commandHandler, IOptions <DiscordSettings> settings, IMediator mediator)
        {
            Client          = client;
            _settings       = settings.Value;
            _commandHandler = commandHandler;
            _mediator       = mediator;

            Client.Log             += Log;
            Client.MessageReceived += Client_ReceivedMessage;
            Client.ReactionAdded   += Client_ReactionAdded;
        }
예제 #18
0
 public ErrorNotificationMiddleware(
     ILogger <ErrorNotificationMiddleware> logger,
     IDiscordRestChannelAPI channelApi,
     IColourPalette colourPalette,
     DiscordSettings discordSettings
     )
 {
     _logger          = logger;
     _channelApi      = channelApi;
     _colourPalette   = colourPalette;
     _discordSettings = discordSettings;
 }
예제 #19
0
        public BotHostedService(
            DiscordSettings settings,
            ILogger <BotHostedService> logger,
            IHostApplicationLifetime applicationLifetime
            )
        {
            _settings            = settings;
            _logger              = logger;
            _applicationLifetime = applicationLifetime;

            DiscordClient = new DiscordSocketClient();
        }
예제 #20
0
 /// <summary>
 /// Instantiates a new instance of <see cref="UserLeftResponder"/> class.
 /// </summary>
 /// <param name="channelApi">The channel API.</param>
 /// <param name="discordSettings">The Discord settings.</param>
 /// <param name="colourPalette">The colour palette.</param>
 /// <param name="guildApi">The guild API.</param>
 public UserLeftResponder(
     IDiscordRestChannelAPI channelApi,
     DiscordSettings discordSettings,
     IColourPalette colourPalette,
     IDiscordRestGuildAPI guildApi
     )
 {
     _channelApi      = channelApi;
     _discordSettings = discordSettings;
     _colourPalette   = colourPalette;
     _guildApi        = guildApi;
 }
 public ModerationBackgroundService(
     IServiceProvider sp,
     ILogger <ModerationBackgroundService> logger,
     IColourPalette colourPalette,
     DiscordSettings discordSettings
     ) : base(TimeBetweenIterationsInMillis, logger)
 {
     _sp              = sp;
     _logger          = logger;
     _colourPalette   = colourPalette;
     _discordSettings = discordSettings;
 }
 public DiscordChatMessageForwarder(
     IPolychatService polychatService,
     PolychatSettings polychatSettings,
     DiscordSettings discordSettings,
     IDiscordSanitiserService sanitiser
     )
 {
     _polychatService  = polychatService;
     _polychatSettings = polychatSettings;
     _discordSettings  = discordSettings;
     _sanitiser        = sanitiser;
 }
예제 #23
0
 /// <summary>
 /// Instantiates a new instance of the <see cref="MemberApplicationCreatedResponder"/> class.
 /// </summary>
 /// <param name="logger">The logging instance.</param>
 /// <param name="channelApi">The channel API.</param>
 /// <param name="mediator">The mediator.</param>
 /// <param name="discordSettings">The Discord settings.</param>
 public MemberApplicationCreatedResponder(
     ILogger <MemberApplicationCreatedResponder> logger,
     IDiscordRestChannelAPI channelApi,
     IMediator mediator,
     DiscordSettings discordSettings
     )
 {
     _logger          = logger;
     _channelApi      = channelApi;
     _mediator        = mediator;
     _discordSettings = discordSettings;
 }
 public DiscordBotHostedService(BaseSocketClient baseSocketClient,
                                IOptions <DiscordSettings> options,
                                IGithubService githubService,
                                ILogger <DiscordBotHostedService> logger,
                                IServiceScopeFactory serviceScopeFactory)
 {
     _client              = baseSocketClient;
     _discordSettings     = options.Value;
     _logger              = logger;
     _githubService       = githubService;
     _serviceScopeFactory = serviceScopeFactory;
 }
예제 #25
0
        public static Type Build(ILogger logger, DiscordSettings settings, RadarrSettingsProvider radarrSettingsProvider, SonarrSettingsProvider sonarrSettingsProvider, OverseerrSettingsProvider overseerrSettingsProvider)
        {
            string code     = GetCode(settings, radarrSettingsProvider.Provide(), sonarrSettingsProvider.Provide(), overseerrSettingsProvider.Provide());
            var    tree     = SyntaxFactory.ParseSyntaxTree(code);
            string fileName = $"{DLLFileName}-{Guid.NewGuid()}.dll";

            var references = new List <PortableExecutableReference>()
            {
                MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location),
                MetadataReference.CreateFromFile(typeof(System.Linq.Enumerable).GetTypeInfo().Assembly.Location),
                MetadataReference.CreateFromFile(typeof(ApplicationCommandModule).GetTypeInfo().Assembly.Location),
                MetadataReference.CreateFromFile(typeof(SlashCommandBuilder).GetTypeInfo().Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Attribute).GetTypeInfo().Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Task).GetTypeInfo().Assembly.Location),
                MetadataReference.CreateFromFile(typeof(DiscordUser).GetTypeInfo().Assembly.Location),
                MetadataReference.CreateFromFile(typeof(IServiceProvider).GetTypeInfo().Assembly.Location),
                MetadataReference.CreateFromFile(typeof(ILogger).GetTypeInfo().Assembly.Location),
            };

            references.Add(MetadataReference.CreateFromFile(AppDomain.CurrentDomain.GetAssemblies().Single(a => a.GetName().Name == "netstandard").Location));

            Assembly.GetEntryAssembly().GetReferencedAssemblies().ToList()
            .ForEach(a => references.Add(MetadataReference.CreateFromFile(Assembly.Load(a).Location)));

            var compilation = CSharpCompilation.Create(fileName)
                              .WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
                              .AddReferences(references)
                              .AddSyntaxTrees(tree);

            var dirInfo      = new DirectoryInfo(Directory.GetCurrentDirectory());
            var tmpDirectory = dirInfo.EnumerateDirectories().Where(x => x.Name == "tmp").Single().FullName;

            string path = Path.Combine(tmpDirectory, fileName);

            var compilationResult = compilation.Emit(path);

            if (compilationResult.Success)
            {
                var asm = AssemblyLoadContext.Default.LoadFromAssemblyPath(path);
                return(asm.GetType("Requestrr.WebApi.RequestrrBot.SlashCommands"));
            }
            else
            {
                foreach (Diagnostic codeIssue in compilationResult.Diagnostics)
                {
                    string issue = $"ID: {codeIssue.Id}, Message: {codeIssue.GetMessage()}, Location: { codeIssue.Location.GetLineSpan()},Severity: { codeIssue.Severity}";
                    logger.LogError("Failed to build SlashCommands assembly: " + issue);
                }
            }

            throw new Exception("Failed to build SlashCommands assembly.");
        }
예제 #26
0
        private void AddDiscordBot(DiscordSettings config)
        {
            var token = config.Token;

            if (string.IsNullOrWhiteSpace(token))
            {
                return;
            }

            var bot = new SysCord <T>(this);

            Task.Run(() => bot.MainAsync(token, CancellationToken.None), CancellationToken.None);
        }
예제 #27
0
        private async Task ApplyBotConfigurationAsync(DiscordSettings discordSettings)
        {
            try
            {
                await _client.UpdateStatusAsync(new DiscordActivity(discordSettings.StatusMessage, ActivityType.Playing));
            }
            catch (System.Exception ex)
            {
                _logger.LogError(ex, "Error update the bot's status: " + ex.Message);
            }

            try
            {
                if (_movieNotificationEngine != null)
                {
                    await _movieNotificationEngine.StopAsync();
                }

                if (_currentSettings.MovieDownloadClient != DownloadClient.Disabled && _currentSettings.NotificationMode != NotificationMode.Disabled)
                {
                    _movieNotificationEngine = _movieWorkflowFactory.CreateMovieNotificationEngine(_client, _logger);
                }

                _movieNotificationEngine?.Start();
            }
            catch (System.Exception ex)
            {
                _logger.LogError(ex, "Error while starting movie notification engine: " + ex.Message);
            }

            try
            {
                if (_tvShowNotificationEngine != null)
                {
                    await _tvShowNotificationEngine.StopAsync();
                }

                if (_currentSettings.TvShowDownloadClient != DownloadClient.Disabled && _currentSettings.NotificationMode != NotificationMode.Disabled)
                {
                    _tvShowNotificationEngine = _tvShowWorkflowFactory.CreateTvShowNotificationEngine(_client, _logger);
                }

                _tvShowNotificationEngine?.Start();
            }
            catch (System.Exception ex)
            {
                _logger.LogError(ex, "Error while starting tv show notification engine: " + ex.Message);
            }
        }
예제 #28
0
 private T GetTvShowClient <T>(DiscordSettings settings) where T : class
 {
     if (settings.TvShowDownloadClient == DownloadClient.Sonarr)
     {
         return(_sonarrDownloadClient as T);
     }
     else if (settings.TvShowDownloadClient == DownloadClient.Ombi)
     {
         return(_ombiDownloadClient as T);
     }
     else
     {
         throw new Exception($"Invalid configured tv show download client {settings.TvShowDownloadClient}");
     }
 }
예제 #29
0
 private T GetMovieClient <T>(DiscordSettings settings) where T : class
 {
     if (settings.MovieDownloadClient == DownloadClient.Radarr)
     {
         return(_radarrDownloadClient as T);
     }
     else if (settings.MovieDownloadClient == DownloadClient.Ombi)
     {
         return(_ombiDownloadClient as T);
     }
     else
     {
         throw new Exception($"Invalid configured movie download client {settings.MovieDownloadClient}");
     }
 }
예제 #30
0
 public CommandHostedService(
     ILogger <CommandHostedService> logger,
     IServiceProvider provider, IBotService botService,
     CommandService commandService,
     DiscordSettings settings,
     IBasicEmbedsService basicEmbedsService
     )
 {
     _logger             = logger;
     _provider           = provider;
     _botService         = botService;
     _commandService     = commandService;
     _settings           = settings;
     _basicEmbedsService = basicEmbedsService;
 }