Beispiel #1
0
        public ChatterBotService(DiscordSocketClient client, PermissionService perms,
                                 Kotocorn bot, CommandHandler cmd, KotocornStrings strings,
                                 IBotCredentials creds)
        {
            _client  = client;
            _log     = LogManager.GetCurrentClassLogger();
            _perms   = perms;
            _cmd     = cmd;
            _strings = strings;
            _creds   = creds;

            ChatterBotGuilds = new ConcurrentDictionary <ulong, Lazy <IChatterBotSession> >(
                bot.AllGuildConfigs
                .Where(gc => gc.CleverbotEnabled)
                .ToDictionary(gc => gc.GuildId, gc => new Lazy <IChatterBotSession>(() => CreateSession(), true)));
        }
        public CurrencyEventsService(DbService db, DiscordSocketClient client,
                                     IBotCredentials creds, ICurrencyService cs, IBotConfigProvider bc)
        {
            _db     = db;
            _client = client;
            _cs     = cs;
            _bc     = bc;
            _creds  = creds;
            _http   = new HttpClient();
            _log    = LogManager.GetCurrentClassLogger();

            if (_client.ShardId == 0)
            {
                Task t = BotlistUpvoteLoop();
            }
        }
        public void SetNullable_CustomSetters_ThrownArgumentException(
            IBotCredentials botCredentials,
            HttpClient httpClient,
            ILogger logger)
        {
            // Act
            Func <IVTopeBot> botBuilder = () => new VTopeBotBuilder()
                                          .SetBot(botCredentials)
                                          .UseHttpClient(httpClient)
                                          .UseLogger(logger)
                                          .Build();

            // Arrange
            Assert.NotNull(botBuilder);
            Assert.Throws <ArgumentNullException>(botBuilder);
        }
Beispiel #4
0
        public GoogleApiService(IBotCredentials creds)
        {
            _creds = creds;

            var bcs = new BaseClientService.Initializer
            {
                ApplicationName = "MitternachtBot",
                ApiKey          = _creds.GoogleApiKey
            };

            Log = LogManager.GetCurrentClassLogger();

            _yt = new YouTubeService(bcs);
            _sh = new UrlshortenerService(bcs);
            _cs = new CustomsearchService(bcs);
        }
Beispiel #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)));
        }
        public RedisLocalDataCache(ConnectionMultiplexer con, IBotCredentials creds, int shardId)
        {
            _con   = con;
            _creds = creds;
            _log   = LogManager.GetCurrentClassLogger();

            if (shardId == 0)
            {
                if (!File.Exists(pokemonListFile))
                {
                    _log.Warn(pokemonListFile + " is missing. Pokemon abilities not loaded.");
                }
                else
                {
                    Pokemons = JsonConvert.DeserializeObject <Dictionary <string, SearchPokemon> >(File.ReadAllText(pokemonListFile));
                }

                if (!File.Exists(pokemonAbilitiesFile))
                {
                    _log.Warn(pokemonAbilitiesFile + " is missing. Pokemon abilities not loaded.");
                }
                else
                {
                    PokemonAbilities = JsonConvert.DeserializeObject <Dictionary <string, SearchPokemonAbility> >(File.ReadAllText(pokemonAbilitiesFile));
                }

                try
                {
                    TriviaQuestions = JsonConvert.DeserializeObject <TriviaQuestion[]>(File.ReadAllText(questionsFile));
                    PokemonMap      = JsonConvert.DeserializeObject <PokemonNameId[]>(File.ReadAllText(pokemonMapPath))
                                      .ToDictionary(x => x.Id, x => x.Name);

                    //ZGD: Friend list from URL into local cache, into Dictionary<> data type
                    //to mimic what's being used in the Pokemon trivia.
                    WebClient wc            = new WebClient();
                    int       friendCounter = 0;
                    FriendMap = JsonConvert.DeserializeObject <FriendsNameId[]>(wc.DownloadString(friendListUrl))
                                .ToDictionary(x => friendCounter++, x => x);
                    //ZGD: end of Friend list code
                }
                catch (Exception ex)
                {
                    _log.Error(ex);
                    throw;
                }
            }
        }
