Skip to content

Commit

Permalink
[Fixes #55] Fixing Channel Point events and Monster Spawning cost
Browse files Browse the repository at this point in the history
  • Loading branch information
JustDerb committed Dec 26, 2024
1 parent d95eb2d commit 32802f3
Show file tree
Hide file tree
Showing 24 changed files with 154 additions and 113 deletions.
2 changes: 1 addition & 1 deletion Events/MonsterSpawner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ private CombatSquad SpawnMonstersInternal(
Destroy(group);
return null;
}
card.directorCreditCost = 0;

SpawnFinalizer finalizer = new SpawnFinalizer()
{
CombatSquad = group,
Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ accordingly when needed. Below you'll see a column for what configurations can b
|------|----|-------|-------------|-----|
|`Channel`|text||✔️|The channel to monitor Twitch chat|
|`Username`|text||✔️|The username to use when calling Twitch APIs. If you aren't using a secondary account, this should be the same as `Channel`|
|`ImplicitOAuth`|text|||The "password" to access Twitch APIs. **Please visit [twitchapps.com][1] to get the password to put here.** Note that this password is not sent to any servers other than Twitch to authenticate. **DO NOT GIVE THIS TO ANYONE.** To revoke this password, go to [Twitch Connections Settings][2] and Disconnect the app named "Twitch Chat OAuth Token Generator".|
|`ImplicitOAuth`|text|||The "password" to access Twitch APIs. **Please visit [twitchapps.com][1] to get the password to put here.** Note that this password is not sent to any servers other than Twitch to authenticate. **DO NOT GIVE THIS TO ANYONE.** To revoke this password, go to [Twitch Connections Settings][2] and Disconnect the app named "Twitch Token Generator by swiftyspiffy".|
|`DebugLogs`|true/false|false|✔️|Enable debug logging for Twitch - will spam to the console!|
|`ClientID`|text|q6batx0epp608isickayubi39itsckt||The client ID of the app that you used to populate the `ImplicitOAuth` field. If you used [twitchapps.com][1] this would be the default value. If you used another Twitch app, this needs to be changed accordingly.|
|`EnableItemVoting`|true/false|true|✔️|Enables the main feature of this mod. Disable it if you only want to enable bit interactions.|
Expand All @@ -42,12 +42,12 @@ accordingly when needed. Below you'll see a column for what configurations can b
|`CurrentBits`|number|0||**Do not edit this field.** Used as storage whenever someone donates bits so that restarting the game doesn't clear the donation count.|
|`PublishToChat`|true/false|true|✔️|Publish events (like voting) to Twitch chat.|

[1]: https://id.twitch.tv/oauth2/authorize?response_type=token&client_id=q6batx0epp608isickayubi39itsckt&redirect_uri=https://twitchapps.com/tmi/&scope=channel_subscriptions+user_subscriptions+channel_check_subscription+bits:read+chat:read+chat:edit+channel:read:redemptions+channel:read:hype_train
[1]: https://twitchtokengenerator.com/quick/Bt3H1fq9dl
[2]: https://www.twitch.tv/settings/connections

### Help, I accidentally gave someone my `ImplicitOAuth` token!

To revoke this password, go to [Twitch Connections Settings][2] and Disconnect the app named "Twitch Chat OAuth Token Generator". You can then regenerate a new token via [twitchapps.com][1] and put it in the config; but, keep it safe this time!
To revoke this password, go to [Twitch Connections Settings][2] and Disconnect the app named "Twitch Token Generator by swiftyspiffy". You can then regenerate a new token via [twitchapps.com][1] and put it in the config; but, keep it safe this time!

## Tiltify

Expand Down
13 changes: 7 additions & 6 deletions Twitch/ChannelPointsManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@ namespace VsTwitch
{
class ChannelPointsManager
{
private readonly Dictionary<string, Action<ChannelPointsManager, OnRewardRedeemedArgs>> channelEvents;
private readonly Dictionary<string, Action<ChannelPointsManager, OnChannelPointsRewardRedeemedArgs>> channelEvents;

public ChannelPointsManager()
{
channelEvents = new Dictionary<string, Action<ChannelPointsManager, OnRewardRedeemedArgs>>();
channelEvents = new Dictionary<string, Action<ChannelPointsManager, OnChannelPointsRewardRedeemedArgs>>();
}

public bool RegisterEvent(string eventName, Action<ChannelPointsManager, OnRewardRedeemedArgs> e) {
public bool RegisterEvent(string eventName, Action<ChannelPointsManager, OnChannelPointsRewardRedeemedArgs> e) {
if (string.IsNullOrWhiteSpace(eventName))
{
return false;
Expand All @@ -34,16 +34,17 @@ public bool UnregisterEvent(string eventName)
return true;
}

public bool TriggerEvent(OnRewardRedeemedArgs e)
public bool TriggerEvent(OnChannelPointsRewardRedeemedArgs e)
{
if (!channelEvents.ContainsKey(e.RewardTitle))
string title = e.RewardRedeemed.Redemption.Reward.Title;
if (!channelEvents.ContainsKey(title))
{
return false;
}

try
{
channelEvents[e.RewardTitle](this, e);
channelEvents[title](this, e);
return true;
}
catch (Exception ex)
Expand Down
108 changes: 57 additions & 51 deletions Twitch/TwitchManager.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
using Newtonsoft.Json;
using TwitchLib.Client.Events;
using TwitchLib.Client.Models;
using TwitchLib.Communication.Events;
using TwitchLib.PubSub.Events;
using TwitchLib.Unity;
using UnityEngine;

namespace VsTwitch
{
Expand All @@ -22,10 +26,10 @@ class TwitchManager

public bool DebugLogs { get; set; }

public event EventHandler<OnMessageReceivedArgs> OnMessageReceived;
public event EventHandler<OnRewardRedeemedArgs> OnRewardRedeemed;
public event EventHandler<OnJoinedChannelArgs> OnConnected;
public event EventHandler<OnDisconnectedEventArgs> OnDisconnected;
public event AsyncEventHandler<OnMessageReceivedArgs> OnMessageReceived;
public event EventHandler<OnChannelPointsRewardRedeemedArgs> OnRewardRedeemed;
public event AsyncEventHandler<OnJoinedChannelArgs> OnConnected;
public event AsyncEventHandler<OnDisconnectedArgs> OnDisconnected;

public TwitchManager()
{
Expand Down Expand Up @@ -63,54 +67,58 @@ public void Connect(string channel, string oauthToken, string username, string c
TwitchApi.Settings.AccessToken = twitchApiOauthToken;
TwitchApi.Settings.ClientId = clientId;
string channelId = null;
try
{
LogDebug("[Twitch API] Trying to find channel ID...");
Task<TwitchLib.Api.Helix.Models.Users.GetUsersResponse> response = TwitchApi.Helix.Users.GetUsersAsync(null,
new List<string>(new string[] { channel }));
response.Wait();
LogDebug("[Twitch API] Trying to find channel ID...");
Task<TwitchLib.Api.Helix.Models.Users.GetUsers.GetUsersResponse> response = TwitchApi.Helix.Users.GetUsersAsync(null,
new List<string>(new string[] { channel }));
response.Wait(5000);

if (response.Result.Users.Length == 1)
{
channelId = response.Result.Users[0].Id;
Log.Info($"[Twitch API] Channel ID for {channel} = {channelId}");
}
else
{
throw new ArgumentException($"Couldn't find Twitch user/channel {channel}!");
}
if (response.IsCompleted && response.Result.Users.Length == 1)
{
channelId = response.Result.Users[0].Id;
Log.Info($"[Twitch API] Channel ID for {channel} = {channelId}");
}
catch (Exception ex)

if (channelId == null)
{
if (ex is ArgumentException)
{
throw ex;
}
Log.Exception(ex);
throw new ArgumentException($"Couldn't find Twitch user/channel {channel}!");
}

LogDebug("[Twitch Client] Creating...");
ConnectionCredentials credentials = new ConnectionCredentials(username, oauthToken);
TwitchClient = new Client();
TwitchClient.Initialize(credentials, channel);
TwitchClient.OnLog += TwitchClient_OnLog;
//TwitchClient.OnLog += TwitchClient_OnLog;
TwitchClient.OnJoinedChannel += OnConnected;
TwitchClient.OnMessageReceived += OnMessageReceived;
TwitchClient.OnConnected += TwitchClient_OnConnected;
TwitchClient.OnConnected += (object sender, TwitchLib.Client.Events.OnConnectedEventArgs e) =>
{
TwitchClient.JoinChannelAsync(channelId);
return Task.CompletedTask;
};
TwitchClient.OnDisconnected += OnDisconnected;
LogDebug("[Twitch Client] Connecting...");
TwitchClient.Connect();
TwitchClient.ConnectAsync();

if (channelId != null && channelId.Trim().Length != 0)
{
ILoggerFactory loggerFactory = LoggerFactory.Create(builder =>
{
builder
.AddFilter((type, category, logLevel) => this.DebugLogs)
.AddConsole();
});
ILogger<PubSub> logger = loggerFactory.CreateLogger<PubSub>();
logger.LogError("Created internal Twitch PubSub logger");

LogDebug("[Twitch PubSub] Creating...");
TwitchPubSub = new PubSub();
TwitchPubSub = new PubSub(logger);
TwitchPubSub.OnLog += TwitchPubSub_OnLog;
TwitchPubSub.OnPubSubServiceConnected += (sender, e) =>
{
Log.Info("[Twitch PubSub] Sending topics to listen too...");
TwitchPubSub.ListenToRewards(channelId);
TwitchPubSub.SendTopics(twitchApiOauthToken);
TwitchPubSub.ListenToChannelPoints(channelId);
TwitchPubSub.ListenToBitsEventsV2(channelId);
TwitchPubSub.SendTopicsAsync(twitchApiOauthToken);
};
TwitchPubSub.OnPubSubServiceError += (sender, e) =>
{
Expand All @@ -124,32 +132,35 @@ public void Connect(string channel, string oauthToken, string username, string c
{
if (!e.Successful)
{
Log.Error($"[Twitch PubSub] Failed to listen! Response: {e.Response}");
Log.Error($"[Twitch PubSub] Failed to listen! Response: {JsonConvert.SerializeObject(e.Response)}");
}
else
{
Log.Info($"[Twitch PubSub] Listening to {e.Topic} - {e.Response}");
Log.Info($"[Twitch PubSub] Listening to {e.Topic} - {JsonConvert.SerializeObject(e.Response)}");
}
};
TwitchPubSub.OnRewardRedeemed += OnRewardRedeemed;
// ListenToChannelPoints
TwitchPubSub.OnChannelPointsRewardRedeemed += OnRewardRedeemed;
// ListenToBitsEventsV2 - This is taken care of automatically via the "OnMessageReceived" event
// TwitchPubSub.OnBitsReceivedV2 += OnBitsReceivedV2;
Log.Info("[Twitch PubSub] Connecting...");
TwitchPubSub.Connect();
TwitchPubSub.ConnectAsync();
}
}

public void Disconnect()
{
LogDebug("TwitchManager::Disconnect");
if (TwitchClient != null)
{
TwitchClient.Disconnect();
TwitchClient = null;
}
if (TwitchPubSub != null)
{
TwitchPubSub.Disconnect();
TwitchPubSub.DisconnectAsync();
TwitchPubSub = null;
}
if (TwitchClient != null)
{
TwitchClient.DisconnectAsync();
TwitchClient = null;
}
if (TwitchApi != null)
{
TwitchApi = null;
Expand All @@ -168,23 +179,18 @@ public void SendMessage(string message)
Log.Warning("[Twitch Client] Not connected to Twitch!");
return;
}
TwitchClient.SendMessage(Channel, message);
}

private void TwitchClient_OnConnected(object sender, OnConnectedArgs e)
{
Log.Info("[Twitch Client] Connected to Twitch using username: " + e.BotUsername);
TwitchClient.SendMessageAsync(Channel, message);
}

private void TwitchPubSub_OnLog(object sender, TwitchLib.PubSub.Events.OnLogArgs e)
{
LogDebug($"[Twitch PubSub] {e.Data}");
}

private void TwitchClient_OnLog(object sender, TwitchLib.Client.Events.OnLogArgs e)
{
LogDebug($"[Twitch Client] {e.DateTime}: {e.BotUsername} - {e.Data}");
}
//private void TwitchClient_OnLog(object sender, TwitchLib.Client.Events.OnLogArgs e)
//{
// LogDebug($"[Twitch Client] {e.DateTime}: {e.BotUsername} - {e.Data}");
//}

private void LogDebug(string message)
{
Expand Down
Loading

0 comments on commit 32802f3

Please sign in to comment.