public AutoAssignRoleService(DiscordSocketClient client, NadekoBot bot)
        {
            _log    = LogManager.GetCurrentClassLogger();
            _client = client;

            AutoAssignedRoles = new ConcurrentDictionary <ulong, ulong>(
                bot.AllGuildConfigs.Where(x => x.AutoAssignRoleId != 0)
                .ToDictionary(k => k.GuildId, v => v.AutoAssignRoleId));

            _client.UserJoined += (user) =>
            {
                var _ = Task.Run(async() =>
                {
                    try
                    {
                        AutoAssignedRoles.TryGetValue(user.Guild.Id, out ulong roleId);

                        if (roleId == 0)
                        {
                            return;
                        }

                        var role = user.Guild.Roles.FirstOrDefault(r => r.Id == roleId);

                        if (role != null)
                        {
                            await user.AddRoleAsync(role).ConfigureAwait(false);
                        }
                    }
                    catch (Exception ex) { _log.Warn(ex); }
                });
                return(Task.CompletedTask);
            };
        }
 public Utility(NadekoBot nadeko, DiscordSocketClient client, IStatsService stats, IBotCredentials creds)
 {
     _client     = client;
     _stats      = stats;
     _creds      = creds;
     _shardCoord = nadeko.ShardCoord;
 }
Exemple #3
0
        public GamesService(CommandHandler cmd, IBotConfigProvider bc, NadekoBot bot,
                            NadekoStrings strings, IDataCache data, CommandHandler cmdHandler,
                            ICurrencyService cs, FontProvider fonts)
        {
            _bc         = bc;
            _cmd        = cmd;
            _strings    = strings;
            _images     = data.LocalImages;
            _cmdHandler = cmdHandler;
            _log        = LogManager.GetCurrentClassLogger();
            _rng        = new NadekoRandom();
            _cs         = cs;
            _fonts      = fonts;

            //8ball
            EightBallResponses = _bc.BotConfig.EightBallResponses.Select(ebr => ebr.Text).ToImmutableArray();

            //girl ratings
            _t = new Timer((_) =>
            {
                GirlRatings.Clear();
            }, null, TimeSpan.FromDays(1), TimeSpan.FromDays(1));

            try
            {
                TypingArticles = JsonConvert.DeserializeObject <List <TypingArticle> >(File.ReadAllText(TypingArticlesPath));
            }
            catch (Exception ex)
            {
                _log.Warn("Error while loading typing articles {0}", ex.ToString());
                TypingArticles = new List <TypingArticle>();
            }
        }
Exemple #4
0
        public FilterService(DiscordSocketClient _client, NadekoBot bot)
        {
            _log = LogManager.GetCurrentClassLogger();

            InviteFilteringServers  = new ConcurrentHashSet <ulong>(bot.AllGuildConfigs.Where(gc => gc.FilterInvites).Select(gc => gc.GuildId));
            InviteFilteringChannels = new ConcurrentHashSet <ulong>(bot.AllGuildConfigs.SelectMany(gc => gc.FilterInvitesChannelIds.Select(fci => fci.ChannelId)));

            var dict = bot.AllGuildConfigs.ToDictionary(gc => gc.GuildId, gc => new ConcurrentHashSet <string>(gc.FilteredWords.Select(fw => fw.Word)));

            ServerFilteredWords = new ConcurrentDictionary <ulong, ConcurrentHashSet <string> >(dict);

            var serverFiltering = bot.AllGuildConfigs.Where(gc => gc.FilterWords);

            WordFilteringServers  = new ConcurrentHashSet <ulong>(serverFiltering.Select(gc => gc.GuildId));
            WordFilteringChannels = new ConcurrentHashSet <ulong>(bot.AllGuildConfigs.SelectMany(gc => gc.FilterWordsChannelIds.Select(fwci => fwci.ChannelId)));

            //LinkFilteringServers = new ConcurrentHashSet<ulong>(bot.AllGuildConfigs.Where(gc => gc.FilterLinks).Select(x => x.GuildId));

            _client.MessageUpdated += (oldData, newMsg, channel) =>
            {
                var _ = Task.Run(() =>
                {
                    var guild  = (channel as ITextChannel)?.Guild;
                    var usrMsg = newMsg as IUserMessage;

                    if (guild == null || usrMsg == null)
                    {
                        return(Task.CompletedTask);
                    }

                    return(TryBlockEarly(guild, usrMsg));
                });
                return(Task.CompletedTask);
            };
        }
