Beispiel #1
0
    public async Task OnGet(string teamId)
    {
        var teamIdToUpper = teamId.ToUpper();
        var team          = await _teamRepo.GetTeam(teamIdToUpper);

        if (team != null)
        {
            Team = team;
            if (team.FplbotLeagueId.HasValue)
            {
                var league = await _leagueClient.GetClassicLeague(team.FplbotLeagueId.Value, tolerate404 : true);

                League = league;
            }

            var slackClient = await CreateSlackClient(teamIdToUpper);

            try
            {
                var channels = await slackClient.ConversationsListPublicChannels(500);

                ChannelStatus = channels.Channels.FirstOrDefault(c => team.FplBotSlackChannel == $"#{c.Name}" || team.FplBotSlackChannel == c.Id) != null;
            }
            catch (Exception e)
            {
                _logger.LogError(e, e.Message);
            }
        }
    }
Beispiel #2
0
    public override async Task <EventHandledResponse> Handle(EventMetaData eventMetadata, AppMentionEvent message)
    {
        var gameweek = await _gameweekHelper.ExtractGameweekOrFallbackToCurrent(message.Text, $"{CommandsFormatted} {{gw}}");


        var team = await _slackTeamRepo.GetTeam(eventMetadata.Team_Id);

        var messageToSend = "You don't follow any league yet. Use the `@fplbot follow` command first.";

        if (team.FplbotLeagueId.HasValue)
        {
            try
            {
                messageToSend =
                    await _transfersClient.GetTransfersByGameweekTexts(gameweek ?? 1, team.FplbotLeagueId.Value);
            }
            catch (HttpRequestException e) when(e.Message.Contains("429"))
            {
                messageToSend = "It seems fetching transfers was a bit heavy for this league. Try again later. ­ЪциРђЇ№ИЈ";
            }
        }

        await _workSpacePublisher.PublishToWorkspace(eventMetadata.Team_Id, message.Channel, messageToSend);

        return(new EventHandledResponse(messageToSend));
    }
        public override async Task <EventHandledResponse> Handle(EventMetaData eventMetadata, AppMentionEvent incomingMessage)
        {
            var isChartRequest = incomingMessage.Text.Contains("chart");

            var gwPattern = $"{Commands.First()} {{gw}}";

            if (isChartRequest)
            {
                gwPattern = $"{Commands.First()} chart {{gw}}|{Commands.First()} {{gw}} chart";
            }
            var gameWeek = await _gameweekHelper.ExtractGameweekOrFallbackToCurrent(incomingMessage.Text, gwPattern);

            if (!gameWeek.HasValue)
            {
                await _workspacePublisher.PublishToWorkspace(eventMetadata.Team_Id, incomingMessage.Channel, "Invalid gameweek :grimacing:");

                return(new EventHandledResponse("Invalid gameweek"));
            }

            var setup = await _slackTeamsRepo.GetTeam(eventMetadata.Team_Id);

            var outgoingMessage = isChartRequest ?
                                  await _captainsByGameWeek.GetCaptainsChartByGameWeek(gameWeek.Value, (int)setup.FplbotLeagueId) :
                                  await _captainsByGameWeek.GetCaptainsByGameWeek(gameWeek.Value, (int)setup.FplbotLeagueId);

            await _workspacePublisher.PublishToWorkspace(eventMetadata.Team_Id, incomingMessage.Channel, outgoingMessage);

            return(new EventHandledResponse(outgoingMessage));
        }
    private async Task <string> GetAndUpdateSubscriptionInfo(string teamId, AppMentionEvent appMentioned)
    {
        try
        {
            var team = await _teamRepo.GetTeam(teamId);

            var currentSubscriptions = team.Subscriptions;
            (var inputSubscriptions, var unableToParse) = ParseSubscriptionsFromInput(appMentioned);

            if (inputSubscriptions.Count() < 1 && unableToParse.Count() < 1)
            {
                return($"You need to pass some arguments\n {FormatAllSubsAvailable()}");
            }

            if (inputSubscriptions.Count() < 1)
            {
                return($"I was not able to understand: *{string.Join(", ", unableToParse)}.* :confused: \n {FormatAllSubsAvailable()}");
            }

            var newSubscriptions = appMentioned.Text.Contains("unsubscribe") ?
                                   UnsubscribeToEvents(inputSubscriptions, currentSubscriptions) :
                                   SubscribeToEvents(inputSubscriptions, currentSubscriptions);

            await _teamRepo.UpdateSubscriptions(teamId, newSubscriptions);

            return(FormatSubscriptionMessage(newSubscriptions, unableToParse));
        }
        catch (Exception e)
        {
            _logger.LogError(e.Message, e);
            return($"Oops, could not update subscriptions.");
        }
    }
        private async Task <string> GetCurrentSubscriptions(string teamId, AppMentionEvent appMentioned)
        {
            try
            {
                var team = await _teamRepo.GetTeam(teamId);

                var currentSubscriptions = team.Subscriptions;

                if (currentSubscriptions.Count() < 1)
                {
                    return("You are not subscribing to any fplbot updates :disappointed:");
                }

                var sb = new StringBuilder();

                sb.Append("This channel will receive notifications for: \n");

                sb.Append($"{Formatter.BulletPoints(team.Subscriptions)}");

                return(sb.ToString());
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message, e);
                return($"Oops, could not get subscriptions.");
            }
        }
