Skip to content

Commit

Permalink
Merge pull request #164 from pulcher/add_timeout_to_dad
Browse files Browse the repository at this point in the history
Add timeout to dad joke command
  • Loading branch information
pulcher authored Jul 9, 2024
2 parents c0a664b + 2ecaa5f commit 4fb5e68
Show file tree
Hide file tree
Showing 19 changed files with 344 additions and 33 deletions.
5 changes: 5 additions & 0 deletions Magic8HeadService/Commands/AskCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@ public AskCommand(ITwitchClient client, ISayingResponse sayingResponse, string m
this.mood = mood;
}

public bool CanExecute()
{
throw new System.NotImplementedException();
}

public void Handle(OnChatCommandReceivedArgs cmd)
{
var message = GetRandomAnswer().ToLower();
Expand Down
41 changes: 36 additions & 5 deletions Magic8HeadService/Commands/DadCommand.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.Extensions.Logging;
using Magic8HeadService.Services;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;
using TwitchLib.Client;
Expand All @@ -12,23 +13,53 @@ internal class DadCommand : IMbhCommand
private ITwitchClient client;
private ISayingResponse sayingResponse;
private readonly IDadJokeService dadJokeService;
private readonly CoolDownService coolDownService;
private TimeSpan coolDownTimeSpan = TimeSpan.FromSeconds(15);
private DateTime coolDown = DateTime.MinValue;
private ILogger<Worker> logger;
private string alternateSite = "https://karljoke.herokuapp.com/jokes/random"; //= string.Empty;

public DadCommand(ITwitchClient client, ISayingResponse sayingResponse, IDadJokeService dadJokeService, ILogger<Worker> logger)
public DadCommand(ITwitchClient client, ISayingResponse sayingResponse, IDadJokeService dadJokeService,
CoolDownService coolDownService, ILogger<Worker> logger)
{
this.client = client;
this.sayingResponse = sayingResponse;
this.dadJokeService = dadJokeService;
this.coolDownService = coolDownService;
this.logger = logger;
}

public void Handle(OnChatCommandReceivedArgs cmd)
{
var dadJoke = dadJokeService.GetDadJoke();
if (CanExecute())
{
//coolDown = DateTime.UtcNow.AddMinutes(1);
//logger.Log(LogLevel.Debug, "Setting the next available DadJoke to {coolDown}", coolDown);

sayingResponse.SaySomethingNiceAsync(dadJoke, client, cmd.Command.ChatMessage.Channel, cmd.Command.ChatMessage.Username);
client.SendMessage(cmd.Command.ChatMessage.Channel, $"Q: {dadJoke}");
var dadJoke = dadJokeService.GetDadJoke();

sayingResponse.SaySomethingNiceAsync(dadJoke, client, cmd.Command.ChatMessage.Channel, cmd.Command.ChatMessage.Username);
client.SendMessage(cmd.Command.ChatMessage.Channel, $"Q: {dadJoke}");

coolDownService.Execute(AvailableCommands.Dad);
}
else
{
client.SendMessage(cmd.Command.ChatMessage.Channel, $"Pull my finger is brewin'");
}
}

public bool CanExecute()
{
var currentTime = DateTime.UtcNow;
var currentCoolDown = coolDownService.GetCurrentCoolDown(AvailableCommands.Dad);

if (currentTime < currentCoolDown)
{
return false;
}

return true;
}
}
}
5 changes: 5 additions & 0 deletions Magic8HeadService/Commands/HelpCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,5 +45,10 @@ private string GetHelpMessage()
trimmedResult += ". To help code me or request another feature head over to my repository at https://github.com/pulcher/TalkingHead";
return trimmedResult;
}

public bool CanExecute()
{
return true;
}
}
}
1 change: 1 addition & 0 deletions Magic8HeadService/Commands/IMbhCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ namespace Magic8HeadService
{
public interface IMbhCommand
{
bool CanExecute();
void Handle(OnChatCommandReceivedArgs cmd);
}
}
5 changes: 5 additions & 0 deletions Magic8HeadService/Commands/InspirationalCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ public InspirationalCommand(ITwitchClient client, ISayingResponse sayingResponse
this.logger = logger;
}

public bool CanExecute()
{
throw new System.NotImplementedException();
}

public void Handle(OnChatCommandReceivedArgs cmd)
{
var message = GetRandomAnswer();
Expand Down
14 changes: 11 additions & 3 deletions Magic8HeadService/Commands/MbhCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using MrBigHead.Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using TwitchLib.Client.Events;
using TwitchLib.Client.Interfaces;
Expand All @@ -18,26 +20,31 @@ public class MbhCommand : ICommandMbhToTwitch
private IMbhCommand action;
private string mood= Moods.Snarky;
private ICommandTracker commandTracker;
private readonly CoolDownService coolDownService;

public string Name => "mbh";

public MbhCommand(ITwitchClient client, IConfiguration config, ISayingResponse sayingResponse,
IDadJokeService dadJokeService, IMessageChecker messageChecker, ICommandTracker commandTracker, ILogger<Worker> logger)
IDadJokeService dadJokeService, IMessageChecker messageChecker, ICommandTracker commandTracker,
CoolDownService coolDownService, ILogger<Worker> logger)
{
this.client = client;
this.config = config;
this.sayingResponse = sayingResponse;
this.dadJokeService = dadJokeService;
this.messageChecker = messageChecker;
this.commandTracker = commandTracker;
this.coolDownService = coolDownService;
this.logger = logger;
}