Exemple #5
0
        public AutoAssignRoleService(DiscordSocketClient client, NadekoBot bot, DbService db)
        {
            _client = client;
            _db     = db;

            _autoAssignableRoles = bot.AllGuildConfigs
                                   .Where(x => !string.IsNullOrWhiteSpace(x.AutoAssignRoleIds))
                                   .ToDictionary <GuildConfig, ulong, IReadOnlyList <ulong> >(k => k.GuildId, v => v.GetAutoAssignableRoles())
                                   .ToConcurrent();

            _ = Task.Run(async() =>
            {
                while (true)
                {
                    var user = await _assignQueue.Reader.ReadAsync();
                    if (!_autoAssignableRoles.TryGetValue(user.Guild.Id, out var savedRoleIds))
                    {
                        continue;
                    }

                    try
                    {
                        var roleIds = savedRoleIds
                                      .Select(roleId => user.Guild.GetRole(roleId))
                                      .Where(x => !(x is null))
                                      .ToList();

                        if (roleIds.Any())
                        {
                            await user.AddRolesAsync(roleIds).ConfigureAwait(false);
                            await Task.Delay(250).ConfigureAwait(false);
                        }
                        else
                        {
                            Log.Warning(
                                "Disabled 'Auto assign role' feature on {GuildName} [{GuildId}] server the roles dont exist",
                                user.Guild.Name,
                                user.Guild.Id);

                            await DisableAarAsync(user.Guild.Id);
                        }
                    }
                    catch (Discord.Net.HttpException ex) when(ex.HttpCode == System.Net.HttpStatusCode.Forbidden)
                    {
                        Log.Warning("Disabled 'Auto assign role' feature on {GuildName} [{GuildId}] server because I don't have role management permissions",
                                    user.Guild.Name,
                                    user.Guild.Id);

                        await DisableAarAsync(user.Guild.Id);
                    }
                    catch (Exception ex)
                    {
                        Log.Warning(ex, "Error in aar. Probably one of the roles doesn't exist");
                    }
                }
            });

            _client.UserJoined  += OnClientOnUserJoined;
            _client.RoleDeleted += OnClientRoleDeleted;
        }
        public ProtectionService(DiscordSocketClient client, NadekoBot bot,
                                 MuteService mute, DbService db, UserPunishService punishService)
        {
            _client        = client;
            _mute          = mute;
            _db            = db;
            _punishService = punishService;

            var ids = client.GetGuildIds();

            using (var uow = db.GetDbContext())
            {
                var configs = uow._context.Set <GuildConfig>()
                              .AsQueryable()
                              .Include(x => x.AntiRaidSetting)
                              .Include(x => x.AntiSpamSetting)
                              .ThenInclude(x => x.IgnoredChannels)
                              .Include(x => x.AntiAltSetting)
                              .Where(x => ids.Contains(x.GuildId))
                              .ToList();

                foreach (var gc in configs)
                {
                    Initialize(gc);
                }
            }

            _client.MessageReceived += HandleAntiSpam;
            _client.UserJoined      += HandleUserJoined;

            bot.JoinedGuild   += _bot_JoinedGuild;
            _client.LeftGuild += _client_LeftGuild;

            _ = Task.Run(RunQueue);
        }
        public CommandHandler(DiscordSocketClient client, DbService db,
                              IBotConfigProvider bcp, CommandService commandService,
                              IBotCredentials credentials, NadekoBot bot, IServiceProvider services)
        {
            _client         = client;
            _commandService = commandService;
            _creds          = credentials;
            _bot            = bot;
            _db             = db;
            _bcp            = bcp;
            _services       = services;

            _log = LogManager.GetCurrentClassLogger();

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

            DefaultPrefix = bcp.BotConfig.DefaultPrefix;
            _prefixes     = bot.AllGuildConfigs
                            .Where(x => x.Prefix != null)
                            .ToDictionary(x => x.GuildId, x => x.Prefix)
                            .ToConcurrent();
        }
Exemple #8
0
 public SelfCommands(DbService db, NadekoBot bot, DiscordSocketClient client,
                     IBotCredentials creds, IDataCache cache)
 {
     _client = client;
     _bot    = bot;
     _creds  = creds;
 }
