Example #1
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);
        }
    }
Example #2
0
    private async Task PublishUsingToken(string token, params ChatPostMessageRequest[] messages)
    {
        var slackClient = _slackClientBuilder.Build(token);

        foreach (var message in messages)
        {
            try
            {
                var res = await slackClient.ChatPostMessage(message);

                if (!res.Ok)
                {
                    _logger.LogWarning($"Could not post to {message.Channel}. {res.Error}");
                }
            }
            catch (WellKnownSlackApiException sae)
            {
                if (sae.Error == "account_inactive")
                {
                    _logger.LogWarning(sae, $"Inactive token!");
                }
                else
                {
                    _logger.LogWarning(sae, $"Could not post to {message.Channel}. {sae.Error} {sae.ResponseContent}");
                }
            }
            catch (Exception e)
            {
                _logger.LogWarning(e, e.Message);
            }
        }
    }
Example #3
0
        public async Task Handle(TwentyFourHoursToDeadline notification, CancellationToken cancellationToken)
        {
            _logger.LogInformation($"Notifying about 24h to (gw{notification.Gameweek.Id}) deadline");
            var fixtures = await _fixtures.GetFixturesByGameweek(notification.Gameweek.Id);

            var teams = (await _globalSettingsClient.GetGlobalSettings()).Teams;

            var allSlackTeams = await _teamRepo.GetAllTeams();

            string message = $"⏳ Gameweek {notification.Gameweek.Id} deadline in 24 hours!";

            foreach (var team in allSlackTeams)
            {
                if (team.Subscriptions.ContainsSubscriptionFor(EventSubscription.Deadlines))
                {
                    await PublishToTeam(team);
                }
            }

            async Task PublishToTeam(SlackTeam team)
            {
                var slackClient = _builder.Build(team.AccessToken);

                try
                {
                    var res = await slackClient.ChatPostMessage(team.FplBotSlackChannel, message);

                    if (res.Ok)
                    {
                        await PublishFixtures(slackClient, res.ts, team);
                    }
                }
                catch (Exception e)
                {
                    _logger.LogWarning(e, e.Message);
                }
            }

            async Task PublishFixtures(ISlackClient slackClient, string ts, SlackTeam team)
            {
                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 fixturesList = Formatter.FixturesForGameweek(notification.Gameweek, fixtures, teams, tzOffset: userTzOffset);

                try
                {
                    await slackClient.ChatPostMessage(new ChatPostMessageRequest
                    {
                        Channel = team.FplBotSlackChannel, thread_ts = ts, Text = fixturesList, unfurl_links = "false"
                    });
                }
                catch (Exception e)
                {
                    _logger.LogWarning(e, e.Message);
                }
            }
        }
Example #4
0
    private async Task <ISlackClient> CreateSlackClient(string teamId)
    {
        var team = await _teamRepo.GetTeam(teamId);

        var slackClient = _builder.Build(token: team.AccessToken);

        return(slackClient);
    }
Example #5
0
        private async Task <ISlackClient> CreateSlackClient(string teamId)
        {
            var token = await _tokenStore.GetTokenByTeamId(teamId);

            var slackClient = _builder.Build(token: token);

            return(slackClient);
        }
    public PublishViaWebHookCommandHandler(IConfiguration config, ISlackClientBuilder builder)
    {
        var token = config.GetValue <string>("SlackToken_FplBot_Workspace");
        var env   = config.GetValue <string>("DOTNET_ENVIRONMENT");

        _prefix = env == "Production" ? "" : $"{env}: ";
        _client = builder.Build(token);
    }
Example #7
0
        public async Task Handle(EventMetaData eventMetadata, AppMentionEvent @event)
        {
            var text = _handlers.Select(handler => handler.GetHelpDescription())
                       .Where(desc => !string.IsNullOrEmpty(desc.HandlerTrigger))
                       .Aggregate("*HALP:*", (current, tuple) => current + $"\n• `{tuple.HandlerTrigger}` : _{tuple.Description}_");

            var token = await _tokenStore.GetTokenByTeamId(eventMetadata.Team_Id);

            var slackClient = _slackClientService.Build(token);
            await slackClient.ChatPostMessage(@event.Channel, text);
        }
    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}"));
    }
