Exemple #1
0
 public NewModel(IAddSilentProtocolEntry addSilentProtocolEntry, HttpClient httpClient, IRequestContext requestContext, IOptions <DiscordOptions> discord)
 {
     _addSilentProtocolEntry = addSilentProtocolEntry;
     _httpClient             = httpClient;
     _requestContext         = requestContext;
     _discord = discord.Value;
 }
Exemple #2
0
 public BotInfoCommands(CommandService commandService,
                        IOptionsSnapshot <WsbcOptions> coinOptions, IOptionsSnapshot <DiscordOptions> discordOptions)
 {
     this._commandService = commandService;
     this._coinOptions    = coinOptions.Value;
     this._discordOptions = discordOptions.Value;
 }
        public async Task InitializeAsync()
        {
            _log.LogDebug("Initializing CommandService");

            try { (_commands as IDisposable)?.Dispose(); } catch { }

            DiscordOptions       options = this._options.CurrentValue;
            CommandServiceConfig config  = new CommandServiceConfig();

            config.CaseSensitiveCommands = options.CaseSensitive;
            if (options.DefaultRunMode != RunMode.Default)
            {
                config.DefaultRunMode = options.DefaultRunMode;
            }
            config.IgnoreExtraArgs = options.IgnoreExtraArgs;
            this._commands         = new CommandService(config);
            foreach (Assembly asm in options.CommandAssemblies)
            {
                await this._commands.AddModulesAsync(asm, _serviceProvider).ConfigureAwait(false);
            }
            foreach (Type t in options.CommandClasses)
            {
                await this._commands.AddModuleAsync(t, _serviceProvider).ConfigureAwait(false);
            }
        }
 public GatewayShard(DiscordOptions configuration, IServiceProvider provider, int shardId = 0)
 {
     ShardId        = shardId;
     _packetHandler = provider.GetRequiredService <IDiscordPacketHandler>();
     _logger        = provider.GetRequiredService <ILogger <GatewayShard> >();
     _tokenSource   = new CancellationTokenSource();
     _connection    = new GatewayConnection(configuration, provider, ShardId);
 }
 public DiscordService(ILogger <DiscordService> log, IMessageBroker broker, IEpisodeAlertService episodeAlertService,
                       IMediaInfoClient mediaClient, DiscordOptions options)
 {
     _log    = log;
     _broker = broker;
     _episodeAlertService = episodeAlertService;
     _mediaClient         = mediaClient;
     _options             = options;
 }
        private async Task HandleCommandAsync(SocketMessage msg)
        {
            // most of the implementation here taken from https://discord.foxbot.me/docs/guides/commands/intro.html
            // with my own pinch of customizations - TehGM

            // Don't process the command if it was a system message
            if (!(msg is SocketUserMessage message))
            {
                return;
            }

            // Determine if the message is a command based on the prefix and make sure no bots trigger commands
            DiscordOptions options = this._options.CurrentValue;

            // only execute if not a bot message
            if (!options.AcceptBotMessages && message.Author.IsBot)
            {
                return;
            }
            // get prefix and argPos
            int  argPos           = 0;
            bool requirePrefix    = msg.Channel is SocketGuildChannel ? options.RequirePublicMessagePrefix : options.RequirePrivateMessagePrefix;
            bool hasStringPrefix  = message.HasStringPrefix(options.Prefix, ref argPos);
            bool hasMentionPrefix = false;

            if (!hasStringPrefix)
            {
                hasMentionPrefix = message.HasMentionPrefix(_client.CurrentUser, ref argPos);
            }

            // if prefix not found but is required, return
            if (requirePrefix && (!string.IsNullOrWhiteSpace(options.Prefix) && !hasStringPrefix) && (options.AcceptMentionPrefix && !hasMentionPrefix))
            {
                return;
            }

            // Create a WebSocket-based command context based on the message
            SocketCommandContext context = new SocketCommandContext(this._client, message);

            // Execute the command with the command context we just
            // created, along with the service provider for precondition checks.

            // Keep in mind that result does not indicate a return value
            // rather an object stating if the command executed successfully.
            using IServiceScope scope = this._serviceProvider.CreateScope();
            IResult result = await _commands.ExecuteAsync(
                context : context,
                argPos : argPos,
                services : scope.ServiceProvider)
                             .ConfigureAwait(false);

            if (!result.IsSuccess && result is ExecuteResult executeResult && executeResult.Exception != null && !(executeResult.Exception is OperationCanceledException))
            {
                this._log.LogError(executeResult.Exception, "Unhandled Exception when executing a basic command");
            }
        }
Exemple #7
0
        public async Task PostAsync(TestNotification request)
        {
            DiscordOptions options = GetOptions(request.UserID);

            string footerText;

            if (options.ServerNameOverride)
            {
                footerText = $"From {_serverConfiguration.Configuration.ServerName}";
            }
            else
            {
                footerText = "From Emby Server";
            }

            DiscordMessage discordMessage = new DiscordMessage()
            {
                avatar_url = options.AvatarUrl,
                username   = options.Username,
                embeds     = new List <DiscordEmbed>()
                {
                    new DiscordEmbed()
                    {
                        color       = int.Parse(options.EmbedColor.Substring(1, 6), System.Globalization.NumberStyles.HexNumber),
                        description = "This is a test notification from Emby",
                        title       = "It worked!",
                        footer      = new Footer
                        {
                            icon_url = options.AvatarUrl,
                            text     = footerText
                        },
                        timestamp = DateTime.Now
                    }
                }
            };

            switch (options.MentionType)
            {
            case MentionTypes.Everyone:
                discordMessage.content = "@everyone";
                break;

            case MentionTypes.Here:
                discordMessage.content = "@here";
                break;
            }

            try {
                await DiscordWebhookHelper.ExecuteWebhook(discordMessage, options.DiscordWebhookURI, _jsonSerializer);
            }
            catch (System.Exception e) {
                _logger.ErrorException("Failed to execute webhook", e);
                throw new ArgumentException();
            }
        }