Beispiel #6
0
    public async Task Handle(PublishLineupsToSlackWorkspace message, IMessageHandlerContext context)
    {
        var team = await _slackTeamRepo.GetTeam(message.WorkspaceId);

        var slackClient  = _builder.Build(team.AccessToken);
        var lineups      = message.Lineups;
        var firstMessage = $"*Lineups {lineups.HomeTeamLineup.TeamName}-{lineups.AwayTeamLineup.TeamName} ready* 👇";

        var res = await slackClient.ChatPostMessage(team.FplBotSlackChannel, firstMessage);

        if (res.Ok)
        {
            var formattedLineup = Formatter.FormatLineup(lineups);
            var options         = new SendOptions();
            options.RequireImmediateDispatch();
            options.RouteToThisEndpoint();
            await context.Send(new PublishSlackThreadMessage
                               (
                                   message.WorkspaceId,
                                   team.FplBotSlackChannel,
                                   res.ts,
                                   formattedLineup
                               ), options);
        }
    }
Beispiel #7
0
    public async Task Handle(PublishFixtureEventsToSlackWorkspace message, IMessageHandlerContext messageContext)
    {
        _logger.LogInformation($"Publishing {message.FixtureEvents.Count} fixture events to {message.WorkspaceId}");
        var slackTeam = await _slackTeamRepo.GetTeam(message.WorkspaceId);

        TauntData tauntData = null;

        if (slackTeam.Subscriptions.ContainsSubscriptionFor(EventSubscription.Taunts) && slackTeam.FplbotLeagueId.HasValue)
        {
            var gws = await _globalSettingsClient.GetGlobalSettings();

            var currentGw  = gws.Gameweeks.GetCurrentGameweek();
            var slackUsers = await GetSlackUsers(slackTeam);

            var entries = await _leagueEntriesByGameweek.GetEntriesForGameweek(currentGw.Id, slackTeam.FplbotLeagueId.Value);

            var transfers = await _transfersByGameWeek.GetTransfersByGameweek(currentGw.Id, slackTeam.FplbotLeagueId.Value);

            tauntData = new TauntData(transfers, entries, entryName => SlackHandleHelper.GetSlackHandleOrFallback(slackUsers, entryName));
        }

        if (!string.IsNullOrEmpty(slackTeam.FplBotSlackChannel))
        {
            var eventMessages = GameweekEventsFormatter.FormatNewFixtureEvents(message.FixtureEvents, slackTeam.Subscriptions.ContainsStat, FormattingType.Slack, tauntData);
            var formattedStr  = eventMessages.Select(evtMsg => $"{evtMsg.Title}\n{evtMsg.Details}");
            await _publisher.PublishToWorkspace(slackTeam.TeamId, slackTeam.FplBotSlackChannel, formattedStr.ToArray());
        }
    }
Beispiel #8
0
        public async Task Uninstall(string teamId)
        {
            var team = await _slackTeamRepo.GetTeam(teamId);

            await _slackTeamRepo.DeleteByTeamId(teamId);

            await _messageSession.Publish(new AppUninstalled(team.TeamId, team.TeamName, (int)team.FplbotLeagueId, team.FplBotSlackChannel));
        }
