Generalized the ChatMessageReader to make it work with ChannelResubscrition. Added connections refresh command.

This commit is contained in:
Tom 2024-08-12 19:45:17 +00:00
parent f503f7c6f4
commit 1d43515fb9
18 changed files with 182 additions and 135 deletions

View File

@ -37,7 +37,8 @@ namespace TwitchChatTTS.Chat.Commands
_logger = logger; _logger = logger;
_stack = new Stack<CommandNode>(); _stack = new Stack<CommandNode>();
Clear(); _root = new CommandNode(new StaticParameter("root", "root"));
_current = _root;
} }
@ -201,7 +202,7 @@ namespace TwitchChatTTS.Chat.Commands
public interface ICommandSelector public interface ICommandSelector
{ {
CommandSelectorResult GetBestMatch(string[] args, ChannelChatMessage message); CommandSelectorResult GetBestMatch(string[] args, TwitchChatFragment[] fragments);
IDictionary<string, CommandParameter> GetNonStaticArguments(string[] args, string path); IDictionary<string, CommandParameter> GetNonStaticArguments(string[] args, string path);
} }
@ -214,12 +215,12 @@ namespace TwitchChatTTS.Chat.Commands
_root = root; _root = root;
} }
public CommandSelectorResult GetBestMatch(string[] args, ChannelChatMessage message) public CommandSelectorResult GetBestMatch(string[] args, TwitchChatFragment[] fragments)
{ {
return GetBestMatch(_root, message, args, null, string.Empty, null); return GetBestMatch(_root, fragments, args, null, string.Empty, null);
} }
private CommandSelectorResult GetBestMatch(CommandNode node, ChannelChatMessage message, IEnumerable<string> args, IChatPartialCommand? match, string path, string[]? permissions) private CommandSelectorResult GetBestMatch(CommandNode node, TwitchChatFragment[] fragments, IEnumerable<string> args, IChatPartialCommand? match, string path, string[]? permissions)
{ {
if (node == null || !args.Any()) if (node == null || !args.Any())
return new CommandSelectorResult(match, path, permissions); return new CommandSelectorResult(match, path, permissions);
@ -234,13 +235,13 @@ namespace TwitchChatTTS.Chat.Commands
if (child.Parameter.GetType() == typeof(StaticParameter)) if (child.Parameter.GetType() == typeof(StaticParameter))
{ {
if (child.Parameter.Name.ToLower() == argumentLower) if (child.Parameter.Name.ToLower() == argumentLower)
return GetBestMatch(child, message, args.Skip(1), child.Command ?? match, (path.Length == 0 ? string.Empty : path + ".") + child.Parameter.Name.ToLower(), perms); return GetBestMatch(child, fragments, args.Skip(1), child.Command ?? match, (path.Length == 0 ? string.Empty : path + ".") + child.Parameter.Name.ToLower(), perms);
continue; continue;
} }
if ((!child.Parameter.Optional || child.Parameter.Validate(argument, message)) && child.Command != null) if ((!child.Parameter.Optional || child.Parameter.Validate(argument, fragments)) && child.Command != null)
return GetBestMatch(child, message, args.Skip(1), child.Command, (path.Length == 0 ? string.Empty : path + ".") + "*", perms); return GetBestMatch(child, fragments, args.Skip(1), child.Command, (path.Length == 0 ? string.Empty : path + ".") + "*", perms);
if (!child.Parameter.Optional) if (!child.Parameter.Optional)
return GetBestMatch(child, message, args.Skip(1), match, (path.Length == 0 ? string.Empty : path + ".") + "*", permissions); return GetBestMatch(child, fragments, args.Skip(1), match, (path.Length == 0 ? string.Empty : path + ".") + "*", permissions);
} }
return new CommandSelectorResult(match, path, permissions); return new CommandSelectorResult(match, path, permissions);

View File