public void Handle(OnChatCommandReceivedArgs args)
{
action = new NullCommand(logger);

var commandToExecute = args.Command.ArgumentsAsList.FirstOrDefault()?.ToLower();

switch (args.Command.ArgumentsAsList.FirstOrDefault()?.ToLower())
switch (commandToExecute)
{
case AvailableCommands.Help:
// case null:
Expand All @@ -47,7 +54,8 @@ public void Handle(OnChatCommandReceivedArgs args)
action = new AskCommand(client, sayingResponse, mood, logger);
break;
case AvailableCommands.Dad:
action = new DadCommand(client, sayingResponse, dadJokeService, logger);
action = new DadCommand(client, sayingResponse, dadJokeService,
coolDownService, logger);
break;
case AvailableCommands.Inspire:
action = new InspirationalCommand(client, sayingResponse, logger);
Expand Down
5 changes: 5 additions & 0 deletions Magic8HeadService/Commands/NullCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ public NullCommand(ILogger<Worker> logger)
this.logger = logger;
}

public bool CanExecute()
{
return false;
}

public void Handle(OnChatCommandReceivedArgs cmd)
{
logger.LogInformation($"Nope.... not gonna do it!");
Expand Down
10 changes: 10 additions & 0 deletions Magic8HeadService/Commands/SayCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,5 +49,15 @@ public void Handle(OnChatCommandReceivedArgs cmd)

var check = string.Empty;
}

bool IMbhCommand.CanExecute()
{
throw new System.NotImplementedException();
}

void IMbhCommand.Handle(OnChatCommandReceivedArgs cmd)
{
throw new System.NotImplementedException();
}
}
}
10 changes: 8 additions & 2 deletions Magic8HeadService/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,17 @@ public static IHostBuilder CreateHostBuilder(string[] args) =>
var configuration = services.BuildServiceProvider().GetService<IConfiguration>();

// probably could convert this into a bind and only need to pass around this object
// well, I believe Huga may have a better idea. :) aka IOptions<T>
// well, I believe Hugo may have a better idea. :) aka IOptions<T>
var twitchBotConfiguration = new TwitchBotConfiguration();
configuration.GetSection("TwitchBotConfiguration").Bind(twitchBotConfiguration);

services.AddSingleton(twitchBotConfiguration);

//var coolDownOptions = new CoolDownOptions();
//configuration.GetSection("CoolDownOptions").Bind(coolDownOptions);
//services.AddSingleton(coolDownOptions);

services.Configure<CoolDownOptions>(configuration.GetSection("CoolDownOptions"));

var credentials = new ConnectionCredentials(twitchBotConfiguration.UserName, twitchBotConfiguration.AccessToken);
services.AddSingleton(credentials);

Expand Down Expand Up @@ -102,6 +107,7 @@ public static IHostBuilder CreateHostBuilder(string[] args) =>
services.AddScoped<IDadJokeService, DadJokeService>();
services.AddScoped<ICommandMbhTwitchHelp, HelpCommandReal>();
services.AddScoped<IMessageStackService, MessageStackService>();
services.AddScoped<CoolDownService, CoolDownService>();

services.AddHostedService<Worker>();

Expand Down
11 changes: 11 additions & 0 deletions Magic8HeadService/Services/CoolDownOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;

namespace Magic8HeadService.Services
{
public class CoolDownOptions
{
public Dictionary<string, int> Options { get; set; }
}
}
62 changes: 62 additions & 0 deletions Magic8HeadService/Services/CoolDownService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Magic8HeadService.Services
{
public class CoolDownService
{
private Dictionary<string, DateTime> CurrentCoolsDowns
= new Dictionary<string, DateTime>();
private IOptions<CoolDownOptions> options;

public CoolDownService(IOptions<CoolDownOptions> options)
{
this.options = options;
}

public DateTime Execute(string commandString)
{
var nextExecutionTime = DateTime.UtcNow.AddSeconds(options.Value.Options[commandString]);

if (CurrentCoolsDowns.TryGetValue(commandString, out DateTime coolDownDateTime))
{
if (DateTime.UtcNow > coolDownDateTime)
{
CurrentCoolsDowns[commandString]
= nextExecutionTime;
}
else
{
return coolDownDateTime;
}
}
else
{
CurrentCoolsDowns.Add(commandString, nextExecutionTime);
}

return nextExecutionTime;
}

public ReadOnlyDictionary<string, DateTime> GetAllCoolDowns()
{
var readOnlyCurrentCurrentCoolDowns = new ReadOnlyDictionary<string, DateTime>(CurrentCoolsDowns);
return readOnlyCurrentCurrentCoolDowns;
}

public DateTime GetCurrentCoolDown(string commandString)
{
if (CurrentCoolsDowns.TryGetValue(commandString, out DateTime coolDownDateTime))
{
return coolDownDateTime;
}

return DateTime.MinValue;
}
}
}
5 changes: 4 additions & 1 deletion Magic8HeadService/TwitchBot.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Magic8HeadService.MqttHandlers;
using Magic8HeadService.Services;
using Microsoft.Extensions.Logging;
using MQTTnet;
using MQTTnet.Client;
Expand Down Expand Up @@ -29,11 +30,12 @@ public class TwitchBot
private readonly ISayingResponse sayingResponse;
private readonly IDadJokeService dadJokeService;
private readonly IMessageStackService messageStackService;
private readonly CoolDownService coolDownService;