Beispiel #9
0
    public async Task OnGet(string teamId)
    {
        var teamIdToUpper = teamId.ToUpper();
        var team          = await _teamRepo.GetTeam(teamIdToUpper);

        Team       = team;
        LeagueName = "Unknown league / league not found!";
        try
        {
            if (team.FplbotLeagueId.HasValue)
            {
                LeagueName = (await _leagueClient.GetClassicLeague(team.FplbotLeagueId.Value)).Properties.Name;
            }
        }
        catch (Exception)
        {
        }
    }
        public override async Task <EventHandledResponse> Handle(EventMetaData eventMetadata, AppMentionEvent appMentioned)
        {
            var team = await _teamRepo.GetTeam(eventMetadata.Team_Id);

            var settings = await _globalSettingsClient.GetGlobalSettings();

            var gameweek = settings.Gameweeks.GetCurrentGameweek();
            await _mediator.Publish(new PublishStandingsCommand(team, gameweek));

            return(new EventHandledResponse("OK"));
        }
    public async Task <EventHandledResponse> Handle(EventMetaData eventMetadata, MemberJoinedChannelEvent joinedEvent)
    {
        var team = await _teamRepo.GetTeam(eventMetadata.Team_Id);

        var slackClient = _slackClientService.Build(team.AccessToken);
        var userProfile = await slackClient.UserProfile(joinedEvent.User);

        if (userProfile.Profile.Api_App_Id == _slackAppId)
        {
            var introMessage = ":wave: Hi, I'm fplbot. Type `@fplbot help` to see what I can do.";
            var setupMessage = "";
            if (team.FplbotLeagueId.HasValue)
            {
                try
                {
                    var league = await _leagueClient.GetClassicLeague(team.FplbotLeagueId.Value);

                    if (!string.IsNullOrEmpty(team.FplBotSlackChannel))
                    {
                        setupMessage = $"I'm pushing notifications relevant to {league.Properties.Name} into {ChannelName()}. ";
                        if (team.FplBotSlackChannel != joinedEvent.Channel)
                        {
                            setupMessage += "If you want to have notifications in this channel instead, use the `@fplbot follow` command in this channel.";
                        }

                        // Back-compat as we currently have a mix of:
                        // - display names (#name)
                        // - channel_ids (C12351)
                        // Man be removed next season when we require updates to leagueids
                        string ChannelName()
                        {
                            return(team.FplBotSlackChannel.StartsWith("#") ? team.FplBotSlackChannel : $"<#{team.FplBotSlackChannel}>");
                        }
                    }
                }
                catch (HttpRequestException e) when(e.Message.Contains("404"))
                {
                    setupMessage = $"I'm currently following no valid league. The invalid leagueid is `{team.FplbotLeagueId}`. Use `@fplbot follow` to setup a new valid leagueid.";
                }
            }
            else
            {
                setupMessage = "To get notifications for a league, use my `@fplbot follow` command";
            }

            await _publisher.PublishToWorkspace(eventMetadata.Team_Id, joinedEvent.Channel, introMessage, setupMessage);

            return(new EventHandledResponse("OK"));
        }
        return(new EventHandledResponse($"IGNORED FOR {userProfile.Profile.Real_Name}"));
    }
        public override async Task <EventHandledResponse> Handle(EventMetaData eventMetadata, AppMentionEvent message)
        {
            var gameweek = await _gameweekHelper.ExtractGameweekOrFallbackToCurrent(message.Text, $"{CommandsFormatted} {{gw}}");


            var team = await _slackTeamRepo.GetTeam(eventMetadata.Team_Id);

            var messageToSend = await _transfersClient.GetTransfersByGameweekTexts(gameweek ?? 1, (int)team.FplbotLeagueId);


            await _workSpacePublisher.PublishToWorkspace(eventMetadata.Team_Id, message.Channel, messageToSend);

            return(new EventHandledResponse(messageToSend));
        }