@ -59,7 +59,7 @@ namespace TwitchChatTTS.Chat.Commands
string[] args = parts.ToArray(); string[] args = parts.ToArray();
string com = args.First().ToLower(); string com = args.First().ToLower();
CommandSelectorResult selectorResult = _commandSelector.GetBestMatch(args, message); CommandSelectorResult selectorResult = _commandSelector.GetBestMatch(args, message.Message.Fragments);
if (selectorResult.Command == null) if (selectorResult.Command == null)
{ {
_logger.Warning($"Could not match '{arg}' to any command [chatter: {message.ChatterUserLogin}][chatter id: {message.ChatterUserId}]"); _logger.Warning($"Could not match '{arg}' to any command [chatter: {message.ChatterUserLogin}][chatter id: {message.ChatterUserId}]");
@ -86,7 +86,7 @@ namespace TwitchChatTTS.Chat.Commands
var parameter = entry.Value; var parameter = entry.Value;
var argument = entry.Key; var argument = entry.Key;
// Optional parameters were validated while fetching this command. // Optional parameters were validated while fetching this command.
if (!parameter.Optional && !parameter.Validate(argument, message)) if (!parameter.Optional && !parameter.Validate(argument, message.Message.Fragments))
{ {
_logger.Warning($"Command failed due to an argument being invalid [argument name: {parameter.Name}][argument value: {argument}][arguments: {arg}][command type: {command.GetType().Name}][chatter: {message.ChatterUserLogin}][chatter id: {message.ChatterUserId}]"); _logger.Warning($"Command failed due to an argument being invalid [argument name: {parameter.Name}][argument value: {argument}][arguments: {arg}][command type: {command.GetType().Name}][chatter: {message.ChatterUserLogin}][chatter id: {message.ChatterUserId}]");
return ChatCommandResult.Syntax; return ChatCommandResult.Syntax;

View File

@ -13,6 +13,6 @@ namespace TwitchChatTTS.Chat.Commands.Parameters
Optional = optional; Optional = optional;
} }
public abstract bool Validate(string value, ChannelChatMessage message); public abstract bool Validate(string value, TwitchChatFragment[] fragments);
} }
} }

View File

@ -8,9 +8,9 @@ namespace TwitchChatTTS.Chat.Commands.Parameters
{ {
} }
public override bool Validate(string value, ChannelChatMessage message) public override bool Validate(string value, TwitchChatFragment[] fragments)
{ {
return value.StartsWith('@') && message.Message.Fragments.Any(f => f.Text == value && f.Mention != null); return value.StartsWith('@') && fragments.Any(f => f.Text == value && f.Mention != null);
} }
} }
} }

View File

@ -10,7 +10,7 @@ namespace TwitchChatTTS.Chat.Commands.Parameters
{ {
} }
public override bool Validate(string value, ChannelChatMessage message) public override bool Validate(string value, TwitchChatFragment[] fragments)
{ {
return _values.Contains(value.ToLower()); return _values.Contains(value.ToLower());
} }

View File

@ -10,7 +10,7 @@ namespace TwitchChatTTS.Chat.Commands.Parameters
{ {
} }
public override bool Validate(string value, ChannelChatMessage message) public override bool Validate(string value, TwitchChatFragment[] fragments)
{ {
return _values.Contains(value.ToLower()); return _values.Contains(value.ToLower());
} }

View File

@ -13,7 +13,7 @@ namespace TwitchChatTTS.Chat.Commands.Parameters
_value = value.ToLower(); _value = value.ToLower();
} }
public override bool Validate(string value, ChannelChatMessage message) public override bool Validate(string value, TwitchChatFragment[] fragments)
{ {
return _value == value.ToLower(); return _value == value.ToLower();
} }

View File