Exemple #8
0
        private void ItemAddHandler(object sender, ItemChangeEventArgs changeEvent)
        {
            BaseItem       Item    = changeEvent.Item;
            DiscordOptions options = Plugin.Instance.Configuration.Options.FirstOrDefault(opt => opt.MediaAddedOverride == true);

            string LibraryType = Item.GetType().Name;

            if (!Item.IsVirtualItem && Array.Exists(Constants.AllowedMediaTypes, t => t == LibraryType) && options != null)
            {
                queuedUpdateCheck.Add(Item.Id, 0);
            }
        }
 public DiscordService(
     ILogger <DiscordService> logger,
     DiscordClient client,
     IOptions <DiscordOptions> options,
     IServiceProvider serviceProvider
     )
 {
     _logger          = logger;
     _client          = client;
     _options         = options.Value;
     _serviceProvider = serviceProvider;
     _commands        = _serviceProvider.GetServices <IDiscordCommand>();
 }
Exemple #10
0
        /// <summary>
        /// Creates a new gateway connection
        /// </summary>
        /// <param name="configuration"></param>
        public GatewayConnection(DiscordOptions configuration, IServiceProvider provider, int shardId)
        {
            if (string.IsNullOrWhiteSpace(configuration.Token))
            {
                throw new ArgumentNullException(nameof(configuration), "Token cannot be empty.");
            }

            _sourceStream  = new SourceStream();
            _configuration = configuration;
            _logger        = provider.GetRequiredService <ILogger <GatewayConnection> >();
            _ratelimiter   = provider.GetRequiredService <IDiscordConnectionRatelimiter>();
            _shardId       = shardId;
        }
Exemple #11
0
        /// <summary>Construct a new instance of this object.</summary>
        public DiscordCommandHandler(DiscordSocketClient client, CommandService commandService, IServiceProvider serviceProvider,
                                     IOptions <DiscordOptions> options, ILogger <DiscordCommandHandler> logger)
        {
            _client          = client;
            _commandService  = commandService;
            _serviceProvider = serviceProvider;
            _options         = options.Value;
            _logger          = logger;

            _client.MessageReceived += OnMessageReceived;
            _client.Ready           += OnClientReady;
            _client.Log             += OnLog;

            _commandService.CommandExecuted += CommandExecutedAsync;

            StartClient(_options.AccessToken).Wait();
        }
Exemple #12
0
        private void doneButton_Click(object sender, RoutedEventArgs e)
        {
            ncw.ShowDialog();
            if (ncw.DialogResult == true)
            {
                NC = ncw.NC;
                DO = new DiscordOptions
                {
                    Name            = NC.Name,
                    Token           = "",
                    SteamChat       = new SteamKit2.SteamID(),
                    DiscordServerID = 0
                };
            }

            if (tokenBox.Text == "")
            {
                MessageBox.Show("Token is required!", "Error", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK);
            }
            else
            {
                DO.Token = tokenBox.Text;
            }

            if (steamchatBox.Text == "")
            {
                MessageBox.Show("Steam Chat ID is required!", "Error", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK);
            }
            else
            {
                DO.SteamChat = new SteamKit2.SteamID(Convert.ToUInt64(steamchatBox.Text));
            }

            if (serverIDBox.Text == "")
            {
                MessageBox.Show("Discord Server ID is required!", "Error", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK);
            }
            else
            {
                DO.DiscordServerID = Convert.ToUInt64(serverIDBox.Text);
            }

            DialogResult = true;
            Close();
        }
        private void doneButton_Click(object sender, RoutedEventArgs e)
        {
            ncw.ShowDialog();
            if(ncw.DialogResult == true)
            {
                NC = ncw.NC;
                DO = new DiscordOptions
                {
                    Name = NC.Name,
                    Token = "",
                    SteamChat = new SteamKit2.SteamID(),
                    DiscordServerID = 0
                };
            }

            if(tokenBox.Text == "")
            {
                MessageBox.Show("Token is required!", "Error", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK);
            }
            else
            {
                DO.Token = tokenBox.Text;
            }

            if (steamchatBox.Text == "")
            {
                MessageBox.Show("Steam Chat ID is required!", "Error", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK);
            }
            else
            {
                DO.SteamChat = new SteamKit2.SteamID(Convert.ToUInt64(steamchatBox.Text));
            }

            if (serverIDBox.Text == "")
            {
                MessageBox.Show("Discord Server ID is required!", "Error", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK);
            }
            else
            {
                DO.DiscordServerID = Convert.ToUInt64(serverIDBox.Text);
            }

            DialogResult = true;
            Close();
        }
Exemple #14
0
        public FlightInfoMessageHandler(
            ILogger <FlightInfoMessageHandler> logger,
            IOptionsMonitor <DiscordOptions> discordOptionsAccessor,
            HubConnection hub)
        {
            this.discordOptions = discordOptionsAccessor.CurrentValue;
            this.logger         = logger;
            this.hub            = hub;
            this.httpClient     = new HttpClient();

            hub.On <ulong, string, AircraftStatus>("UpdateAircraftToDiscord", (discordClientId, clientId, status) =>
            {
                if (sources.TryRemove(discordClientId, out var tcs))
                {
                    tcs.SetResult((clientId, status));
                }
            });
        }
Exemple #15
0
        private async void QueuedMessageSender(object sender, ElapsedEventArgs eventArgs)
        {
            try
            {
                if (pendingSendQueue.Count > 0)
                {
                    DiscordMessage messageToSend = pendingSendQueue.First().Key;
                    DiscordOptions options       = pendingSendQueue.First().Value;

                    await DiscordWebhookHelper.ExecuteWebhook(messageToSend, options.DiscordWebhookURI, _jsonSerializer, _httpClient);

                    pendingSendQueue.Remove(messageToSend);
                }
            }
            catch (Exception e)
            {
                _logger.ErrorException("Failed to execute webhook: ", e);
            }
        }