Beispiel #13
0
    public async Task Handle(PublishFulltimeMessageToSlackWorkspace message, IMessageHandlerContext context)
    {
        var team = await _slackTeamRepo.GetTeam(message.WorkspaceId);

        var slackClient = _builder.Build(team.AccessToken);
        var res         = await slackClient.ChatPostMessage(team.FplBotSlackChannel, message.Title);

        if (!string.IsNullOrEmpty(message.ThreadMessage) && res.Ok)
        {
            await slackClient.ChatPostMessage(new ChatPostMessageRequest
            {
                Channel = team.FplBotSlackChannel, thread_ts = res.ts, Text = message.ThreadMessage, unfurl_links = "false"
            });
        }
    }
    public override async Task <EventHandledResponse> Handle(EventMetaData eventMetadata, AppMentionEvent appMentioned)
    {
        var team = await _teamRepo.GetTeam(eventMetadata.Team_Id);

        var settings = await _globalSettingsClient.GetGlobalSettings();

        var gameweek = settings.Gameweeks.GetCurrentGameweek();

        if (team.HasChannelAndLeagueSetup())
        {
            await _session.Send("FplBot.EventHandlers.Slack", new PublishStandingsToSlackWorkspace(team.TeamId, appMentioned.Channel, team.FplbotLeagueId.Value, gameweek.Id));
        }

        return(new EventHandledResponse("OK"));
    }
Beispiel #15
0
    public async Task Handle(PublishPriceChangesToSlackWorkspace message, IMessageHandlerContext context)
    {
        _logger.LogInformation($"Publish price changes to {message.WorkspaceId}");
        var filtered = message.PlayersWithPriceChanges.Where(c => c.OwnershipPercentage > 7);

        if (filtered.Any())
        {
            var slackTeam = await _slackTeamRepo.GetTeam(message.WorkspaceId);

            var formatted = Formatter.FormatPriceChanged(filtered);
            await _publisher.PublishToWorkspace(slackTeam.TeamId, slackTeam.FplBotSlackChannel, formatted);
        }
        else
        {
            _logger.LogInformation("All price changes were irrelevant, so not sending any notification");
        }
    }
Beispiel #16
0
    public async Task Handle(EventMetaData eventMetadata, AppMentionEvent @event)
    {
        var team = await _tokenStore.GetTeam(eventMetadata.Team_Id);

        var slackClient = _slackClientService.Build(team.AccessToken);
        var text        = $"*HELP:*\n";

        if (team.HasChannelAndLeagueSetup())
        {
            try
            {
                var league = await _leagueClient.GetClassicLeague(team.FplbotLeagueId.Value);

                text += $"Currently following {league.Properties.Name} in {ChannelName()}\n";
            }
            catch (HttpRequestException e) when(e.StatusCode == HttpStatusCode.NotFound)
            {
                text += $"Currently following {team.FplbotLeagueId} in {ChannelName()}\n";
            }

            string ChannelName()
            {
                return(team.FplBotSlackChannel.StartsWith("#") ? team.FplBotSlackChannel : $"<#{team.FplBotSlackChannel}>");
            }
        }
        else
        {
            text += "Currently not following any leagues\n";
        }

        if (team.Subscriptions.Any())
        {
            text += $"Active subscriptions:\n{Formatter.BulletPoints(team.Subscriptions)}\n";
        }

        await slackClient.ChatPostMessage(@event.Channel, text);

        var handlerHelp = _handlers.Select(handler => handler.GetHelpDescription())
                          .Where(desc => !string.IsNullOrEmpty(desc.HandlerTrigger))
                          .Aggregate($"\n*Available commands:*", (current, tuple) => current + $"\n• `@fplbot {tuple.HandlerTrigger}` : _{tuple.Description}_");



        await slackClient.ChatPostMessage(new ChatPostMessageRequest { Channel = @event.Channel, Text = handlerHelp, Link_Names = false });
    }