Exemple #9
0
        internal override void Init(CommandGroupBuilder cgb)
        {
            cgb.CreateCommand(Module.Prefix + "typestart")
            .Description("Starts a typing contest.")
            .Do(DoFunc());

            cgb.CreateCommand(Module.Prefix + "typestop")
            .Description("Stops a typing contest on the current channel.")
            .Do(QuitFunc());

            cgb.CreateCommand(Module.Prefix + "typeadd")
            .Description("Adds a new article to the typing contest. Owner only.")
            .Parameter("text", ParameterType.Unparsed)
            .Do(async e => {
                if (!NadekoBot.IsOwner(e.User.Id) || string.IsNullOrWhiteSpace(e.GetArg("text")))
                {
                    return;
                }

                DbHandler.Instance.InsertData(new TypingArticle {
                    Text      = e.GetArg("text"),
                    DateAdded = DateTime.Now
                });

                await e.Channel.SendMessage("Added new article for typing game.");
            });

            //todo add user submissions
        }
Exemple #10
0
        public PlantPickService(DbService db, CommandHandler cmd, NadekoBot bot, NadekoStrings strings,
                                IDataCache cache, FontProvider fonts, IBotConfigProvider bc, ICurrencyService cs,
                                CommandHandler cmdHandler, DiscordSocketClient client)
        {
            _db         = db;
            _strings    = strings;
            _images     = cache.LocalImages;
            _fonts      = fonts;
            _bc         = bc;
            _log        = LogManager.GetCurrentClassLogger();
            _cs         = cs;
            _cmdHandler = cmdHandler;
            _rng        = new NadekoRandom();
            _client     = client;

            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)));
            }
        }
Exemple #11
0
 public SelfCommands(NadekoBot bot, DiscordSocketClient client,
                     IBotCredentials creds)
 {
     _client = client;
     _bot    = bot;
     _creds  = creds;
 }
Exemple #12
0
        public GuildTimezoneService(DiscordSocketClient client, NadekoBot bot, DbService db)
        {
            _timezones = bot.AllGuildConfigs
                         .Select(x =>
            {
                TimeZoneInfo tz;
                try
                {
                    if (x.TimeZoneId == null)
                    {
                        tz = null;
                    }
                    else
                    {
                        tz = TimeZoneInfo.FindSystemTimeZoneById(x.TimeZoneId);
                    }
                }
                catch
                {
                    tz = null;
                }
                return(x.GuildId, Timezone: tz);
            })
                         .Where(x => x.Timezone != null)
                         .ToDictionary(x => x.GuildId, x => x.Timezone)
                         .ToConcurrent();

            var curUser = client.CurrentUser;

            if (curUser != null)
            {
                AllServices.TryAdd(curUser.Id, this);
            }
            _db = db;
        }
        public StreamRoleService(DiscordSocketClient client, DbService db, NadekoBot bot)
        {
            this._log    = LogManager.GetCurrentClassLogger();
            this._db     = db;
            this._client = client;

            guildSettings = bot.AllGuildConfigs
                            .ToDictionary(x => x.GuildId, x => x.StreamRole)
                            .Where(x => x.Value != null && x.Value.Enabled)
                            .ToConcurrent();

            _client.GuildMemberUpdated += Client_GuildMemberUpdated;

            var _ = Task.Run(async() =>
            {
                try
                {
                    await Task.WhenAll(client.Guilds.Select(g => RescanUsers(g))).ConfigureAwait(false);
                }
                catch
                {
                    // ignored
                }
            });
        }
Exemple #14
0
        public MessageRepeaterService(NadekoBot bot, DiscordSocketClient client, DbService db)
        {
            _db  = db;
            _log = LogManager.GetCurrentClassLogger();
            var _ = Task.Run(async() =>
            {
                await bot.Ready.Task.ConfigureAwait(false);
                try
                {
                    Repeaters = new ConcurrentDictionary <ulong, ConcurrentDictionary <int, RepeatRunner> >(
                        bot.AllGuildConfigs
                        .Select(gc =>
                    {
                        var guild = client.GetGuild(gc.GuildId);
                        if (guild == null)
                        {
                            return(0, null);
                        }
                        return(gc.GuildId, new ConcurrentDictionary <int, RepeatRunner>(gc.GuildRepeaters
                                                                                        .Select(gr => new KeyValuePair <int, RepeatRunner>(gr.Id, new RepeatRunner(guild, gr, this)))
                                                                                        .Where(x => x.Value.Guild != null)));
                    })
                        .Where(x => x.Item2 != null)
                        .ToDictionary(x => x.GuildId, x => x.Item2));

                    RepeaterReady = true;
                }
                catch (Exception ex)
                {
                    _log.Error("Failed to load repeaters on shard {0}.", bot.Client.ShardId);
                    _log.Error(ex);
                }
            });
        }