Beispiel #7
0
        public DbService(IBotCredentials creds)
        {
            var builder = new SqliteConnectionStringBuilder(creds.Db.ConnectionString);

            builder.DataSource = Path.Combine(AppContext.BaseDirectory, builder.DataSource);

            var optionsBuilder = new DbContextOptionsBuilder <NadekoContext>()
                                 //.UseLoggerFactory(_loggerFactory)
            ;

            optionsBuilder.UseSqlite(builder.ToString());
            options = optionsBuilder.Options;

            optionsBuilder = new DbContextOptionsBuilder <NadekoContext>();
            optionsBuilder.UseSqlite(builder.ToString(), x => x.SuppressForeignKeyEnforcement());
            migrateOptions = optionsBuilder.Options;
        }
        public PatreonRewardsService(IBotCredentials creds, DbService db,
                                     ICurrencyService currency, IHttpClientFactory factory,
                                     DiscordSocketClient client, IBotConfigProvider bc)
        {
            _log         = LogManager.GetCurrentClassLogger();
            _creds       = creds;
            _db          = db;
            _currency    = currency;
            _bc          = bc;
            _httpFactory = factory;

            if (client.ShardId == 0)
            {
                _updater = new Timer(async _ => await RefreshPledges().ConfigureAwait(false),
                                     null, TimeSpan.Zero, Interval);
            }
        }
Beispiel #9
0
        public PatreonRewardsService(IBotCredentials creds, DbService db,
                                     ICurrencyService currency, IHttpClientFactory factory,
                                     DiscordSocketClient client, GamblingConfigService gamblingConfigService)
        {
            _creds    = creds;
            _db       = db;
            _currency = currency;
            _gamblingConfigService = gamblingConfigService;
            _httpFactory           = factory;
            _client = client;

            if (client.ShardId == 0)
            {
                _updater = new Timer(async _ => await RefreshPledges().ConfigureAwait(false),
                                     null, TimeSpan.Zero, Interval);
            }
        }
Beispiel #10
0
        public GoogleApiService(IBotCredentials creds, IHttpClientFactory factory)
        {
            _creds       = creds;
            _httpFactory = factory;

            var bcs = new BaseClientService.Initializer
            {
                ApplicationName = "Nadeko Bot",
                ApiKey          = _creds.GoogleApiKey,
            };

            _log = LogManager.GetCurrentClassLogger();

            yt = new YouTubeService(bcs);
            sh = new UrlshortenerService(bcs);
            cs = new CustomsearchService(bcs);
        }
Beispiel #11
0
        public WebMiningService(Kotocorn Kotocorn, IBotCredentials creds, DbService db, CurrencyService cs)
        {
            _log   = LogManager.GetCurrentClassLogger();
            _creds = creds;
            _http  = new HttpClient();
            _db    = db;
            _cs    = cs;

            if (!string.IsNullOrWhiteSpace(_creds.MiningProxyCreds))
            {
                var byteArray = Encoding.ASCII.GetBytes(_creds.MiningProxyCreds);
                _http.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
            }
            if (Kotocorn.Client.ShardId == 0)
            {
                _reqTask = RequestAsync();
            }
        }
Beispiel #12
0
        public DbService(IBotCredentials creds)
        {
            var optionsBuilder = new DbContextOptionsBuilder();

            optionsBuilder.UseSqlite(creds.Db.ConnectionString);
            _options = optionsBuilder.Options;
            //switch (_creds.Db.Type.ToUpperInvariant())
            //{
            //    case "SQLITE":
            //        dbType = typeof(NadekoSqliteContext);
            //        break;
            //    //case "SQLSERVER":
            //    //    dbType = typeof(NadekoSqlServerContext);
            //    //    break;
            //    default:
            //        break;

            //}
        }