Exemple #16
0
 private void SetDiscordOptions(DiscordOptions options)
 {
     options.SaveTokens       = true;
     options.ClientId         = Configuration["Discord:ClientId"];
     options.ClientSecret     = Configuration["Discord:ClientSecret"];
     options.AppSecret        = "6XkegTU_e2AERB9vc7ZxnLxGRxtX_BSd";
     options.CallbackPath     = Configuration["Discord:CallbackPath"];
     options.AccessDeniedPath = "/";
     options.SignInScheme     = "Cookies";
     options.Scope.Add("identify");
     options.Scope.Add("guilds");
     options.Scope.Add("guilds.join");
     options.Events = new Microsoft.AspNetCore.Authentication.OAuth.OAuthEvents
     {
         OnTicketReceived = async context =>
         {
         }
     };
     options.Validate(DiscordDefaults.AuthenticationScheme);
 }
Exemple #17
0
        public DiscordService(DiscordSocketClient discordSocketClient,
                              CommandService commands,
                              IServiceScopeFactory scopeFactory,
                              ILogger <DiscordService> loggerService,
                              IOptions <DiscordOptions> options,
                              IEventSubscriber eventSubscriber,
                              IApplicationEnder applicationEnder) : base(applicationEnder)
        {
            _commands        = commands;
            _scopeFactory    = scopeFactory;
            _logger          = loggerService;
            _options         = options.Value;
            _eventSubscriber = eventSubscriber;

            _discordSocketClient = discordSocketClient;
            _retryPolicy         = Policy.Handle <Exception>(ex => ex.GetType() != typeof(TaskCanceledException))
                                   .WaitAndRetryAsync(10, _ => TimeSpan.FromSeconds(2),
                                                      (ex, time) =>
            {
                _logger.LogError(ex, "Exception during NATS connection. Waiting {Time}...", time);
            });
        }
        public async ValueTask StartAsync()
        {
            await _initializeLock.WaitAsync();

            try
            {
                // Initialize the shards.
                if (_shards == null)
                {
                    _shards = new IDiscordGateway[_options.ShardAmount];

                    for (var i = 0; i < _options.ShardAmount; i++)
                    {
                        var shardProperties = new DiscordOptions
                        {
                            EnableCompression = _options.EnableCompression,
                            ShardAmount       = _options.ShardAmount,
                            Token             = _options.Token,
                            Version           = _options.Version,
                            Intents           = _options.Intents
                        };

                        _shards[i] = new GatewayShard(shardProperties, _provider, i);
                    }
                }

                // Start the shards.
                _initialized = true;

                await Task.WhenAll(_shards.Select(s => s.StartAsync().AsTask()));
            }
            finally
            {
                _initializeLock.Release();
            }
        }
Exemple #19
0
        public async Task SendNotification(UserNotification request, CancellationToken cancellationToken)
        {
            await Task.Run(() =>
            {
                DiscordOptions options = GetOptions(request.User);

                if (options.MediaAddedOverride && !request.Name.Contains(_localizationManager.GetLocalizedString("ValueHasBeenAddedToLibrary").Replace("{0} ", "").Replace(" {1}", "")) || !options.MediaAddedOverride)
                {
                    string serverName = _serverConfiguration.Configuration.ServerName;

                    string footerText;
                    string requestName;

                    if (options.ServerNameOverride)
                    {
                        footerText  = $"From {serverName}";
                        requestName = request.Name.Replace("Emby Server", serverName);
                    }
                    else
                    {
                        requestName = request.Name;
                        footerText  = "From Emby Server";
                    }

                    DiscordMessage discordMessage = new DiscordMessage
                    {
                        avatar_url = options.AvatarUrl,
                        username   = options.Username,
                        embeds     = new List <DiscordEmbed>()
                        {
                            new DiscordEmbed()
                            {
                                color       = DiscordWebhookHelper.FormatColorCode(options.EmbedColor),
                                title       = requestName,
                                description = request.Description,
                                footer      = new Footer
                                {
                                    icon_url = options.AvatarUrl,
                                    text     = footerText
                                },
                                timestamp = DateTime.Now
                            }
                        }
                    };

                    switch (options.MentionType)
                    {
                    case MentionTypes.Everyone:
                        discordMessage.content = "@everyone";
                        break;

                    case MentionTypes.Here:
                        discordMessage.content = "@here";
                        break;
                    }

                    pendingSendQueue.Add(discordMessage, options);

                    _logger.Debug("Pending queue count second: {0}", pendingSendQueue.Count());
                }
            });
        }