public TwitchBot(ITwitchClient client, ConnectionCredentials clientCredentials, TwitchBotConfiguration twitchBotConfiguration,
ISayingResponse sayingResponse, IDadJokeService dadJokeService, IEnumerable<ICommandMbhToTwitch> listOfCommands,
ICommandMbhTwitchHelp helpCommand, MqttFactory mqttFactory, IEnumerable<IMqttHandler> mqttHandlers,
IMessageStackService messageStackService, ILogger<Worker> logger)
IMessageStackService messageStackService, CoolDownService coolDownService, ILogger<Worker> logger)
{
this.client = client;

Expand All @@ -42,6 +44,7 @@ public TwitchBot(ITwitchClient client, ConnectionCredentials clientCredentials,
this.sayingResponse = sayingResponse;
this.dadJokeService = dadJokeService;
this.messageStackService = messageStackService;
this.coolDownService = coolDownService;
var listOfNames = listOfCommands.Select(x => x.Name);
this.logger.LogInformation($"-------------- List of Names : {string.Join(',', listOfNames)}");
dictOfCommands = listOfCommands
Expand Down
8 changes: 7 additions & 1 deletion Magic8HeadService/Worker.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Magic8HeadService.MqttHandlers;
using Magic8HeadService.Services;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
Expand Down Expand Up @@ -29,6 +30,7 @@ public class Worker : BackgroundService
readonly IDadJokeService scopedDadJokeService;
readonly MqttFactory scopedMqttFactory;
readonly IMessageStackService scopedMessageStackService;
readonly CoolDownService scopedCoolDownService;

public Worker(IServiceProvider service, IConfiguration config, TwitchBotConfiguration twitchBotConfiguration,
ILogger<Worker> logger)
Expand Down Expand Up @@ -63,14 +65,18 @@ public Worker(IServiceProvider service, IConfiguration config, TwitchBotConfigur
scope.ServiceProvider
.GetRequiredService<IMessageStackService>();

scopedCoolDownService =
scope.ServiceProvider
.GetRequiredService<CoolDownService>();

var listOfCommands = scope.ServiceProvider.GetServices<ICommandMbhToTwitch>();
var helpCommand = scope.ServiceProvider.GetService<ICommandMbhTwitchHelp>();
var mqttHandlers = scope.ServiceProvider.GetServices<IMqttHandler>();

var twitchBot = new TwitchBot(twitchClient, connectionCredentials, twitchBotConfiguration,
scopedSayingResponse, scopedDadJokeService, listOfCommands,
helpCommand, scopedMqttFactory, mqttHandlers, scopedMessageStackService,
logger);
scopedCoolDownService, logger);

SetupGPIO();
}
Expand Down
9 changes: 8 additions & 1 deletion MrBigHead.Web/Pages/Quips.razor
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
@page "/quips"
@using Microsoft.AspNetCore.Components.QuickGrid
@using MrBigHead.Shared
@using MrBigHead.Web.Services
@inject HttpClient Http
@inject UserInformationProvider UserInformationProvider

<h1>Phrases</h1>

Expand All @@ -15,7 +18,7 @@ else
<QuickGrid Items="@sayings.AsQueryable()" Pagination="@pagination">
<PropertyColumn Property="@(m => m.Mood)" Sortable="true" />
<PropertyColumn Property="@(p => p.Phrase)" Sortable="true" />
@if (isAdmin)
@if (userInformation.Tier == "3000")
{
<TemplateColumn Title="Actions">
<button>Edit</button>
Expand All @@ -30,11 +33,15 @@ else
@code {
private IEnumerable<Sayings> sayings;
PaginationState pagination = new PaginationState { ItemsPerPage = 20 };
UserInformation userInformation { get; set; }
bool isAdmin { get; set; } = true;

protected override async Task OnInitializedAsync()
{
sayings = await Http.GetFromJsonAsync<IEnumerable<Sayings>>("https://bigheadfuncs.azurewebsites.net/api/getallphrases");

userInformation = await UserInformationProvider.GetUserInformation(null);
Console.WriteLine($"Tier: {userInformation.Tier}");
}

public class Sayings
Expand Down
Loading

0 comments on commit 4fb5e68

Please sign in to comment.