Beispiel #13
0
        public SelfService(DiscordSocketClient client, NadekoBot bot, CommandHandler cmdHandler, DbService db,
                           IBotConfigProvider bc, ILocalization localization, NadekoStrings strings, IBotCredentials creds)
        {
            _bot          = bot;
            _cmdHandler   = cmdHandler;
            _db           = db;
            _log          = LogManager.GetCurrentClassLogger();
            _localization = localization;
            _strings      = strings;
            _client       = client;
            _creds        = creds;
            _bc           = bc;

            Task.Run(async() =>
            {
                await bot.Ready.Task.ConfigureAwait(false);

                foreach (var cmd in bc.BotConfig.StartupCommands)
                {
                    var prefix = _cmdHandler.GetPrefix(cmd.GuildId);
                    //if someone already has .die as their startup command, ignore it
                    if (cmd.CommandText.StartsWith(prefix + "die"))
                    {
                        continue;
                    }
                    await cmdHandler.ExecuteExternal(cmd.GuildId, cmd.ChannelId, cmd.CommandText);
                    await Task.Delay(400).ConfigureAwait(false);
                }
            });

            Task.Run(async() =>
            {
                await bot.Ready.Task.ConfigureAwait(false);

                await Task.Delay(5000);

                if (client.ShardId == 0)
                {
                    LoadOwnerChannels();
                }
            });
        }
Beispiel #14
0
        public CommandHandler(DiscordSocketClient client, DbService db, IBotConfigProvider bc, IEnumerable <GuildConfig> gcs, CommandService commandService, IBotCredentials credentials, NadekoBot bot)
        {
            _client         = client;
            _commandService = commandService;
            _creds          = credentials;
            _bot            = bot;
            _db             = db;

            _log = LogManager.GetCurrentClassLogger();

            _clearUsersOnShortCooldown = new Timer(_ =>
            {
                UsersOnShortCooldown.Clear();
            }, null, GlobalCommandsCooldown, GlobalCommandsCooldown);

            DefaultPrefix = bc.BotConfig.DefaultPrefix;
            _prefixes     = gcs
                            .Where(x => x.Prefix != null)
                            .ToDictionary(x => x.GuildId, x => x.Prefix)
                            .ToConcurrent();
        }
Beispiel #15
0
        public RedisCache(IBotCredentials creds, int shardId)
        {
            _log = LogManager.GetCurrentClassLogger();

            ConfigurationOptions conf;

            if (!string.IsNullOrWhiteSpace(creds.RedisOptions))
            {
                conf = ConfigurationOptions.Parse(creds.RedisOptions);
            }
            else
            {
                conf = ConfigurationOptions.Parse("127.0.0.1,syncTimeout=3000");
            }

            Redis = ConnectionMultiplexer.Connect(conf);
            Redis.PreserveAsyncOrder = false;
            LocalImages = new RedisImagesCache(Redis, creds);
            LocalData   = new RedisLocalDataCache(Redis, creds, shardId);
            _redisKey   = creds.RedisKey();
        }
Beispiel #16
0
        public DbService(IBotCredentials creds)
        {
            var optionsBuilder = new DbContextOptionsBuilder <NadekoContext>()
                                 //.UseLoggerFactory(_loggerFactory)
            ;

            if (creds.Db.Type.ToLower() == "sqlserver")
            {
                optionsBuilder.UseSqlServer(creds.Db.ConnectionString);
            }
            else
            {
                optionsBuilder.UseNpgsql(creds.Db.ConnectionString);
            }

            options = optionsBuilder.Options;

            //optionsBuilder = new DbContextOptionsBuilder<NadekoContext>();
            //optionsBuilder.UseSqlServer(builder.ToString(), x => x.SuppressForeignKeyEnforcement());
            migrateOptions = optionsBuilder.Options;
        }
Beispiel #17
0
        public MusicService(DiscordSocketClient client, IGoogleApiService google,
                            NadekoStrings strings, ILocalization localization, DbService db,
                            SoundCloudApiService sc, IBotCredentials creds, IEnumerable <GuildConfig> gcs)
        {
            _client       = client;
            _google       = google;
            _strings      = strings;
            _localization = localization;
            _db           = db;
            _sc           = sc;
            _creds        = creds;
            _log          = LogManager.GetCurrentClassLogger();

            try { Directory.Delete(MusicDataPath, true); } catch { }

            _defaultVolumes = new ConcurrentDictionary <ulong, float>(gcs.ToDictionary(x => x.GuildId, x => x.DefaultMusicVolume));

            Directory.CreateDirectory(MusicDataPath);

            //_t = new Timer(_ => _log.Info(MusicPlayers.Count(x => x.Value.Current.Current != null)), null, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5));
        }
