Exemplo n.º 1
0
        public TranslateService(IDatabase database, LicenseService license, LogHandler logger, DiscordShardedClient client, LocalManagementService localManagementService)
        {
            Database = database;
            License  = license;
            Logger   = logger;
            Client   = client;
            LocalManagementService = localManagementService;
            Config = GetTranslateConfig();
            if (Config.APIKey != null && Config.Enabled)
            {
                if (Config.ApiKeyType == TranslateConfig.ApiKey.Google)
                {
                    Translator = new GoogleTranslator(Config.APIKey);
                }
                else if (Config.ApiKeyType == TranslateConfig.ApiKey.Yandex)
                {
                    Translator = new YandexTranslator(Config.APIKey);
                }
                else
                {
                    throw new NotImplementedException("The specified api type is not implemented");
                }

                Client.ReactionAdded += ReactionAdded;
            }
            else if (Config.APIKey == null && Config.Enabled)
            {
                logger.Log("Translate API is enabled but no API Key is specified.", LogSeverity.Warning);
            }
        }
Exemplo n.º 2
0
 public AutomessageHandler(IDatabase database, DiscordShardedClient client, LocalManagementService localManagementService)
 {
     Database = database;
     Client   = client;
     LocalManagementService  = localManagementService;
     Client.MessageReceived += MessageReceived;
 }
Exemplo n.º 3
0
 public MediaRestrictorHelper(IDatabase database, DiscordShardedClient client, LocalManagementService local)
 {
     Database = database;
     Client   = client;
     Local    = local;
     Client.MessageReceived += MessageReceivedAsync;
 }
Exemplo n.º 4
0
 public GreetingsService(IDatabase database, DiscordShardedClient client, LocalManagementService localManagementService)
 {
     Database = database;
     Client   = client;
     LocalManagementService = localManagementService;
     Client.UserJoined     += UserJoined;
     Client.UserLeft       += UserLeft;
 }
Exemplo n.º 5
0
 public LevelService(IDatabase database, DiscordShardedClient client, LocalManagementService localManagementService)
 {
     Database = database;
     Client   = client;
     LocalManagementService = localManagementService;
     Timer = new Timer(TimerEvent, null, TimeSpan.Zero, TimeSpan.FromMinutes(1));
     Client.MessageReceived += LevelEvent;
 }
Exemplo n.º 6
0
 public RoleManager(IDatabase database, HttpClient httpClient, DiscordShardedClient client, LocalManagementService local)
 {
     Database                = database;
     HttpClient              = httpClient;
     Client                  = client;
     Local                   = local;
     Client.ReactionAdded   += ReactionAdded;
     Client.ReactionRemoved += ReactionRemoved;
 }
Exemplo n.º 7
0
 public Developer(IDatabase database, Random random, ELOService service, PatreonIntegration prem, ELOMigrator migrator, LocalManagementService local)
 {
     Database       = database;
     Random         = random;
     Service        = service;
     PremiumService = prem;
     Migrator       = migrator;
     Local          = local;
 }
Exemplo n.º 8
0
 public Audio(VictoriaService vic, LogHandler logger, HelpService helpService, LocalManagementService local)
 {
     Vic             = vic;
     Logger          = logger;
     HelpService     = helpService;
     Local           = local;
     RestClient      = vic.RestClient;
     LavaShardClient = vic.Client;
 }
Exemplo n.º 9
0
 public BirthdayService(DiscordShardedClient client, ShardChecker checker, IDatabase database, LocalManagementService localManagementService)
 {
     Client   = client;
     Database = database;
     LocalManagementService  = localManagementService;
     checker.AllShardsReady += () =>
     {
         Timer = new Timer(TimerEvent, null, TimeSpan.FromMinutes(0), TimeSpan.FromHours(1));
         return(Task.CompletedTask);
     };
 }
Exemplo n.º 10
0
        public CaptchaService(IDatabase database, DiscordShardedClient client, GuildService prefixService, LocalManagementService localManagementService)
        {
            Database = database;

            Client                 = client;
            PrefixService          = prefixService;
            LocalManagementService = localManagementService;
            Client.ChannelCreated += ChannelCreated;
            Client.UserJoined     += UserJoined;
            Random                 = new Random();
        }