Exemple #15
0
 internal override void Init(CommandGroupBuilder cgb)
 {
     cgb.CreateCommand(Module.Prefix + "leave")
     .Description("Makes Nadeko leave the server. Either name or id required.\n**Usage**: `.leave 123123123331`")
     .Parameter("arg", ParameterType.Required)
     .AddCheck(SimpleCheckers.OwnerOnly())
     .Do(async e =>
     {
         var arg    = e.GetArg("arg").Trim();
         var server = NadekoBot.Client.Servers.FirstOrDefault(s => s.Id.ToString() == arg) ??
                      NadekoBot.Client.FindServers(arg).FirstOrDefault();
         if (server == null)
         {
             await e.Channel.SendMessage("Cannot find that server").ConfigureAwait(false);
             return;
         }
         if (!server.IsOwner)
         {
             await server.Leave().ConfigureAwait(false);
         }
         else
         {
             await server.Delete().ConfigureAwait(false);
         }
         await NadekoBot.SendMessageToOwner("Left server " + server.Name).ConfigureAwait(false);
     });
 }
Exemple #16
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();
            _musicSettings = bot.AllGuildConfigs.ToDictionary(x => x.GuildId, x => x.MusicSettings)
                             .ToConcurrent();

            _client.LeftGuild += _client_LeftGuild;

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

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

            AutoDcServers = new ConcurrentHashSet <ulong>(bot.AllGuildConfigs.Where(x => x.AutoDcFromVc).Select(x => x.GuildId));

            Directory.CreateDirectory(MusicDataPath);
        }
Exemple #17
0
        public MessageRepeaterService(NadekoBot bot, DiscordSocketClient client, DbService db)
        {
            _db = db;
            var _ = Task.Run(async() =>
            {
                await bot.Ready.Task.ConfigureAwait(false);

                Repeaters = new ConcurrentDictionary <ulong, ConcurrentDictionary <int, RepeatRunner> >(
                    bot.AllGuildConfigs
                    .Select(gc =>
                {
                    var guild = client.GetGuild(gc.GuildId);
                    if (guild == null)
                    {
                        return(0, null);
                    }
                    return(gc.GuildId, new ConcurrentDictionary <int, RepeatRunner>(gc.GuildRepeaters
                                                                                    .Select(gr => new KeyValuePair <int, RepeatRunner>(gr.Id, new RepeatRunner(guild, gr, this)))
                                                                                    .Where(x => x.Value.Guild != null)));
                })
                    .Where(x => x.Item2 != null)
                    .ToDictionary(x => x.GuildId, x => x.Item2));
                RepeaterReady = true;
            });
        }
        public GamesService(CommandHandler cmd, IBotConfigProvider bc, NadekoBot bot,
                            NadekoStrings strings, IImagesService images, CommandHandler cmdHandler)
        {
            _bc         = bc;
            _cmd        = cmd;
            _strings    = strings;
            _images     = images;
            _cmdHandler = cmdHandler;
            _log        = LogManager.GetCurrentClassLogger();

            //8ball
            EightBallResponses = _bc.BotConfig.EightBallResponses.Select(ebr => ebr.Text).ToImmutableArray();

            //girl ratings
            _t = new Timer((_) =>
            {
                GirlRatings.Clear();
            }, null, TimeSpan.FromDays(1), TimeSpan.FromDays(1));

            //plantpick
            _cmd.OnMessageNoTrigger += PotentialFlowerGeneration;
            GenerationChannels       = new ConcurrentHashSet <ulong>(bot
                                                                     .AllGuildConfigs
                                                                     .SelectMany(c => c.GenerateCurrencyChannelIds.Select(obj => obj.ChannelId)));

            try
            {
                TypingArticles = JsonConvert.DeserializeObject <List <TypingArticle> >(File.ReadAllText(TypingArticlesPath));
            }
            catch (Exception ex)
            {
                _log.Warn("Error while loading typing articles {0}", ex.ToString());
                TypingArticles = new List <TypingArticle>();
            }
        }
        public AdministrationService(NadekoBot bot, CommandHandler cmdHandler)
        {
            _log = LogManager.GetCurrentClassLogger();
            _bot = bot;

            DeleteMessagesOnCommand     = new ConcurrentHashSet <ulong>(bot.AllGuildConfigs.Where(g => g.DeleteMessageOnCommand).Select(g => g.GuildId));
            cmdHandler.CommandExecuted += DelMsgOnCmd_Handler;
        }
