コード例 #1
0
        public async Task <ActionResult> RegisterGame([FromForm] SlackRequest data)
        {
            var(team_id, channel_id, channel_name, _, _, _) = data;

            // TODO: check DMs
            // check if game already exists
            var existingGame = _context
                               .Games
                               .FirstOrDefault(a => a.TeamId == team_id && a.SlackId == channel_id);

            if (existingGame != null)
            {
                return(Ok(this._responseFactory.CreateSimpleChannelMessage($"Hold up! {existingGame.ChannelName} has already been created")));
            }
            else
            {
                // create a new game
                var game = new Game
                {
                    ChannelName = channel_name,
                    SlackId     = channel_id,
                    TeamId      = team_id
                };

                // save it
                _context.Add(game);
                await _context.SaveChangesAsync();

                return(Ok(this._responseFactory.CreateSimpleChannelMessage($"Success! {existingGame.ChannelName} has been created")));
            }
        }
コード例 #2
0
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            bool success = false;

            if (context.ActionArguments.Keys.Contains("slackRequest"))
            {
                SlackRequest sr = context.ActionArguments["slackRequest"] as SlackRequest;
                if (sr.token == config.GetValue <string>("SlackVerificationToken"))
                {
                    success = true;
                }
            }

            if (context.ActionArguments.Keys.Contains("payload"))
            {
                SlackActionRequest sr = JsonConvert.DeserializeObject <SlackActionRequest>(context.ActionArguments["payload"] as string);
                if (sr.token == config.GetValue <string>("SlackVerificationToken"))
                {
                    success = true;
                }
            }

            if (!success)
            {
                context.HttpContext.Response.StatusCode = 403;
                context.Result = new ContentResult()
                {
                    Content = "Bad Slack verification token"
                };
            }
        }
コード例 #3
0
        private async Task <IActionResult> DoAsync()
        {
            var workspaceName = HttpContext.SlackWorkspaceName();
            var request       = new SlackRequest(HttpContext, await _slackService.GetWorkspaceAsync(workspaceName));
            var response      = new SlackResponse(request);

            // 기다리지 않는다.
            Task.Run(() => ExecuteCommand(_dbContextOptions, request, response));
            return(Ok());
        }
コード例 #4
0
 public UnoService(SlackRequest request, TraceWriter log)
 {
     _log         = log;
     _request     = request;
     _slackClient = new SlackClient(Environment.GetEnvironmentVariable("SlackWebhookUrl"));
     _redis       = new RedisClient();
     _cosmos      = new CosmosDbService();
     _deckOfCards = new DeckOfCards();
     _aiService   = new AiService();
 }
コード例 #5
0
 private async void ExecuteCommand(DbContextOptions options, SlackRequest request, SlackResponse response)
 {
     using var context = new CoffeeContext(options);
     try
     {
         await ExecuteCommandAsync(context, request, response);
     }
     catch (Exception e)
     {
         _logger.LogError(e, $"Error occured while handling {request}");
     }
 }
コード例 #6
0
        public ActionResult Create(SlackRequest slackRequest)
        {
            string personGettingTicket = slackRequest.text.Trim();
            var    ticket = new Ticket(slackRequest.text, DateTime.UtcNow, slackRequest.team_id);

            context.Tickets.Add(ticket);
            context.SaveChanges();
            int totalTicketsForPerson = context.Tickets.Where(p => string.Equals(p.Name, personGettingTicket, StringComparison.OrdinalIgnoreCase)).Count();
            var messageResponse       = BuildCreateTicketMessageResponse(personGettingTicket, totalTicketsForPerson, ticket.ID);

            return(Json(messageResponse));
        }
