Example #1
0
        public PlantPickService(DbService db, CommandHandler cmd, IBotStrings strings,
                                IDataCache cache, FontProvider fonts, ICurrencyService cs,
                                CommandHandler cmdHandler, DiscordSocketClient client, GamblingConfigService gss)
        {
            _db         = db;
            _strings    = strings;
            _images     = cache.LocalImages;
            _fonts      = fonts;
            _cs         = cs;
            _cmdHandler = cmdHandler;
            _rng        = new NadekoRandom();
            _client     = client;
            _gss        = gss;

            cmd.OnMessageNoTrigger += PotentialFlowerGeneration;
            using (var uow = db.GetDbContext())
            {
                var guildIds = client.Guilds.Select(x => x.Id).ToList();
                var configs  = uow._context.Set <GuildConfig>()
                               .AsQueryable()
                               .Include(x => x.GenerateCurrencyChannelIds)
                               .Where(x => guildIds.Contains(x.GuildId))
                               .ToList();

                _generationChannels = new ConcurrentHashSet <ulong>(configs
                                                                    .SelectMany(c => c.GenerateCurrencyChannelIds.Select(obj => obj.ChannelId)));
            }
        }
Example #2
0
        public SelfService(DiscordSocketClient client, CommandHandler cmdHandler, DbService db,
                           IBotStrings strings, IBotCredentials creds, IDataCache cache, IHttpClientFactory factory,
                           BotConfigService bss)
        {
            _redis       = cache.Redis;
            _cmdHandler  = cmdHandler;
            _db          = db;
            _strings     = strings;
            _client      = client;
            _creds       = creds;
            _cache       = cache;
            _imgs        = cache.LocalImages;
            _httpFactory = factory;
            _bss         = bss;

            var sub = _redis.GetSubscriber();

            if (_client.ShardId == 0)
            {
                sub.Subscribe(_creds.RedisKey() + "_reload_images",
                              delegate { _imgs.Reload(); }, CommandFlags.FireAndForget);
            }

            sub.Subscribe(_creds.RedisKey() + "_leave_guild", async(ch, v) =>
            {
                try
                {
                    var guildStr = v.ToString()?.Trim().ToUpperInvariant();
                    if (string.IsNullOrWhiteSpace(guildStr))
                    {
                        return;
                    }
                    var server = _client.Guilds.FirstOrDefault(g => g.Id.ToString() == guildStr) ??
                                 _client.Guilds.FirstOrDefault(g => g.Name.Trim().ToUpperInvariant() == guildStr);

                    if (server == null)
                    {
                        return;
                    }

                    if (server.OwnerId != _client.CurrentUser.Id)
                    {
                        await server.LeaveAsync().ConfigureAwait(false);
                        Log.Information($"Left server {server.Name} [{server.Id}]");
                    }
                    else
                    {
                        await server.DeleteAsync().ConfigureAwait(false);
                        Log.Information($"Deleted server {server.Name} [{server.Id}]");
                    }
                }
                catch
                {
                }
            }, CommandFlags.FireAndForget);
        }
Example #3
0
        public Help(GlobalPermissionService perms, CommandService cmds, BotConfigService bss,
                    IServiceProvider services, DiscordSocketClient client, IBotStrings strings)
        {
            _cmds     = cmds;
            _bss      = bss;
            _perms    = perms;
            _services = services;
            _client   = client;
            _strings  = strings;

            _lazyClientId = new AsyncLazy <ulong>(async() => (await _client.GetApplicationInfoAsync()).Id);
        }
Example #4
0
        public HelpService(CommandHandler ch, IBotStrings strings,
                           DiscordPermOverrideService dpos, BotConfigService bss)
        {
            _ch      = ch;
            _strings = strings;
            _dpos    = dpos;
            _bss     = bss;


            _rep = new ReplacementBuilder()
                   .WithOverride("%prefix%", () => _bss.GetRawData().Prefix)
                   .WithOverride("%bot.prefix%", () => _bss.GetRawData().Prefix)
                   .Build();
        }