@ -13,7 +13,7 @@ namespace TwitchChatTTS.Chat.Commands.Parameters
_user = user; _user = user;
} }
public override bool Validate(string value, ChannelChatMessage message) public override bool Validate(string value, TwitchChatFragment[] fragments)
{ {
if (_user.VoicesAvailable == null) if (_user.VoicesAvailable == null)
return false; return false;

View File

@ -8,7 +8,7 @@ namespace TwitchChatTTS.Chat.Commands.Parameters
{ {
} }
public override bool Validate(string value, ChannelChatMessage message) public override bool Validate(string value, TwitchChatFragment[] fragments)
{ {
return true; return true;
} }

View File

@ -4,7 +4,6 @@ using Microsoft.Extensions.DependencyInjection;
using Serilog; using Serilog;
using TwitchChatTTS.Hermes.Socket; using TwitchChatTTS.Hermes.Socket;
using TwitchChatTTS.OBS.Socket; using TwitchChatTTS.OBS.Socket;
using TwitchChatTTS.Twitch.Socket;
using TwitchChatTTS.Twitch.Socket.Messages; using TwitchChatTTS.Twitch.Socket.Messages;
using static TwitchChatTTS.Chat.Commands.TTSCommands; using static TwitchChatTTS.Chat.Commands.TTSCommands;
@ -37,7 +36,8 @@ namespace TwitchChatTTS.Chat.Commands
.CreateStaticInputParameter("default_voice", b => b.CreateCommand(new RefreshTTSDefaultVoice())) .CreateStaticInputParameter("default_voice", b => b.CreateCommand(new RefreshTTSDefaultVoice()))
.CreateStaticInputParameter("redemptions", b => b.CreateCommand(new RefreshRedemptions())) .CreateStaticInputParameter("redemptions", b => b.CreateCommand(new RefreshRedemptions()))
.CreateStaticInputParameter("obs_cache", b => b.CreateCommand(new RefreshObs(_obs, _logger))) .CreateStaticInputParameter("obs_cache", b => b.CreateCommand(new RefreshObs(_obs, _logger)))
.CreateStaticInputParameter("permissions", b => b.CreateCommand(new RefreshPermissions())); .CreateStaticInputParameter("permissions", b => b.CreateCommand(new RefreshPermissions()))
.CreateStaticInputParameter("connections", b => b.CreateCommand(new RefreshConnections()));
}); });
} }
@ -113,7 +113,6 @@ namespace TwitchChatTTS.Chat.Commands
private sealed class RefreshPermissions : IChatPartialCommand private sealed class RefreshPermissions : IChatPartialCommand
{ {
public bool AcceptCustomPermission { get => true; } public bool AcceptCustomPermission { get => true; }
public async Task Execute(IDictionary<string, string> values, ChannelChatMessage message, HermesSocketClient hermes) public async Task Execute(IDictionary<string, string> values, ChannelChatMessage message, HermesSocketClient hermes)
@ -121,5 +120,15 @@ namespace TwitchChatTTS.Chat.Commands
await hermes.FetchPermissions(); await hermes.FetchPermissions();
} }
} }
private sealed class RefreshConnections : IChatPartialCommand
{
public bool AcceptCustomPermission { get => true; }
public async Task Execute(IDictionary<string, string> values, ChannelChatMessage message, HermesSocketClient hermes)
{
await hermes.FetchConnections();
}
}
} }
} }

View File