コード例 #7
0
        //[ValidateAntiForgeryToken]
        public IActionResult Search([FromForm] SlackRequest request, [FromServices] IServiceScopeFactory scopeFactory)
        {
            //Request.EnableBuffering();
            //Request.Body.Position = 0;
            //using (var reader = new StreamReader(
            //    Request.Body,
            //    encoding: Encoding.UTF8,
            //    detectEncodingFromByteOrderMarks: false,
            //    bufferSize: 1024,
            //    leaveOpen: true))
            //        {
            //            var body = reader.ReadToEnd();
            //            // Do some processing with body

            //            // Reset the request body stream position so the next middleware can read it
            //            Request.Body.Position = 0;
            //}

            //bool getTimestamp = Request.Headers.TryGetValue("X-Slack-Request-Timestamp", out var timestamps);
            //if (!getTimestamp)
            //{
            //    return BadRequest("Timestamp missing from request");
            //}
            //else
            //{
            //    if (!_slackVerificationProvider.VerifySlackRequest(Request))
            //    {
            //        return Unauthorized("Request cannot be verified");
            //    }
            //}

            // Validate empty
            if (string.IsNullOrEmpty(request.Text))
            {
                return(Ok($"Please enter the name of the location to find."));
            }

            // Validate minimum length
            if (request.Text.Length < 3)
            {
                return(Ok($"Please enter a name with at least 3 characters."));
            }

            _logger.LogInformation($"Queuing search task for {request.Text}");

            var searchTask = GetTaskForSearch(request.Text, new Uri(request.Response_Url), scopeFactory);

            //service.StartAsync(new CancellationToken());
            _taskQueue.QueueBackgroundWorkItem(searchTask);
            // Processing, acknowledge receipt
            return(Ok());
        }
コード例 #8
0
 public void Post([FromForm] SlackRequest request)
 {
     if (request != null)
     {
         var spokenText = System.IO.File.ReadAllBytes(Directory.GetCurrentDirectory() + "\\Assets\\despacito.mp3");
         if (spokenText != null)
         {
             _slackClient.SendAudio(spokenText, request.Channel_Name, "despascito");
         }
         Ok();
     }
     BadRequest();
 }
コード例 #9
0
        public async Task <ActionResult> GiveBottleCap([FromForm] SlackRequest data)
        {
            var(team_id, channel_id, channel_name, text, user_id, user_name) = data;
            // validate
            if (!(text.First() == '<' && text.Last() == '>'))
            {
                return(Ok(this._responseFactory.CreateSimpleChannelMessage($"Thats not a real player! = {text}", false)));
            }

            // get all players for a game
            var existingGame = await _context
                               .Games
                               .Include(g => g.Players)
                               .Include(i => i.DungeonMasters)
                               .FirstOrDefaultAsync(a => a.TeamId == team_id && a.SlackId == channel_id);

            if (existingGame == null)
            {
                return(Ok(this._responseFactory.GameNotFoundMessage(channel_name)));
            }
            else
            {
                // DM Check
                if (existingGame.DungeonMasters.Any(a => a.SlackId != user_id))
                {
                    return(Ok(this._responseFactory.CreateSimpleChannelMessage($"Sneaky Bastard! You are not the DM of {existingGame.ChannelName}. Too many bottle caps can crash the economy!", false)));
                }
                // get username
                var userName = text.Trim();
                // update/create player
                var player = existingGame.Players.FirstOrDefault(f => f.SlackId == userName);
                if (player == null)
                {
                    var newPlayer = new Player
                    {
                        SlackId    = userName,
                        GameId     = existingGame.Id,
                        BottleCaps = 1,
                    };
                    _context.Players.Add(newPlayer);
                }
                else
                {
                    player.BottleCaps++;
                }
                await _context.SaveChangesAsync();

                return(Ok(this._responseFactory.CreateSimpleChannelMessage($"Success! Bottle cap for {text}!")));
            };
        }