Example #5
0
        public ChatterBotService(DiscordSocketClient client, PermissionService perms,
                                 NadekoBot bot, CommandHandler cmd, IBotStrings strings, IHttpClientFactory factory,
                                 IBotCredentials creds)
        {
            _client      = client;
            _perms       = perms;
            _cmd         = cmd;
            _strings     = strings;
            _creds       = creds;
            _httpFactory = factory;

            ChatterBotGuilds = new ConcurrentDictionary <ulong, Lazy <IChatterBotSession> >(
                bot.AllGuildConfigs
                .Where(gc => gc.CleverbotEnabled)
                .ToDictionary(gc => gc.GuildId, gc => new Lazy <IChatterBotSession>(() => CreateSession(), true)));
        }
Example #6
0
        public TriviaGame(IBotStrings strings, DiscordSocketClient client, GamesConfig config,
                          IDataCache cache, ICurrencyService cs, IGuild guild, ITextChannel channel,
                          TriviaOptions options, string quitCommand)
        {
            _cache        = cache;
            _questionPool = new TriviaQuestionPool(_cache);
            _strings      = strings;
            _client       = client;
            _config       = config;
            _cs           = cs;
            _options      = options;
            _quitCommand  = quitCommand;

            Guild   = guild;
            Channel = channel;
        }
        public void GetContainerExist()
        {
            //ARRANGE
            //mock configuration
            Mock <IConfiguration> mockConfig = new Mock <IConfiguration>();

            mockConfig.SetupGet(x => x[It.IsAny <string>()]).Returns($"{_testDir}/_testfiles/BotStringsContainerFiles");
            //setup container
            BotStringsContainer sutBotStringsCntr = new BotStringsContainer(mockConfig.Object);
            //ACT
            IBotStrings container1 = sutBotStringsCntr.getContainer("file1");
            IBotStrings container2 = sutBotStringsCntr.getContainer("file2");

            //ASSERT
            Assert.That(container1.Container.Count, Is.EqualTo(3));
            Assert.That(container2.Container.Count, Is.EqualTo(2));
        }
Example #8
0
        public PollService(DbService db, IBotStrings strs)
        {
            _db   = db;
            _strs = strs;

            using (var uow = db.GetDbContext())
            {
                ActivePolls = uow.Polls.GetAllPolls()
                              .ToDictionary(x => x.GuildId, x =>
                {
                    var pr      = new PollRunner(db, x);
                    pr.OnVoted += Pr_OnVoted;
                    return(pr);
                })
                              .ToConcurrent();
            }
        }
Example #9
0
        public TicTacToe(IBotStrings strings, DiscordSocketClient client, ITextChannel channel,
                         IGuildUser firstUser, Options options)
        {
            _channel = channel;
            _strings = strings;
            _client  = client;
            _options = options;

            _users = new[] { firstUser, null };
            _state = new int?[, ] {
                { null, null, null },
                { null, null, null },
                { null, null, null },
            };

            _phase    = Phase.Starting;
            _moveLock = new SemaphoreSlim(1, 1);
        }
Example #10
0
        public PermissionService(DiscordSocketClient client, DbService db, CommandHandler cmd, IBotStrings strings)
        {
            _db = db;
            _cmd = cmd;
            _strings = strings;

            using (var uow = _db.GetDbContext())
            {
                foreach (var x in uow.GuildConfigs.Permissionsv2ForAll(client.Guilds.ToArray().Select(x => x.Id).ToList()))
                {
                    Cache.TryAdd(x.GuildId, new PermissionCache()
                    {
                        Verbose = x.VerbosePermissions,
                        PermRole = x.PermissionRole,
                        Permissions = new PermissionsCollection<Permissionv2>(x.Permissions)
                    });
                }
            }
        }
Example #11
0
        public CustomReactionsService(PermissionService perms, DbService db, IBotStrings strings, NadekoBot bot,
                                      DiscordSocketClient client, CommandHandler cmd, GlobalPermissionService gperm, CmdCdService cmdCds,
                                      IPubSub pubSub)
        {
            _db      = db;
            _client  = client;
            _perms   = perms;
            _cmd     = cmd;
            _strings = strings;
            _bot     = bot;
            _gperm   = gperm;
            _cmdCds  = cmdCds;
            _pubSub  = pubSub;
            _rng     = new NadekoRandom();

            _pubSub.Sub(_crsReloadedKey, OnCrsShouldReload);
            pubSub.Sub(_gcrAddedKey, OnGcrAdded);
            pubSub.Sub(_gcrDeletedkey, OnGcrDeleted);
            pubSub.Sub(_gcrEditedKey, OnGcrEdited);

            bot.JoinedGuild   += OnJoinedGuild;
            _client.LeftGuild += OnLeftGuild;
        }
