예제 #1
0
        public async Task Vote(ICommand command)
        {
            var poll = await _settings.Modify(command.GuildId, (PollSettings s) =>
            {
                var p = s.Polls.FirstOrDefault(x => x.Channel == command.Message.Channel.Id);
                if (p != null)
                {
                    if (command["Answer"].AsString.All(x => char.IsDigit(x)))
                    {
                        var vote = command["Answer"].AsInt.Value;
                        if (vote > p.Answers.Count || vote < 1)
                            throw new IncorrectParametersCommandException("There is no answer with this number.");

                        p.Votes[command.Message.Author.Id] = vote;
                    }
                    else
                    {
                        var tokens = new string(command["Answer"].AsString.Select(c => char.IsLetterOrDigit(c) ? c : ' ').ToArray()).Split(new char[] { }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.ToLowerInvariant()).ToList();
                        var scores = new List<int>();
                        foreach (var answerTokens in p.Answers.Select(x => new string(x.Select(c => char.IsLetterOrDigit(c) ? c : ' ').ToArray()).Split(new char[] { }, StringSplitOptions.RemoveEmptyEntries).Select(y => y.ToLowerInvariant()).ToList()))
                            scores.Add(tokens.Where(x => answerTokens.Contains(x)).Count());

                        if (!scores.Any(x => x > 0))
                            throw new UnclearParametersCommandException($"I don't recognize this answer. Try to vote with `{command.Prefix}vote answer number` instead.", false);

                        var max = scores.Max();
                        if (scores.Where(x => x == max).Count() > 1)
                            throw new UnclearParametersCommandException($"I'm not sure which answer you meant. Try to vote with `{command.Prefix}vote answer number` instead.", false);

                        p.Votes[command.Message.Author.Id] = scores.FindIndex(x => x == max) + 1;
                    }
                }

                return p;
            });
            
            if (poll == null)
            {
                await command.ReplyError("There is no poll running in this channel.");
            }
            else
            {
                var confMessage = await command.ReplySuccess($"**{DiscordHelpers.EscapeMentions("@" + command.Message.Author.Username)}** vote cast.");
                if (poll.Anonymous)
                {
                    if ((await command.Guild.GetCurrentUserAsync()).GetPermissions((IGuildChannel)command.Channel).ManageMessages)
                        await command.Message.DeleteAsync();

                    confMessage.First().DeleteAfter(2);
                }
            }
        }