Beispiel #18
0
        public RedisLocalDataCache(ConnectionMultiplexer con, IBotCredentials creds, int shardId)
        {
            _con   = con;
            _creds = creds;
            _log   = LogManager.GetCurrentClassLogger();

            if (shardId == 0)
            {
                if (!File.Exists(pokemonListFile))
                {
                    _log.Warn(pokemonListFile + " is missing. Pokemon abilities not loaded.");
                }
                else
                {
                    Pokemons = JsonConvert.DeserializeObject <Dictionary <string, SearchPokemon> >(File.ReadAllText(pokemonListFile));
                }

                if (!File.Exists(pokemonAbilitiesFile))
                {
                    _log.Warn(pokemonAbilitiesFile + " is missing. Pokemon abilities not loaded.");
                }
                else
                {
                    PokemonAbilities = JsonConvert.DeserializeObject <Dictionary <string, SearchPokemonAbility> >(File.ReadAllText(pokemonAbilitiesFile));
                }

                try
                {
                    TriviaQuestions = JsonConvert.DeserializeObject <TriviaQuestion[]>(File.ReadAllText(questionsFile));
                    PokemonMap      = JsonConvert.DeserializeObject <PokemonNameId[]>(File.ReadAllText(pokemonMapPath))
                                      .ToDictionary(x => x.Id, x => x.Name);
                }
                catch (Exception ex)
                {
                    _log.Error(ex);
                    throw;
                }
            }
        }
Beispiel #19
0
        public SelfService(DiscordSocketClient client, Mitternacht.MitternachtBot bot, CommandHandler cmdHandler, DbService db,
                           IBotConfigProvider bc, ILocalization localization, StringService strings, IBotCredentials creds)
        {
            _bot          = bot;
            _cmdHandler   = cmdHandler;
            _db           = db;
            _log          = LogManager.GetCurrentClassLogger();
            _localization = localization;
            _strings      = strings;
            _client       = client;
            _creds        = creds;
            _bc           = bc;

            var _ = Task.Run(async() =>
            {
                await bot.Ready.Task.ConfigureAwait(false);

                foreach (var cmd in bc.BotConfig.StartupCommands)
                {
                    await cmdHandler.ExecuteExternal(cmd.GuildId, cmd.ChannelId, cmd.CommandText);
                    await Task.Delay(400).ConfigureAwait(false);
                }
            });

            var ___ = Task.Run(async() =>
            {
                await bot.Ready.Task.ConfigureAwait(false);

                await Task.Delay(5000);

                _client.Guilds.SelectMany(g => g.Users);

                if (client.ShardId == 0)
                {
                    LoadOwnerChannels();
                }
            });
        }