Beispiel #17
0
    public async Task Handle(PublishDeadlineNotificationToSlackWorkspace message, IMessageHandlerContext context)
    {
        string notification = $"⏳ Gameweek {message.Gameweek.Id} deadline in 24 hours!";

        var team = await _teamRepo.GetTeam(message.WorkspaceId);

        await PublishToTeam();

        async Task PublishToTeam()
        {
            var slackClient = _builder.Build(team.AccessToken);
            var res         = await slackClient.ChatPostMessage(team.FplBotSlackChannel, notification);

            if (res.Ok)
            {
                await PublishFixtures(slackClient, res.ts);
            }
        }

        async Task PublishFixtures(ISlackClient slackClient, string ts)
        {
            var fixtures = await _fixtures.GetFixturesByGameweek(message.Gameweek.Id);

            var teams = (await _globalSettingsClient.GetGlobalSettings()).Teams;
            var users = await slackClient.UsersList();

            var user = users.Members.FirstOrDefault(u =>
                                                    u.Is_Admin); // could have selected app_install user here, if we had this stored
            var userTzOffset = user?.Tz_Offset ?? 0;
            var messageGameweekNearingDeadline = message.Gameweek;
            var fixturesList = Formatter.FixturesForGameweek(messageGameweekNearingDeadline.Id,
                                                             messageGameweekNearingDeadline.Name, messageGameweekNearingDeadline.Deadline, fixtures, teams,
                                                             tzOffset: userTzOffset);

            await slackClient.ChatPostMessage(new ChatPostMessageRequest
            {
                Channel      = team.FplBotSlackChannel,
                thread_ts    = ts,
                Text         = fixturesList,
                unfurl_links = "false"
            });
        }
    }
Beispiel #18
0
        public async Task <EventHandledResponse> Handle(EventMetaData eventMetadata, MemberJoinedChannelEvent joinedEvent)
        {
            _logger.LogInformation(JsonConvert.SerializeObject(joinedEvent));
            _logger.LogInformation(JsonConvert.SerializeObject(eventMetadata));
            var team = await _teamRepo.GetTeam(eventMetadata.Team_Id);

            var slackClient = _slackClientService.Build(team.AccessToken);
            var userProfile = await slackClient.UserProfile(joinedEvent.User);

            if (userProfile.Profile.Api_App_Id == FplBotProdAppId || userProfile.Profile.Api_App_Id == FplBotTestAppId)
            {
                var introMessage = ":wave: Hi, I'm fplbot. Type `@fplbot help` to see what I can do.";
                var league       = await _leagueClient.GetClassicLeague((int)team.FplbotLeagueId);

                var setupMessage = $"I'm pushing notifications relevant to {league.Properties.Name} into {team.FplBotSlackChannel}";
                await _publisher.PublishToWorkspace(eventMetadata.Team_Id, joinedEvent.Channel, introMessage, setupMessage);

                return(new EventHandledResponse("OK"));
            }
            return(new EventHandledResponse($"IGNORED FOR {userProfile.Profile.Real_Name}"));
        }
    public async Task <EventHandledResponse> Handle(EventMetaData eventMetadata, AppHomeOpenedEvent appHomeEvent)
    {
        var team = await _repo.GetTeam(eventMetadata.Team_Id);

        var client = _builder.Build(team.AccessToken);



        var viewPublishRequest  = BuildViewRequest(appHomeEvent.User, team.FplbotLeagueId);
        ViewPublishResponse res = null;

        try
        {
            res = await client.ViewPublish(viewPublishRequest);

            return(!res.Ok ? new EventHandledResponse(res.Error) : new EventHandledResponse("Opened AppHome"));
        }
        catch (WellKnownSlackApiException se)
        {
            _logger.LogError(se.Message, se);
            return(new EventHandledResponse(se.Message));
        }
    }
    public override async Task <EventHandledResponse> Handle(EventMetaData eventMetadata, AppMentionEvent slackEvent)
    {
        var team = await _tokenStore.GetTeam(eventMetadata.Team_Id);

        var slackClient = _slackClientService.Build(team.AccessToken);
        var usersTask   = slackClient.UsersList();
        var settings    = await _globalSettingsClient.GetGlobalSettings();

        var users     = await usersTask;
        var gameweeks = settings.Gameweeks;
        var teams     = settings.Teams;

        var nextGw   = gameweeks.First(gw => gw.IsNext);
        var fixtures = await _fixtureClient.GetFixturesByGameweek(nextGw.Id);

        var user         = users.Members.FirstOrDefault(x => x.Id == slackEvent.User);
        var userTzOffset = user?.Tz_Offset ?? 0;

        var textToSend = Formatter.FixturesForGameweek(nextGw.Id, nextGw.Name, nextGw.Deadline, fixtures, teams, userTzOffset);

        await _workspacePublisher.PublishToWorkspace(eventMetadata.Team_Id, slackEvent.Channel, textToSend);

        return(new EventHandledResponse(textToSend));
    }