Exemplo n.º 11
0
 public ConversationService(IDatabase database, DiscordShardedClient client, LogHandler logger, LocalManagementService localManagementService)
 {
     //TODO: Log if conversation api key is not set.
     Database = database;
     Client   = client;
     Logger   = logger;
     LocalManagementService = localManagementService;
     SetAgent();
     Client.MessageReceived += MessageReceived;
     ConversationFunctions   = new ConversationFunctions();
 }
Exemplo n.º 12
0
        public ReminderHandler(IDatabase database, ShardChecker checker, DiscordShardedClient client, LocalManagementService localManagementService)
        {
            Database = database;
            Client   = client;
            LocalManagementService = localManagementService;
            Reminders           = Database.Query <Reminder>().ToList();
            PersistentReminders = Database.Query <PersistentReminder>().Select(MakeTimer).ToList();

            checker.AllShardsReady += () =>
            {
                Timer = new System.Threading.Timer(TimerEvent, null, TimeSpan.Zero, TimeSpan.FromMinutes(1));
                return(Task.CompletedTask);
            };
        }
Exemplo n.º 13
0
        public EventService(DiscordShardedClient client, IDatabase database, LocalManagementService localManagementService)
        {
            Client   = client;
            Database = database;
            LocalManagementService = localManagementService;

            Client.ChannelCreated      += Client_ChannelCreated;
            Client.ChannelDestroyed    += Client_ChannelDestroyed;
            Client.ChannelUpdated      += Client_ChannelUpdated;
            Client.MessageDeleted      += Client_MessageDeleted;
            Client.MessageUpdated      += Client_MessageUpdated;
            Client.UserJoined          += Client_UserJoined;
            Client.UserLeft            += Client_UserLeft;
            Client.GuildMemberUpdated  += GuildMemberUpdated;
            Client.MessagesBulkDeleted += MessagesBulkDeleted;

            Timer = new Timer(TimerEvent, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));
        }
Exemplo n.º 14
0
        //private Dictionary<ulong, ModerationConfig> ModerationConfigs { get; }

        public ModerationService(IDatabase database, DiscordShardedClient client, LocalManagementService localManagementService)
        {
            Database = database;
            //ModerationConfigs = new Dictionary<ulong, ModerationConfig>();
            var setupDoc = database.Load <PerspectiveSetup>(PerspectiveSetup.DocumentName());

            if (setupDoc == null)
            {
                setupDoc = new PerspectiveSetup();
                database.Store(setupDoc, PerspectiveSetup.DocumentName());
            }

            Perspective             = setupDoc.PerspectiveToken != null ? new Perspective.Api(setupDoc.PerspectiveToken) : null;
            Client                  = client;
            LocalManagementService  = localManagementService;
            Client.MessageReceived += MessageReceived;
            Client.UserJoined      += UserJoined;
            //Client.GuildMemberUpdated += MemberUpdated;
        }
Exemplo n.º 15
0
        public VictoriaService(DiscordShardedClient client, ShardChecker checker, IDatabase database, HttpClient httpClient, LogHandler logger, LocalManagementService local)
        {
            DiscordClient = client;
            Database      = database;
            HttpClient    = httpClient;
            Logger        = logger;
            Local         = local;

            var localConfig = local.GetConfig();
            var vicConfig   = localConfig.GetConfig <VictoriaConfig>(ConfigKey);

            if (vicConfig == null)
            {
                Logger.Log($"Victoria config not found in LocalConfig. \nUnable to initialize music module correctly.", LogSeverity.Warning);
            }
            else
            {
                checker.AllShardsReady += Configure;
            }
        }