Beispiel #20
0
        public RepeaterService(DiscordSocketClient client, DbService db, IBotCredentials creds)
        {
            _db     = db;
            _creds  = creds;
            _client = client;

            var uow            = _db.GetDbContext();
            var shardRepeaters = uow
                                 ._context
                                 .Set <Repeater>()
                                 .FromSqlInterpolated($@"select * from repeaters 
where ((guildid >> 22) % {_creds.TotalShards}) == {_client.ShardId};")
                                 .AsNoTracking()
                                 .ToList();

            _noRedundant = new ConcurrentHashSet <int>(shardRepeaters
                                                       .Where(x => x.NoRedundant)
                                                       .Select(x => x.Id));

            _repeaterQueue = new LinkedList <RunningRepeater>(shardRepeaters
                                                              .Select(rep => new RunningRepeater(rep))
                                                              .OrderBy(x => x.NextTime));
        }
Beispiel #21
0
        public MusicService(DiscordSocketClient client, IGoogleApiService google,
                            NadekoStrings strings, ILocalization localization, DbService db,
                            SoundCloudApiService sc, IBotCredentials creds, NadekoBot bot)
        {
            _client       = client;
            _google       = google;
            _strings      = strings;
            _localization = localization;
            _db           = db;
            _sc           = sc;
            _creds        = creds;
            _log          = LogManager.GetCurrentClassLogger();

            _client.LeftGuild += _client_LeftGuild;

            try { Directory.Delete(MusicDataPath, true); } catch { }

            _defaultVolumes = new ConcurrentDictionary <ulong, float>(
                bot.AllGuildConfigs
                .ToDictionary(x => x.GuildId, x => x.DefaultMusicVolume));

            Directory.CreateDirectory(MusicDataPath);
        }
Beispiel #22
0
        public XpService(DiscordSocketClient client, CommandHandler cmd, IBotConfigProvider bc,
                         NadekoBot bot, DbService db, NadekoStrings strings, IDataCache cache,
                         FontProvider fonts, IBotCredentials creds, ICurrencyService cs, IHttpClientFactory http)
        {
            _db          = db;
            _cmd         = cmd;
            _bc          = bc;
            _images      = cache.LocalImages;
            _log         = LogManager.GetCurrentClassLogger();
            _strings     = strings;
            _cache       = cache;
            _fonts       = fonts;
            _creds       = creds;
            _cs          = cs;
            _httpFactory = http;
            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);

            _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;

            updateXpTask = Task.Run(async() =>
            {
                while (true)
                {
                    await Task.Delay(TimeSpan.FromSeconds(5));
                    try
                    {
                        var toNotify    = new List <(IMessageChannel MessageChannel, IUser User, int Level, XpNotificationType NotifyType, NotifOf NotifOf)>();
                        var roleRewards = new Dictionary <ulong, List <XpRoleReward> >();
                        var curRewards  = new Dictionary <ulong, List <XpCurrencyReward> >();

                        var toAddTo = new List <UserCacheItem>();
                        while (_addMessageXp.TryDequeue(out var usr))
                        {
                            toAddTo.Add(usr);
                        }

                        var group = toAddTo.GroupBy(x => (GuildId: x.Guild.Id, x.User));
                        if (toAddTo.Count == 0)
                        {
                            continue;
                        }

                        using (var uow = _db.UnitOfWork)
                        {
                            foreach (var item in group)
                            {
                                var xp = item.Select(x => bc.BotConfig.XpPerMessage).Sum();

                                //1. Mass query discord users and userxpstats and get them from local dict
                                //2. (better but much harder) Move everything to the database, and get old and new xp
                                // amounts for every user (in order to give rewards)

                                var usr = uow.Xp.GetOrCreateUser(item.Key.GuildId, item.Key.User.Id);
                                var du  = uow.DiscordUsers.GetOrCreate(item.Key.User);

                                var globalXp           = du.TotalXp;
                                var oldGlobalLevelData = new LevelStats(globalXp);
                                var newGlobalLevelData = new LevelStats(globalXp + xp);

                                var oldGuildLevelData = new LevelStats(usr.Xp + usr.AwardedXp);
                                usr.Xp     += xp;
                                du.TotalXp += xp;
                                if (du.Club != null)
                                {
                                    du.Club.Xp += xp;
                                }
                                var newGuildLevelData = new LevelStats(usr.Xp + usr.AwardedXp);

                                if (oldGlobalLevelData.Level < newGlobalLevelData.Level)
                                {
                                    du.LastLevelUp = DateTime.UtcNow;
                                    var first      = item.First();
                                    if (du.NotifyOnLevelUp != XpNotificationType.None)
                                    {
                                        toNotify.Add((first.Channel, first.User, newGlobalLevelData.Level, du.NotifyOnLevelUp, NotifOf.Global));
                                    }
                                }

                                if (oldGuildLevelData.Level < newGuildLevelData.Level)
                                {
                                    usr.LastLevelUp = DateTime.UtcNow;
                                    //send level up notification
                                    var first = item.First();
                                    if (usr.NotifyOnLevelUp != XpNotificationType.None)
                                    {
                                        toNotify.Add((first.Channel, first.User, newGuildLevelData.Level, usr.NotifyOnLevelUp, NotifOf.Server));
                                    }

                                    //give role
                                    if (!roleRewards.TryGetValue(usr.GuildId, out var rrews))
                                    {
                                        rrews = uow.GuildConfigs.XpSettingsFor(usr.GuildId).RoleRewards.ToList();
                                        roleRewards.Add(usr.GuildId, rrews);
                                    }

                                    if (!curRewards.TryGetValue(usr.GuildId, out var crews))
                                    {
                                        crews = uow.GuildConfigs.XpSettingsFor(usr.GuildId).CurrencyRewards.ToList();
                                        curRewards.Add(usr.GuildId, crews);
                                    }

                                    var rrew = rrews.FirstOrDefault(x => x.Level == newGuildLevelData.Level);
                                    if (rrew != null)
                                    {
                                        var role = first.User.Guild.GetRole(rrew.RoleId);
                                        if (role != null)
                                        {
                                            var __ = first.User.AddRoleAsync(role);
                                        }
                                    }
                                    //get currency reward for this level
                                    var crew = crews.FirstOrDefault(x => x.Level == newGuildLevelData.Level);
                                    if (crew != null)
                                    {
                                        //give the user the reward if it exists
                                        await _cs.AddAsync(item.Key.User.Id, "Level-up Reward", crew.Amount);
                                    }
                                }
                            }

                            uow.Complete();
                        }

                        await Task.WhenAll(toNotify.Select(async x =>
                        {
                            if (x.NotifOf == NotifOf.Server)
                            {
                                if (x.NotifyType == XpNotificationType.Dm)
                                {
                                    var chan = await x.User.GetOrCreateDMChannelAsync();
                                    if (chan != null)
                                    {
                                        await chan.SendConfirmAsync(_strings.GetText("level_up_dm",
                                                                                     (x.MessageChannel as ITextChannel)?.GuildId,
                                                                                     "xp",
                                                                                     x.User.Mention, Format.Bold(x.Level.ToString()),
                                                                                     Format.Bold((x.MessageChannel as ITextChannel)?.Guild.ToString() ?? "-")));
                                    }
                                }
                                else // channel
                                {
                                    await x.MessageChannel.SendConfirmAsync(_strings.GetText("level_up_channel",
                                                                                             (x.MessageChannel as ITextChannel)?.GuildId,
                                                                                             "xp",
                                                                                             x.User.Mention, Format.Bold(x.Level.ToString())));
                                }
                            }
                            else
                            {
                                IMessageChannel chan;
                                if (x.NotifyType == XpNotificationType.Dm)
                                {
                                    chan = await x.User.GetOrCreateDMChannelAsync();
                                }
                                else // channel
                                {
                                    chan = x.MessageChannel;
                                }
                                await chan.SendConfirmAsync(_strings.GetText("level_up_global",
                                                                             (x.MessageChannel as ITextChannel)?.GuildId,
                                                                             "xp",
                                                                             x.User.Mention, Format.Bold(x.Level.ToString())));
                            }
                        }));
                    }
                    catch (Exception ex)
                    {
                        _log.Warn(ex);
                    }
                }
            });
        }