Beispiel #21
0
    public override async Task <EventHandledResponse> Handle(EventMetaData eventMetadata, AppMentionEvent message)
    {
        var newLeagueId = ParseArguments(message);

        if (string.IsNullOrEmpty(newLeagueId))
        {
            var help = $"No leagueId provided. Usage: `@fplbot follow 123`";
            await _publisher.PublishToWorkspace(eventMetadata.Team_Id, message.Channel, help);

            return(new EventHandledResponse(help));
        }

        var couldParse = int.TryParse(newLeagueId, out var theLeagueId);

        if (!couldParse)
        {
            var res = $"Could not update league to id '{newLeagueId}'. Make sure it's a valid number.";
            await _publisher.PublishToWorkspace(eventMetadata.Team_Id, message.Channel, res);

            return(new EventHandledResponse(res));
        }

        var failure = $"Could not find league {newLeagueId} :/ Could you find it at https://fantasy.premierleague.com/leagues/{newLeagueId}/standings/c ?";

        try
        {
            var league = await _leagueClient.GetClassicLeague(theLeagueId);

            if (league?.Properties != null)
            {
                var team = await _slackTeamRepository.GetTeam(eventMetadata.Team_Id);

                await _slackTeamRepository.UpdateLeagueId(eventMetadata.Team_Id, theLeagueId);

                await _slackTeamRepository.UpdateChannel(eventMetadata.Team_Id, message.Channel);

                if (!team.Subscriptions.Any())
                {
                    await _slackTeamRepository.UpdateSubscriptions(eventMetadata.Team_Id, new[] { EventSubscription.All });
                }
                var success = $"Thanks! You're now following the '{league.Properties.Name}' league (leagueId: {theLeagueId}) in {ChannelName()}";
                await _publisher.PublishToWorkspace(eventMetadata.Team_Id, message.Channel, success);

                return(new EventHandledResponse(success));

                string ChannelName()
                {
                    return($"<#{message.Channel}>");
                }
            }
            await _publisher.PublishToWorkspace(eventMetadata.Team_Id, message.Channel, failure);

            return(new EventHandledResponse(failure));
        }
        catch (HttpRequestException e)
        {
            _logger.LogError(e.Message, e);
            await _publisher.PublishToWorkspace(eventMetadata.Team_Id, message.Channel, failure);

            return(new EventHandledResponse(failure));
        }
    }
Beispiel #22
0
        public override async Task <EventHandledResponse> Handle(EventMetaData eventMetadata, AppMentionEvent message)
        {
            var term = ParseArguments(message);

            SlackTeam slackTeam = null;

            try
            {
                slackTeam = await _slackTeamRepo.GetTeam(eventMetadata.Team_Id);
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Unable to get team {teamId} during search.", eventMetadata.Team_Id);
            }

            string countryToBoost = await GetCountryToBoost(slackTeam);

            var searchMetaData = GetSearchMetaData(slackTeam, message);

            var entriesTask = _searchService.SearchForEntry(term, 0, 10, searchMetaData);
            var leaguesTask = _searchService.SearchForLeague(term, 0, 10, searchMetaData, countryToBoost);

            var entries = await entriesTask;
            var leagues = await leaguesTask;

            var sb = new StringBuilder();

            sb.Append("Matching teams:\n");

            int?currentGameweek = null;

            if (entries.Any() || leagues.Any())
            {
                try
                {
                    var globalSettings = await _globalSettingsClient.GetGlobalSettings();

                    var gameweeks = globalSettings.Gameweeks;
                    currentGameweek = gameweeks.GetCurrentGameweek().Id;
                }
                catch (Exception e)
                {
                    _logger.LogError(e, "Unable to obtain current gameweek when creating search result links");
                }
            }

            if (entries.Any())
            {
                sb.Append(Formatter.BulletPoints(entries.ExposedHits.Select(e => Formatter.FormatEntryItem(e, currentGameweek))));
                if (entries.HitCountExceedingExposedOnes > 0)
                {
                    sb.Append($"\n...and {entries.HitCountExceedingExposedOnes} more");
                }
            }
            else
            {
                sb.Append("Found no matching teams :shrug:");
            }

            sb.Append("\n\nMatching leagues:\n");

            if (leagues.Any())
            {
                sb.Append(Formatter.BulletPoints(leagues.ExposedHits.Select(e => Formatter.FormatLeagueItem(e, currentGameweek))));
                if (leagues.HitCountExceedingExposedOnes > 0)
                {
                    sb.Append($"\n...and {leagues.HitCountExceedingExposedOnes} more");
                }
            }
            else
            {
                sb.Append("Found no matching leagues :shrug:");
            }

            await _workSpacePublisher.PublishToWorkspace(eventMetadata.Team_Id, message.Channel, sb.ToString());

            return(new EventHandledResponse(sb.ToString()));
        }
