Example #1
0
        public async Task Run(string serverId, IChatResponseToken icrt, string id)
        {
            try
            {
                _containerStore.TryGetValue(id, out DockerContainer gameServerContainer);
                if (gameServerContainer == null)
                {
                    _logger.LogWarning($"Couldn't find container with id {id}");
                    return;
                }

                var gameServer = gameServerContainer.GameServer;
                _logger.LogInformation($"{gameServer.ServerName} for ServerId:{serverId} starting run.");

                var mounts          = new List <Mount>();
                var portAssignments = await GeneratePortAssignments(gameServer);

                var environmentVariables = await GenerateEnvironmentVariables(gameServer);

                // Create basic server dirs if they don't exist already
                var gameFilesPath = await _fileStore.GetGameServerDirectoryOrCreateIt(serverId, gameServer);

                // Create all the mounts for the containers
                foreach (var bindData in gameServer.Binds ?? Enumerable.Empty <string>())
                {
                    mounts.Add(await CreateContainerMount(gameFilesPath, bindData));
                }

                var response = await _client.Containers.CreateContainerAsync(new CreateContainerParameters
                {
                    Image        = $"{gameServer.ContainerName}:{gameServer.ContainerTag}",
                    Name         = $"{serverId}-{gameServer.ServerName.Replace(" ", "")}",
                    ExposedPorts = portAssignments.Item2,
                    HostConfig   = new HostConfig
                    {
                        PortBindings    = portAssignments.Item1,
                        PublishAllPorts = false,
                        Mounts          = mounts
                    },
                    Env = environmentVariables,
                    Cmd = gameServer.Commands
                });

                await _client.Containers.StartContainerAsync(response.ID, null);

                _logger.LogInformation($"{gameServer.ServerName} for ServerId:{serverId} now running.");
                await icrt.UpdateLastInteractedWithMessage($"{gameServer.ServerName} available at: "
                                                           + $"{await _ipGetter.GetIp()} With Ports:\n {String.Join("\n", portAssignments.Item2.Select(x => x.Key))}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Error running docker container. {ex.Message}");
            }
        }
Example #2
0
        public async Task ProcessMessage(string serverID, IChatResponseToken icrt, string senderID, string input)
        {
            // Make the initial command case insensitive
            var firstCommand = input.Split(" ")[0].ToLower();

            // Switch statement for all commands that are constant
            switch (firstCommand)
            {
            case "-help":
                await icrt.Respond(@"Command list:
                    `-ping` Will return if Sergen is alive.
                    `-ip` Will respond the ip of the main.
                    `-version` Will return 1.0.0 because I'm too lazy to fix the version.
                    `-running` Will return all the running game servers for this discord server.
                    `-possible` Will return all possible game servers.
                    `-run {Game Server}` Will start a game server of that type.
                    `-stop {Game Server}` Will stop a game server of that type.
                    `-allowlist` Will show you your current allowlist.
                    `-allowlist enable/disable` Will enable/disable the allowlist.
                    `-allowlist add @user` Will enable that user to control servers.
                    `-allowlist remove @user` Will stop that user from controlling servers.
                     ");

                break;

            case "-ping":
                var processingTime = DateTime.Now.Subtract(icrt.SendTime);
                await icrt.Respond(processingTime.Milliseconds + "ms");

                break;

            case "-ip":
                await icrt.Respond($"My IP Address is: {await _ipGetter.GetIp()}");

                break;

            case "-whoami":
                await icrt.Respond($"You are: {_context.GetUsername(senderID)}");

                break;

            case "-version":
                System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
                FileVersionInfo            fvi      = FileVersionInfo.GetVersionInfo(assembly.Location);
                string version = fvi.FileVersion;
                await icrt.Respond($"My version is: {version}");

                break;

            case "-running":
                var allcontainers = ObjectToString.Convert(await _containerInterface.GetRunningContainers(serverID));
                await icrt.Respond($"Running containers are: {allcontainers}");

                break;

            case "-possible":
                var servers          = _serverStore.GetAllServers(GetContainerInterfaceType());
                var serverNames      = servers.Select(s => s.ServerName).ToList();
                var serverStringList = ObjectToString.Convert(serverNames);
                await icrt.Respond($"Possible game servers are: {serverStringList}");

                break;
            }

            if (input.StartsWith("-run ") || input.StartsWith("-start "))
            {
                if (await VerifyUser(serverID, senderID, icrt))
                {
                    await AttemptRun(serverID, input, icrt);
                }
                return;
            }

            if (input.StartsWith("-stop "))
            {
                if (await VerifyUser(serverID, senderID, icrt))
                {
                    await AttemptStop(serverID, input, icrt);
                }
                return;
            }

            if (input.StartsWith("-allowlist"))
            {
                if (await _allowList.IsUserAllowedToManage(serverID, senderID))
                {
                    if (input.StartsWith("-allowlist add "))
                    {
                        await _allowList.AddUser(serverID, input.Replace("-allowlist add ", ""));

                        await icrt.Respond("User added.");

                        return;
                    }

                    if (input.StartsWith("-allowlist remove "))
                    {
                        await _allowList.RemoveUser(serverID, input.Replace("-allowlist remove ", ""));

                        await icrt.Respond("User removed.");

                        return;
                    }

                    if (input.StartsWith("-allowlist enable"))
                    {
                        await _allowList.SetAllowListStatus(serverID, true);

                        await icrt.Respond("Allow list enabled.");

                        return;
                    }

                    if (input.StartsWith("-allowlist disable"))
                    {
                        await _allowList.SetAllowListStatus(serverID, false);

                        await icrt.Respond("Allow list disabled.");

                        return;
                    }

                    var allowList = await _allowList.GetAllowList(serverID);

                    var rawAllowList = string.Join("\n", allowList.Select(x => x.ToString()).ToArray());
                    await icrt.Respond("Allow list:\n" + rawAllowList);

                    return;
                }

                await icrt.Respond("I'm not allowed to talk to you, ask your server admin to allowlist you!");
            }
        }