Beispiel #23
0
        public StatsService(DiscordSocketClient client, CommandHandler cmdHandler,
                            IBotCredentials creds, NadekoBot nadeko,
                            IDataCache cache)
        {
            _client = client;
            _creds  = creds;
            _redis  = cache.Redis;

            _started = DateTime.UtcNow;
            _client.MessageReceived    += _ => Task.FromResult(Interlocked.Increment(ref _messageCounter));
            cmdHandler.CommandExecuted += (_, e) => Task.FromResult(Interlocked.Increment(ref _commandsRan));

            _client.ChannelCreated += (c) =>
            {
                var _ = Task.Run(() =>
                {
                    if (c is ITextChannel)
                    {
                        Interlocked.Increment(ref _textChannels);
                    }
                    else if (c is IVoiceChannel)
                    {
                        Interlocked.Increment(ref _voiceChannels);
                    }
                });

                return(Task.CompletedTask);
            };

            _client.ChannelDestroyed += (c) =>
            {
                var _ = Task.Run(() =>
                {
                    if (c is ITextChannel)
                    {
                        Interlocked.Decrement(ref _textChannels);
                    }
                    else if (c is IVoiceChannel)
                    {
                        Interlocked.Decrement(ref _voiceChannels);
                    }
                });

                return(Task.CompletedTask);
            };

            _client.GuildAvailable += (g) =>
            {
                var _ = Task.Run(() =>
                {
                    var tc = g.Channels.Count(cx => cx is ITextChannel);
                    var vc = g.Channels.Count - tc;
                    Interlocked.Add(ref _textChannels, tc);
                    Interlocked.Add(ref _voiceChannels, vc);
                });
                return(Task.CompletedTask);
            };

            _client.JoinedGuild += (g) =>
            {
                var _ = Task.Run(() =>
                {
                    var tc = g.Channels.Count(cx => cx is ITextChannel);
                    var vc = g.Channels.Count - tc;
                    Interlocked.Add(ref _textChannels, tc);
                    Interlocked.Add(ref _voiceChannels, vc);
                });
                return(Task.CompletedTask);
            };

            _client.GuildUnavailable += (g) =>
            {
                var _ = Task.Run(() =>
                {
                    var tc = g.Channels.Count(cx => cx is ITextChannel);
                    var vc = g.Channels.Count - tc;
                    Interlocked.Add(ref _textChannels, -tc);
                    Interlocked.Add(ref _voiceChannels, -vc);
                });

                return(Task.CompletedTask);
            };

            _client.LeftGuild += (g) =>
            {
                var _ = Task.Run(() =>
                {
                    var tc = g.Channels.Count(cx => cx is ITextChannel);
                    var vc = g.Channels.Count - tc;
                    Interlocked.Add(ref _textChannels, -tc);
                    Interlocked.Add(ref _voiceChannels, -vc);
                });

                return(Task.CompletedTask);
            };

            if (_client.ShardId == 0)
            {
                _carbonitexTimer = new Timer(async(state) =>
                {
                    if (string.IsNullOrWhiteSpace(_creds.CarbonKey))
                    {
                        return;
                    }
                    try
                    {
                        using (var http = new HttpClient())
                        {
                            using (var content = new FormUrlEncodedContent(
                                       new Dictionary <string, string> {
                                { "servercount", nadeko.GuildCount.ToString() },
                                { "key", _creds.CarbonKey }
                            }))
                            {
                                content.Headers.Clear();
                                content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

                                await http.PostAsync("https://www.carbonitex.net/discord/data/botdata.php", content).ConfigureAwait(false);
                            }
                        }
                    }
                    catch
                    {
                        // ignored
                    }
                }, null, TimeSpan.FromHours(1), TimeSpan.FromHours(1));

                var platform = "other";
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    platform = "linux";
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                {
                    platform = "osx";
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    platform = "windows";
                }

                _dataTimer = new Timer(async(state) =>
                {
                    try
                    {
                        using (var http = new HttpClient())
                        {
                            using (var content = new FormUrlEncodedContent(
                                       new Dictionary <string, string> {
                                { "id", string.Concat(MD5.Create().ComputeHash(Encoding.ASCII.GetBytes(_creds.ClientId.ToString())).Select(x => x.ToString("X2"))) },
                                { "guildCount", nadeko.GuildCount.ToString() },
                                { "version", BotVersion },
                                { "platform", platform }
                            }))
                            {
                                content.Headers.Clear();
                                content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

                                await http.PostAsync("https://selfstats.nadekobot.me/", content).ConfigureAwait(false);
                            }
                        }
                    }
                    catch
                    {
                        // ignored
                    }
                }, null, TimeSpan.FromSeconds(1), TimeSpan.FromHours(1));
            }
        }