Beispiel #23
0
    public async Task Handle(ProcessGameweekStartedForSlackWorkspace message, IMessageHandlerContext context)
    {
        var newGameweek = message.GameweekId;

        var team = await _teamRepo.GetTeam(message.WorkspaceId);

        if (team.HasRegisteredFor(EventSubscription.Captains) || team.HasRegisteredFor(EventSubscription.Transfers))
        {
            await _publisher.PublishToWorkspace(team.TeamId, team.FplBotSlackChannel, $"Gameweek {message.GameweekId}!");
        }

        var messages = new List <string>();

        var           leagueExists = false;
        ClassicLeague league       = null;

        if (team.FplbotLeagueId.HasValue)
        {
            league = await _leagueClient.GetClassicLeague(team.FplbotLeagueId.Value, tolerate404 : true);
        }
        leagueExists = league != null;

        if (leagueExists && team.HasRegisteredFor(EventSubscription.Captains))
        {
            var captainPicks = await _captainsByGameweek.GetEntryCaptainPicks(newGameweek, team.FplbotLeagueId.Value);

            if (league.Standings.Entries.Count < MemberCountForLargeLeague)
            {
                messages.Add(_captainsByGameweek.GetCaptainsByGameWeek(newGameweek, captainPicks));
                messages.Add(_captainsByGameweek.GetCaptainsChartByGameWeek(newGameweek, captainPicks));
            }
            else
            {
                messages.Add(_captainsByGameweek.GetCaptainsStatsByGameWeek(captainPicks));
            }
        }
        else if (team.FplbotLeagueId.HasValue && !leagueExists && team.HasRegisteredFor(EventSubscription.Captains))
        {
            messages.Add($"⚠️ You're subscribing to captains notifications, but following a league ({team.FplbotLeagueId.Value}) that does not exist. Update to a valid classic league, or unsubscribe to captains to avoid this message in the future.");
        }
        else
        {
            _logger.LogInformation("Team {team} hasn't subscribed for gw start captains, so bypassing it", team.TeamId);
        }

        if (leagueExists && team.HasRegisteredFor(EventSubscription.Transfers))
        {
            try
            {
                if (league.Standings.Entries.Count < MemberCountForLargeLeague)
                {
                    messages.Add(await _transfersByGameweek.GetTransfersByGameweekTexts(newGameweek, team.FplbotLeagueId.Value));
                }
                else
                {
                    var externalLink = $"See https://www.fplbot.app/leagues/{team.FplbotLeagueId.Value} for all transfers";
                    messages.Add(externalLink);
                }
            }
            catch (HttpRequestException hre) when(hre.StatusCode == HttpStatusCode.TooManyRequests) // fallback
            {
                var externalLink = $"See https://www.fplbot.app/leagues/{team.FplbotLeagueId.Value} for all transfers";

                messages.Add(externalLink);
            }
        }
        else if (team.FplbotLeagueId.HasValue && !leagueExists && team.HasRegisteredFor(EventSubscription.Transfers))
        {
            messages.Add($"⚠️ You're subscribing to transfers notifications, but following a league ({team.FplbotLeagueId.Value}) that does not exist. Update to a valid classic league, or unsubscribe to transfers to avoid this message in the future.");
        }
        else
        {
            _logger.LogInformation("Team {team} hasn't subscribed for gw start transfers, so bypassing it", team.TeamId);
        }

        await _publisher.PublishToWorkspace(team.TeamId, team.FplBotSlackChannel, messages.ToArray());
    }
Beispiel #24
0
    public async Task PublishToWorkspace(string teamId, params ChatPostMessageRequest[] messages)
    {
        var team = await _repository.GetTeam(teamId);

        await PublishUsingToken(team.AccessToken, messages);
    }
Beispiel #25
0
        public async Task OnGet(string teamId)
        {
            var teamIdToUpper = teamId.ToUpper();

            Team = await _teamRepo.GetTeam(teamIdToUpper);
        }