@ -3,10 +3,7 @@ using CommonSocketLibrary.Abstract;
using CommonSocketLibrary.Common; using CommonSocketLibrary.Common;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Serilog; using Serilog;
using TwitchChatTTS.Chat.Commands;
using TwitchChatTTS.Chat.Emotes; using TwitchChatTTS.Chat.Emotes;
using TwitchChatTTS.Chat.Groups;
using TwitchChatTTS.Chat.Groups.Permissions;
using TwitchChatTTS.Chat.Speech; using TwitchChatTTS.Chat.Speech;
using TwitchChatTTS.Hermes.Socket; using TwitchChatTTS.Hermes.Socket;
using TwitchChatTTS.OBS.Socket; using TwitchChatTTS.OBS.Socket;
@ -17,13 +14,8 @@ namespace TwitchChatTTS.Chat.Messaging
{ {
public class ChatMessageReader public class ChatMessageReader
{ {
public string Name => "channel.chat.message";
private readonly User _user; private readonly User _user;
private readonly TTSPlayer _player; private readonly TTSPlayer _player;
private readonly ICommandManager _commands;
private readonly IGroupPermissionManager _permissionManager;
private readonly IChatterGroupManager _chatterGroupManager;
private readonly IEmoteDatabase _emotes; private readonly IEmoteDatabase _emotes;
private readonly OBSSocketClient _obs; private readonly OBSSocketClient _obs;
private readonly HermesSocketClient _hermes; private readonly HermesSocketClient _hermes;
@ -36,9 +28,6 @@ namespace TwitchChatTTS.Chat.Messaging
public ChatMessageReader( public ChatMessageReader(
User user, User user,
TTSPlayer player, TTSPlayer player,
ICommandManager commands,
IGroupPermissionManager permissionManager,
IChatterGroupManager chatterGroupManager,
IEmoteDatabase emotes, IEmoteDatabase emotes,
[FromKeyedServices("hermes")] SocketClient<WebSocketMessage> hermes, [FromKeyedServices("hermes")] SocketClient<WebSocketMessage> hermes,
[FromKeyedServices("obs")] SocketClient<WebSocketMessage> obs, [FromKeyedServices("obs")] SocketClient<WebSocketMessage> obs,
@ -48,9 +37,6 @@ namespace TwitchChatTTS.Chat.Messaging
{ {
_user = user; _user = user;
_player = player; _player = player;
_commands = commands;
_permissionManager = permissionManager;
_chatterGroupManager = chatterGroupManager;
_emotes = emotes; _emotes = emotes;
_obs = (obs as OBSSocketClient)!; _obs = (obs as OBSSocketClient)!;
_hermes = (hermes as HermesSocketClient)!; _hermes = (hermes as HermesSocketClient)!;
@ -61,58 +47,42 @@ namespace TwitchChatTTS.Chat.Messaging
_logger = logger; _logger = logger;
} }
public async Task Execute(TwitchWebsocketClient sender, ChannelChatMessage message) public async Task Read(TwitchWebsocketClient sender, long broadcasterId, long? chatterId, string? chatterLogin, string? messageId, TwitchReplyInfo? reply, TwitchChatFragment[] fragments, int priority)
{ {
if (_hermes.Connected && !_hermes.Ready) if (_hermes.Connected && !_hermes.Ready)
{ {
_logger.Debug($"TTS is not yet ready. Ignoring chat messages [message id: {message.MessageId}]"); _logger.Debug($"TTS is not yet ready. Ignoring chat messages [message id: {messageId}]");
return; // new MessageResult(MessageStatus.NotReady, -1, -1); return;
} }
if (_configuration.Twitch?.TtsWhenOffline != true && !_obs.Streaming) if (_configuration.Twitch?.TtsWhenOffline != true && !_obs.Streaming)
{ {
_logger.Debug($"OBS is not streaming. Ignoring chat messages [message id: {message.MessageId}]"); _logger.Debug($"OBS is not streaming. Ignoring chat messages [message id: {messageId}]");
return; // new MessageResult(MessageStatus.NotReady, -1, -1);
}
var chatterId = long.Parse(message.ChatterUserId);
var broadcasterId = long.Parse(message.BroadcasterUserId);
var messageId = message.MessageId;
var groups = GetGroups(message, chatterId);
var commandResult = await CheckForChatCommand(message.Message.Text, message, groups);
if (commandResult != ChatCommandResult.Unknown)
return;
var bits = GetTotalBits(message);
if (!HasPermission(message, chatterId, groups, bits))
{
_logger.Debug($"Blocked message by {message.ChatterUserLogin}: {message.Message.Text}");
return; return;
} }
var emoteUsage = GetEmoteUsage(message); var emoteUsage = GetEmoteUsage(fragments);
var tasks = new List<Task>(); var tasks = new List<Task>();
if (_obs.Streaming) if (_obs.Streaming)
{ {
if (emoteUsage.NewEmotes.Any()) if (emoteUsage.NewEmotes.Any())
tasks.Add(_hermes.SendEmoteDetails(emoteUsage.NewEmotes)); tasks.Add(_hermes.SendEmoteDetails(emoteUsage.NewEmotes));
if (emoteUsage.EmotesUsed.Any()) if (emoteUsage.EmotesUsed.Any() && messageId != null && chatterId != null)
tasks.Add(_hermes.SendEmoteUsage(message.MessageId, chatterId, emoteUsage.EmotesUsed)); tasks.Add(_hermes.SendEmoteUsage(messageId, chatterId.Value, emoteUsage.EmotesUsed));
if (!_user.Chatters.Contains(chatterId)) if (!string.IsNullOrEmpty(chatterLogin) && chatterId != null && !_user.Chatters.Contains(chatterId.Value))
{ {
tasks.Add(_hermes.SendChatterDetails(chatterId, message.ChatterUserLogin)); tasks.Add(_hermes.SendChatterDetails(chatterId.Value, chatterLogin));
_user.Chatters.Add(chatterId); _user.Chatters.Add(chatterId.Value);
} }
} }
if (_user.Raids.TryGetValue(message.BroadcasterUserId, out var raid) && !raid.Chatters.Contains(chatterId)) if (chatterId != null && _user.Raids.TryGetValue(broadcasterId.ToString(), out var raid) && !raid.Chatters.Contains(chatterId.Value))
{ {
_logger.Information($"Potential chat message from raider ignored due to potential raid message spam [chatter: {message.ChatterUserLogin}][chatter id: {message.ChatterUserId}]"); _logger.Information($"Potential chat message from raider ignored due to potential raid message spam [chatter: {chatterLogin}][chatter id: {chatterId}]");
return; return;
} }
var msg = FilterMessage(message); var msg = FilterMessage(fragments, reply);
int priority = _chatterGroupManager.GetPriorityFor(groups); string voiceSelected = chatterId == null ? _user.DefaultTTSVoice : GetSelectedVoiceFor(chatterId.Value);
string voiceSelected = GetSelectedVoiceFor(chatterId);
var messages = GetPartialTTSMessages(msg, voiceSelected).ToList(); var messages = GetPartialTTSMessages(msg, voiceSelected).ToList();
var groupedMessage = new TTSGroupedMessage(broadcasterId, chatterId, messageId, messages, DateTime.UtcNow, priority); var groupedMessage = new TTSGroupedMessage(broadcasterId, chatterId, messageId, messages, DateTime.UtcNow, priority);
_player.Add(groupedMessage, groupedMessage.Priority); _player.Add(groupedMessage, groupedMessage.Priority);
@ -175,25 +145,11 @@ namespace TwitchChatTTS.Chat.Messaging
return list; return list;
} }
private async Task<ChatCommandResult> CheckForChatCommand(string arguments, ChannelChatMessage message, IEnumerable<string> groups) private string FilterMessage(TwitchChatFragment[] fragments, TwitchReplyInfo? reply)
{ {
try var msg = string.Join(string.Empty, fragments.Where(f => f.Type != "cheermote").Select(f => f.Text)).Trim();
{ if (reply != null)
var commandResult = await _commands.Execute(arguments, message, groups); msg = msg.Substring(reply.ParentUserLogin.Length + 2);
return commandResult;
}
catch (Exception ex)
{
_logger.Error(ex, $"Failed executing a chat command [message: {arguments}][chatter: {message.ChatterUserLogin}][chatter id: {message.ChatterUserId}][message id: {message.MessageId}]");
}
return ChatCommandResult.Fail;
}
private string FilterMessage(ChannelChatMessage message)
{
var msg = string.Join(string.Empty, message.Message.Fragments.Where(f => f.Type != "cheermote").Select(f => f.Text)).Trim();
if (message.Reply != null)
msg = msg.Substring(message.Reply.ParentUserLogin.Length + 2);
// Replace filtered words. // Replace filtered words.
if (_user.RegexFilters != null) if (_user.RegexFilters != null)
@ -222,11 +178,11 @@ namespace TwitchChatTTS.Chat.Messaging
return msg; return msg;
} }
private ChatMessageEmoteUsage GetEmoteUsage(ChannelChatMessage message) private ChatMessageEmoteUsage GetEmoteUsage(TwitchChatFragment[] fragments)
{ {
var emotesUsed = new HashSet<string>(); var emotesUsed = new HashSet<string>();
var newEmotes = new Dictionary<string, string>(); var newEmotes = new Dictionary<string, string>();
foreach (var fragment in message.Message.Fragments) foreach (var fragment in fragments)
{ {
if (fragment.Emote != null) if (fragment.Emote != null)
{ {
@ -256,30 +212,6 @@ namespace TwitchChatTTS.Chat.Messaging
return new ChatMessageEmoteUsage(emotesUsed, newEmotes); return new ChatMessageEmoteUsage(emotesUsed, newEmotes);
} }
private int GetTotalBits(ChannelChatMessage message)
{
return message.Message.Fragments.Where(f => f.Type == "cheermote" && f.Cheermote != null)
.Select(f => f.Cheermote!.Bits)
.Sum();
}
private string GetGroupNameByBadgeName(string badgeName)
{
if (badgeName == "subscriber")
return "subscribers";
if (badgeName == "moderator")
return "moderators";
return badgeName.ToLower();
}
private IEnumerable<string> GetGroups(ChannelChatMessage message, long chatterId)
{
var defaultGroups = new string[] { "everyone" };
var badgesGroups = message.Badges.Select(b => b.SetId).Select(GetGroupNameByBadgeName);
var customGroups = _chatterGroupManager.GetGroupNamesFor(chatterId);
return defaultGroups.Union(badgesGroups).Union(customGroups);
}
private IEnumerable<TTSMessage> GetPartialTTSMessages(string message, string defaultVoice) private IEnumerable<TTSMessage> GetPartialTTSMessages(string message, string defaultVoice)
{ {
var matches = _user.VoiceNameRegex?.Matches(message).ToArray(); var matches = _user.VoiceNameRegex?.Matches(message).ToArray();
@ -319,17 +251,6 @@ namespace TwitchChatTTS.Chat.Messaging
return voiceSelected ?? "Brian"; return voiceSelected ?? "Brian";
} }
private bool HasPermission(ChannelChatMessage message, long chatterId, IEnumerable<string> groups, int bits)
{
var permissionPath = "tts.chat.messages.read";
if (!string.IsNullOrWhiteSpace(message.ChannelPointsCustomRewardId))
permissionPath = "tts.chat.redemptions.read";
else if (bits > 0)
permissionPath = "tts.chat.bits.read";
return chatterId == _user.OwnerId ? true : _permissionManager.CheckIfAllowed(groups, permissionPath) == true;
}
private class ChatMessageEmoteUsage private class ChatMessageEmoteUsage
{ {
public readonly HashSet<string> EmotesUsed = new HashSet<string>(); public readonly HashSet<string> EmotesUsed = new HashSet<string>();

View File

@ -194,15 +194,15 @@ namespace TwitchChatTTS.Chat.Speech
public class TTSGroupedMessage public class TTSGroupedMessage
{ {
public long RoomId { get; set; } public long RoomId { get; set; }
public long ChatterId { get; set; } public long? ChatterId { get; set; }
public string MessageId { get; set; } public string? MessageId { get; set; }
public DateTime Timestamp { get; set; } public DateTime Timestamp { get; set; }
public int Priority { get; set; } public int Priority { get; set; }
public IList<TTSMessage> Messages { get; set; } public IList<TTSMessage> Messages { get; set; }
public ISampleProvider? Audio { get; set; } public ISampleProvider? Audio { get; set; }
public TTSGroupedMessage(long broadcasterId, long chatterId, string messageId, IList<TTSMessage> messages, DateTime timestamp, int priority) public TTSGroupedMessage(long broadcasterId, long? chatterId, string? messageId, IList<TTSMessage> messages, DateTime timestamp, int priority)
{ {
RoomId = broadcasterId; RoomId = broadcasterId;
ChatterId = chatterId; ChatterId = chatterId;

View File

@ -2,5 +2,5 @@ public class Account {
public string Id { get; set; } public string Id { get; set; }
public string Username { get; set; } public string Username { get; set; }
public string Role { get; set; } public string Role { get; set; }
public string? BroadcasterId { get; set; } public string BroadcasterId { get; set; }
} }

View File

@ -19,6 +19,8 @@ namespace TwitchChatTTS.Hermes.Socket.Handlers
{ {
private User _user; private User _user;
private readonly ICallbackManager<HermesRequestData> _callbackManager; private readonly ICallbackManager<HermesRequestData> _callbackManager;
private readonly TwitchApiClient _twitch;
private readonly NightbotApiClient _nightbot;
private readonly IServiceProvider _serviceProvider; private readonly IServiceProvider _serviceProvider;
private readonly JsonSerializerOptions _options; private readonly JsonSerializerOptions _options;
private readonly ILogger _logger; private readonly ILogger _logger;
@ -30,6 +32,8 @@ namespace TwitchChatTTS.Hermes.Socket.Handlers
public RequestAckHandler( public RequestAckHandler(
ICallbackManager<HermesRequestData> callbackManager, ICallbackManager<HermesRequestData> callbackManager,
TwitchApiClient twitch,
NightbotApiClient nightbot,
IServiceProvider serviceProvider, IServiceProvider serviceProvider,
User user, User user,
JsonSerializerOptions options, JsonSerializerOptions options,
@ -37,6 +41,8 @@ namespace TwitchChatTTS.Hermes.Socket.Handlers
) )
{ {
_callbackManager = callbackManager; _callbackManager = callbackManager;
_twitch = twitch;
_nightbot = nightbot;
_serviceProvider = serviceProvider; _serviceProvider = serviceProvider;
_user = user; _user = user;
_options = options; _options = options;
@ -142,6 +148,26 @@ namespace TwitchChatTTS.Hermes.Socket.Handlers
_user.VoicesAvailable[voiceId] = voice; _user.VoicesAvailable[voiceId] = voice;
_logger.Information($"Updated TTS voice [voice: {voice}][id: {voiceId}]"); _logger.Information($"Updated TTS voice [voice: {voice}][id: {voiceId}]");
} }
else if (message.Request.Type == "get_connections")
{
var connections = JsonSerializer.Deserialize<IEnumerable<Connection>>(message.Data?.ToString(), _options);
if (connections == null)
{
_logger.Error("Null value was given when attempting to fetch connections.");
_logger.Debug(message.Data?.ToString());
return;
}
_user.TwitchConnection = connections.FirstOrDefault(c => c.Type == "twitch" && c.Default);
_user.NightbotConnection = connections.FirstOrDefault(c => c.Type == "nightbot" && c.Default);
if (_user.TwitchConnection != null)
_twitch.Initialize(_user.TwitchConnection.ClientId, _user.TwitchConnection.AccessToken);
if (_user.NightbotConnection != null)
_nightbot.Initialize(_user.NightbotConnection.ClientId, _user.NightbotConnection.AccessToken);
_logger.Information($"Fetched connections from TTS account [count: {connections.Count()}][twitch: {_user.TwitchConnection != null}][nightbot: {_user.NightbotConnection != null}]");
}
else if (message.Request.Type == "get_tts_users") else if (message.Request.Type == "get_tts_users")
{ {
var users = JsonSerializer.Deserialize<IDictionary<long, string>>(message.Data.ToString(), _options); var users = JsonSerializer.Deserialize<IDictionary<long, string>>(message.Data.ToString(), _options);

View File

@ -215,6 +215,15 @@ namespace TwitchChatTTS.Hermes.Socket
}); });
} }
public async Task FetchConnections()
{
await Send(3, new RequestMessage()
{
Type = "get_connections",
Data = null
});
}
public void Initialize() public void Initialize()
{ {
_logger.Information("Initializing Hermes websocket client."); _logger.Information("Initializing Hermes websocket client.");

5
TTS.cs
View File

@ -1,5 +1,3 @@
using System.Runtime.InteropServices;
using System.Web;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using Serilog; using Serilog;
@ -16,7 +14,6 @@ using TwitchChatTTS.Twitch.Socket;
using TwitchChatTTS.Chat.Commands; using TwitchChatTTS.Chat.Commands;
using System.Text; using System.Text;
using TwitchChatTTS.Chat.Speech; using TwitchChatTTS.Chat.Speech;
using NAudio.Wave;
namespace TwitchChatTTS namespace TwitchChatTTS
{ {
@ -95,7 +92,7 @@ namespace TwitchChatTTS
_logger.Information($"A new update for TTS is avaiable! Version {hermesVersion.MajorVersion}.{hermesVersion.MinorVersion} is available at {hermesVersion.Download}"); _logger.Information($"A new update for TTS is avaiable! Version {hermesVersion.MajorVersion}.{hermesVersion.MinorVersion} is available at {hermesVersion.Download}");
var changes = hermesVersion.Changelog.Split("\n"); var changes = hermesVersion.Changelog.Split("\n");
if (changes != null && changes.Any()) if (changes != null && changes.Any())
_logger.Information("Changelogs:\n - " + string.Join("\n - ", changes) + "\n\n"); _logger.Information("Changelog:\n - " + string.Join("\n - ", changes) + "\n\n");
await Task.Delay(15 * 1000); await Task.Delay(15 * 1000);
} }

View File

@ -1,4 +1,7 @@
using Serilog; using Serilog;
using TwitchChatTTS.Chat.Commands;
using TwitchChatTTS.Chat.Groups;
using TwitchChatTTS.Chat.Groups.Permissions;
using TwitchChatTTS.Chat.Messaging; using TwitchChatTTS.Chat.Messaging;
using TwitchChatTTS.Twitch.Socket.Messages; using TwitchChatTTS.Twitch.Socket.Messages;
@ -9,18 +12,27 @@ namespace TwitchChatTTS.Twitch.Socket.Handlers
public string Name => "channel.chat.message"; public string Name => "channel.chat.message";
private readonly ChatMessageReader _reader; private readonly ChatMessageReader _reader;
private readonly Configuration _configuration; private readonly User _user;
private readonly ICommandManager _commands;
private readonly IGroupPermissionManager _permissionManager;
private readonly IChatterGroupManager _chatterGroupManager;
private readonly ILogger _logger; private readonly ILogger _logger;
public ChannelChatMessageHandler( public ChannelChatMessageHandler(
ChatMessageReader reader, ChatMessageReader reader,
Configuration configuration, ICommandManager commands,
IGroupPermissionManager permissionManager,
IChatterGroupManager chatterGroupManager,
User user,
ILogger logger ILogger logger
) )
{ {
_reader = reader; _reader = reader;
_configuration = configuration; _user = user;
_commands = commands;
_permissionManager = permissionManager;
_chatterGroupManager = chatterGroupManager;
_logger = logger; _logger = logger;
} }
@ -32,7 +44,74 @@ namespace TwitchChatTTS.Twitch.Socket.Handlers
if (data is not ChannelChatMessage message) if (data is not ChannelChatMessage message)
return; return;
await _reader.Execute(sender, message); var broadcasterId = long.Parse(message.BroadcasterUserId);
var chatterId = long.Parse(message.ChatterUserId);
var chatterLogin = message.ChatterUserLogin;
var messageId = message.MessageId;
var fragments = message.Message.Fragments;
var groups = GetGroups(message.Badges, chatterId);
var bits = GetTotalBits(fragments);
var commandResult = await CheckForChatCommand(message.Message.Text, message, groups);
if (commandResult != ChatCommandResult.Unknown)
return;
if (!HasPermission(message.ChannelPointsCustomRewardId, chatterId, groups, bits))
{
_logger.Debug($"Blocked message by {chatterLogin}: {message}");
return;
}
int priority = _chatterGroupManager.GetPriorityFor(groups);
await _reader.Read(sender, broadcasterId, chatterId, chatterLogin, messageId, message.Reply, fragments, priority);
}
private async Task<ChatCommandResult> CheckForChatCommand(string arguments, ChannelChatMessage message, IEnumerable<string> groups)
{
try
{
return await _commands.Execute(arguments, message, groups);
}
catch (Exception ex)
{
_logger.Error(ex, $"Failed executing a chat command [message: {arguments}][chatter: {message.ChatterUserLogin}][chatter id: {message.ChatterUserId}][message id: {message.MessageId}]");
}
return ChatCommandResult.Fail;
}
private string GetGroupNameByBadgeName(string badgeName)
{
if (badgeName == "subscriber")
return "subscribers";
if (badgeName == "moderator")
return "moderators";
return badgeName.ToLower();
}
private IEnumerable<string> GetGroups(TwitchBadge[] badges, long chatterId)
{
var defaultGroups = new string[] { "everyone" };
var badgesGroups = badges.Select(b => b.SetId).Select(GetGroupNameByBadgeName);
var customGroups = _chatterGroupManager.GetGroupNamesFor(chatterId);
return defaultGroups.Union(badgesGroups).Union(customGroups);
}
private int GetTotalBits(TwitchChatFragment[] fragments)
{
return fragments.Where(f => f.Type == "cheermote" && f.Cheermote != null)
.Select(f => f.Cheermote!.Bits)
.Sum();
}
private bool HasPermission(string? customRewardId, long chatterId, IEnumerable<string> groups, int bits)
{
var permissionPath = "tts.chat.messages.read";
if (!string.IsNullOrWhiteSpace(customRewardId))
permissionPath = "tts.chat.redemptions.read";
else if (bits > 0)
permissionPath = "tts.chat.bits.read";
return chatterId == _user.OwnerId ? true : _permissionManager.CheckIfAllowed(groups, permissionPath) == true;
} }
} }
} }

View File

@ -25,7 +25,12 @@ namespace TwitchChatTTS.Twitch.Socket.Handlers
if (data is not ChannelResubscriptionMessage message) if (data is not ChannelResubscriptionMessage message)
return; return;
_logger.Debug($"Resubscription occured [chatter: {message.UserLogin}][chatter id: {message.UserId}][Tier: {message.Tier}][Streak: {message.StreakMonths}][Cumulative: {message.CumulativeMonths}][Duration: {message.DurationMonths}]"); _logger.Debug($"Resubscription occured [chatter: {message.UserLogin}][chatter id: {message.UserId}][tier: {message.Tier}][streak: {message.StreakMonths}][cumulative: {message.CumulativeMonths}][duration: {message.DurationMonths}]");
long broadcasterId = long.Parse(message.BroadcasterUserId);
long chatterId = message.UserId == null ? 0 : long.Parse(message.UserId);
Task.Run(async () => await _reader.Read(sender, broadcasterId, chatterId, message.UserLogin, null, null, message.Message.Fragments, 100));
try try
{ {
var actions = _redemptionManager.Get("subscription"); var actions = _redemptionManager.Get("subscription");