コード例 #10
0
        public string Draw(SlackRequest slackRequest)
        {
            string errorMessage = "Couldn't parse date. Please enter a date in the format m/d/yyyy";

            if (string.IsNullOrEmpty(slackRequest.text))
            {
                return(errorMessage);
            }

            string [] parsedDate = slackRequest.text.Split('/');
            if (parsedDate.Length != 3)
            {
                return(errorMessage);
            }

            int month = Int32.Parse(parsedDate[0]);
            int day   = Int32.Parse(parsedDate[1]);
            int year  = Int32.Parse(parsedDate[2]);

            // I realize that not all months have 31 days, but
            // I don't want to implement that checking logic.
            // Also, the year is just a ballpark to make sure the number seems right
            if (month < 1 || month > 12 || day < 1 || day > 31 ||
                year < 2000 || year > 3000)
            {
                return(errorMessage);
            }

            DateTime dt;

            try {
                dt = new DateTime(year, month, day);
            }
            catch (Exception ex) {
                return($"The date {month}/{day}/{year} is invalid. {ex.Message}");
            }

            IEnumerable <Ticket> ticketsAfterDateForTeam = context.Tickets.Where(t => t.CreatedAt > dt &&
                                                                                 t.TeamId == slackRequest.team_id);

            if (!ticketsAfterDateForTeam.Any())
            {
                return($"There are no tickets after the date {dt.ToString()}");
            }

            Random rand          = new Random();
            Ticket winningTicket = ticketsAfterDateForTeam.ElementAt(rand.Next(ticketsAfterDateForTeam.Count()));

            return($"{winningTicket.Name} won!");
        }
コード例 #11
0
        public async Task <IActionResult> PostIta([FromForm] SlackRequest request)
        {
            if (request != null)
            {
                var spokenText = await _talkingService.TextToTalk(request.Text, "ita");

                if (spokenText != null)
                {
                    _slackClient.SendAudio(spokenText, request.Channel_Name, request.Text);
                }
                return(Ok());
            }
            return(BadRequest());
        }
コード例 #12
0
        public SlackResponse Process(SlackRequest slackRequest)
        {
            var bAuthorized = _validator.IsAuthorized(slackRequest);

            if (!bAuthorized)
            {
                return(new SlackResponse
                {
                    Text = UnauthorizedResponse,
                    ResponseType = ResponseType.Ephemeral
                });
            }
            _formTextContent = slackRequest.CommandText;
            _channelInfo     = _databaseClient.GetSlackChannelInfo(slackRequest.ChannelName);
            return(_triggerWordMap[slackRequest.CommandType]());
        }
コード例 #13
0
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, TraceWriter log)
        {
            var factory = StartUp();
            var request = new SlackRequest(req.Form);

            try
            {
                log.Info(request.user_name);
                var result = factory.GetResult(request.ToDrinkRequest(request));
                return(new OkObjectResult(new SlackResponse(result.Message)));
            }
            catch (System.Exception)
            {
                return(new OkObjectResult(new SlackResponse("Tyvärr gick något fel.")));
            }
        }
コード例 #14
0
        public void Post([FromForm] SlackRequest slackRequest)
        {
            HttpClient client = new HttpClient();

            var obj = new { text = Get() };

            string json = JsonConvert.SerializeObject(obj);

            var response = client.PostAsync(
                slackRequest.response_url,
                new StringContent(json, Encoding.UTF8, "application/json")).Result;

            var responseString = response.Content.ReadAsStringAsync();

            responseString.Wait();
        }
コード例 #15
0
        public async Task <object> Post(SlackRequest request)
        {
            if (request.token != Important.token)
            {
                return(new
                {
                    text = "Bad request. Token mismatch. Check config."
                });
            }

            using (var client = new HttpClient())
            {
                var parsed = request.text.Trim().Substring(request.text.IndexOf(':'));

                if (parsed.Length < 3)
                {
                    return(new
                    {
                        text = "Unable to find a stock symbol in your request."
                    });
                }

                var sendstring = string.Format(yahooUrl, parsed);
                var result     = await client.GetAsync(sendstring);

                var response = "";

                switch (result.StatusCode)
                {
                case System.Net.HttpStatusCode.OK:
                    response = await ProcessResult(result, request.text);

                    break;

                default:
                    response = string.Format("A network error occurred. Status code {0} from Yahoo.", result.StatusCode);
                    break;
                }

                var objtosend = new
                {
                    text = response
                };

                return(objtosend);
            }
        }