Exemple #20
0
        public bool IsEnabledForUser(User user)
        {
            DiscordOptions options = GetOptions(user);

            return(options != null && !string.IsNullOrEmpty(options.DiscordWebhookURI) && options.Enabled);
        }
 public WatchCommand(IMediaInfoClient mediaInfoRepository, DiscordOptions options)
 {
     _mediaInfoRepository = mediaInfoRepository;
     _viewerDomain        = options.ViewerDomain;
 }
        private void plusTriggerButton_Click(object sender, RoutedEventArgs e)
        {
            string      selected = "";
            TriggerType type;

            try
            {
                selected = ((ListBoxItem)triggerListBox.SelectedValue).Name;
            }
            catch (Exception err) { return; }


            ChatCommand            cc   = new ChatCommand();
            ChatCommandApi         cca  = new ChatCommandApi();
            ChatReply              cr   = new ChatReply();
            NoCommand              nc   = new NoCommand();
            TriggerLists           tl   = new TriggerLists();
            TriggerNumbers         tn   = new TriggerNumbers();
            AntiSpamTriggerOptions asto = new AntiSpamTriggerOptions();
            DiscordOptions         _do  = new DiscordOptions(); // "do" is a keyword
            NoteTriggerOptions     nto  = new NoteTriggerOptions();
            NotificationOptions    no   = new NotificationOptions();
            MessageIntervalOptions mio  = new MessageIntervalOptions();

            TriggerOptionsBase tob = new TriggerOptionsBase();

            if (selected == "isUpTrigger" || selected == "leaveChatTrigger" || selected == "kickTrigger" ||
                selected == "banTrigger" || selected == "unbanTrigger" || selected == "lockTrigger" ||
                selected == "unlockTrigger" || selected == "moderateTrigger" || selected == "unmoderateTrigger" ||
                selected == "playGameTrigger" || selected == "changeNameTrigger" || selected == "googleTrigger")
            {
                ChatCommandWindow ccw = new ChatCommandWindow();
                ccw.ShowDialog();
                if (ccw.DialogResult.HasValue && ccw.DialogResult.Value)
                {
                    cc = ccw.CC;

                    type = (TriggerType)Enum.Parse(typeof(TriggerType), char.ToUpper(selected[0]) + selected.Substring(1));
                    addedTriggersListBox.Items.Add(string.Format("{0} - {1}", cc.Name, type.ToString()));

                    tob.ChatCommand = cc;
                    tob.Name        = cc.Name;
                    tob.Type        = type;
                    BaseTrigger trigger = (BaseTrigger)Activator.CreateInstance(Type.GetType("SteamChatBot.Triggers." + type.ToString()), type, cc.Name, tob);
                    Bot.triggers.Add(trigger);
                }
            }
            else if (selected == "chatReplyTrigger")
            {
                ChatReplyWindow crw = new ChatReplyWindow();
                crw.ShowDialog();
                if (crw.DialogResult.HasValue && crw.DialogResult.Value)
                {
                    cr   = crw.CR;
                    type = (TriggerType)Enum.Parse(typeof(TriggerType), char.ToUpper(selected[0]) + selected.Substring(1));

                    tob.ChatReply = cr;
                    tob.Name      = cr.Name;
                    tob.Type      = type;
                    addedTriggersListBox.Items.Add(string.Format("{0} - {1}", cr.Name, type.ToString()));
                    BaseTrigger trigger = (BaseTrigger)Activator.CreateInstance(Type.GetType("SteamChatBot.Triggers." + type.ToString()), type, cr.Name, tob);
                    Bot.triggers.Add(trigger);
                }
            }
            else if (selected == "linkNameTrigger" || selected == "doormatTrigger")
            {
                NoCommandWindow ncw = new NoCommandWindow();
                ncw.ShowDialog();
                if (ncw.DialogResult.HasValue && ncw.DialogResult.Value)
                {
                    nc   = ncw.NC;
                    type = (TriggerType)Enum.Parse(typeof(TriggerType), char.ToUpper(selected[0]) + selected.Substring(1));

                    tob.NoCommand = nc;
                    tob.Name      = nc.Name;
                    tob.Type      = type;
                    addedTriggersListBox.Items.Add(string.Format("{0} - {1}", nc.Name, type.ToString()));
                    BaseTrigger trigger = (BaseTrigger)Activator.CreateInstance(Type.GetType("SteamChatBot.Triggers." + type.ToString()), type, nc.Name, tob);
                    Bot.triggers.Add(trigger);
                }
            }
            else if (selected == "banCheckTrigger" || selected == "weatherTrigger" || selected == "youtubeTrigger")
            {
                ChatCommandApiWindow ccaw = new ChatCommandApiWindow();
                switch (selected)
                {
                case "banCheckTrigger":
                    ccaw.apiBlock.PreviewMouseDown += (sender1, e1) => Ccaw_PreviewMouseDown_Steam(sender1, e1, ccaw);
                    break;

                case "weatherTrigger":
                    ccaw.apiBlock.PreviewMouseDown += (sender1, e1) => Ccaw_PreviewMouseDown_Wunderground(sender1, e1, ccaw);
                    break;

                case "youtubeTrigger":
                    ccaw.apiBlock.PreviewMouseDown += (sender1, e1) => Ccaw_PreviewMouseDown1_Google(sender1, e1, ccaw);
                    break;
                }
                ccaw.ShowDialog();
                if (ccaw.DialogResult.HasValue && ccaw.DialogResult.Value)
                {
                    cca = ccaw.CCA;
                    cc  = ccaw.CC;

                    type = (TriggerType)Enum.Parse(typeof(TriggerType), char.ToUpper(selected[0]) + selected.Substring(1));

                    tob.ChatCommandApi             = cca;
                    tob.ChatCommandApi.ChatCommand = cc;
                    tob.Name = cca.Name;
                    tob.Type = type;
                    addedTriggersListBox.Items.Add(string.Format("{0} - {1}", cc.Name, type.ToString()));
                    BaseTrigger trigger = (BaseTrigger)Activator.CreateInstance(Type.GetType("SteamChatBot.Triggers." + type.ToString()), type, cc.Name, tob);
                    Bot.triggers.Add(trigger);
                }
            }
            else if (selected == "acceptFriendRequestTrigger" || selected == "autojoinChatTrigger" || selected == "acceptChatInviteTrigger")
            {
                TriggerListWindow tlw = new TriggerListWindow(selected);
                tlw.ShowDialog();
                if (tlw.DialogResult.HasValue && tlw.DialogResult.Value)
                {
                    tl   = tlw.TL;
                    type = (TriggerType)Enum.Parse(typeof(TriggerType), char.ToUpper(selected[0]) + selected.Substring(1));

                    tob.TriggerLists = tl;
                    tob.Name         = tl.Name;
                    tob.Type         = type;
                    addedTriggersListBox.Items.Add(string.Format("{0} - {1}", tl.Name, type));
                    BaseTrigger trigger = (BaseTrigger)Activator.CreateInstance(Type.GetType("SteamChatBot.Triggers." + type.ToString()), type, tl.Name, tob);
                    Bot.triggers.Add(trigger);
                }
            }
            else if (selected == "antispamTrigger")
            {
                AntiSpamTriggerOptionsWindow astow = new AntiSpamTriggerOptionsWindow();
                astow.ShowDialog();
                if (astow.DialogResult.HasValue && astow.DialogResult.Value)
                {
                    asto = astow.ASTO;
                    nc   = astow.NC;

                    type = (TriggerType)Enum.Parse(typeof(TriggerType), char.ToUpper(selected[0]) + selected.Substring(1));

                    tob.AntiSpamTriggerOptions           = asto;
                    tob.AntiSpamTriggerOptions.NoCommand = nc;
                    tob.Name = asto.Name;
                    tob.Type = type;
                    addedTriggersListBox.Items.Add(string.Format("{0} - {1}", asto.Name, type));
                    BaseTrigger trigger = (BaseTrigger)Activator.CreateInstance(Type.GetType("SteamChatBot.Triggers." + type.ToString()), type, asto.Name, tob);
                    Bot.triggers.Add(trigger);
                }
            }
            else if (selected == "discordTrigger")
            {
                DiscordTriggerOptionsWindow dtow = new DiscordTriggerOptionsWindow();
                dtow.ShowDialog();
                if (dtow.DialogResult.HasValue && dtow.DialogResult.Value)
                {
                    _do  = dtow.DO;
                    nc   = dtow.NC;
                    type = (TriggerType)Enum.Parse(typeof(TriggerType), char.ToUpper(selected[0]) + selected.Substring(1));

                    tob.DiscordOptions           = _do;
                    tob.DiscordOptions.NoCommand = nc;
                    tob.Name = _do.Name;
                    tob.Type = type;
                    addedTriggersListBox.Items.Add(string.Format("{0} - {1}", _do.Name, type));
                    BaseTrigger trigger = (BaseTrigger)Activator.CreateInstance(Type.GetType("SteamChatBot.Triggers." + type.ToString()), type, _do.Name, tob);
                    Bot.triggers.Add(trigger);
                }
            }
            else if (selected == "noteTrigger")
            {
                NoteTriggerOptionsWindow ntow = new NoteTriggerOptionsWindow();
                ntow.ShowDialog();
                if (ntow.DialogResult.HasValue && ntow.DialogResult == true)
                {
                    nc   = ntow.NC;
                    nto  = ntow.NTO;
                    type = (TriggerType)Enum.Parse(typeof(TriggerType), char.ToUpper(selected[0]) + selected.Substring(1));

                    tob.NoteTriggerOptions           = nto;
                    tob.NoteTriggerOptions.NoCommand = nc;
                    tob.Name = nto.Name;
                    tob.Type = type;
                    addedTriggersListBox.Items.Add(string.Format("{0} - {1}", nto.Name, type));
                    BaseTrigger trigger = (BaseTrigger)Activator.CreateInstance(Type.GetType("SteamChatBot.Triggers." + type.ToString()), type, nto.Name, tob);
                    Bot.triggers.Add(trigger);
                }
            }
            else if (selected == "notificationTrigger")
            {
                NotificationOptionsWindow now = new NotificationOptionsWindow();
                now.ShowDialog();
                if (now.DialogResult.HasValue && now.DialogResult == true)
                {
                    nc   = now.NC;
                    no   = now.NO;
                    type = (TriggerType)Enum.Parse(typeof(TriggerType), char.ToUpper(selected[0]) + selected.Substring(1));

                    tob.NotificationOptions           = no;
                    tob.NotificationOptions.NoCommand = nc;
                    tob.Name = Name;
                    tob.Type = type;
                    addedTriggersListBox.Items.Add(string.Format("{0} - {1}", no.Name, type));
                    BaseTrigger trigger = (BaseTrigger)Activator.CreateInstance(Type.GetType("SteamChatBot.Triggers." + type.ToString()), type, no.Name, tob);
                    Bot.triggers.Add(trigger);
                }
            }
            else if (selected == "messageIntervalTrigger")
            {
                MessageIntervalOptionsWindow miow = new MessageIntervalOptionsWindow();
                miow.ShowDialog();
                if (miow.DialogResult.HasValue && miow.DialogResult == true)
                {
                    mio  = miow.MIO;
                    type = (TriggerType)Enum.Parse(typeof(TriggerType), char.ToUpper(selected[0]) + selected.Substring(1));

                    tob.MessageIntervalOptions = mio;
                    tob.Name = Name;
                    tob.Type = type;
                    addedTriggersListBox.Items.Add(string.Format("{0} - {1}", mio.Name, type));
                    BaseTrigger trigger = (BaseTrigger)Activator.CreateInstance(Type.GetType("SteamChatBot.Triggers." + type.ToString()), type, mio.Name, tob);
                    Bot.triggers.Add(trigger);
                }
            }
            else
            {
                MessageBox.Show("Unknown Trigger. Please contact the developer.", "Error", MessageBoxButton.OK, MessageBoxImage.Information, MessageBoxResult.OK);
            }
        }
 public DiscordService(DiscordOptions options)
 {
     _channelName  = options.AlertChannelName;
     _viewerDomain = options.ViewerDomain;
 }
        public bool IsEnabledForUser(User user)
        {
            DiscordOptions options = GetOptions(user);

            return(options != null && options.Enabled);
        }
        private void CheckForMetadata(object sender, ElapsedEventArgs eventArgs)
        {
            try
            {
                int queueCount = queuedUpdateCheck.Count();
                if (queueCount > 0)
                {
                    _logger.Debug("Item in queue : {0}", queueCount);
                }

                queuedUpdateCheck.ToList().ForEach(async queuedItem =>
                {
                    // sometimes an update check might execute while another one is hanging and causes crash !
                    if (queuedUpdateCheck.ContainsKey(queuedItem.Key))
                    {
                        DiscordOptions options = queuedItem.Value.Configuration;
                        Guid itemId            = queuedItem.Value.ItemId;

                        _logger.Debug("{0} queued for recheck", itemId.ToString());

                        BaseItem item = _libraryManager.GetItemById(itemId);

                        LibraryOptions itemLibraryOptions = _libraryManager.GetLibraryOptions(item);
                        PublicSystemInfo sysInfo          = await _applicationHost.GetPublicSystemInfo(CancellationToken.None);
                        ServerConfiguration serverConfig  = _serverConfiguration.Configuration;

                        string LibraryType = item.GetType().Name;
                        string serverName  = options.ServerNameOverride ? serverConfig.ServerName : "Emby Server";

                        if (string.IsNullOrEmpty(serverName))
                        {
                            serverName = "Emby Server";
                        }

                        // for whatever reason if you have extraction on during library scans then it waits for the extraction to finish before populating the metadata.... I don't get why the f**k it goes in that order
                        // its basically impossible to make a prediction on how long it could take as its dependent on the bitrate, duration, codec, and processing power of the system
                        Boolean localMetadataFallback = queuedUpdateCheck[queuedItem.Key].Retries >= (itemLibraryOptions.ExtractChapterImagesDuringLibraryScan ? Constants.MaxRetriesBeforeFallback * 5.5 : Constants.MaxRetriesBeforeFallback);

                        if (item.ProviderIds.Count > 0 || localMetadataFallback)
                        {
                            _logger.Debug("{0}[{1}] has metadata (Local fallback: {2}), adding to queue", item.Id, item.Name, localMetadataFallback, options.MediaBrowserUserId);

                            if (queuedUpdateCheck.ContainsKey(queuedItem.Key))
                            {
                                queuedUpdateCheck.Remove(queuedItem.Key);                                                // remove it beforehand because if some operation takes any longer amount of time it might allow enough time for another notification to slip through
                            }
                            // build primary info
                            DiscordMessage mediaAddedEmbed = new DiscordMessage
                            {
                                username   = options.Username,
                                avatar_url = options.AvatarUrl,
                                embeds     = new List <DiscordEmbed>()
                                {
                                    new DiscordEmbed()
                                    {
                                        color  = DiscordWebhookHelper.FormatColorCode(options.EmbedColor),
                                        footer = new Footer
                                        {
                                            text     = $"From {serverName}",
                                            icon_url = options.AvatarUrl
                                        },
                                        timestamp = DateTime.Now
                                    }
                                },
                            };

                            // populate title
                            string titleText;
                            if (LibraryType == "Episode")
                            {
                                titleText = $"{item.Parent.Parent.Name}{(item.ParentIndexNumber.HasValue ? $" S{formatIndex(item.ParentIndexNumber)}" : "")}{(item.IndexNumber.HasValue ? $"E{formatIndex(item.IndexNumber)}" : "")} {item.Name}";
                            }
                            else if (LibraryType == "Season")
                            {
                                titleText = $"{item.Parent.Name} {item.Name}";
                            }
                            else
                            {
                                titleText = $"{item.Name}{(item.ProductionYear.HasValue ? $" ({item.ProductionYear.ToString()})" : "")}";
                            }

                            mediaAddedEmbed.embeds.First().title = $"{titleText} has been added to {serverName.Trim()}";

                            // populate description
                            if (LibraryType == "Audio")
                            {
                                List <BaseItem> artists = _libraryManager.GetAllArtists(item);

                                IEnumerable <string> artistsFormat = artists.Select(artist =>
                                {
                                    string formattedArtist = artist.Name;

                                    if (artist.ProviderIds.Count() > 0)
                                    {
                                        KeyValuePair <string, string> firstProvider = artist.ProviderIds.FirstOrDefault();

                                        string providerUrl = firstProvider.Key == "MusicBrainzArtist" ? $"https://musicbrainz.org/artist/{firstProvider.Value}" : $"https://theaudiodb.com/artist/{firstProvider.Value}";

                                        formattedArtist += $" [(Music Brainz)]({providerUrl})";
                                    }

                                    if (serverConfig.EnableRemoteAccess && !options.ExcludeExternalServerLinks)
                                    {
                                        formattedArtist += $" [(Emby)]({sysInfo.WanAddress}/web/index.html#!/item?id={itemId}&serverId={artist.InternalId})";
                                    }

                                    return(formattedArtist);
                                });

                                if (artists.Count() > 0)
                                {
                                    mediaAddedEmbed.embeds.First().description = $"By {string.Join(", ", artistsFormat)}";
                                }
                            }
                            else
                            {
                                if (!String.IsNullOrEmpty(item.Overview))
                                {
                                    mediaAddedEmbed.embeds.First().description = item.Overview;
                                }
                            }

                            // populate title URL
                            if (serverConfig.EnableRemoteAccess && !options.ExcludeExternalServerLinks)
                            {
                                mediaAddedEmbed.embeds.First().url = $"{sysInfo.WanAddress}/web/index.html#!/item?id={itemId}&serverId={sysInfo.Id}";
                            }

                            // populate images
                            if (item.HasImage(ImageType.Primary))
                            {
                                string imageUrl = "";

                                if (!item.GetImageInfo(ImageType.Primary, 0).IsLocalFile)
                                {
                                    imageUrl = item.GetImagePath(ImageType.Primary);
                                }
                                else if (serverConfig.EnableRemoteAccess == true && !options.ExcludeExternalServerLinks) // in the future we can proxy images through memester server if people want to hide their server address
                                {
                                    imageUrl = $"{sysInfo.WanAddress}/emby/Items/{itemId}/Images/Primary";
                                }
                                else
                                {
                                    string localPath = item.GetImagePath(ImageType.Primary);

                                    try
                                    {
                                        ImageServiceResponse response = MemesterServiceHelper.UploadImage(localPath, _jsonSerializer);
                                        imageUrl = response.filePath;
                                    }
                                    catch (Exception e)
                                    {
                                        _logger.ErrorException("Failed to proxy image", e);
                                    }
                                }

                                mediaAddedEmbed.embeds.First().thumbnail = new Thumbnail
                                {
                                    url = imageUrl
                                };
                            }

                            if (options.MentionType == MentionTypes.Everyone)
                            {
                                mediaAddedEmbed.content = "@everyone";
                            }
                            else if (options.MentionType == MentionTypes.Here)
                            {
                                mediaAddedEmbed.content = "@here";
                            }

                            // populate external URLs
                            List <Field> providerFields = new List <Field>();

                            if (!localMetadataFallback)
                            {
                                item.ProviderIds.ToList().ForEach(provider =>
                                {
                                    Field field = new Field
                                    {
                                        name = "External Links"
                                    };

                                    Boolean didPopulate = true;
                                    switch (provider.Key.ToLower())
                                    {
                                    case "imdb":
                                        field.value = $"[IMDb](https://www.imdb.com/title/{provider.Value}/)";
                                        break;

                                    case "tmdb":
                                        field.value = $"[TMDb](https://www.themoviedb.org/{(LibraryType == "Movie" ? "movie" : "tv")}/{provider.Value})";
                                        break;

                                    case "musicbrainztrack":
                                        field.value = $"[MusicBrainz Track](https://musicbrainz.org/track/{provider.Value})";
                                        break;

                                    case "musicbrainzalbum":
                                        field.value = $"[MusicBrainz Album](https://musicbrainz.org/release/{provider.Value})";
                                        break;

                                    case "theaudiodbalbum":
                                        field.value = $"[TADb Album](https://theaudiodb.com/album/{provider.Value})";
                                        break;

                                    default:
                                        didPopulate = false;
                                        break;
                                    }

                                    if (didPopulate == true)
                                    {
                                        providerFields.Add(field);
                                    }
                                });

                                if (providerFields.Count() > 0)
                                {
                                    mediaAddedEmbed.embeds.First().fields = providerFields;
                                }
                            }

                            pendingSendQueue.Add(mediaAddedEmbed, options);
                        }
                        else
                        {
                            if (queuedUpdateCheck.ContainsKey(queuedItem.Key))
                            {
                                queuedUpdateCheck[queuedItem.Key].Retries++;
                            }
                        }
                    }
                });
            }
            catch (Exception e)
            {
                _logger.ErrorException("Something unexpected happened in the item update checker", e);
            }
        }