Beispiel #24
0
 public Searches(IBotCredentials creds, IGoogleApiService google)
 {
     _creds  = creds;
     _google = google;
 }
Beispiel #25
0
        public XpService(DiscordSocketClient client, CommandHandler cmd, IBotConfigProvider bc,
                         NadekoBot bot, DbService db, NadekoStrings strings, IDataCache cache,
                         FontProvider fonts, IBotCredentials creds, ICurrencyService cs, IHttpClientFactory http)
        {
            _db          = db;
            _cmd         = cmd;
            _bc          = bc;
            _images      = cache.LocalImages;
            _log         = LogManager.GetCurrentClassLogger();
            _strings     = strings;
            _cache       = cache;
            _fonts       = fonts;
            _creds       = creds;
            _cs          = cs;
            _httpFactory = http;
            _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);
        }
Beispiel #26
0
        public SelfService(DiscordSocketClient client, NadekoBot bot, CommandHandler cmdHandler, DbService db,
                           IBotConfigProvider bc, ILocalization localization, NadekoStrings strings, IBotCredentials creds,
                           IDataCache cache)
        {
            _redis        = cache.Redis;
            _bot          = bot;
            _cmdHandler   = cmdHandler;
            _db           = db;
            _log          = LogManager.GetCurrentClassLogger();
            _localization = localization;
            _strings      = strings;
            _client       = client;
            _creds        = creds;
            _bc           = bc;
            _cache        = cache;
            _imgs         = cache.LocalImages;
            if (_client.ShardId == 0)
            {
                _updateTimer = new Timer(async _ =>
                {
                    try
                    {
                        var ch = ownerChannels?.Values.FirstOrDefault();

                        if (ch == null) // no owner channels
                        {
                            return;
                        }

                        var cfo = _bc.BotConfig.CheckForUpdates;
                        if (cfo == UpdateCheckType.None)
                        {
                            return;
                        }

                        string data;
                        if ((cfo == UpdateCheckType.Commit && (data = await GetNewCommit()) != null) ||
                            (cfo == UpdateCheckType.Release && (data = await GetNewRelease()) != null))
                        {
                            await ch.SendConfirmAsync("New Bot Update", data).ConfigureAwait(false);
                        }
                    }
                    catch (Exception ex)
                    {
                        _log.Warn(ex);
                    }
                }, null, TimeSpan.FromHours(8), TimeSpan.FromHours(8));
            }

            var sub = _redis.GetSubscriber();

            sub.Subscribe(_creds.RedisKey() + "_reload_images",
                          delegate { _imgs.Reload(); }, CommandFlags.FireAndForget);
            sub.Subscribe(_creds.RedisKey() + "_reload_bot_config",
                          delegate { _bc.Reload(); }, CommandFlags.FireAndForget);

            Task.Run(async() =>
            {
                await bot.Ready.Task.ConfigureAwait(false);

                _autoCommands = bc.BotConfig
                                .StartupCommands
                                .Where(x => x.Interval >= 5)
                                .GroupBy(x => x.GuildId)
                                .ToDictionary(
                    x => x.Key,
                    y => y.ToDictionary(x => x.Id,
                                        x => TimerFromStartupCommand((StartupCommand)x))
                    .ToConcurrent())
                                .ToConcurrent();

                foreach (var cmd in bc.BotConfig.StartupCommands.Where(x => x.Interval <= 0))
                {
                    try { await ExecuteCommand(cmd); } catch { }
                }
            });

            Task.Run(async() =>
            {
                await bot.Ready.Task.ConfigureAwait(false);

                await Task.Delay(5000).ConfigureAwait(false);

                if (client.ShardId == 0)
                {
                    await LoadOwnerChannels().ConfigureAwait(false);
                }
            });
        }
Beispiel #27
0
 public OsuCommands(IGoogleApiService google, IBotCredentials creds, IHttpClientFactory factory)
 {
     _google      = google;
     _creds       = creds;
     _httpFactory = factory;
 }
Beispiel #28
0
 public BlacklistCommands(BlacklistService bs, DbService db, IBotCredentials creds)
 {
     _bs    = bs;
     _db    = db;
     _creds = creds;
 }
Beispiel #29
0
 public RedisImagesCache(ConnectionMultiplexer con, IBotCredentials creds)
 {
     _con   = con;
     _creds = creds;
     _log   = LogManager.GetCurrentClassLogger();
 }
 public CustomReactions(IBotCredentials creds, IHttpClientFactory clientFactory)
 {
     _creds         = creds;
     _clientFactory = clientFactory;
 }