コード例 #16
0
        private async Task ExecuteCommandAsync(CoffeeContext context, SlackRequest request, SlackResponse response)
        {
            var splitted = request.Text.ToString().Trim().Split(' ', 2);

            var command = splitted[0];
            var option  = splitted.Length > 1 ? splitted[1] : "";

            using var coffee = new CoffeeService(context);

            var user = await coffee.FindUserAsync(request.UserId);

            if (user == null)
            {
                var userName = await GetUserNameAsync(request.Workspace.Name, request.UserId);

                user = await coffee.CreateUserAsync(request.UserId, userName, false);

                await coffee.SaveAsync();
            }
            else if (string.IsNullOrEmpty(user.Name))
            {
                var userName = await GetUserNameAsync(request.Workspace.Name, request.UserId);

                user = await coffee.UpdateUserNameAsync(request.UserId, userName);

                await coffee.SaveAsync();
            }

            try
            {
                await commands.HandleCommandAsync(coffee, user, command, option, response, _logger);

                await coffee.SaveAsync();
            }
            catch (BadRequestException e)
            {
                response.Empty();
                response.Ephemeral(e.ResponseMsg);
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"Error occured during handling command: {command}");
            }

            await response.SendAsync(_slackService);
        }
コード例 #17
0
        public async Task <ActionResult> GetBottleCaps([FromForm] SlackRequest data)
        {
            var(team_id, channel_id, channel_name, _, _, _) = data;
            // get all players for a game
            var existingGame = await _context
                               .Games
                               .Include(i => i.Players)
                               .FirstOrDefaultAsync(a => a.TeamId == team_id && a.SlackId == channel_id);

            if (existingGame == null)
            {
                return(Ok(this._responseFactory.GameNotFoundMessage(channel_name)));
            }
            else
            {
                var response = new
                {
                    blocks = new List <Object> {
                        new {
                            type = "header",
                            text = new {
                                type  = "plain_text",
                                text  = $":spinning-coin: Bottle caps for {existingGame.ChannelName} :spinning-coin:",
                                emoji = true
                            }
                        },
                        new {
                            type = "divider",
                        },
                        new {
                            type = "section",
                            text = new {
                                type = "mrkdwn",
                                text = MarkdownFactory.CreateTable(existingGame.Players)
                            }
                        }
                    }
                };
                return(Ok(new
                {
                    blocks = response.blocks,
                    response_type = "in_channel"
                }));
            }
        }
コード例 #18
0
ファイル: EventsController.cs プロジェクト: coldraydk/coldbot
        public async Task <IActionResult> Post([FromBody] SlackRequest request)
        {
            logger.LogInformation(JsonConvert.SerializeObject(request));

            if (!string.IsNullOrEmpty(request?.Challenge))
            {
                return(Ok(request.Challenge));
            }

            if (!string.IsNullOrEmpty(request?.Event?.BotId))
            {
                return(Ok());
            }

            magicLeagueService.ProcessEvent(request?.Event);

            return(Ok());
        }
コード例 #19
0
 public static FunctionBody GenerateFromRequest(ApiGatewayProxyRequest request, ILambdaContext context)
 {
     if (request.IsSlackRequest())
     {
         var slackRequest = new SlackRequest(request.Body);
         var decodedText  = WebUtility.UrlDecode(slackRequest.Text);
         slackRequest.Text = decodedText.TrimStart('<').TrimEnd('>');
         context.Logger.LogLine(SerializerUtil.Serialize(slackRequest));
         return(new FunctionBody
         {
             url = slackRequest.Text,
         });
     }
     else
     {
         return(SerializerUtil.Deserialize <FunctionBody>(request.Body));
     }
 }