Exemplo n.º 16
0
        public void RunMigration(LocalManagementService local)
        {
            if (oldDatabase == null)
            {
                oldDatabase = new RavenDatabase(local);
            }

            try
            {
                var tokenModel = oldDatabase.Load <TokenModel>("tokens");
                if (tokenModel != null)
                {
                    currentDatabase.Store(tokenModel, "legacyELOTokens");
                }


                using (var session = oldDatabase.DocumentStore.OpenSession())
                {
                    var query = session.Query <GuildModel>();

                    int guilds = 0;
                    int games  = 0;
                    int users  = 0;
                    int lobbys = 0;
                    using (var enumerator = session.Advanced.Stream(query))
                    {
                        while (enumerator.MoveNext())
                        {
                            var config = enumerator.Current.Document;
                            try
                            {
                                //Do not use if new competition already exists
                                var newComp = currentDatabase.Load <CompetitionConfig>(CompetitionConfig.DocumentName(config.ID));
                                if (newComp != null)
                                {
                                    if (config.Settings.Premium.Expiry > DateTime.UtcNow)
                                    {
                                        Legacy.SaveConfig(new LegacyIntegration.LegacyPremium
                                        {
                                            GuildId    = config.ID,
                                            ExpiryDate = config.Settings.Premium.Expiry
                                        });
                                    }
                                    continue;
                                }

                                newComp = new CompetitionConfig();

                                //Do not set this due to incompatibilities with new replacements
                                //newComp.NameFormat = config.Settings.Registration.NameFormat;
                                newComp.UpdateNames             = true;
                                newComp.RegisterMessageTemplate = config.Settings.Registration.Message;
                                newComp.RegisteredRankId        = config.Ranks.FirstOrDefault(x => x.IsDefault)?.RoleID ?? 0;
                                newComp.Ranks = config.Ranks.Select(x => new Rank
                                {
                                    RoleId       = x.RoleID,
                                    WinModifier  = x.WinModifier,
                                    LossModifier = x.LossModifier,
                                    Points       = x.Threshold
                                }).ToList();
                                newComp.GuildId             = config.ID;
                                newComp.DefaultWinModifier  = config.Settings.Registration.DefaultWinModifier;
                                newComp.DefaultLossModifier = config.Settings.Registration.DefaultLossModifier;
                                newComp.AllowReRegister     = config.Settings.Registration.AllowMultiRegistration;
                                newComp.AllowSelfRename     = config.Settings.Registration.AllowMultiRegistration;
                                newComp.AllowNegativeScore  = config.Settings.GameSettings.AllowNegativeScore;
                                newComp.BlockMultiQueueing  = config.Settings.GameSettings.BlockMultiQueuing;
                                newComp.AdminRole           = config.Settings.Moderation.AdminRoles.FirstOrDefault();
                                newComp.ModeratorRole       = config.Settings.Moderation.ModRoles.FirstOrDefault();
                                newComp.RegistrationCount   = config.Users.Count;
                                if (config.Settings.GameSettings.ReQueueDelay != TimeSpan.Zero)
                                {
                                    newComp.RequeueDelay = config.Settings.GameSettings.ReQueueDelay;
                                }
                                //TODO: Remove user on afk

                                if (config.Settings.Premium.Expiry > DateTime.UtcNow)
                                {
                                    Legacy.SaveConfig(new LegacyIntegration.LegacyPremium
                                    {
                                        GuildId    = config.ID,
                                        ExpiryDate = config.Settings.Premium.Expiry
                                    });
                                }

                                currentDatabase.Store(newComp, CompetitionConfig.DocumentName(config.ID));
                                guilds++;

                                foreach (var game in config.Results)
                                {
                                    //Skip games for lobbys that dont exist
                                    var lobby = config.Lobbies.FirstOrDefault(x => x.ChannelID == game.LobbyID);
                                    if (lobby == null)
                                    {
                                        continue;
                                    }

                                    var newResult = new GameResult();
                                    newResult.GameId       = game.GameNumber;
                                    newResult.LobbyId      = game.LobbyID;
                                    newResult.GuildId      = config.ID;
                                    newResult.CreationTime = game.Time;

                                    if (game.Result == GuildModel.GameResult._Result.Canceled)
                                    {
                                        newResult.GameState = GameResult.State.Canceled;
                                    }
                                    else if (game.Result == GuildModel.GameResult._Result.Team1)
                                    {
                                        newResult.GameState   = GameResult.State.Decided;
                                        newResult.WinningTeam = 1;
                                    }
                                    else if (game.Result == GuildModel.GameResult._Result.Team2)
                                    {
                                        newResult.GameState   = GameResult.State.Decided;
                                        newResult.WinningTeam = 2;
                                    }
                                    else if (game.Result == GuildModel.GameResult._Result.Undecided)
                                    {
                                        newResult.GameState = GameResult.State.Undecided;
                                    }

                                    newResult.Team1.Players = game.Team1.ToHashSet();
                                    newResult.Team2.Players = game.Team2.ToHashSet();

                                    if (lobby.PickMode == GuildModel.Lobby._PickMode.Captains)
                                    {
                                        newResult.GamePickMode = Lobby.PickMode.Captains_HighestRanked;
                                        newResult.PickOrder    = GameResult.CaptainPickOrder.PickOne;
                                    }
                                    else if (lobby.PickMode == GuildModel.Lobby._PickMode.Pick2)
                                    {
                                        newResult.GamePickMode = Lobby.PickMode.Captains_HighestRanked;
                                        newResult.PickOrder    = GameResult.CaptainPickOrder.PickTwo;
                                    }
                                    else if (lobby.PickMode == GuildModel.Lobby._PickMode.CompleteRandom)
                                    {
                                        newResult.GamePickMode = Lobby.PickMode.Random;
                                    }
                                    else if (lobby.PickMode == GuildModel.Lobby._PickMode.SortByScore)
                                    {
                                        newResult.GamePickMode = Lobby.PickMode.TryBalance;
                                    }

                                    newResult.LegacyGame = true;
                                    currentDatabase.Store(newResult, GameResult.DocumentName(newResult.GameId, newResult.LobbyId, newResult.GuildId));
                                    games++;


                                    //Untransferrable info: Captains
                                    //Unfortunately, the old ELO bot didn't store captains
                                    //Also the undogame method will not work on these
                                }

                                foreach (var lobby in config.Lobbies)
                                {
                                    var newLobby = new Lobby();
                                    newLobby.GuildId                       = config.ID;
                                    newLobby.ChannelId                     = lobby.ChannelID;
                                    newLobby.DmUsersOnGameReady            = config.Settings.GameSettings.DMAnnouncements;
                                    newLobby.GameResultAnnouncementChannel = config.Settings.GameSettings.AnnouncementsChannel;
                                    newLobby.GameReadyAnnouncementChannel  = config.Settings.GameSettings.AnnouncementsChannel;
                                    newLobby.PlayersPerTeam                = lobby.UserLimit / 2;
                                    newLobby.Description                   = lobby.Description;
                                    var results = config.Results.Where(x => x.LobbyID == lobby.ChannelID).ToArray();
                                    if (results.Length == 0)
                                    {
                                        newLobby.CurrentGameCount = 0;
                                    }
                                    else
                                    {
                                        newLobby.CurrentGameCount = results.Max(x => x.GameNumber) + 1;
                                    }

                                    if (lobby.Maps.Any())
                                    {
                                        newLobby.MapSelector      = new MapSelector();
                                        newLobby.MapSelector.Maps = lobby.Maps.ToHashSet();
                                    }
                                    //TODO: Lobby requeue delay


                                    if (lobby.PickMode == GuildModel.Lobby._PickMode.Captains)
                                    {
                                        newLobby.TeamPickMode     = Lobby.PickMode.Captains_HighestRanked;
                                        newLobby.CaptainPickOrder = GameResult.CaptainPickOrder.PickOne;
                                    }
                                    else if (lobby.PickMode == GuildModel.Lobby._PickMode.CompleteRandom)
                                    {
                                        newLobby.TeamPickMode = Lobby.PickMode.Random;
                                    }
                                    else if (lobby.PickMode == GuildModel.Lobby._PickMode.Pick2)
                                    {
                                        newLobby.CaptainPickOrder = GameResult.CaptainPickOrder.PickTwo;
                                        newLobby.TeamPickMode     = Lobby.PickMode.Captains_HighestRanked;
                                    }
                                    else if (lobby.PickMode == GuildModel.Lobby._PickMode.SortByScore)
                                    {
                                        newLobby.TeamPickMode = Lobby.PickMode.TryBalance;
                                    }

                                    currentDatabase.Store(newLobby, Lobby.DocumentName(config.ID, lobby.ChannelID));
                                    lobbys++;
                                }

                                foreach (var user in config.Users)
                                {
                                    var newUser = new Player(user.UserID, config.ID, user.Username);
                                    newUser.Points = user.Stats.Points;
                                    newUser.Wins   = user.Stats.Wins;
                                    newUser.Losses = user.Stats.Losses;
                                    newUser.Draws  = user.Stats.Draws;

                                    //TODO: Kills/Deaths/Assists

                                    if (user.Banned != null && user.Banned.Banned)
                                    {
                                        var length = user.Banned.ExpiryTime - DateTime.UtcNow;
                                        newUser.BanHistory.Add(new Player.Ban(length, user.Banned.Moderator, user.Banned.Reason));
                                    }

                                    currentDatabase.Store(newUser, Player.DocumentName(config.ID, user.UserID));
                                    users++;
                                }
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e);
                            }
                        }

                        Console.WriteLine($"Guilds: {guilds} Lobbys: {lobbys} Games: {games} Users: {users}");
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Exemplo n.º 17
0
        public async Task RunAsync(string[] args = null)
        {
            string dbPathOverride = null;

            if (args != null)
            {
                Parser.Default.ParseArguments <Options>(args)
                .WithParsed <Options>(o =>
                {
                    if (o.Path != null)
                    {
                        LocalManagementService.ConfigPath = o.Path;
                    }

                    if (o.DatabaseConfigPath != null)
                    {
                        dbPathOverride = o.DatabaseConfigPath;
                    }
                });
            }

            var       localManagement = new LocalManagementService();
            IDatabase database        = new RavenDatabase(localManagement);

            var types = AppDomain.CurrentDomain.GetAssemblies()
                        .SelectMany(s => s.GetTypes())
                        .Where(p => typeof(IServiceable).IsAssignableFrom(p) && !p.IsInterface);

            IServiceCollection collection = new ServiceCollection();

            foreach (var type in types)
            {
                collection = collection.AddSingleton(type);
            }

            //Configure the service provider with all relevant and required services to be injected into other classes.
            Provider = collection
                       .AddSingleton(database)
                       .AddSingleton(x => new DiscordShardedClient(new DiscordSocketConfig
            {
                AlwaysDownloadUsers = false,
                MessageCacheSize    = 50,
                LogLevel            = LogSeverity.Info,
                ExclusiveBulkDelete = true,

                //You may want to edit the shard count as the bot grows more and more popular.
                //Discord will block single shards that try to connect to more than 2500 servers
                //May be advisable to fetch from a config file OR default to 1
                TotalShards = 1
            }))
                       .AddSingleton(x => new LogHandler(x.GetRequiredService <DiscordShardedClient>(), x.GetRequiredService <IDatabase>()))
                       .AddSingleton(localManagement)
                       .AddSingleton(x =>
            {
                //Initialize the bot config by asking for token and name
                var config = x.GetRequiredService <IDatabase>().Load <BotConfig>("BotConfig");
                if (config == null)
                {
                    Console.WriteLine("Please enter your bot token (found at https://discordapp.com/developers/applications/ )");
                    var token = Console.ReadLine();

                    Console.WriteLine("Input a bot name (this will be used for certain database tasks)");
                    var name = Console.ReadLine();

                    Console.WriteLine("Input a bot prefix (this will be used to run commands, ie. prefix = f. command will be f.command)");
                    var prefix = Console.ReadLine();
                    config     = new BotConfig(token, prefix, name);

                    x.GetRequiredService <IDatabase>().Store(config, "BotConfig");
                }

                return(config);
            })
                       .AddSingleton <DeveloperSettings>()
                       .AddSingleton <GuildService>()
                       //.AddSingleton(x => new ModuleManagementService(x.GetRequiredService<IDatabase>(), x.GetRequiredService<PrefixService>(), localConfig.Developer))
                       .AddSingleton(x => new HelpService(x.GetRequiredService <CommandService>(), x.GetRequiredService <BotConfig>(), x.GetRequiredService <GuildService>(), x.GetRequiredService <DeveloperSettings>(), x))
                       .AddSingleton(new CommandService(new CommandServiceConfig
            {
                ThrowOnError          = false,
                CaseSensitiveCommands = false,
                IgnoreExtraArgs       = false,
                DefaultRunMode        = RunMode.Async,
                LogLevel = LogSeverity.Info
            }))
                       //.AddSingleton(x => new PrefixService(x.GetRequiredService<IDatabase>(), localConfig.Developer ? localConfig.DeveloperPrefix : x.GetRequiredService<BotConfig>().Prefix))
                       .AddSingleton <EventHandler>()
                       .AddSingleton(x => new LicenseService(x.GetRequiredService <IDatabase>()))
                       .AddSingleton <Random>()
                       .AddSingleton <HttpClient>()
                       .BuildServiceProvider();

            try
            {
                await Provider.GetRequiredService <EventHandler>().InitializeAsync();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

            await Task.Delay(-1);
        }
Exemplo n.º 18
0
 public ELOEventHandler(DiscordShardedClient client, CommandService commandService, GuildService guildService, LocalManagementService local, LogHandler handler, IServiceProvider provider) : base(client, commandService, guildService, local, handler, provider)
 {
     GuildSchedule.Service  = commandService;
     GuildSchedule.Provider = provider;
 }
Exemplo n.º 19
0
        public async Task RunAsync(string[] args = null)
        {
            if (args != null)
            {
                Parser.Default.ParseArguments <Options>(args)
                .WithParsed(o =>
                {
                    if (o.Path != null)
                    {
                        LocalManagementService.ConfigPath = o.Path;
                    }
                });
            }

            var       localManagement = new LocalManagementService();
            IDatabase database        = new LiteDataStore(localManagement);

            var types = AppDomain.CurrentDomain.GetAssemblies()
                        .SelectMany(s => s.GetTypes())
                        .Where(p => typeof(IServiceable).IsAssignableFrom(p) && !p.IsInterface);

            IServiceCollection collection = new ServiceCollection();

            foreach (var type in types)
            {
                collection = collection.AddSingleton(type);
            }

            //Configure the service provider with all relevant and required services to be injected into other classes.
            Provider = collection
                       .AddSingleton(database)
                       .AddSingleton(x => new DiscordShardedClient(new DiscordSocketConfig
            {
                AlwaysDownloadUsers = false,
                MessageCacheSize    = 50,
                LogLevel            = LogSeverity.Info,
                ExclusiveBulkDelete = true,

                //You may want to edit the shard count as the bot grows more and more popular.
                //Discord will block single shards that try to connect to more than 2500 servers
                //May be advisable to fetch from a config file OR default to 1
                TotalShards = 1
            }))
                       .AddSingleton(x => new LogHandler(x.GetRequiredService <DiscordShardedClient>(), x.GetRequiredService <IDatabase>()))
                       .AddSingleton(localManagement)
                       .AddSingleton <DeveloperSettings>()
                       .AddSingleton <GuildService>()
                       .AddSingleton(x => new HelpService(x.GetRequiredService <CommandService>(), localManagement, x.GetRequiredService <GuildService>(), x.GetRequiredService <DeveloperSettings>(), x))
                       .AddSingleton(new CommandService(new CommandServiceConfig
            {
                ThrowOnError          = false,
                CaseSensitiveCommands = false,
                IgnoreExtraArgs       = false,
                DefaultRunMode        = RunMode.Async,
                LogLevel = LogSeverity.Info
            }))
                       .AddSingleton <ELOEventHandler>()
                       .AddSingleton(x => new LicenseService(x.GetRequiredService <IDatabase>()))
                       .AddSingleton <Random>()
                       .AddSingleton <HttpClient>()
                       .BuildServiceProvider();

            try
            {
                await Provider.GetRequiredService <ELOEventHandler>().InitializeAsync();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

            await Task.Delay(-1);
        }