Exemple #20
0
 public MessageRepeaterService(NadekoBot bot, DiscordSocketClient client, DbService db)
 {
     _db     = db;
     _log    = LogManager.GetCurrentClassLogger();
     _bot    = bot;
     _client = client;
     var _ = LoadRepeaters();
 }
Exemple #21
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;

            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);
                }
            });
        }
Exemple #22
0
 public Utility(NadekoBot nadeko, DiscordSocketClient client,
                IStatsService stats, IBotCredentials creds, DownloadTracker tracker)
 {
     _client  = client;
     _stats   = stats;
     _creds   = creds;
     _bot     = nadeko;
     _tracker = tracker;
 }
Exemple #23
0
 public SelfCommands(NadekoBot bot, DiscordSocketClient client,
                     IBotCredentials creds, IDataCache cache, IHttpClientFactory http)
 {
     _client = client;
     _bot    = bot;
     _creds  = creds;
     _cache  = cache;
     _http   = http;
 }
Exemple #24
0
 public Utility(NadekoBot nadeko, DiscordSocketClient client,
                IStatsService stats, IBotCredentials creds,
                DbService db)
 {
     _client = client;
     _stats  = stats;
     _creds  = creds;
     _bot    = nadeko;
     _db     = db;
 }
Exemple #25
0
 //commandmap
 public CommandMapService(NadekoBot bot)
 {
     _log      = LogManager.GetCurrentClassLogger();
     AliasMaps = new ConcurrentDictionary <ulong, ConcurrentDictionary <string, string> >(
         bot.AllGuildConfigs.ToDictionary(
             x => x.GuildId,
             x => new ConcurrentDictionary <string, string>(x.CommandAliases
                                                            .Distinct(new CommandAliasEqualityComparer())
                                                            .ToDictionary(ca => ca.Trigger, ca => ca.Mapping))));
 }
Exemple #26
0
 public SelfCommands(DbService db, NadekoBot bot, DiscordSocketClient client,
                     IBotCredentials creds, IDataCache cache)
 {
     _db     = db;
     _client = client;
     _images = cache.LocalImages;
     _bot    = bot;
     _creds  = creds;
     _cache  = cache;
 }
Exemple #27
0
        public VplusTService(DiscordSocketClient client, NadekoBot bot, NadekoStrings strings,
                             DbService db)
        {
            _client  = client;
            _strings = strings;
            _db      = db;
            _log     = LogManager.GetCurrentClassLogger();

            VoicePlusTextCache             = new ConcurrentHashSet <ulong>(bot.AllGuildConfigs.Where(g => g.VoicePlusTextEnabled).Select(g => g.GuildId));
            _client.UserVoiceStateUpdated += UserUpdatedEventHandler;
        }
Exemple #28
0
 public LeaderboardService(DbService db, NadekoBot bot, ICurrencyService cs, IBotConfigProvider bc,
                           DiscordSocketClient client, IDataCache cache)
 {
     _db     = db;
     _cs     = cs;
     _bc     = bc;
     _bot    = bot;
     _log    = LogManager.GetCurrentClassLogger();
     _client = client;
     _cache  = cache;
 }
Exemple #29
0
 public Utility(NadekoBot nadeko, DiscordSocketClient client,
                IStatsService stats, IBotCredentials creds,
                DbService db, IHttpClientFactory factory)
 {
     _client      = client;
     _stats       = stats;
     _creds       = creds;
     _bot         = nadeko;
     _db          = db;
     _httpFactory = factory;
 }
        public GameVoiceChannelService(DiscordSocketClient client, DbService db, NadekoBot bot)
        {
            _log    = LogManager.GetCurrentClassLogger();
            _db     = db;
            _client = client;

            GameVoiceChannels = new ConcurrentHashSet <ulong>(
                bot.AllGuildConfigs.Where(gc => gc.GameVoiceChannel != null)
                .Select(gc => gc.GameVoiceChannel.Value));

            _client.UserVoiceStateUpdated += Client_UserVoiceStateUpdated;
        }