コード例 #20
0
        protected async override Task ProcessSlackRequestAsync(SlackRequest request)
        {
            // parse request into two strings and check if the first one is a recognized command
            var args = request.Text?.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries) ?? new[] { "" };

            switch (args[0].ToLowerInvariant())
            {
            case "add":
                if ((args.Length == 1) || string.IsNullOrWhiteSpace(args[1]))
                {
                    Console.WriteLine("Missing task after the 'add' command.");
                }
                else
                {
                    await AddTask(request.UserId, args[1]);
                }
                break;

            case "remove":
                if ((args.Length == 1) || string.IsNullOrWhiteSpace(args[1]) || !int.TryParse(args[1], out var index))
                {
                    Console.WriteLine("Missing or invalid task number after the `remove` command.");
                }
                else if (!await RemoveTask(request.UserId, index))
                {
                    Console.WriteLine("Invalid task number after the `remove` command.");
                }
                break;

            case "list":
                await ListTasks(request.UserId);

                break;

            case "clear":
                await ClearTasks(request.UserId);

                break;

            default:
                Console.WriteLine("Sorry, I only understand `add`, `remove`, `list`, and `clear` commands.");
                break;
            }
        }
コード例 #21
0
        private static FileListRequest ToFileListRequst(SlackRequest slackRequest)
        {
            var slackRequestTextList = ToSlackRequestTextList(slackRequest.text);

            var timeStampFrom = GetTimeStampFrom(slackRequestTextList);
            var timeStampTo   = GetTimeStampTo(slackRequestTextList);
            var channel       = GetTargetChannel(slackRequestTextList, slackRequest.channel_id);
            var user          = GetTargetUser(slackRequestTextList, slackRequest.user_id);

            var request = new FileListRequest
            {
                Token   = token,
                From    = timeStampFrom,
                To      = timeStampTo,
                Channel = channel,
                User    = user
            };

            return(request);
        }
コード例 #22
0
        public async Task <ActionResult> UpdateDisplayName([FromForm] SlackRequest data)
        {
            Console.WriteLine(data);
            var(team_id, channel_id, channel_name, text, _, _) = data;
            // TODO: add DM check
            // check if game already exists
            var existingGame = _context
                               .Games
                               .FirstOrDefault(a => a.TeamId == team_id && a.SlackId == channel_id);

            if (existingGame == null)
            {
                return(Ok(this._responseFactory.GameNotFoundMessage(channel_name)));
            }
            else
            {
                existingGame.ChannelName = text;
                await _context.SaveChangesAsync();

                return(Ok(this._responseFactory.CreateSimpleChannelMessage($"Success! {channel_name} has been renamed to {existingGame.ChannelName}", false)));
            }
        }
コード例 #23
0
        public async Task <ActionResult> ClaimDm([FromForm] SlackRequest data)
        {
            var(team_id, channel_id, channel_name, _, user_id, user_name) = data;

            // get the game
            // check if game already exists
            var existingGame = _context
                               .Games
                               .Include(i => i.DungeonMasters)
                               .FirstOrDefault(a => a.TeamId == team_id && a.SlackId == channel_id);

            if (existingGame == null)
            {
                return(Ok(this._responseFactory.GameNotFoundMessage(channel_name)));
            }
            else
            {
                if (existingGame.DungeonMasters.Count() > 0)
                {
                    return(Ok(this._responseFactory.CreateSimpleChannelMessage($"Muntiny is it?! {existingGame.ChannelName} has already has a DM.")));
                }
                else
                {
                    var dm = new DungeonMaster
                    {
                        SlackId   = user_id,
                        SlackName = user_name,
                        GameId    = existingGame.Id
                    };

                    this._context.DungeonMasters.Add(dm);
                    await this._context.SaveChangesAsync();

                    return(Ok(this._responseFactory.CreateSimpleChannelMessage($"Claimed! {existingGame.ChannelName} now belongs to <@{dm.SlackId}|{dm.SlackName}>", false)));
                }
            }
        }
コード例 #24
0
 public static SlackActionRequest ToActionRequest(this SlackRequest request)
 {
     return(new SlackActionRequest
     {
         ResponseUrl = request.ResponseUrl,
         Token = request.Token,
         TriggerId = request.TriggerId,
         Channel = new IdName
         {
             Id = request.ChannelId,
             Name = request.ChannelName
         },
         User = new IdName
         {
             Id = request.UserId,
             Name = request.UserName
         },
         Team = new Team
         {
             Id = request.TeamId,
             Domain = request.TeamDomain
         }
     });
 }
