public Task <EventHandledResponse> Handle(EventMetaData eventMetadata, AppHomeOpenedEvent payload) { string json = JsonConvert.SerializeObject(payload); Console.WriteLine(json); return(Task.FromResult(new EventHandledResponse(json))); }
public override async Task <EventHandledResponse> Handle(EventMetaData eventMetadata, AppMentionEvent message) { var globalSettings = await _globalSettingsClient.GetGlobalSettings(); var allPlayers = globalSettings.Players; var teams = globalSettings.Teams; var priceChangedPlayers = allPlayers.Where(p => p.CostChangeEvent != 0 && p.IsRelevant()) .Select(p => { var t = teams.First(t => t.Code == p.TeamCode); return(new PlayerWithPriceChange(p.Id, p.WebName, p.CostChangeEvent, p.NowCost, p.OwnershipPercentage, t.Id, t.ShortName)); }); if (priceChangedPlayers.Any()) { var messageToSend = Formatter.FormatPriceChanged(priceChangedPlayers); await _workSpacePublisher.PublishToWorkspace(eventMetadata.Team_Id, message.Channel, messageToSend); } else { await _workSpacePublisher.PublishToWorkspace(eventMetadata.Team_Id, message.Channel, "No relevant price changes yet"); } return(new EventHandledResponse("Ok")); }
/// <summary> /// @smartbot tell @john bull hop stuff /// </summary> /// <param name="message"></param> /// <returns></returns> public async Task <EventHandledResponse> Handle(EventMetaData data, AppMentionEvent message) { var args = message.Text.Split(' '); var recipient = message.Channel; var content = "Psst"; if (args.Length == 2) { content = "lol, du må gi meg et navn å sende til..`@smartbot tell @nash du er en tufs`"; } if (args.Length == 3) { content = "lol, du må gi meg noe innhold å sende! `@smartbot tell @nash du er en tufs`"; } if (args.Length > 3) { var parsedName = args[2]; var users = await _slackClient.UsersList(); var usr = users.Members.FirstOrDefault(u => $"<@{u.Id}>" == parsedName); var channels = await _slackClient.ConversationsListPublicChannels(); var channel = channels.Channels.FirstOrDefault(c => string.Equals($"<#{c.Id}|{c.Name}>", parsedName, StringComparison.InvariantCultureIgnoreCase)); content = string.Join(" ", args[3..args.Length]);
public async Task <EventHandledResponse> Handle(EventMetaData eventMetadata, AppMentionEvent slackEvent) { string mentionTextStripped = Regex.Replace(slackEvent.Text, "<@(\\w+)>", "$1"); await _session.Publish(new UnknownAppMentionReceived(eventMetadata.Team_Id, slackEvent.User, mentionTextStripped)); return(new EventHandledResponse("OK")); }
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)); }
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 message) { var globalSettings = await _globalSettingsClient.GetGlobalSettings(); var players = globalSettings.Players; var teams = globalSettings.Teams; var name = ParseArguments(message); var allPlayers = players.OrderByDescending(player => player.OwnershipPercentage); var mostPopularMatchingPlayer = FindMostPopularMatchingPlayer(allPlayers.ToArray(), name); if (mostPopularMatchingPlayer == null) { await _workSpacePublisher.PublishToWorkspace(eventMetadata.Team_Id, message.Channel, $"Couldn't find {name}"); return(new EventHandledResponse($"Found no matching player for {name}: ")); } var playerName = $"{mostPopularMatchingPlayer.FirstName} {mostPopularMatchingPlayer.SecondName}"; await _workSpacePublisher.PublishToWorkspace(eventMetadata.Team_Id, new ChatPostMessageRequest { Channel = message.Channel, Blocks = Formatter.GetPlayerCard(mostPopularMatchingPlayer, teams) }); return(new EventHandledResponse($"Found matching player for {name}: " + playerName)); }
public override async Task <EventHandledResponse> Handle(EventMetaData eventMetadata, AppMentionEvent appMentioned) { var subscriptionInfo = await GetAndUpdateSubscriptionInfo(eventMetadata.Team_Id, appMentioned); await _workspacePublisher.PublishToWorkspace(eventMetadata.Team_Id, appMentioned.Channel, subscriptionInfo); return(new EventHandledResponse(subscriptionInfo)); }
public async Task <EventHandledResponse> Handle(EventMetaData data, AppMentionEvent message) { var index = new Random().Next(_smartinger.Smartingene.Count); var randomSmarting = _smartinger.Smartingene[index]; await _client.ChatPostMessage(message.Channel, randomSmarting.Name); return(new EventHandledResponse("OK")); }
private static string SerializeMetaData(IDomainEvent @event) { var metaData = new EventMetaData { EventType = @event.GetType().AssemblyQualifiedName }; return(JsonConvert.SerializeObject(metaData)); }
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 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 void Received(SensorOnline @event, EventMetaData metaData) { _uptimeReporter.Up(metaData.TimeStamp); var timeOffline = _uptimeReporter.OnlineAt.Subtract(_uptimeReporter.OfflineAt).TotalSeconds; if (timeOffline < THRESHOLD_IN_SECONDS) { _eventStream.Process(new IntermittentSensor(@event.Name)); } }
/// <summary> /// Gain the specified amount of armor. /// </summary> /// <param name="source"></param> /// <param name="armor"></param> public void GainArmor(IPlayable source, int armor) { Game.Log(LogLevel.INFO, BlockType.ACTION, "Character", !Game.Logging? "":$"{this} gaining armor for {armor}."); Armor += armor; EventMetaData temp = Game.CurrentEventData; Game.CurrentEventData = new EventMetaData(source, this, armor); Game.TriggerManager.OnArmorTrigger(this); //Game.ProcessTasks(); Game.CurrentEventData = temp; }
public Task <NewStreamMessage> SerializeEvent(Event @event) { var type = @event.GetType(); var typeName = type.FullName; var serializedEvent = JsonSerializer.Serialize(@event, type); var metaData = new EventMetaData(@event); var serializedMetaData = JsonSerializer.Serialize(metaData, typeof(EventMetaData)); return(Task.FromResult(new NewStreamMessage(@event.EventId, typeName, serializedEvent, serializedMetaData))); }
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)); }
/// <summary> /// Heal a specified amount of health. /// </summary> /// <param name="source"></param> /// <param name="heal"></param> public void TakeHeal(IPlayable source, int heal) { // TODO: Power Word: Glory interaction https://hearthstone.gamepedia.com/Healing#Advanced_rules if ((source is Spell || source is HeroPower) && source.Controller.ControllerAuraEffects[GameTag.HEALING_DOUBLE] > 0) { heal *= (int)Math.Pow(2, source.Controller.ControllerAuraEffects[GameTag.HEALING_DOUBLE]); } if (source.Controller.ControllerAuraEffects[GameTag.RESTORE_TO_DAMAGE] == 1) { if (_lifestealChecker) { return; } _lifestealChecker = true; TakeDamage(source, heal); _lifestealChecker = false; return; } // we don't heal undamaged entities if (Damage == 0) { return; } int amount = Damage > heal ? heal : Damage; if (Game.Logging) { Game.Log(LogLevel.INFO, BlockType.ACTION, "Character", $"{this} took healing for {amount}."); } Damage -= amount; // Heal event created // Process gathered tasks Game.TaskQueue.StartEvent(); EventMetaData temp = Game.CurrentEventData; Game.CurrentEventData = new EventMetaData(source, this, amount); Game.TriggerManager.OnHealTrigger(this); Game.ProcessTasks(); Game.TaskQueue.EndEvent(); Game.CurrentEventData = temp; if (this is Hero) { Controller.AmountHeroHealedThisTurn += amount; } }
private EventData SeralizeEvent <T>(T @event) where T : Event { var type = @event.GetType(); var typeName = type.FullName; var serializedEvent = JsonSerializer.Serialize(@event, type); var dataBytes = Encoding.UTF8.GetBytes(serializedEvent); var metaData = new EventMetaData(@event); var serializedMetaData = JsonSerializer.Serialize(metaData, typeof(EventMetaData)); var metaDataBytes = Encoding.UTF8.GetBytes(serializedMetaData); return(new EventData(@event.EventId, typeName, true, dataBytes, metaDataBytes)); }
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 updateleagueid 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) { await _slackTeamRepository.UpdateLeagueId(eventMetadata.Team_Id, theLeagueId); var success = $"Thanks! You're now following the '{league.Properties.Name}' league (leagueId: {theLeagueId})"; await _publisher.PublishToWorkspace(eventMetadata.Team_Id, message.Channel, success); return(new EventHandledResponse(success)); } 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)); } }
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")); }
public override async Task <EventHandledResponse> Handle(EventMetaData eventMetadata, AppMentionEvent message) { var globalSettings = await _globalSettingsClient.GetGlobalSettings(); var injuredPlayers = FindInjuredPlayers(globalSettings.Players); var textToSend = Formatter.GetInjuredPlayers(injuredPlayers); if (string.IsNullOrEmpty(textToSend)) { return(new EventHandledResponse("Not found")); } await _workspacePublisher.PublishToWorkspace(eventMetadata.Team_Id, message.Channel, textToSend); return(new EventHandledResponse(textToSend)); }
public async Task <EventHandledResponse> Handle(EventMetaData data, AppMentionEvent message) { var unanswered = await _inviter.SendRemindersToUnanswered(); if (unanswered.Any()) { var uText = unanswered.Select(u => $"Reminded {u.SlackUsername} to RSVP {u.EventTopic}"); var aggr = $"{uText.Aggregate((x, y) => x + "\n" + y)}"; await _client.ChatPostMessage(message.Channel, aggr); } else { await _client.ChatPostMessage(message.Channel, $"No unanswered invites or no existing invites for next storsdag"); } return(new EventHandledResponse("OK")); }
public Task Handle(EventMetaData eventMetadata, AppMentionEvent @event) { var publicHandlersToBeListedBack = _handlers.Where(handler => handler.GetHelpDescription().HandlerTrigger != string.Empty) .Aggregate("*Public trigger mentions*", (current, kvPair) => current + $"\n• `{kvPair.GetType()}. `{kvPair.GetHelpDescription().HandlerTrigger}` : _{kvPair.GetHelpDescription().Description}_"); Console.WriteLine(publicHandlersToBeListedBack); var ssh = _handlers.Where(handler => handler.GetHelpDescription().HandlerTrigger == string.Empty) .Aggregate("*Private trigger handlers*", (current, kvPair) => current + $"\n• `{kvPair.GetType()}`"); Console.WriteLine(ssh); return(Task.CompletedTask); }
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 }); }
public async Task <EventHandledResponse> Handle(EventMetaData data, AppMentionEvent message) { var nextStorsdag = await _eventStorage.GetNextEvent(EventTypes.StorsdagEventType); var invitations = await _inviteStorage.GetInvitations(nextStorsdag.RowKey); var rapport = nextStorsdag.Topic; foreach (var inviteGroup in invitations.GroupBy(i => i.Rsvp)) { string names = inviteGroup.Select(i => i.SlackUsername).Aggregate((x, y) => x + ", " + y); rapport += $"\n• `{inviteGroup.Key}` : {names}"; } await _client.ChatPostMessage(message.Channel, rapport); return(new EventHandledResponse("OK")); }
public async Task <EventHandledResponse> Handle(EventMetaData eventMetadata, AppMentionEvent slackEvent) { var debugDetails = MetaService.DebugInfo(); var debugInfo = $"▪️ v{debugDetails.MajorMinorPatch}\n" + $"▪️ {debugDetails.Informational}\n"; var releaseNotes = await GitHubReleaseService.GetReleaseNotes(debugDetails.MajorMinorPatch); if (!string.IsNullOrEmpty(releaseNotes)) { debugInfo += releaseNotes; } else if (debugDetails.Sha != "0") { debugInfo += $"️▪️ <https://github.com/fplbot/fplbot/tree/{debugDetails.Sha}|{debugDetails.Sha?.Substring(0, debugDetails.Sha.Length - 1)}>\n"; } await _session.Send("FplBot.EventHandlers.Slack", new PublishToSlack(eventMetadata.Team_Id, slackEvent.Channel, debugInfo)); return(new EventHandledResponse("OK")); }
internal static EventData ToEvent <T>(this T value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } var json = JsonConvert.SerializeObject(value); var data = Encoding.UTF8.GetBytes(json); var eventName = value.GetType().FullName; var metadata = new EventMetaData { TimeStamp = DateTime.UtcNow }; var metadataJson = JsonConvert.SerializeObject(metadata); return(new EventData(Guid.NewGuid(), eventName, true, data, Encoding.UTF8.GetBytes(metadataJson))); }
public override async Task <EventHandledResponse> Handle(EventMetaData eventMetadata, AppMentionEvent message) { var globalSettings = await _globalSettingsClient.GetGlobalSettings(); var allPlayers = globalSettings.Players; var teams = globalSettings.Teams; var priceChangedPlayers = allPlayers.Where(p => p.CostChangeEvent != 0 && p.IsRelevant()); if (priceChangedPlayers.Any()) { var messageToSend = Formatter.FormatPriceChanged(priceChangedPlayers, teams); await _workSpacePublisher.PublishToWorkspace(eventMetadata.Team_Id, message.Channel, messageToSend); } else { await _workSpacePublisher.PublishToWorkspace(eventMetadata.Team_Id, message.Channel, "No relevant price changes yet"); } return(new EventHandledResponse("Ok")); }
public void Transform(TweetReceived @event, EventMetaData metaData) { var usersMentioned = Regex.Matches(@event.Message, _userPattern) .Cast <Match>() .Select(m => new UserMentioned(@event.MessageId, m.Value)) .ToArray(); var topicsMentioned = Regex.Matches(@event.Message, _topicPattern) .Cast <Match>() .Select(m => new TopicMentioned(@event.MessageId, m.Value)) .ToArray(); foreach (var u in usersMentioned) { _eventStream.Process(u); } foreach (var t in topicsMentioned) { _eventStream.Process(t); } }