Example #9
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"
            });
        }
    }
        protected async Task Publish(string msg)
        {
            var tokens = await _tokenStore.GetTokens();

            foreach (var token in tokens)
            {
                var slackClient = _slackClientBuilder.Build(token);
                //TODO: Fetch channel to post to from some storage for distributed app
                var res = await slackClient.ChatPostMessage(_options.Value.Channel, msg);

                if (!res.Ok)
                {
                    _logger.LogError($"Could not post to {_options.Value.Channel}", res.Error);
                }
            }
        }
Example #11
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 });
    }
Example #12
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"
            });
        }
    }
Example #13
0
        private async Task <IEnumerable <User> > GetSlackUsers(SlackTeam t)
        {
            var slackClient = _service.Build(t.AccessToken);

            try
            {
                var usersResponse = await slackClient.UsersList();

                if (usersResponse.Ok)
                {
                    return(usersResponse.Members);
                }
                return(Enumerable.Empty <User>());
            }
            catch (Exception e)
            {
                _logger.LogError(e, e.Message);
                return(Enumerable.Empty <User>());
            }
        }
Example #14
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}"));
        }
Example #15
0
        public async Task Handle(FixturesFinished notification, CancellationToken cancellationToken)
        {
            _logger.LogInformation("Handling fixture full time");
            var teams = await _slackTeamRepo.GetAllTeams();

            foreach (var slackTeam in teams)
            {
                if (slackTeam.Subscriptions.ContainsSubscriptionFor(EventSubscription.FixtureFullTime))
                {
                    foreach (var fixture in notification.FinishedFixture)
                    {
                        var title     = $"*FT: {fixture.HomeTeam.ShortName} {fixture.Fixture.HomeTeamScore}-{fixture.Fixture.AwayTeamScore} {fixture.AwayTeam.ShortName}*";
                        var formatted = Formatter.FormatProvisionalFinished(fixture);
                        await PublishFulltimeMessage(slackTeam, title, formatted);
                    }
                }
            }

            async Task PublishFulltimeMessage(SlackTeam team, string title, string thread)
            {
                var slackClient = _builder.Build(team.AccessToken);

                try
                {
                    var res = await slackClient.ChatPostMessage(team.FplBotSlackChannel, title);

                    if (res.Ok)
                    {
                        await slackClient.ChatPostMessage(new ChatPostMessageRequest
                        {
                            Channel = team.FplBotSlackChannel, thread_ts = res.ts, Text = thread, unfurl_links = "false"
                        });
                    }
                }
                catch (Exception e)
                {
                    _logger.LogWarning(e, e.Message);
                }
            }
        }
Example #16
0
        public async Task Handle(LineupReady notification, CancellationToken cancellationToken)
        {
            _logger.LogInformation("Handling new lineups");
            var lineups    = notification.Lineups;
            var slackTeams = await _slackTeamRepo.GetAllTeams();

            var firstMessage    = $"*Lineups {lineups.HomeTeamNameAbbr}-{lineups.AwayTeamNameAbbr} ready* 👇";
            var formattedLineup = Formatter.FormatLineup(lineups);

            foreach (var slackTeam in slackTeams)
            {
                if (slackTeam.Subscriptions.ContainsSubscriptionFor(EventSubscription.Lineups))
                {
                    await PublishLineupToTeam(slackTeam);
                }
            }

            async Task PublishLineupToTeam(SlackTeam team)
            {
                var slackClient = _builder.Build(team.AccessToken);

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

                    if (res.Ok)
                    {
                        await slackClient.ChatPostMessage(new ChatPostMessageRequest
                        {
                            Channel = team.FplBotSlackChannel, thread_ts = res.ts, Text = formattedLineup, unfurl_links = "false"
                        });
                    }
                }
                catch (Exception e)
                {
                    _logger.LogWarning(e, e.Message);
                }
            }
        }
    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));
    }