Example #12
0
        public StreamNotificationService(DbService db, DiscordSocketClient client,
                                         IBotStrings strings, IDataCache cache, IBotCredentials creds, IHttpClientFactory httpFactory,
                                         NadekoBot bot)
        {
            _db            = db;
            _client        = client;
            _strings       = strings;
            _multi         = cache.Redis;
            _creds         = creds;
            _streamTracker = new NotifChecker(httpFactory, cache.Redis, creds.RedisKey(), client.ShardId == 0);

            using (var uow = db.GetDbContext())
            {
                var ids          = client.GetGuildIds();
                var guildConfigs = uow._context.Set <GuildConfig>()
                                   .AsQueryable()
                                   .Include(x => x.FollowedStreams)
                                   .Where(x => ids.Contains(x.GuildId))
                                   .ToList();

                _offlineNotificationServers = new ConcurrentHashSet <ulong>(guildConfigs
                                                                            .Where(gc => gc.NotifyStreamOffline)
                                                                            .Select(x => x.GuildId)
                                                                            .ToList());

                var followedStreams = guildConfigs
                                      .SelectMany(x => x.FollowedStreams)
                                      .ToList();

                _shardTrackedStreams = followedStreams
                                       .GroupBy(x => new { Type = x.Type, Name = x.Username.ToLower() })
                                       .ToList()
                                       .ToDictionary(
                    x => new StreamDataKey(x.Key.Type, x.Key.Name.ToLower()),
                    x => x.GroupBy(y => y.GuildId)
                    .ToDictionary(y => y.Key, y => y.AsEnumerable().ToHashSet()));

                // shard 0 will keep track of when there are no more guilds which track a stream
                if (client.ShardId == 0)
                {
                    var allFollowedStreams = uow._context.Set <FollowedStream>()
                                             .AsQueryable()
                                             .ToList();

                    foreach (var fs in allFollowedStreams)
                    {
                        _streamTracker.CacheAddData(fs.CreateKey(), null, replace: false);
                    }

                    _trackCounter = allFollowedStreams
                                    .GroupBy(x => new { Type = x.Type, Name = x.Username.ToLower() })
                                    .ToDictionary(
                        x => new StreamDataKey(x.Key.Type, x.Key.Name),
                        x => x.Select(fs => fs.GuildId).ToHashSet());
                }
            }

            var sub = _multi.GetSubscriber();

            sub.Subscribe($"{_creds.RedisKey()}_streams_offline", HandleStreamsOffline);
            sub.Subscribe($"{_creds.RedisKey()}_streams_online", HandleStreamsOnline);

            if (client.ShardId == 0)
            {
                // only shard 0 will run the tracker,
                // and then publish updates with redis to other shards
                _streamTracker.OnStreamsOffline += OnStreamsOffline;
                _streamTracker.OnStreamsOnline  += OnStreamsOnline;
                _ = _streamTracker.RunAsync();
                _notifCleanupTimer = new Timer(_ =>
                {
                    try
                    {
                        var errorLimit     = TimeSpan.FromHours(12);
                        var failingStreams = _streamTracker.GetFailingStreams(errorLimit, true)
                                             .ToList();

                        if (!failingStreams.Any())
                        {
                            return;
                        }

                        var deleteGroups = failingStreams.GroupBy(x => x.Type)
                                           .ToDictionary(x => x.Key, x => x.Select(x => x.Name).ToList());

                        using (var uow = _db.GetDbContext())
                        {
                            foreach (var kvp in deleteGroups)
                            {
                                Log.Information($"Deleting {kvp.Value.Count} {kvp.Key} streams because " +
                                                $"they've been erroring for more than {errorLimit}: {string.Join(", ", kvp.Value)}");

                                var toDelete = uow._context.Set <FollowedStream>()
                                               .AsQueryable()
                                               .Where(x => x.Type == kvp.Key && kvp.Value.Contains(x.Username))
                                               .ToList();

                                uow._context.RemoveRange(toDelete);
                                uow.SaveChanges();

                                foreach (var loginToDelete in kvp.Value)
                                {
                                    _streamTracker.UntrackStreamByKey(new StreamDataKey(kvp.Key, loginToDelete));
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Error("Error cleaning up FollowedStreams");
                        Log.Error(ex.ToString());
                    }
                }, null, TimeSpan.FromMinutes(30), TimeSpan.FromMinutes(30));

                sub.Subscribe($"{_creds.RedisKey()}_follow_stream", HandleFollowStream);
                sub.Subscribe($"{_creds.RedisKey()}_unfollow_stream", HandleUnfollowStream);
            }

            bot.JoinedGuild  += ClientOnJoinedGuild;
            client.LeftGuild += ClientOnLeftGuild;
        }
Example #13
0
 public static string[] RealRemarksArr(this CommandInfo cmd, IBotStrings strings, ulong?guildId, string prefix)
 => Array.ConvertAll(strings.GetCommandStrings(cmd.MethodName(), guildId).Args,
                     arg => GetFullUsage(cmd.Name, arg, prefix));
Example #14
0
 public static string RealSummary(this CommandInfo cmd, IBotStrings strings, ulong?guildId, string prefix)
 => string.Format(strings.GetCommandStrings(cmd.Name, guildId).Desc, prefix);
Example #15
0
 public SelfCommands(DiscordSocketClient client, NadekoBot bot, IBotStrings strings)
 {
     _client  = client;
     _bot     = bot;
     _strings = strings;
 }
Example #16
0
        public XpService(DiscordSocketClient client, CommandHandler cmd, NadekoBot bot, DbService db,
                         IBotStrings strings, IDataCache cache, FontProvider fonts, IBotCredentials creds,
                         ICurrencyService cs, IHttpClientFactory http, XpConfigService xpConfig)
        {
            _db               = db;
            _cmd              = cmd;
            _images           = cache.LocalImages;
            _strings          = strings;
            _cache            = cache;
            _fonts            = fonts;
            _creds            = creds;
            _cs               = cs;
            _httpFactory      = http;
            _xpConfig         = xpConfig;
            _excludedServers  = new ConcurrentHashSet <ulong>();
            _excludedChannels = new ConcurrentDictionary <ulong, ConcurrentHashSet <ulong> >();
            _client           = client;

            InternalReloadXpTemplate();

            if (client.ShardId == 0)
            {
                var sub = _cache.Redis.GetSubscriber();
                sub.Subscribe(_creds.RedisKey() + "_reload_xp_template",
                              (ch, val) => InternalReloadXpTemplate());
            }

            //load settings
            var allGuildConfigs = bot.AllGuildConfigs
                                  .Where(x => x.XpSettings != null)
                                  .ToList();

            _excludedChannels = allGuildConfigs
                                .ToDictionary(
                x => x.GuildId,
                x => new ConcurrentHashSet <ulong>(x.XpSettings
                                                   .ExclusionList
                                                   .Where(ex => ex.ItemType == ExcludedItemType.Channel)
                                                   .Select(ex => ex.ItemId)
                                                   .Distinct()))
                                .ToConcurrent();

            _excludedRoles = allGuildConfigs
                             .ToDictionary(
                x => x.GuildId,
                x => new ConcurrentHashSet <ulong>(x.XpSettings
                                                   .ExclusionList
                                                   .Where(ex => ex.ItemType == ExcludedItemType.Role)
                                                   .Select(ex => ex.ItemId)
                                                   .Distinct()))
                             .ToConcurrent();

            _excludedServers = new ConcurrentHashSet <ulong>(
                allGuildConfigs.Where(x => x.XpSettings.ServerExcluded)
                .Select(x => x.GuildId));

            _cmd.OnMessageNoTrigger += _cmd_OnMessageNoTrigger;

#if !GLOBAL_NADEKO
            _client.UserVoiceStateUpdated += _client_OnUserVoiceStateUpdated;

            // Scan guilds on startup.
            _client.GuildAvailable += _client_OnGuildAvailable;
            foreach (var guild in _client.Guilds)
            {
                _client_OnGuildAvailable(guild);
            }
#endif
            updateXpTask = Task.Run(UpdateLoop);
        }