コード例 #25
0
        private async Task <APIGatewayProxyResponse> HandleRequest(SlackRequest request)
        {
            Console.WriteLine("HandleRequest invoked with Type " + request.Type);
            Console.WriteLine("HandleRequest invoked with Event text " + request.Event.Text);
            Console.WriteLine("HandleRequest invoked with Event_id " + request.Event_Id);

            switch (request.Type)
            {
            case "url_verification":
                return(new APIGatewayProxyResponse
                {
                    Headers = GetCorsHeaders(),
                    StatusCode = 200,
                    Body = JsonConvert.SerializeObject(new
                    {
                        Challenge = request.Challenge
                    })
                });

            case "event_callback":
                EventId existingId = _eventIdList.Find(i => i.id == request.Event_Id);
                Console.WriteLine("event_callback Existing in the list " + "  " + existingId?.id + "  ", existingId?.count);
                if (existingId == null)
                {
                    Console.WriteLine("Adding new event to list and processing the message ");
                    _eventIdList.Add(new EventId
                    {
                        id    = request.Event_Id,
                        count = 1
                    });

                    await _slackMessage.ProcessMessage(request.Event);
                }
                else if (existingId.count > 5)
                {
                    _eventIdList.Remove(existingId);
                }
                else
                {
                    existingId.count = existingId.count + 1;
                }

                return(new APIGatewayProxyResponse
                {
                    Headers = GetCorsHeaders(),
                    StatusCode = 200,
                    Body = JsonConvert.SerializeObject(new
                    {
                        Message = request.Event.Text
                    })
                });

            default:
                return(new APIGatewayProxyResponse
                {
                    Headers = GetCorsHeaders(),
                    StatusCode = 200,
                    Body = JsonConvert.SerializeObject(new
                    {
                        Error = "unhandled"
                    })
                });
            }
        }
コード例 #26
0
        protected async override Task HandleSlackRequestAsync(SlackRequest request)
        {
            // parse request into two strings and check if the first one is a recognized command
            var args = request.Text?.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries) ?? new[] { "" };

            switch (args[0].ToLowerInvariant())
            {
            case "clear": {
                var messages = await _table.ListMessagesAsync();

                // enumerate message from the message table
                if (messages.Any())
                {
                    foreach (var message in messages)
                    {
                        await _table.DeleteMessage(message.MessageId);
                    }
                    Console.WriteLine($"{messages.Count():N0} messages cleared.");
                }
                else
                {
                    Console.WriteLine("There are no messages to clear out.");
                }
            }
            break;

            case "list": {
                var messages = await _table.ListMessagesAsync();

                // enumerate message from the message table
                if (messages.Any())
                {
                    Console.WriteLine($"{messages.Count():N0} messages found.");
                    var count = 0;
                    foreach (var message in messages)
                    {
                        Console.WriteLine($"{++count:N0}: {message.Text} [from {message.Source}]");
                    }
                }
                else
                {
                    Console.WriteLine("There are no messages.");
                }
            }
            break;

            case "send":

                // add a new message to the message table
                if ((args.Length == 1) || string.IsNullOrWhiteSpace(args[1]))
                {
                    Console.WriteLine("No messages after the `send` command to send.");
                }
                else
                {
                    await _table.InsertMessageAsync(new Message {
                        Source = "Slack",
                        Text   = args[1]
                    });

                    Console.WriteLine("Message sent.");
                }
                break;

            case "error":
                throw new Exception("Oh no, I haz br0ken!");

            default:
                Console.WriteLine("Sorry, I only understand `send`, `list`, and `clear` commands.");
                break;
            }
        }
コード例 #27
0
        public async Task <IActionResult> Post([FromServices] ISlackClient slackClient, [FromForm] SlackRequest slackRequest, CancellationToken cancellationToken)
        {
            await slackClient.PostOnChannelAsync(slackRequest.TeamDomain, slackRequest.ChannelId, "command [list]", cancellationToken);

            return(Ok(new SlackResponse
            {
                ResponseType = SlackResponseType.InChannel,
                Text = "teste"
            }));
        }
