Big update introducing ghetto command interface, settings, database and howl.gg bet feed scraping

This commit is contained in:
barelyprofessional
2024-07-18 01:37:15 +10:00
parent 936bf743a5
commit d61a171e54
46 changed files with 2198 additions and 218 deletions

View File

@@ -0,0 +1,88 @@
using KfChatDotNetKickBot.Commands;
using KfChatDotNetWsClient.Models.Events;
using NLog;
namespace KfChatDotNetKickBot.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 KickBot _bot;
private Logger _logger = LogManager.GetCurrentClassLogger();
private char CommandPrefix = '!';
private IEnumerable<ICommand> Commands;
private CancellationToken _cancellationToken;
private List<Task> _commandTasks = [];
internal BotCommands(KickBot 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.", 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);
}
}
}

View File

@@ -7,7 +7,7 @@ using Websocket.Client;
namespace KfChatDotNetKickBot.Services;
public class DiscordService : IDisposable
public class DiscordService
{
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
private WebsocketClient _wsClient;
@@ -111,8 +111,14 @@ public class DiscordService : IDisposable
private void WsDisconnection(DisconnectionInfo disconnectionInfo)
{
_logger.Error($"Client disconnected from Discord (or never successfully connected). Type is {disconnectionInfo.Type}");
_logger.Error(JsonSerializer.Serialize(disconnectionInfo));
_logger.Error($"Close Status => {disconnectionInfo.CloseStatus}; Close Status Description => {disconnectionInfo.CloseStatusDescription}");
_logger.Error(disconnectionInfo.Exception);
OnWsDisconnection?.Invoke(this, disconnectionInfo);
if (disconnectionInfo.Type == DisconnectionType.ByServer)
{
_logger.Info("Forcing reconnection as the type was ByServer");
_wsClient.Reconnect().Wait(_cancellationToken);
}
}
private void WsReconnection(ReconnectionInfo reconnectionInfo)
@@ -144,7 +150,7 @@ public class DiscordService : IDisposable
if (packet.OpCode == 10)
{
_logger.Info("Discord op code 10 (hello) sent. Setting up heartbeat timer and sending init");
_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\":" +
@@ -205,14 +211,6 @@ public class DiscordService : IDisposable
_logger.Error("--- End of JSON Payload ---");
}
}
public void Dispose()
{
_logger.Info("Disposing Discord");
_wsClient.Dispose();
_pingCts.Cancel();
GC.SuppressFinalize(this);
}
}
public class DiscordPacketModel<T>

View File

@@ -0,0 +1,178 @@
using System.Net;
using System.Net.Http.Json;
using System.Net.WebSockets;
using System.Text.Json;
using KfChatDotNetKickBot.Models;
using NLog;
using Websocket.Client;
namespace KfChatDotNetKickBot.Services;
public class Howlgg
{
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)
};
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.SendInstant(packet).Wait(_cancellationToken);
}
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;
}
if (!IsConnected())
{
_logger.Info("Not connected not going to try send a ping actually");
continue;
}
_logger.Debug("Sending Howl.gg ping packet");
await _wsClient.SendInstant("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);
if (disconnectionInfo.Type == DisconnectionType.ByServer)
{
_logger.Info("Forcing reconnection as the type was ByServer");
_wsClient.Reconnect().Wait(_cancellationToken);
}
}
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.Debug("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());
_heartbeatTask?.Dispose();
_heartbeatTask = Task.Run(HeartbeatTimer, _cancellationToken);
_logger.Info("Received connection packet from Howl.gg. Setting up heartbeat timer");
return;
}
if (message.Text == "40")
{
_logger.Trace("Ready to subscribe, sending main subscription");
_wsClient.SendInstant("40/main,").Wait(_cancellationToken);
// 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 ---");
}
}
}

View File