Exemple #26
0
 public BaseCommand(IServiceProvider serviceProvider)
 {
     _serviceProvider = serviceProvider;
     _baseOptions     = _serviceProvider.GetRequiredService <IOptions <DiscordOptions> >().Value;
 }
 public DiscordController(IOptionsMonitor <DiscordOptions> optionsAccessor, DiscordLogic discordLogic)
 {
     this.options      = optionsAccessor.CurrentValue;
     this.discordLogic = discordLogic;
 }
 public EpisodeAlertService(IMediaInfoClient mediaInfoClient, DiscordOptions options)
     : base(options)
 {
     _mediaInfoClient = mediaInfoClient;
 }
Exemple #29
0
 public GuildOptionsModule(IOptionsSnapshot <DiscordOptions> discordOptions)
 {
     _discordOptions = discordOptions.Value;
 }
Exemple #30
0
        private void CheckForMetadata(object sender, ElapsedEventArgs eventArgs)
        {
            try
            {
                queuedUpdateCheck.ToList().ForEach(async updateCheck =>
                {
                    Guid itemId = updateCheck.Key;

                    _logger.Debug("{0} queued for recheck", itemId.ToString());

                    BaseItem item = _libraryManager.GetItemById(itemId);

                    LibraryOptions itemLibraryOptions = _libraryManager.GetLibraryOptions(item);
                    DiscordOptions options            = Plugin.Instance.Configuration.Options.FirstOrDefault(opt => opt.MediaAddedOverride == true);
                    PublicSystemInfo sysInfo          = await _applicationHost.GetPublicSystemInfo(CancellationToken.None);
                    ServerConfiguration serverConfig  = _serverConfiguration.Configuration;

                    if (!isInVisibleLibrary(options.MediaBrowserUserId, item))
                    {
                        queuedUpdateCheck.Remove(itemId);
                        _logger.Debug("User does not have access to library, skipping...");
                        return;
                    }

                    // for whatever reason if you have extraction on during library scans then it waits for the extraction to finish before populating the metadata.... I don't get why the f**k it goes in that order
                    // its basically impossible to make a prediction on how long it could take as its dependent on the bitrate, duration, codec, and processing power of the system
                    Boolean localMetadataFallback = queuedUpdateCheck[itemId] >= (itemLibraryOptions.ExtractChapterImagesDuringLibraryScan ? Constants.MaxRetriesBeforeFallback * 5.5 : Constants.MaxRetriesBeforeFallback);

                    if (item.ProviderIds.Count > 0 || localMetadataFallback)
                    {
                        _logger.Debug("{0}[{1}] has metadata, sending notification", item.Id, item.Name);

                        string serverName  = options.ServerNameOverride ? serverConfig.ServerName : "Emby Server";
                        string LibraryType = item.GetType().Name;

                        // build primary info
                        DiscordMessage mediaAddedEmbed = new DiscordMessage
                        {
                            username   = options.Username,
                            avatar_url = options.AvatarUrl,
                            embeds     = new List <DiscordEmbed>()
                            {
                                new DiscordEmbed()
                                {
                                    color  = DiscordWebhookHelper.FormatColorCode(options.EmbedColor),
                                    footer = new Footer
                                    {
                                        text     = $"From {serverName}",
                                        icon_url = options.AvatarUrl
                                    },
                                    timestamp = DateTime.Now
                                }
                            },
                        };

                        // populate title

                        string titleText;

                        if (LibraryType == "Episode")
                        {
                            titleText = $"{item.Parent.Parent.Name} {(item.ParentIndexNumber != null ? $"S{formatIndex(item.ParentIndexNumber)}" : "")}{(item.IndexNumber != null ? $"E{formatIndex(item.IndexNumber)}" : "")} {item.Name}";
                        }
                        else
                        {
                            titleText = $"{item.Name} {(!String.IsNullOrEmpty(item.ProductionYear.ToString()) ? $"({item.ProductionYear.ToString()})" : "")}";
                        }

                        mediaAddedEmbed.embeds.First().title = _localizationManager.GetLocalizedString("ValueHasBeenAddedToLibrary").Replace("{0}", titleText).Replace("{1}", serverName);

                        // populate description
                        if (LibraryType == "Audio")
                        {
                            List <BaseItem> artists = _libraryManager.GetAllArtists(item);

                            IEnumerable <string> artistsFormat = artists.Select(artist =>
                            {
                                if (artist.ProviderIds.Count() > 0)
                                {
                                    KeyValuePair <string, string> firstProvider = artist.ProviderIds.FirstOrDefault();

                                    string providerUrl = firstProvider.Key == "MusicBrainzArtist" ? $"https://musicbrainz.org/artist/{firstProvider.Value}" : $"https://theaudiodb.com/artist/{firstProvider.Value}";

                                    return($"[{artist.Name}]({providerUrl})");
                                }
                                else
                                {
                                    return(artist.Name);
                                }
                            });

                            if (artists.Count() > 0)
                            {
                                mediaAddedEmbed.embeds.First().description = $"By {string.Join(", ", artistsFormat)}";
                            }
                        }
                        else
                        {
                            if (!String.IsNullOrEmpty(item.Overview))
                            {
                                mediaAddedEmbed.embeds.First().description = item.Overview;
                            }
                        }

                        // populate title URL
                        if (!String.IsNullOrEmpty(sysInfo.WanAddress) && !options.ExcludeExternalServerLinks)
                        {
                            mediaAddedEmbed.embeds.First().url = $"{sysInfo.WanAddress}/web/index.html#!/item?id={itemId}&serverId={sysInfo.Id}";
                        }

                        // populate images
                        if (item.HasImage(ImageType.Primary))
                        {
                            string imageUrl = "";

                            if (!item.GetImageInfo(ImageType.Primary, 0).IsLocalFile)
                            {
                                imageUrl = item.GetImagePath(ImageType.Primary);
                            }
                            else if (serverConfig.EnableRemoteAccess == true && !options.ExcludeExternalServerLinks) // in the future we can proxy images through memester server if people want to hide their server address
                            {
                                imageUrl = $"{sysInfo.WanAddress}/emby/Items/{itemId}/Images/Primary";
                            }
                            else
                            {
                                string localPath = item.GetImagePath(ImageType.Primary);
                                Stream imageData = _fileSystem.OpenRead(localPath);

                                try
                                {
                                    imageUrl = await MemesterServiceHelper.UploadImage(imageData, _jsonSerializer, _httpClient);
                                }
                                catch (Exception e)
                                {
                                    _logger.ErrorException("Failed to proxy image", e);
                                }
                            }

                            mediaAddedEmbed.embeds.First().thumbnail = new Thumbnail
                            {
                                url = imageUrl
                            };
                        }


                        if (options.MentionType == MentionTypes.Everyone)
                        {
                            mediaAddedEmbed.content = "@everyone";
                        }
                        else if (options.MentionType == MentionTypes.Here)
                        {
                            mediaAddedEmbed.content = "@here";
                        }

                        // populate external URLs
                        List <Field> providerFields = new List <Field>();

                        if (!localMetadataFallback)
                        {
                            item.ProviderIds.ToList().ForEach(provider =>
                            {
                                Field field = new Field
                                {
                                    name = "External Details"
                                };

                                Boolean didPopulate = true;

                                switch (provider.Key.ToLower())
                                {
                                case "imdb":
                                    field.value = $"[IMDb](https://www.imdb.com/title/{provider.Value}/)";
                                    break;

                                case "tmdb":
                                    field.value = $"[TMDb](https://www.themoviedb.org/{(LibraryType == "Movie" ? "movie" : "tv")}/{provider.Value})";
                                    break;

                                case "musicbrainztrack":
                                    field.value = $"[MusicBrainz Track](https://musicbrainz.org/track/{provider.Value})";
                                    break;

                                case "musicbrainzalbum":
                                    field.value = $"[MusicBrainz Album](https://musicbrainz.org/release/{provider.Value})";
                                    break;

                                case "theaudiodbalbum":
                                    field.value = $"[TADb Album](https://theaudiodb.com/album/{provider.Value})";
                                    break;

                                default:
                                    didPopulate = false;
                                    break;
                                }

                                if (didPopulate == true)
                                {
                                    providerFields.Add(field);
                                }
                            });

                            if (providerFields.Count() > 0)
                            {
                                mediaAddedEmbed.embeds.First().fields = providerFields;
                            }
                        }

                        pendingSendQueue.Add(mediaAddedEmbed, options);

                        queuedUpdateCheck.Remove(itemId);
                    }
                    else
                    {
                        queuedUpdateCheck[itemId]++;

                        _logger.Debug("Attempt: {0}", queuedUpdateCheck[itemId]);
                    }
                });
            }
            catch (Exception e)
            {
                _logger.ErrorException("Something unexpected happened in the update checker", e);
            }
        }
Exemple #31
0
 public LifetimeMonitoringHostedService(ILogger <LifetimeMonitoringHostedService> logger, IOptions <DiscordOptions> discordOptions, IOptions <TwitchOptions> twitchOptions)
 {
     _logger         = logger;
     _discordOptions = discordOptions.Value;
     _twitchOptions  = twitchOptions.Value;
 }