コード例 #28
0
        public async Task <IActionResult> Help([FromServices] ISlackClient slackClient, [FromForm] SlackRequest slackRequest, [FromQuery] string extraParameters, CancellationToken cancellationToken)
        {
            await slackClient.PostOnChannelAsync(slackRequest.TeamDomain, slackRequest.ChannelId, $"command [list help] parameters: [{extraParameters}]", cancellationToken);

            return(Ok(new SlackResponse
            {
                ResponseType = SlackResponseType.InChannel,
                Text = String.Join(Environment.NewLine, new List <string>
                {
                    $"Hey, there!",
                    $"This is the [{slackRequest.Command} list]. With it you can"
                }),
                Attachments = new List <SlackAttachment>
                {
                    new SlackAttachment
                    {
                        Text = $"List flags: Try [{slackRequest.Command} list flags] list all available flags."
                    }
                }
            }));
        }
コード例 #29
0
ファイル: Function.cs プロジェクト: schoukri/LambdaSharpTool
 protected async override Task ProcessSlackRequestAsync(SlackRequest request)
 => Console.WriteLine("Hello world!");
コード例 #30
0
        public async Task <ActionResult> UseBottleCap([FromForm] SlackRequest data)
        {
            var(team_id, channel_id, channel_name, text, user_id, user_name) = data;

            // get all players for a game
            var existingGame = await _context
                               .Games
                               .Include(g => g.Players)
                               .Include(i => i.DungeonMasters)
                               .FirstOrDefaultAsync(a => a.TeamId == team_id && a.SlackId == channel_id);

            if (existingGame == null)
            {
                return(Ok(this._responseFactory.GameNotFoundMessage(channel_name)));
            }


            // if no text (then the user is using their own cap)
            if (String.IsNullOrWhiteSpace(text))
            {
                // update/create player
                var userId = $"<@{user_id}|{user_name}>";
                var player = existingGame.Players.FirstOrDefault(f => f.SlackId == userId);
                if (player == null)
                {
                    return(Ok(this._responseFactory.CreateSimpleChannelMessage($"Whomp! {text} does not have any bottle caps!")));
                }
                else
                {
                    if (player.BottleCaps <= 0)
                    {
                        return(Ok(this._responseFactory.CreateSimpleChannelMessage($"Whomp! {text} has run out of bottle caps!")));
                    }
                    else
                    {
                        player.BottleCaps--;
                        await _context.SaveChangesAsync();

                        return(Ok(this._responseFactory.CreateSimpleChannelMessage($"Ca-ching! Bottle cap for {userId} has been cashed in!")));
                    }
                }
            }
            // if text (this is the DM giving bottlecaps)
            else
            {
                // DM Check
                if (existingGame.DungeonMasters.Any(a => a.SlackId != user_id))
                {
                    return(Ok(this._responseFactory.CreateSimpleChannelMessage($"! You are not the DM of {existingGame.ChannelName}", false)));
                }
                // validate
                if (!(text.First() == '<' && text.Last() == '>'))
                {
                    return(Ok(this._responseFactory.CreateSimpleChannelMessage($"Thats not a real player! = {text}", false)));
                }
                // get username
                var userName = text.Trim();
                // update/create player
                var player = existingGame.Players.FirstOrDefault(f => f.SlackId == userName);
                if (player == null)
                {
                    return(Ok(this._responseFactory.CreateSimpleChannelMessage($"Whomp! {text} does not have any bottle caps!")));
                }
                else
                {
                    if (player.BottleCaps <= 0)
                    {
                        return(Ok(this._responseFactory.CreateSimpleChannelMessage($"Whomp! {text} has run out of bottle caps!")));
                    }
                    else
                    {
                        player.BottleCaps--;
                        await _context.SaveChangesAsync();

                        return(Ok(this._responseFactory.CreateSimpleChannelMessage($"Ca-ching! Bottle cap for {text} has been cashed in!")));
                    }
                }
            }
        }