@@ -8,7 +8,7 @@ using Websocket.Client;
namespace KfChatDotNetKickBot.Services;
public class Shuffle : IDisposable
public class Shuffle
{
private Logger _logger = LogManager.GetCurrentClassLogger();
private WebsocketClient _wsClient;
@@ -99,8 +99,14 @@ public class Shuffle : IDisposable
private void WsDisconnection(DisconnectionInfo disconnectionInfo)
{
_logger.Error($"Client disconnected from Shuffle (or never successfully connected). Type is {disconnectionInfo.Type}");
_logger.Error(JsonSerializer.Serialize(disconnectionInfo));
_logger.Error($"Close Status => {disconnectionInfo.CloseStatus}; Close Status Description => {disconnectionInfo.CloseStatusDescription}");
_logger.Error(disconnectionInfo.Exception);
OnWsDisconnection?.Invoke(this, disconnectionInfo);
if (disconnectionInfo.Type == DisconnectionType.ByServer)
{
_logger.Info("Forcing reconnection as the type was ByServer");
_wsClient.Reconnect().Wait(_cancellationToken);
}
}
private void WsReconnection(ReconnectionInfo reconnectionInfo)
@@ -120,7 +126,7 @@ public class Shuffle : IDisposable
_logger.Info("Shuffle sent a null message");
return;
}
_logger.Debug($"Received event from Shuffle: {message.Text}");
_logger.Trace($"Received event from Shuffle: {message.Text}");
try
{
@@ -135,7 +141,7 @@ public class Shuffle : IDisposable
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.Send(payload);
_wsClient.SendInstant(payload).Wait(_cancellationToken);
return;
}
@@ -148,7 +154,6 @@ public class Shuffle : IDisposable
// GAMBA
if (packetType == "next")
{
_logger.Debug("Got a bet! Deserializing it");
var bet = packet.GetProperty("payload").GetProperty("data").GetProperty("latestBetUpdated")
.Deserialize<ShuffleLatestBetModel>();
if (bet == null)
@@ -156,7 +161,6 @@ public class Shuffle : IDisposable
_logger.Error("Caught a null before invoking bet event");
throw new NullReferenceException("Caught a null before invoking bet event");
}
_logger.Debug("Invoking event");
OnLatestBetUpdated?.Invoke(this, bet);
return;
}
@@ -212,11 +216,4 @@ public class Shuffle : IDisposable
}
public class ShuffleUserNotFoundException : Exception;
public void Dispose()
{
_pingCts.Cancel();
_wsClient.Dispose();
GC.SuppressFinalize(this);
}
}

View File

@@ -0,0 +1,57 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using KfChatDotNetKickBot.Models;
using NLog;
namespace KfChatDotNetKickBot.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;
}
}

View File

@@ -84,7 +84,13 @@ public class Twitch
private void WsDisconnection(DisconnectionInfo disconnectionInfo)
{
_logger.Error($"Client disconnected from the chat (or never successfully connected). Type is {disconnectionInfo.Type}");
_logger.Error(JsonSerializer.Serialize(disconnectionInfo));
_logger.Error($"Close Status => {disconnectionInfo.CloseStatus}; Close Status Description => {disconnectionInfo.CloseStatusDescription}");
_logger.Error(disconnectionInfo.Exception);
if (disconnectionInfo.Type == DisconnectionType.ByServer)
{
_logger.Info("Forcing reconnection as the type was ByServer");
_wsClient.Reconnect().Wait(_cancellationToken);
}
}
private void WsReconnection(ReconnectionInfo reconnectionInfo)

View File

@@ -7,7 +7,7 @@ using Websocket.Client;
namespace KfChatDotNetKickBot.Services;
public class TwitchChat : IDisposable
public class TwitchChat
{
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
private WebsocketClient _wsClient;
@@ -76,8 +76,14 @@ public class TwitchChat : IDisposable
private void WsDisconnection(DisconnectionInfo disconnectionInfo)
{
_logger.Error($"Client disconnected from Discord (or never successfully connected). Type is {disconnectionInfo.Type}");
_logger.Error(JsonSerializer.Serialize(disconnectionInfo));
_logger.Error($"Close Status => {disconnectionInfo.CloseStatus}; Close Status Description => {disconnectionInfo.CloseStatusDescription}");
_logger.Error(disconnectionInfo.Exception);
OnWsDisconnection?.Invoke(this, disconnectionInfo);
if (disconnectionInfo.Type == DisconnectionType.ByServer)
{
_logger.Info("Forcing reconnection as the type was ByServer");
_wsClient.Reconnect().Wait(_cancellationToken);
}
}
private void WsReconnection(ReconnectionInfo reconnectionInfo)
@@ -169,11 +175,4 @@ public class TwitchChat : IDisposable
_logger.Error("--- End of IRC Message ---");
}
}
public void Dispose()
{
_logger.Info("Disposing Twitch Chat");
_wsClient.Dispose();
GC.SuppressFinalize(this);
}
}