mirror of
https://github.com/barelyprofessional/KfChatDotNet.git
synced 2026-05-02 04:22:04 -04:00
Renamed the bot from KickBot -> ChatBot and removed the reference to Kick in the project name
This commit is contained in:
89
KfChatDotNetBot/Services/BotCommands.cs
Normal file
89
KfChatDotNetBot/Services/BotCommands.cs
Normal file
@@ -0,0 +1,89 @@
|
||||
using Humanizer;
|
||||
using KfChatDotNetBot.Commands;
|
||||
using KfChatDotNetWsClient.Models.Events;
|
||||
using NLog;
|
||||
|
||||
namespace KfChatDotNetBot.Services;
|
||||
|
||||
// Took one look at GambaSesh's code, and it made my head explode
|
||||
// This implementation is inspired by similar bot I wrote years ago
|
||||
internal class BotCommands
|
||||
{
|
||||
private ChatBot _bot;
|
||||
private Logger _logger = LogManager.GetCurrentClassLogger();
|
||||
private char CommandPrefix = '!';
|
||||
private IEnumerable<ICommand> Commands;
|
||||
private CancellationToken _cancellationToken;
|
||||
private List<Task> _commandTasks = [];
|
||||
|
||||
internal BotCommands(ChatBot bot, CancellationToken? ctx = null)
|
||||
{
|
||||
_cancellationToken = ctx ?? CancellationToken.None;
|
||||
_bot = bot;
|
||||
var interfaceType = typeof(ICommand);
|
||||
Commands =
|
||||
AppDomain.CurrentDomain.GetAssemblies()
|
||||
.SelectMany(x => x.GetTypes())
|
||||
.Where(x => interfaceType.IsAssignableFrom(x) && x is { IsInterface: false, IsAbstract: false })
|
||||
.Select(Activator.CreateInstance).Cast<ICommand>();
|
||||
|
||||
foreach (var command in Commands)
|
||||
{
|
||||
_logger.Debug($"Found command {command.GetType().Name}");
|
||||
}
|
||||
}
|
||||
|
||||
internal void ProcessMessage(MessageModel message)
|
||||
{
|
||||
if (string.IsNullOrEmpty(message.MessageRaw))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!message.MessageRaw.StartsWith(CommandPrefix))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var messageTrimmed = message.MessageRaw.TrimStart(CommandPrefix);
|
||||
foreach (var command in Commands)
|
||||
{
|
||||
foreach (var regex in command.Patterns)
|
||||
{
|
||||
var match = regex.Match(messageTrimmed);
|
||||
if (!match.Success) continue;
|
||||
_logger.Debug($"Message matches {regex}");
|
||||
using var db = new ApplicationDbContext();
|
||||
var user = db.Users.FirstOrDefault(u => u.KfId == message.Author.Id);
|
||||
// This should never happen as brand-new users are created upon join
|
||||
if (user == null) return;
|
||||
if (user.UserRight < command.RequiredRight)
|
||||
{
|
||||
_bot.SendChatMessage($"@{message.Author.Username}, you do not have access to use this command. Your rank: {user.UserRight.Humanize()}; Required rank: {command.RequiredRight.Humanize()}", true);
|
||||
break;
|
||||
}
|
||||
var task = Task.Run(() => command.RunCommand(_bot, message, match.Groups, _cancellationToken), _cancellationToken);
|
||||
_commandTasks.Add(task);
|
||||
}
|
||||
}
|
||||
|
||||
// Check on the state of the tasks, there's no way to know what error they produce if they failed otherwise
|
||||
List<Task> removals = [];
|
||||
foreach (var task in _commandTasks)
|
||||
{
|
||||
if (!task.IsCompleted) continue;
|
||||
if (task.IsFaulted)
|
||||
{
|
||||
_logger.Error("Command task failed at some point");
|
||||
_logger.Error(task.Exception);
|
||||
}
|
||||
|
||||
removals.Add(task);
|
||||
}
|
||||
// .NET doesn't support modifying a collection you're iterating over
|
||||
foreach (var removal in removals)
|
||||
{
|
||||
_commandTasks.Remove(removal);
|
||||
}
|
||||
}
|
||||
}
|
||||
257
KfChatDotNetBot/Services/Discord.cs
Normal file
257
KfChatDotNetBot/Services/Discord.cs
Normal file
@@ -0,0 +1,257 @@
|
||||
using System.Net;
|
||||
using System.Net.WebSockets;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using NLog;
|
||||
using Websocket.Client;
|
||||
|
||||
namespace KfChatDotNetBot.Services;
|
||||
|
||||
public class DiscordService : IDisposable
|
||||
{
|
||||
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
|
||||
private WebsocketClient _wsClient;
|
||||
private readonly Uri _wsUri = new Uri("wss://gateway.discord.gg/?encoding=json&v=9");
|
||||
// Not sure what a good value for this would be
|
||||
private const int ReconnectTimeout = 60;
|
||||
private readonly string? _proxy;
|
||||
private readonly string _authorization;
|
||||
private int _sequence;
|
||||
private const string UserAgent = "Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0";
|
||||
|
||||
public delegate void MessageReceivedEventHandler(object sender, DiscordMessageModel message);
|
||||
public delegate void PresenceUpdateEventHandler(object sender, DiscordPresenceUpdateModel presence);
|
||||
public delegate void WsDisconnectionEventHandler(object sender, DisconnectionInfo e);
|
||||
public delegate void InvalidCredentialsEventHandler(object sender, DiscordPacketReadModel packet);
|
||||
public event MessageReceivedEventHandler OnMessageReceived;
|
||||
public event PresenceUpdateEventHandler OnPresenceUpdated;
|
||||
public event WsDisconnectionEventHandler OnWsDisconnection;
|
||||
public event InvalidCredentialsEventHandler OnInvalidCredentials;
|
||||
|
||||
private readonly CancellationToken _cancellationToken = CancellationToken.None;
|
||||
private readonly CancellationTokenSource _pingCts = new();
|
||||
private Task? _heartbeatTask;
|
||||
// Discord tells us the heartbeat interval to use in the op 10 response so this is just a placeholder
|
||||
private TimeSpan _heartbeatInterval = TimeSpan.FromSeconds(40);
|
||||
|
||||
public DiscordService(string authorization, string? proxy = null, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
_proxy = proxy;
|
||||
if (cancellationToken != null) _cancellationToken = cancellationToken.Value;
|
||||
_authorization = authorization;
|
||||
_logger.Info("Discord Service created");
|
||||
}
|
||||
|
||||
public async Task StartWsClient()
|
||||
{
|
||||
_logger.Debug("StartWsClient() called, creating client");
|
||||
await CreateWsClient();
|
||||
}
|
||||
|
||||
private async Task CreateWsClient()
|
||||
{
|
||||
var factory = new Func<ClientWebSocket>(() =>
|
||||
{
|
||||
var clientWs = new ClientWebSocket();
|
||||
clientWs.Options.SetRequestHeader("Origin", "https://discord.com");
|
||||
clientWs.Options.SetRequestHeader("User-Agent", UserAgent);
|
||||
if (_proxy == null) return clientWs;
|
||||
_logger.Debug($"Using proxy address {_proxy}");
|
||||
clientWs.Options.Proxy = new WebProxy(_proxy);
|
||||
return clientWs;
|
||||
});
|
||||
|
||||
var client = new WebsocketClient(_wsUri, factory)
|
||||
{
|
||||
ReconnectTimeout = TimeSpan.FromSeconds(ReconnectTimeout),
|
||||
IsReconnectionEnabled = false
|
||||
};
|
||||
|
||||
client.ReconnectionHappened.Subscribe(WsReconnection);
|
||||
client.MessageReceived.Subscribe(WsMessageReceived);
|
||||
client.DisconnectionHappened.Subscribe(WsDisconnection);
|
||||
|
||||
_wsClient = client;
|
||||
|
||||
_logger.Debug("Websocket client has been built, about to start");
|
||||
await client.Start();
|
||||
_logger.Debug("Websocket client started!");
|
||||
}
|
||||
public bool IsConnected()
|
||||
{
|
||||
return _wsClient is { IsRunning: true };
|
||||
}
|
||||
|
||||
private async Task HeartbeatTimer()
|
||||
{
|
||||
using var timer = new PeriodicTimer(_heartbeatInterval);
|
||||
while (await timer.WaitForNextTickAsync(_pingCts.Token))
|
||||
{
|
||||
if (_wsClient == null)
|
||||
{
|
||||
_logger.Debug("_wsClient doesn't exist yet, not going to try ping");
|
||||
continue;
|
||||
}
|
||||
var heartbeatPacket = JsonSerializer.Serialize(new DiscordPacketWriteModel
|
||||
{
|
||||
OpCode = 1,
|
||||
Sequence = _sequence,
|
||||
});
|
||||
_logger.Debug("Sending heartbeat packet");
|
||||
_logger.Debug(heartbeatPacket);
|
||||
await _wsClient.SendInstant(heartbeatPacket);
|
||||
}
|
||||
}
|
||||
|
||||
private void WsDisconnection(DisconnectionInfo disconnectionInfo)
|
||||
{
|
||||
_logger.Error($"Client disconnected from Discord (or never successfully connected). Type is {disconnectionInfo.Type}");
|
||||
_logger.Error($"Close Status => {disconnectionInfo.CloseStatus}; Close Status Description => {disconnectionInfo.CloseStatusDescription}");
|
||||
_logger.Error(disconnectionInfo.Exception);
|
||||
OnWsDisconnection?.Invoke(this, disconnectionInfo);
|
||||
}
|
||||
|
||||
private void WsReconnection(ReconnectionInfo reconnectionInfo)
|
||||
{
|
||||
_logger.Error($"Websocket connection dropped and reconnected. Reconnection type is {reconnectionInfo.Type}");
|
||||
}
|
||||
|
||||
private void WsMessageReceived(ResponseMessage message)
|
||||
{
|
||||
if (message.Text == null)
|
||||
{
|
||||
_logger.Info("Discord sent a null message");
|
||||
return;
|
||||
}
|
||||
|
||||
_logger.Debug($"Received event from Discord: {message.Text}");
|
||||
|
||||
try
|
||||
{
|
||||
var packet = JsonSerializer.Deserialize<DiscordPacketReadModel>(message.Text);
|
||||
if (packet == null) throw new InvalidOperationException("Caught a null when deserializing Discord packet");
|
||||
_sequence = packet.Sequence ?? _sequence;
|
||||
if (packet.OpCode == 9)
|
||||
{
|
||||
_logger.Info("Discord sent op code indicating invalid credentials. Raising event.");
|
||||
OnInvalidCredentials?.Invoke(this, packet);
|
||||
return;
|
||||
}
|
||||
|
||||
if (packet.OpCode == 10)
|
||||
{
|
||||
_logger.Info("Discord op code 10 (hello) received. Setting up heartbeat timer and sending init");
|
||||
_logger.Info("Sending connection_init");
|
||||
var initPayload =
|
||||
"{\"op\":2,\"d\":{\"token\":\"" + _authorization + "\",\"capabilities\":30717,\"properties\":" +
|
||||
"{\"os\":\"Linux\",\"browser\":\"Firefox\",\"device\":\"\",\"system_locale\":\"en-US\",\"browser_user_agent\":" +
|
||||
"\"" + UserAgent + "\",\"browser_version\":\"115.0\",\"os_version\":\"\",\"referrer\":\"\",\"referring_domain\":\"\"," +
|
||||
"\"referrer_current\":\"\",\"referring_domain_current\":\"\",\"release_channel\":\"stable\"," +
|
||||
"\"client_build_number\":306208,\"client_event_source\":null,\"design_id\":0},\"presence\":{\"status\":\"unknown\"," +
|
||||
"\"since\":0,\"activities\":[],\"afk\":false},\"compress\":false,\"client_state\":{\"guild_versions\":{}}}}";
|
||||
_logger.Debug(initPayload);
|
||||
_wsClient.SendInstant(initPayload).Wait(_cancellationToken);
|
||||
_heartbeatInterval =
|
||||
TimeSpan.FromMilliseconds(packet.Data.GetProperty("heartbeat_interval").GetInt32());
|
||||
if (_heartbeatTask != null) return;
|
||||
_heartbeatTask = Task.Run(HeartbeatTimer, _cancellationToken);
|
||||
return;
|
||||
}
|
||||
|
||||
if (packet.OpCode == 11)
|
||||
{
|
||||
_logger.Info("Received heartbeat ack from Discord");
|
||||
return;
|
||||
}
|
||||
|
||||
if (packet.OpCode != 0)
|
||||
{
|
||||
_logger.Info($"Op code {packet.OpCode} was unhandled. JSON follows");
|
||||
_logger.Info(message.Text);
|
||||
return;
|
||||
}
|
||||
|
||||
switch (packet.DispatchEvent)
|
||||
{
|
||||
case null:
|
||||
throw new InvalidOperationException("t was null");
|
||||
case "READY":
|
||||
_logger.Info("Discord is now ready");
|
||||
return;
|
||||
case "PRESENCE_UPDATE":
|
||||
OnPresenceUpdated?.Invoke(this,
|
||||
packet.Data.Deserialize<DiscordPresenceUpdateModel>() ?? throw new InvalidOperationException());
|
||||
return;
|
||||
case "MESSAGE_CREATE":
|
||||
OnMessageReceived?.Invoke(this,
|
||||
packet.Data.Deserialize<DiscordMessageModel>() ?? throw new InvalidOperationException());
|
||||
return;
|
||||
default:
|
||||
_logger.Debug($"{packet.DispatchEvent} was unhandled. JSON follows");
|
||||
_logger.Debug(message.Text);
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.Error("Failed to handle message from Discord");
|
||||
_logger.Error(e);
|
||||
_logger.Error("--- JSON Payload ---");
|
||||
_logger.Error(message.Text);
|
||||
_logger.Error("--- End of JSON Payload ---");
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_logger.Info("Disposing of the Discord service");
|
||||
_wsClient.Dispose();
|
||||
_pingCts.Cancel();
|
||||
_pingCts.Dispose();
|
||||
_heartbeatTask?.Dispose();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
|
||||
public class DiscordPacketModel<T>
|
||||
{
|
||||
[JsonPropertyName("t")]
|
||||
public string? DispatchEvent { get; set; }
|
||||
[JsonPropertyName("op")]
|
||||
public int OpCode { get; set; }
|
||||
[JsonPropertyName("d")]
|
||||
public T? Data { get; set; }
|
||||
[JsonPropertyName("s")]
|
||||
public int? Sequence { get; set; }
|
||||
}
|
||||
|
||||
public class DiscordPacketWriteModel : DiscordPacketModel<object>;
|
||||
public class DiscordPacketReadModel : DiscordPacketModel<JsonElement>;
|
||||
|
||||
public class DiscordPresenceUpdateModel
|
||||
{
|
||||
[JsonPropertyName("user")]
|
||||
public required DiscordUserModel User { get; set; }
|
||||
[JsonPropertyName("status")]
|
||||
public required string Status { get; set; }
|
||||
[JsonPropertyName("client_status")]
|
||||
public required Dictionary<string, string> ClientStatus { get; set; }
|
||||
}
|
||||
|
||||
public class DiscordUserModel
|
||||
{
|
||||
[JsonPropertyName("id")]
|
||||
public required string Id { get; set; }
|
||||
[JsonPropertyName("username")]
|
||||
public string? Username { get; set; }
|
||||
}
|
||||
|
||||
public class DiscordMessageModel
|
||||
{
|
||||
[JsonPropertyName("content")]
|
||||
public string? Content { get; set; }
|
||||
[JsonPropertyName("author")]
|
||||
public required DiscordUserModel Author { get; set; }
|
||||
[JsonPropertyName("attachments")]
|
||||
public JsonElement[]? Attachments { get; set; }
|
||||
}
|
||||
176
KfChatDotNetBot/Services/Howlgg.cs
Normal file
176
KfChatDotNetBot/Services/Howlgg.cs
Normal file
@@ -0,0 +1,176 @@
|
||||
using System.Net;
|
||||
using System.Net.WebSockets;
|
||||
using System.Text.Json;
|
||||
using KfChatDotNetBot.Models;
|
||||
using NLog;
|
||||
using Websocket.Client;
|
||||
|
||||
namespace KfChatDotNetBot.Services;
|
||||
|
||||
public class Howlgg : IDisposable
|
||||
{
|
||||
private Logger _logger = LogManager.GetCurrentClassLogger();
|
||||
private WebsocketClient _wsClient;
|
||||
private Uri _wsUri = new("wss://howl.gg/socket.io/?EIO=3&transport=websocket");
|
||||
// Howl will send its own timeout but seems it's always 30 seconds
|
||||
private int _reconnectTimeout = 30;
|
||||
private string? _proxy;
|
||||
public delegate void OnHowlggBetHistoryResponse(object sender, HowlggBetHistoryResponseModel data);
|
||||
public delegate void OnWsDisconnectionEventHandler(object sender, DisconnectionInfo e);
|
||||
public event OnHowlggBetHistoryResponse OnHowlggBetHistory;
|
||||
public event OnWsDisconnectionEventHandler OnWsDisconnection;
|
||||
private CancellationToken _cancellationToken = CancellationToken.None;
|
||||
private CancellationTokenSource _pingCts = new();
|
||||
private Task? _heartbeatTask;
|
||||
// Howl.gg tells us the heartbeat interval to use in the initial payload so this is just a placeholder
|
||||
private TimeSpan _heartbeatInterval = TimeSpan.FromSeconds(40);
|
||||
|
||||
public Howlgg(string? proxy = null, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
_proxy = proxy;
|
||||
if (cancellationToken != null) _cancellationToken = cancellationToken.Value;
|
||||
_logger.Info("Howlgg WebSocket client created");
|
||||
}
|
||||
|
||||
public async Task StartWsClient()
|
||||
{
|
||||
_logger.Debug("StartWsClient() called, creating client");
|
||||
await CreateWsClient();
|
||||
}
|
||||
|
||||
private async Task CreateWsClient()
|
||||
{
|
||||
var factory = new Func<ClientWebSocket>(() =>
|
||||
{
|
||||
var clientWs = new ClientWebSocket();
|
||||
clientWs.Options.SetRequestHeader("Origin", "https://howl.gg");
|
||||
clientWs.Options.SetRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:126.0) Gecko/20100101 Firefox/126.0");
|
||||
if (_proxy == null) return clientWs;
|
||||
_logger.Debug($"Using proxy address {_proxy}");
|
||||
clientWs.Options.Proxy = new WebProxy(_proxy);
|
||||
return clientWs;
|
||||
});
|
||||
|
||||
var client = new WebsocketClient(_wsUri, factory)
|
||||
{
|
||||
ReconnectTimeout = TimeSpan.FromSeconds(_reconnectTimeout),
|
||||
IsReconnectionEnabled = false
|
||||
};
|
||||
|
||||
client.ReconnectionHappened.Subscribe(WsReconnection);
|
||||
client.MessageReceived.Subscribe(WsMessageReceived);
|
||||
client.DisconnectionHappened.Subscribe(WsDisconnection);
|
||||
|
||||
_wsClient = client;
|
||||
|
||||
_logger.Debug("Websocket client has been built, about to start");
|
||||
await client.Start();
|
||||
_logger.Debug("Websocket client started!");
|
||||
}
|
||||
|
||||
public bool IsConnected()
|
||||
{
|
||||
return _wsClient is { IsRunning: true };
|
||||
}
|
||||
|
||||
public void GetUserInfo(string userId)
|
||||
{
|
||||
var packet = "42/main,0[\"getUserInfo\",{\"userOrSteamId\":\"" + userId + "\",\"interval\":\"lifetime\"}]";
|
||||
_logger.Debug($"Sending packet: {packet}");
|
||||
_wsClient.Send(packet);
|
||||
}
|
||||
|
||||
private async Task HeartbeatTimer()
|
||||
{
|
||||
using var timer = new PeriodicTimer(_heartbeatInterval);
|
||||
while (await timer.WaitForNextTickAsync(_pingCts.Token))
|
||||
{
|
||||
if (_wsClient == null)
|
||||
{
|
||||
_logger.Debug("_wsClient doesn't exist yet, not going to try ping");
|
||||
continue;
|
||||
}
|
||||
_logger.Debug("Sending Howl.gg ping packet");
|
||||
_wsClient.Send("2");
|
||||
}
|
||||
}
|
||||
|
||||
private void WsDisconnection(DisconnectionInfo disconnectionInfo)
|
||||
{
|
||||
_logger.Error($"Client disconnected from Howl.gg (or never successfully connected). Type is {disconnectionInfo.Type}");
|
||||
_logger.Error($"Close Status => {disconnectionInfo.CloseStatus}; Close Status Description => {disconnectionInfo.CloseStatusDescription}");
|
||||
_logger.Error(disconnectionInfo.Exception);
|
||||
OnWsDisconnection?.Invoke(this, disconnectionInfo);
|
||||
}
|
||||
|
||||
private void WsReconnection(ReconnectionInfo reconnectionInfo)
|
||||
{
|
||||
_logger.Error($"Websocket connection dropped and reconnected. Reconnection type is {reconnectionInfo.Type}");
|
||||
}
|
||||
|
||||
private void WsMessageReceived(ResponseMessage message)
|
||||
{
|
||||
if (message.Text == null)
|
||||
{
|
||||
_logger.Info("Howl.gg sent a null message");
|
||||
return;
|
||||
}
|
||||
_logger.Trace($"Received event from Howl.gg: {message.Text}");
|
||||
|
||||
try
|
||||
{
|
||||
var packetType = message.Text.Split('/')[0];
|
||||
if (packetType == "3")
|
||||
{
|
||||
_logger.Info("Received pong from Howl.gg");
|
||||
return;
|
||||
}
|
||||
|
||||
// For some reason there's no / for the initial connection
|
||||
if (packetType.StartsWith("0{"))
|
||||
{
|
||||
// Received on initial connection
|
||||
var packetData = JsonSerializer.Deserialize<JsonElement>(message.Text.TrimStart('0'));
|
||||
_heartbeatInterval = TimeSpan.FromMilliseconds(packetData.GetProperty("pingInterval").GetInt32());
|
||||
_logger.Info("Received connection packet from Howl.gg. Setting up heartbeat timer");
|
||||
if (_heartbeatTask != null) return;
|
||||
_heartbeatTask = Task.Run(HeartbeatTimer, _cancellationToken);
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.Text == "40")
|
||||
{
|
||||
_logger.Trace("Ready to subscribe, sending main subscription");
|
||||
_wsClient.Send("40/main,");
|
||||
// To indicate successful subscription it echoes back the channel to you
|
||||
return;
|
||||
}
|
||||
|
||||
if (packetType == "43")
|
||||
{
|
||||
// Bet History
|
||||
var jsonPayload = message.Text.Replace("43/main,0[null,", string.Empty).TrimEnd(']');
|
||||
var data = JsonSerializer.Deserialize<HowlggBetHistoryResponseModel>(jsonPayload);
|
||||
if (data != null) OnHowlggBetHistory?.Invoke(this, data);
|
||||
return;
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.Error("Failed to handle message from Howl.gg");
|
||||
_logger.Error(e);
|
||||
_logger.Error("--- Payload ---");
|
||||
_logger.Error(message.Text);
|
||||
_logger.Error("--- End of Payload ---");
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_wsClient.Dispose();
|
||||
_pingCts.Cancel();
|
||||
_pingCts.Dispose();
|
||||
_heartbeatTask?.Dispose();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
187
KfChatDotNetBot/Services/Jackpot.cs
Normal file
187
KfChatDotNetBot/Services/Jackpot.cs
Normal file
@@ -0,0 +1,187 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Net.WebSockets;
|
||||
using System.Text.Json;
|
||||
using KfChatDotNetBot.Models;
|
||||
using NLog;
|
||||
using Websocket.Client;
|
||||
|
||||
namespace KfChatDotNetBot.Services;
|
||||
|
||||
public class Jackpot : IDisposable
|
||||
{
|
||||
private Logger _logger = LogManager.GetCurrentClassLogger();
|
||||
private WebsocketClient _wsClient;
|
||||
private Uri _wsUri = new("wss://api.jackpot.bet/feeds/websocket");
|
||||
// Ping interval is 30 seconds
|
||||
private int _reconnectTimeout = 60;
|
||||
private string? _proxy;
|
||||
public delegate void OnJackpotBetEventHandler(object sender, JackpotWsBetPayloadModel data);
|
||||
public delegate void OnWsDisconnectionEventHandler(object sender, DisconnectionInfo e);
|
||||
public event OnJackpotBetEventHandler OnJackpotBet;
|
||||
public event OnWsDisconnectionEventHandler OnWsDisconnection;
|
||||
private CancellationToken _cancellationToken = CancellationToken.None;
|
||||
private CancellationTokenSource _pingCts = new();
|
||||
private Task? _heartbeatTask;
|
||||
// There's no smarts, it just does 30-second pings
|
||||
private TimeSpan _heartbeatInterval = TimeSpan.FromSeconds(30);
|
||||
|
||||
public Jackpot(string? proxy = null, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
_proxy = proxy;
|
||||
if (cancellationToken != null) _cancellationToken = cancellationToken.Value;
|
||||
_logger.Info("Jackpot WebSocket client created");
|
||||
}
|
||||
|
||||
public async Task StartWsClient()
|
||||
{
|
||||
_logger.Debug("StartWsClient() called, creating client");
|
||||
await CreateWsClient();
|
||||
}
|
||||
|
||||
private async Task CreateWsClient()
|
||||
{
|
||||
var factory = new Func<ClientWebSocket>(() =>
|
||||
{
|
||||
var clientWs = new ClientWebSocket();
|
||||
clientWs.Options.SetRequestHeader("Origin", "https://jackpot.bet");
|
||||
clientWs.Options.SetRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:126.0) Gecko/20100101 Firefox/126.0");
|
||||
if (_proxy == null) return clientWs;
|
||||
_logger.Debug($"Using proxy address {_proxy}");
|
||||
clientWs.Options.Proxy = new WebProxy(_proxy);
|
||||
return clientWs;
|
||||
});
|
||||
|
||||
var client = new WebsocketClient(_wsUri, factory)
|
||||
{
|
||||
ReconnectTimeout = TimeSpan.FromSeconds(_reconnectTimeout),
|
||||
IsReconnectionEnabled = false
|
||||
};
|
||||
|
||||
client.ReconnectionHappened.Subscribe(WsReconnection);
|
||||
client.MessageReceived.Subscribe(WsMessageReceived);
|
||||
client.DisconnectionHappened.Subscribe(WsDisconnection);
|
||||
|
||||
_wsClient = client;
|
||||
|
||||
_logger.Debug("Websocket client has been built, about to start");
|
||||
await client.Start();
|
||||
_logger.Debug("Websocket client started!");
|
||||
}
|
||||
|
||||
public bool IsConnected()
|
||||
{
|
||||
return _wsClient is { IsRunning: true };
|
||||
}
|
||||
|
||||
private async Task HeartbeatTimer()
|
||||
{
|
||||
using var timer = new PeriodicTimer(_heartbeatInterval);
|
||||
while (await timer.WaitForNextTickAsync(_pingCts.Token))
|
||||
{
|
||||
if (_wsClient == null)
|
||||
{
|
||||
_logger.Debug("_wsClient doesn't exist yet, not going to try ping");
|
||||
continue;
|
||||
}
|
||||
_logger.Debug("Sending Jackpot ping packet");
|
||||
_wsClient.Send("{\"id\":\"lfgkenokasino\",\"type\":\"ping\"}");
|
||||
}
|
||||
}
|
||||
|
||||
private void WsDisconnection(DisconnectionInfo disconnectionInfo)
|
||||
{
|
||||
_logger.Error($"Client disconnected from Jackpot (or never successfully connected). Type is {disconnectionInfo.Type}");
|
||||
_logger.Error($"Close Status => {disconnectionInfo.CloseStatus}; Close Status Description => {disconnectionInfo.CloseStatusDescription}");
|
||||
_logger.Error(disconnectionInfo.Exception);
|
||||
OnWsDisconnection?.Invoke(this, disconnectionInfo);
|
||||
}
|
||||
|
||||
private void WsReconnection(ReconnectionInfo reconnectionInfo)
|
||||
{
|
||||
_logger.Error($"Websocket connection dropped and reconnected. Reconnection type is {reconnectionInfo.Type}");
|
||||
if (reconnectionInfo.Type == ReconnectionType.Initial)
|
||||
{
|
||||
_logger.Debug("Sending initial payload");
|
||||
_wsClient.Send("{\"id\":\"lfgkenokasinoinit\",\"type\":\"connection_init\"}");
|
||||
}
|
||||
}
|
||||
|
||||
private void WsMessageReceived(ResponseMessage message)
|
||||
{
|
||||
if (message.Text == null)
|
||||
{
|
||||
_logger.Info("Jackpot sent a null message");
|
||||
return;
|
||||
}
|
||||
_logger.Debug($"Received event from Jackpot: {message.Text}");
|
||||
|
||||
try
|
||||
{
|
||||
var packet = JsonSerializer.Deserialize<JackpotWsPacketModel>(message.Text);
|
||||
if (packet == null) throw new InvalidOperationException("Caught a null when deserializing Jackpot packet");
|
||||
if (packet.Type == "pong")
|
||||
{
|
||||
_logger.Info("Received pong from Jackpot");
|
||||
return;
|
||||
}
|
||||
|
||||
if (packet.Type == "connection_ack")
|
||||
{
|
||||
_logger.Debug("Received ack from Jackpot. Sending subscription");
|
||||
_wsClient.Send(
|
||||
"{\"id\":\"lfgkenokasinoallbets\",\"type\":\"subscribe\",\"payload\":{\"feed\":\"all_bets\"}}\n");
|
||||
_logger.Debug("Setting up heartbeat timer");
|
||||
if (_heartbeatTask != null) return;
|
||||
_heartbeatTask = Task.Run(HeartbeatTimer, _cancellationToken);
|
||||
return;
|
||||
}
|
||||
|
||||
if (packet.Type == "data")
|
||||
{
|
||||
_logger.Debug("Received bet from Jackpot");
|
||||
if (packet.Payload == null)
|
||||
throw new InvalidOperationException("Payload can't be null when type is data");
|
||||
var data = packet.Payload.Value.Deserialize<JackpotWsBetPayloadModel>();
|
||||
if (data == null) throw new InvalidOperationException("Payload deserialized to a null");
|
||||
OnJackpotBet?.Invoke(this, data);
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.Error("Failed to handle message from Jackpot");
|
||||
_logger.Error(e);
|
||||
_logger.Error("--- Payload ---");
|
||||
_logger.Error(message.Text);
|
||||
_logger.Error("--- End of Payload ---");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<JackpotQuickviewModel> GetJackpotUser(string username)
|
||||
{
|
||||
var url = $"https://api.jackpot.bet/user/quickview/{username}";
|
||||
_logger.Debug($"Formatted URL for quickview: {url}");
|
||||
var handler = new HttpClientHandler { AutomaticDecompression = DecompressionMethods.All };
|
||||
if (_proxy != null)
|
||||
{
|
||||
handler.UseProxy = false;
|
||||
handler.Proxy = new WebProxy(_proxy);
|
||||
_logger.Debug($"Configured to use proxy {_proxy}");
|
||||
}
|
||||
|
||||
using var client = new HttpClient(handler);
|
||||
var response = await client.GetAsync(url, _cancellationToken);
|
||||
var content = await response.Content.ReadFromJsonAsync<JackpotQuickviewModel>(_cancellationToken);
|
||||
if (content == null) throw new Exception("Failed to deserialize Jackpot quickview data");
|
||||
return content;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_wsClient.Dispose();
|
||||
_pingCts.Cancel();
|
||||
_pingCts.Dispose();
|
||||
_heartbeatTask?.Dispose();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
83
KfChatDotNetBot/Services/KfTokenService.cs
Normal file
83
KfChatDotNetBot/Services/KfTokenService.cs
Normal file
@@ -0,0 +1,83 @@
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using NLog;
|
||||
using PuppeteerSharp;
|
||||
|
||||
namespace KfChatDotNetBot.Services;
|
||||
|
||||
public class KfTokenService
|
||||
{
|
||||
// Shout out Gamba Sesh for open sourcing his token retriever which heavily inspired this implementation
|
||||
public static async Task<string> FetchSessionTokenAsync(string domain, string username, string password, string browserPath, string? proxy = null)
|
||||
{
|
||||
var logger = LogManager.GetCurrentClassLogger();
|
||||
var browserFetcher = new BrowserFetcher(new BrowserFetcherOptions
|
||||
{ Browser = SupportedBrowser.Chromium, Path = browserPath });
|
||||
if (proxy != null)
|
||||
{
|
||||
browserFetcher.WebProxy = new WebProxy(proxy);
|
||||
logger.Debug($"Detected proxy settings for browser download: {proxy}");
|
||||
}
|
||||
|
||||
var installedBrowser = await browserFetcher.DownloadAsync();
|
||||
logger.Debug("Downloaded browser");
|
||||
List<string> launchArgs = ["--no-sandbox"];
|
||||
if (proxy != null)
|
||||
{
|
||||
logger.Debug($"Configuring Chromium to use proxy {proxy}");
|
||||
launchArgs.Add($"--proxy-server=\"{proxy}\"");
|
||||
}
|
||||
|
||||
var launchOptions = new LaunchOptions
|
||||
{
|
||||
Headless = false, ExecutablePath = installedBrowser.GetExecutablePath(), UserDataDir = "kf_profile",
|
||||
Args = launchArgs.ToArray()
|
||||
};
|
||||
|
||||
await using var browser = await Puppeteer.LaunchAsync(launchOptions);
|
||||
await using var page = await browser.NewPageAsync();
|
||||
await page.GoToAsync($"https://{domain}/login");
|
||||
await page.WaitForSelectorAsync("img[alt=\"Kiwi Farms\"]");
|
||||
if (await page.QuerySelectorAsync("html[data-template=\"login\"]") == null)
|
||||
{
|
||||
logger.Debug("Page template is not login. This is expected if we're already logged in. Reloading page to get the freshest cookies then retrieving");
|
||||
await page.ReloadAsync();
|
||||
return await GetXfSessionCookie();
|
||||
}
|
||||
|
||||
var usernameFieldSelector = await page.QuerySelectorAsync("input[autocomplete=\"username\"]");
|
||||
var passwordFieldSelector = await page.QuerySelectorAsync("input[autocomplete=\"current-password\"]");
|
||||
var loginButtonSelector = await page.QuerySelectorAsync("div[class=\"formSubmitRow-controls\"] > button[type=\"submit\"]");
|
||||
if (usernameFieldSelector == null || passwordFieldSelector == null || loginButtonSelector == null)
|
||||
{
|
||||
// Realistically this shouldn't happen unless Null changes the login template in a big way
|
||||
logger.Error("Username/password fields could not be found");
|
||||
throw new MissingLoginElementsException();
|
||||
}
|
||||
|
||||
await usernameFieldSelector.TypeAsync(username);
|
||||
await passwordFieldSelector.TypeAsync(password);
|
||||
await loginButtonSelector.ClickAsync();
|
||||
logger.Debug("Login fields have been filled out and button clicked. Awaiting page navigation.");
|
||||
await page.WaitForNavigationAsync();
|
||||
logger.Debug("Navigation completed. Doing the cookie needful");
|
||||
return await GetXfSessionCookie();
|
||||
|
||||
async Task<string> GetXfSessionCookie()
|
||||
{
|
||||
var cookies = await page.GetCookiesAsync();
|
||||
var xfSession = cookies.FirstOrDefault(x => x.Name == "xf_session");
|
||||
if (xfSession == null)
|
||||
{
|
||||
logger.Error("xf_session cookie not set. Cookie data follows");
|
||||
logger.Error(JsonSerializer.Serialize(cookies));
|
||||
throw new MissingSessionCookieException();
|
||||
}
|
||||
logger.Debug($"Returning xf_session value: {xfSession.Value}");
|
||||
return xfSession.Value;
|
||||
}
|
||||
}
|
||||
|
||||
public class MissingSessionCookieException : Exception;
|
||||
public class MissingLoginElementsException : Exception;
|
||||
}
|
||||
215
KfChatDotNetBot/Services/Shuffle.cs
Normal file
215
KfChatDotNetBot/Services/Shuffle.cs
Normal file
@@ -0,0 +1,215 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Net.WebSockets;
|
||||
using System.Text.Json;
|
||||
using KfChatDotNetBot.Models;
|
||||
using NLog;
|
||||
using Websocket.Client;
|
||||
|
||||
namespace KfChatDotNetBot.Services;
|
||||
|
||||
public class Shuffle : IDisposable
|
||||
{
|
||||
private Logger _logger = LogManager.GetCurrentClassLogger();
|
||||
private WebsocketClient _wsClient;
|
||||
private Uri _wsUri = new("wss://subscription-temp.shuffle.com/graphql");
|
||||
private int _reconnectTimeout = 60;
|
||||
private string? _proxy;
|
||||
public delegate void OnLatestBetUpdatedEventHandler(object sender, ShuffleLatestBetModel bet);
|
||||
public delegate void OnWsDisconnectionEventHandler(object sender, DisconnectionInfo e);
|
||||
public event OnLatestBetUpdatedEventHandler OnLatestBetUpdated;
|
||||
public event OnWsDisconnectionEventHandler OnWsDisconnection;
|
||||
private CancellationToken _cancellationToken = CancellationToken.None;
|
||||
private CancellationTokenSource _pingCts = new();
|
||||
private Task _pingTask;
|
||||
|
||||
public Shuffle(string? proxy = null, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
_proxy = proxy;
|
||||
if (cancellationToken != null) _cancellationToken = cancellationToken.Value;
|
||||
// Moved it up here as I'm concerned about the possibility of reconnections creating multiple ping tasks
|
||||
_pingTask = PeriodicPing();
|
||||
}
|
||||
|
||||
public async Task StartWsClient()
|
||||
{
|
||||
_logger.Debug("StartWsClient() called, creating client");
|
||||
await CreateWsClient();
|
||||
}
|
||||
|
||||
private async Task CreateWsClient()
|
||||
{
|
||||
var factory = new Func<ClientWebSocket>(() =>
|
||||
{
|
||||
var clientWs = new ClientWebSocket();
|
||||
clientWs.Options.AddSubProtocol("graphql-transport-ws");
|
||||
clientWs.Options.SetRequestHeader("Origin", "https://shuffle.com");
|
||||
clientWs.Options.SetRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:126.0) Gecko/20100101 Firefox/126.0");
|
||||
if (_proxy == null) return clientWs;
|
||||
_logger.Debug($"Using proxy address {_proxy}");
|
||||
clientWs.Options.Proxy = new WebProxy(_proxy);
|
||||
return clientWs;
|
||||
});
|
||||
|
||||
var client = new WebsocketClient(_wsUri, factory)
|
||||
{
|
||||
ReconnectTimeout = TimeSpan.FromSeconds(_reconnectTimeout),
|
||||
IsReconnectionEnabled = false // Watchdog will self-destruct this instead
|
||||
};
|
||||
|
||||
client.ReconnectionHappened.Subscribe(WsReconnection);
|
||||
client.MessageReceived.Subscribe(WsMessageReceived);
|
||||
client.DisconnectionHappened.Subscribe(WsDisconnection);
|
||||
|
||||
_wsClient = client;
|
||||
|
||||
_logger.Debug("Websocket client has been built, about to start");
|
||||
await client.Start();
|
||||
_logger.Debug("Websocket client started!");
|
||||
}
|
||||
|
||||
public bool IsConnected()
|
||||
{
|
||||
return _wsClient is { IsRunning: true };
|
||||
}
|
||||
|
||||
private async Task PeriodicPing()
|
||||
{
|
||||
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(10));
|
||||
while (await timer.WaitForNextTickAsync(_pingCts.Token))
|
||||
{
|
||||
if (_wsClient == null)
|
||||
{
|
||||
_logger.Debug("_wsClient doesn't exist yet, not going to try ping");
|
||||
continue;
|
||||
}
|
||||
_logger.Debug("Sending ping to Shuffle");
|
||||
_wsClient.Send("{\"type\":\"ping\"}");
|
||||
}
|
||||
}
|
||||
|
||||
private void WsDisconnection(DisconnectionInfo disconnectionInfo)
|
||||
{
|
||||
_logger.Error($"Client disconnected from Shuffle (or never successfully connected). Type is {disconnectionInfo.Type}");
|
||||
_logger.Error($"Close Status => {disconnectionInfo.CloseStatus}; Close Status Description => {disconnectionInfo.CloseStatusDescription}");
|
||||
_logger.Error(disconnectionInfo.Exception);
|
||||
OnWsDisconnection?.Invoke(this, disconnectionInfo);
|
||||
}
|
||||
|
||||
private void WsReconnection(ReconnectionInfo reconnectionInfo)
|
||||
{
|
||||
_logger.Error($"Websocket connection dropped and reconnected. Reconnection type is {reconnectionInfo.Type}");
|
||||
_logger.Info("Sending connection_init");
|
||||
var initPayload =
|
||||
"{\"type\":\"connection_init\",\"payload\":{\"x-correlation-id\":\"pdvlnd9tej-di27abvq19-1.30.2-1i0nef1m7-g::anon\",\"authorization\":\"\"}}";
|
||||
_logger.Debug(initPayload);
|
||||
_wsClient.Send(initPayload);
|
||||
}
|
||||
|
||||
private void WsMessageReceived(ResponseMessage message)
|
||||
{
|
||||
if (message.Text == null)
|
||||
{
|
||||
_logger.Info("Shuffle sent a null message");
|
||||
return;
|
||||
}
|
||||
_logger.Trace($"Received event from Shuffle: {message.Text}");
|
||||
|
||||
try
|
||||
{
|
||||
var packet = JsonSerializer.Deserialize<JsonElement>(message.Text);
|
||||
var packetType = packet.GetProperty("type").GetString();
|
||||
|
||||
if (packetType == "connection_ack")
|
||||
{
|
||||
_logger.Debug("connection_ack packet, sending subscribe payload");
|
||||
_logger.Info("Sending subscription request");
|
||||
// we're super ghetto today
|
||||
var payload = "{\"id\":\"" + Guid.NewGuid() +
|
||||
"\",\"type\":\"subscribe\",\"payload\":{\"variables\":{},\"extensions\":{},\"operationName\":\"LatestBetUpdated\",\"query\":\"subscription LatestBetUpdated {\\n latestBetUpdated {\\n ...BetActivityFields\\n __typename\\n }\\n}\\n\\nfragment BetActivityFields on BetActivityPayload {\\n id\\n username\\n vipLevel\\n currency\\n amount\\n payout\\n multiplier\\n gameName\\n gameCategory\\n gameSlug\\n __typename\\n}\"}}";
|
||||
_logger.Debug(payload);
|
||||
_wsClient.SendInstant(payload).Wait(_cancellationToken);
|
||||
return;
|
||||
}
|
||||
|
||||
if (packetType == "pong")
|
||||
{
|
||||
_logger.Info("Shuffle pong packet");
|
||||
return;
|
||||
}
|
||||
|
||||
// GAMBA
|
||||
if (packetType == "next")
|
||||
{
|
||||
var bet = packet.GetProperty("payload").GetProperty("data").GetProperty("latestBetUpdated")
|
||||
.Deserialize<ShuffleLatestBetModel>();
|
||||
if (bet == null)
|
||||
{
|
||||
_logger.Error("Caught a null before invoking bet event");
|
||||
throw new NullReferenceException("Caught a null before invoking bet event");
|
||||
}
|
||||
OnLatestBetUpdated?.Invoke(this, bet);
|
||||
return;
|
||||
}
|
||||
_logger.Info("Message from Shuffle was unhandled");
|
||||
_logger.Info(message.Text);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.Error("Failed to handle message from Shuffle");
|
||||
_logger.Error(e);
|
||||
_logger.Error("--- JSON Payload ---");
|
||||
_logger.Error(message.Text);
|
||||
_logger.Error("--- End of JSON Payload ---");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<ShuffleUserModel> GetShuffleUser(string username)
|
||||
{
|
||||
var graphQl =
|
||||
"query GetUserProfile($username: String!) {\n user(username: $username) {\n id\n username\n vipLevel\n createdAt\n avatar\n avatarBackground\n bets\n usdWagered\n __typename\n }\n}";
|
||||
_logger.Debug($"Grabbing details for Shuffle user {username}");
|
||||
var jsonBody = new Dictionary<string, object>
|
||||
{
|
||||
{ "operationName", "GetUserProfile" },
|
||||
{ "query", graphQl },
|
||||
{ "variables", new Dictionary<string, string> { { "username", username } } }
|
||||
};
|
||||
_logger.Debug("Created dictionary object for the JSON payload, should serialize to following value:");
|
||||
_logger.Debug(JsonSerializer.Serialize(jsonBody));
|
||||
var handler = new HttpClientHandler { AutomaticDecompression = DecompressionMethods.All };
|
||||
if (_proxy != null)
|
||||
{
|
||||
handler.UseProxy = false;
|
||||
handler.Proxy = new WebProxy(_proxy);
|
||||
_logger.Debug($"Configured to use proxy {_proxy}");
|
||||
}
|
||||
|
||||
using var client = new HttpClient(handler);
|
||||
client.DefaultRequestHeaders.Add("content-type", "application/json");
|
||||
var postBody = JsonContent.Create(jsonBody);
|
||||
var response = await client.PostAsync("https://shuffle.com/graphql", postBody, _cancellationToken);
|
||||
var responseContent = await response.Content.ReadFromJsonAsync<JsonElement>(cancellationToken: _cancellationToken);
|
||||
_logger.Debug("Shuffle returned following JSON");
|
||||
_logger.Debug(responseContent.GetRawText);
|
||||
var user = responseContent.GetProperty("data").GetProperty("user");
|
||||
if (user.ValueKind == JsonValueKind.Null)
|
||||
{
|
||||
_logger.Debug("data.user was null");
|
||||
throw new ShuffleUserNotFoundException();
|
||||
}
|
||||
|
||||
return user.Deserialize<ShuffleUserModel>() ?? throw new InvalidOperationException();
|
||||
}
|
||||
|
||||
public class ShuffleUserNotFoundException : Exception;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_wsClient.Dispose();
|
||||
_pingCts.Cancel();
|
||||
_pingCts.Dispose();
|
||||
_pingTask.Dispose();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
57
KfChatDotNetBot/Services/ThreeXplPocketWatch.cs
Normal file
57
KfChatDotNetBot/Services/ThreeXplPocketWatch.cs
Normal file
@@ -0,0 +1,57 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using KfChatDotNetBot.Models;
|
||||
using NLog;
|
||||
|
||||
namespace KfChatDotNetBot.Services;
|
||||
|
||||
public class ThreeXplPocketWatch
|
||||
{
|
||||
private Logger _logger = LogManager.GetCurrentClassLogger();
|
||||
private string _3xplToken = "3A0_t3st3xplor3rpub11cb3t4efcd21748a5e";
|
||||
private string? _proxy;
|
||||
private List<PocketWatchModel> _addresses = [];
|
||||
private CancellationToken _cancellationToken = CancellationToken.None;
|
||||
public delegate void OnPocketWatchEventHandler(object sender, PocketWatchEventModel e);
|
||||
public event OnPocketWatchEventHandler OnPocketWatchEvent;
|
||||
|
||||
public ThreeXplPocketWatch(string? proxy = null, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
_logger.Info("Starting the pocket watch");
|
||||
_proxy = proxy;
|
||||
if (cancellationToken != null) _cancellationToken = cancellationToken.Value;
|
||||
}
|
||||
|
||||
private async Task CheckAddress(PocketWatchModel addy)
|
||||
{
|
||||
_logger.Debug($"Getting data for {addy.Network}/{addy.Address}");
|
||||
var data = await GetAddress(addy.Network, addy.Address);
|
||||
_logger.Debug("Received following data");
|
||||
_logger.Debug(data.GetRawText);
|
||||
var events = data.GetProperty("events").Deserialize<Dictionary<string, List<ThreeXplEventModel>>>();
|
||||
if (events == null) throw new InvalidOperationException();
|
||||
foreach (var chain in events.Keys)
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<JsonElement> GetAddress(string network, string address)
|
||||
{
|
||||
var url =
|
||||
$"https://api.3xpl.com/{network}/address/{address}?data=address,balances,events,mempool&from=all&token=3A0_t3st3xplor3rpub11cb3t4efcd21748a5e&library=currencies,rates(usd)";
|
||||
_logger.Debug($"Retrieving {url}");
|
||||
var handler = new HttpClientHandler { AutomaticDecompression = DecompressionMethods.All };
|
||||
if (_proxy != null)
|
||||
{
|
||||
handler.UseProxy = true;
|
||||
handler.Proxy = new WebProxy(_proxy);
|
||||
_logger.Debug($"Configured to use proxy {_proxy}");
|
||||
}
|
||||
|
||||
using var client = new HttpClient(handler);
|
||||
var response = await client.GetFromJsonAsync<JsonElement>(url, _cancellationToken);
|
||||
return response;
|
||||
}
|
||||
}
|
||||
215
KfChatDotNetBot/Services/Twitch.cs
Normal file
215
KfChatDotNetBot/Services/Twitch.cs
Normal file
@@ -0,0 +1,215 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Net.WebSockets;
|
||||
using System.Text.Json;
|
||||
using NLog;
|
||||
using Websocket.Client;
|
||||
|
||||
namespace KfChatDotNetBot.Services;
|
||||
|
||||
public class Twitch : IDisposable
|
||||
{
|
||||
private Logger _logger = LogManager.GetCurrentClassLogger();
|
||||
private WebsocketClient _wsClient;
|
||||
private Uri _wsUri = new("wss://pubsub-edge.twitch.tv/v1");
|
||||
private int _reconnectTimeout = 300;
|
||||
private string? _proxy;
|
||||
private List<int> _channels;
|
||||
public delegate void OnStreamStateUpdateEventHandler(object sender, int channelId, bool isLive);
|
||||
public event OnStreamStateUpdateEventHandler OnStreamStateUpdated;
|
||||
private CancellationToken _cancellationToken = CancellationToken.None;
|
||||
private Task? _pingTask = null;
|
||||
private CancellationTokenSource _pingCts = new();
|
||||
|
||||
public Twitch(List<int> channels, string? proxy = null, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
_proxy = proxy;
|
||||
_channels = channels;
|
||||
if (cancellationToken != null) _cancellationToken = cancellationToken.Value;
|
||||
}
|
||||
|
||||
public async Task StartWsClient()
|
||||
{
|
||||
_logger.Debug("StartWsClient() called, creating client");
|
||||
await CreateWsClient();
|
||||
}
|
||||
|
||||
private async Task CreateWsClient()
|
||||
{
|
||||
var factory = new Func<ClientWebSocket>(() =>
|
||||
{
|
||||
var clientWs = new ClientWebSocket();
|
||||
if (_proxy == null) return clientWs;
|
||||
_logger.Debug($"Using proxy address {_proxy}");
|
||||
clientWs.Options.Proxy = new WebProxy(_proxy);
|
||||
return clientWs;
|
||||
});
|
||||
|
||||
var client = new WebsocketClient(_wsUri, factory)
|
||||
{
|
||||
ReconnectTimeout = TimeSpan.FromSeconds(_reconnectTimeout),
|
||||
IsReconnectionEnabled = false
|
||||
};
|
||||
|
||||
client.ReconnectionHappened.Subscribe(WsReconnection);
|
||||
client.MessageReceived.Subscribe(WsMessageReceived);
|
||||
client.DisconnectionHappened.Subscribe(WsDisconnection);
|
||||
|
||||
_wsClient = client;
|
||||
|
||||
_logger.Debug("Websocket client has been built, about to start");
|
||||
await client.Start();
|
||||
_logger.Debug("Websocket client started!");
|
||||
SendPing();
|
||||
_pingTask = PeriodicPing();
|
||||
}
|
||||
|
||||
public bool IsConnected()
|
||||
{
|
||||
return _wsClient is { IsRunning: true };
|
||||
}
|
||||
|
||||
private void SendPing()
|
||||
{
|
||||
_logger.Info("Sending ping to Twitch");
|
||||
_wsClient.Send("{\"type\":\"PING\"}");
|
||||
}
|
||||
|
||||
private async Task PeriodicPing()
|
||||
{
|
||||
using var timer = new PeriodicTimer(TimeSpan.FromMinutes(1));
|
||||
while (await timer.WaitForNextTickAsync(_pingCts.Token))
|
||||
{
|
||||
SendPing();
|
||||
}
|
||||
}
|
||||
|
||||
private void WsDisconnection(DisconnectionInfo disconnectionInfo)
|
||||
{
|
||||
_logger.Error($"Client disconnected from the chat (or never successfully connected). Type is {disconnectionInfo.Type}");
|
||||
_logger.Error($"Close Status => {disconnectionInfo.CloseStatus}; Close Status Description => {disconnectionInfo.CloseStatusDescription}");
|
||||
_logger.Error(disconnectionInfo.Exception);
|
||||
}
|
||||
|
||||
private void WsReconnection(ReconnectionInfo reconnectionInfo)
|
||||
{
|
||||
_logger.Error($"Websocket connection dropped and reconnected. Reconnection type is {reconnectionInfo.Type}");
|
||||
_logger.Info("Sending subscription requests");
|
||||
foreach (var channel in _channels)
|
||||
{
|
||||
_logger.Info($"Subscribing to {channel}");
|
||||
var payload = "{\"data\":{\"topics\":[\"video-playback-by-id." + channel + "\"]},\"nonce\":\"" +
|
||||
Guid.NewGuid() + "\",\"type\":\"LISTEN\"}";
|
||||
_logger.Debug("Sending the following JSON to Twitch");
|
||||
_logger.Debug(payload);
|
||||
_wsClient.Send(payload);
|
||||
}
|
||||
}
|
||||
|
||||
// Stream start JSON
|
||||
// {"type":"MESSAGE","data":{"topic":"video-playback-by-id.114122847","message":"{\"server_time\":1718631487,\"play_delay\":0,\"type\":\"stream-up\"}"}}
|
||||
// View count update (every 30 seconds)
|
||||
// {"type":"MESSAGE","data":{"topic":"video-playback-by-id.114122847","message":"{\"type\":\"viewcount\",\"server_time\":1718631500.636146,\"viewers\":62}"}}
|
||||
// {"type":"MESSAGE","data":{"topic":"video-playback-by-id.114122847","message":"{\"type\":\"viewcount\",\"server_time\":1718631530.654308,\"viewers\":162}"}}
|
||||
// {"type":"MESSAGE","data":{"topic":"video-playback-by-id.114122847","message":"{\"type\":\"viewcount\",\"server_time\":1718631560.551188,\"viewers\":179}"}}
|
||||
private void WsMessageReceived(ResponseMessage message)
|
||||
{
|
||||
if (message.Text == null)
|
||||
{
|
||||
_logger.Info("Twitch sent a null message");
|
||||
return;
|
||||
}
|
||||
_logger.Debug($"Received event from Twitch: {message.Text}");
|
||||
|
||||
try
|
||||
{
|
||||
var packet = JsonSerializer.Deserialize<JsonElement>(message.Text);
|
||||
if (packet.GetProperty("type").GetString() != "MESSAGE")
|
||||
return;
|
||||
var data = packet.GetProperty("data")!;
|
||||
var topicString = data.GetProperty("topic")!.GetString()!;
|
||||
if (!topicString.StartsWith("video-playback-by-id."))
|
||||
return;
|
||||
var topicParts = topicString.Split('.');
|
||||
var channelId = int.Parse(topicParts[^1]);
|
||||
var twitchMessage = data.GetProperty("message")!.GetString()!;
|
||||
|
||||
if (twitchMessage.Contains("\"type\":\"stream-up\""))
|
||||
{
|
||||
OnStreamStateUpdated?.Invoke(this, channelId, true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (twitchMessage.Contains("\"type\":\"stream-down\""))
|
||||
{
|
||||
OnStreamStateUpdated?.Invoke(this, channelId, false);
|
||||
return;
|
||||
}
|
||||
_logger.Info("Message from Twitch was unhandled");
|
||||
_logger.Info(message.Text);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.Error("Failed to handle message from Twitch");
|
||||
_logger.Error(e);
|
||||
_logger.Error("--- JSON Payload ---");
|
||||
_logger.Error(message.Text);
|
||||
_logger.Error("--- End of JSON Payload ---");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> IsStreamLive(string channel)
|
||||
{
|
||||
var clientId = "kimne78kx3ncx6brgo4mv6wki5h1ko";
|
||||
var graphQl = "query {\n user(login: \"" + channel + "\") {\n stream {\n id\n }\n }\n}";
|
||||
_logger.Debug($"Built GraphQL query string: {graphQl}");
|
||||
var jsonBody = new Dictionary<string, object>
|
||||
{
|
||||
{ "query", graphQl },
|
||||
{ "variables", new object() }
|
||||
};
|
||||
_logger.Debug("Created dictionary object for the JSON payload, should serialize to following value:");
|
||||
_logger.Debug(JsonSerializer.Serialize(jsonBody));
|
||||
var handler = new HttpClientHandler {AutomaticDecompression = DecompressionMethods.All};
|
||||
if (_proxy != null)
|
||||
{
|
||||
handler.UseProxy = true;
|
||||
handler.Proxy = new WebProxy(_proxy);
|
||||
_logger.Debug($"Configured to use proxy {_proxy}");
|
||||
}
|
||||
|
||||
using var client = new HttpClient(handler);
|
||||
client.DefaultRequestHeaders.Add("client-id", clientId);
|
||||
var postBody = JsonContent.Create(jsonBody);
|
||||
var response = await client.PostAsync("https://gql.twitch.tv/gql", postBody, _cancellationToken);
|
||||
//response.EnsureSuccessStatusCode();
|
||||
var responseContent = await response.Content.ReadFromJsonAsync<JsonElement>(cancellationToken: _cancellationToken);
|
||||
_logger.Debug("Twitch API returned following JSON");
|
||||
_logger.Debug(responseContent.GetRawText);
|
||||
if (responseContent.GetProperty("data").GetProperty("user").ValueKind == JsonValueKind.Null)
|
||||
{
|
||||
_logger.Debug("data.user was null");
|
||||
throw new TwitchUserNotFoundException();
|
||||
}
|
||||
|
||||
if (responseContent.GetProperty("data").GetProperty("user").GetProperty("stream").ValueKind ==
|
||||
JsonValueKind.Null)
|
||||
{
|
||||
_logger.Debug("stream property was null. Means streamer is not live");
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public class TwitchUserNotFoundException : Exception;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_wsClient.Dispose();
|
||||
_pingCts.Cancel();
|
||||
_pingCts.Dispose();
|
||||
_pingTask?.Dispose();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
180
KfChatDotNetBot/Services/TwitchChat.cs
Normal file
180
KfChatDotNetBot/Services/TwitchChat.cs
Normal file
@@ -0,0 +1,180 @@
|
||||
using System.Net;
|
||||
using System.Net.WebSockets;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using NLog;
|
||||
using Websocket.Client;
|
||||
|
||||
namespace KfChatDotNetBot.Services;
|
||||
|
||||
public class TwitchChat : IDisposable
|
||||
{
|
||||
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
|
||||
private WebsocketClient _wsClient;
|
||||
private readonly Uri _wsUri = new("wss://irc-ws.chat.twitch.tv/");
|
||||
private const int ReconnectTimeout = 600;
|
||||
private readonly string? _proxy;
|
||||
private readonly string _channel;
|
||||
private readonly string _nick;
|
||||
|
||||
public delegate void MessageReceivedEventHandler(object sender, string nick, string target, string message);
|
||||
public delegate void WsDisconnectionEventHandler(object sender, DisconnectionInfo e);
|
||||
public event MessageReceivedEventHandler OnMessageReceived;
|
||||
public event WsDisconnectionEventHandler OnWsDisconnection;
|
||||
|
||||
private readonly CancellationToken _cancellationToken = CancellationToken.None;
|
||||
|
||||
public TwitchChat(string channel, string? proxy = null, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
_proxy = proxy;
|
||||
if (cancellationToken != null) _cancellationToken = cancellationToken.Value;
|
||||
_channel = channel;
|
||||
var justinFan = new Random().Next(10000, 99999);
|
||||
_nick = $"justinfan{justinFan}";
|
||||
_logger.Debug($"Using nick {_nick}");
|
||||
_logger.Info("Twitch Chat Service created");
|
||||
}
|
||||
|
||||
public async Task StartWsClient()
|
||||
{
|
||||
_logger.Debug("StartWsClient() called, creating client");
|
||||
await CreateWsClient();
|
||||
}
|
||||
|
||||
private async Task CreateWsClient()
|
||||
{
|
||||
var factory = new Func<ClientWebSocket>(() =>
|
||||
{
|
||||
var clientWs = new ClientWebSocket();
|
||||
if (_proxy == null) return clientWs;
|
||||
_logger.Debug($"Using proxy address {_proxy}");
|
||||
clientWs.Options.Proxy = new WebProxy(_proxy);
|
||||
return clientWs;
|
||||
});
|
||||
|
||||
var client = new WebsocketClient(_wsUri, factory)
|
||||
{
|
||||
ReconnectTimeout = TimeSpan.FromSeconds(ReconnectTimeout),
|
||||
IsReconnectionEnabled = false
|
||||
};
|
||||
|
||||
client.ReconnectionHappened.Subscribe(WsReconnection);
|
||||
client.MessageReceived.Subscribe(WsMessageReceived);
|
||||
client.DisconnectionHappened.Subscribe(WsDisconnection);
|
||||
|
||||
_wsClient = client;
|
||||
|
||||
_logger.Debug("Websocket client has been built, about to start");
|
||||
await client.Start();
|
||||
_logger.Debug("Websocket client started!");
|
||||
}
|
||||
|
||||
public bool IsConnected()
|
||||
{
|
||||
return _wsClient is { IsRunning: true };
|
||||
}
|
||||
|
||||
private void WsDisconnection(DisconnectionInfo disconnectionInfo)
|
||||
{
|
||||
_logger.Error($"Client disconnected from Discord (or never successfully connected). Type is {disconnectionInfo.Type}");
|
||||
_logger.Error($"Close Status => {disconnectionInfo.CloseStatus}; Close Status Description => {disconnectionInfo.CloseStatusDescription}");
|
||||
_logger.Error(disconnectionInfo.Exception);
|
||||
OnWsDisconnection?.Invoke(this, disconnectionInfo);
|
||||
}
|
||||
|
||||
private void WsReconnection(ReconnectionInfo reconnectionInfo)
|
||||
{
|
||||
_logger.Error($"Websocket connection dropped and reconnected. Reconnection type is {reconnectionInfo.Type}");
|
||||
_logger.Info("Sending registration info to Twitch IRC");
|
||||
// I've found if you use the message queue then things come out of order, hence using SendInstant
|
||||
_wsClient.SendInstant("CAP REQ :twitch.tv/tags twitch.tv/commands").Wait(_cancellationToken);
|
||||
// Would be an oauth token if you were signed in, but this is just guest access
|
||||
_wsClient.SendInstant("PASS SCHMOOPIIE").Wait(_cancellationToken);
|
||||
// Guest users are just justinfan12345 where the 5 digits are random
|
||||
_wsClient.SendInstant($"NICK {_nick}").Wait(_cancellationToken);
|
||||
// I'm ashamed I've forgotten so much IRC protocol shit that I can't remember what the USER params mean :(
|
||||
_wsClient.SendInstant($"USER {_nick} 8 * :{_nick}").Wait(_cancellationToken);
|
||||
}
|
||||
|
||||
private void WsMessageReceived(ResponseMessage message)
|
||||
{
|
||||
if (message.Text == null)
|
||||
{
|
||||
_logger.Info("Twitch sent a null message");
|
||||
return;
|
||||
}
|
||||
|
||||
_logger.Debug($"Received message from Twitch IRC: {message.Text}");
|
||||
|
||||
try
|
||||
{
|
||||
if (message.Text.Contains("PRIVMSG"))
|
||||
{
|
||||
// This regex basically ignores all the IRCv3 stuff so handles PRIVMSG fine
|
||||
var privmsgRegex =
|
||||
new Regex(
|
||||
":(?<nick>[^ ]+?)\\!(?<user>[^ ]+?)@(?<host>[^ ]+?) PRIVMSG (?<target>[^ ]+?) :(?<message>.*)");
|
||||
var privmsg = privmsgRegex.Match(message.Text);
|
||||
if (!privmsg.Success)
|
||||
{
|
||||
throw new InvalidOperationException("PRIVMSG regex failed to match");
|
||||
}
|
||||
|
||||
OnMessageReceived?.Invoke(this, privmsg.Groups["nick"].Value, privmsg.Groups["target"].Value,
|
||||
privmsg.Groups["message"].Value);
|
||||
return;
|
||||
}
|
||||
|
||||
// These are generally filled with IRCv3 gobbledegook and I don't care if it's not a PRIVMSG
|
||||
if (message.Text.StartsWith('@'))
|
||||
{
|
||||
_logger.Debug("Ignoring non-PRIVMSG IRCv3 filled junk");
|
||||
return;
|
||||
}
|
||||
// This regex is pretty good for parsing most messages but chokes hard on some Twitch IRCv3 insanity
|
||||
var ircMessageRegex =
|
||||
new Regex(
|
||||
"(?::(?<Prefix>[^ ]+) +)?(?<Command>[^ :]+)(?<middle>(?: +[^ :]+))*(?<coda> +:(?<trailing>.*)?)?");
|
||||
var ircMessageMatch = ircMessageRegex.Match(message.Text);
|
||||
if (!ircMessageMatch.Success)
|
||||
{
|
||||
throw new InvalidOperationException("Failed to match IRC message");
|
||||
}
|
||||
var command = ircMessageMatch.Groups["Command"].Value;
|
||||
var trailing = ircMessageMatch.Groups["trailing"].Value;
|
||||
_logger.Debug($"Received command {command} with trailing: {trailing}");
|
||||
switch (command)
|
||||
{
|
||||
case "PING":
|
||||
_logger.Info("Received PING, sending PONG");
|
||||
_wsClient.Send("PONG");
|
||||
return;
|
||||
case "JOIN":
|
||||
_logger.Debug("Received JOIN response");
|
||||
return;
|
||||
// MOTD
|
||||
case "001":
|
||||
_logger.Debug("Received MOTD. Sending JOIN");
|
||||
_wsClient.Send($"JOIN {_channel}");
|
||||
return;
|
||||
default:
|
||||
_logger.Debug($"Command {command} was not handled");
|
||||
return;
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.Error("Failed to handle message from Twitch IRC");
|
||||
_logger.Error(e);
|
||||
_logger.Error("--- IRC Message ---");
|
||||
_logger.Error(message.Text);
|
||||
_logger.Error("--- End of IRC Message ---");
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_wsClient.Dispose();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user