Renamed the bot from KickBot -> ChatBot and removed the reference to Kick in the project name

This commit is contained in:
barelyprofessional
2024-07-26 16:50:39 +08:00
parent f4db00246a
commit f9d87220d2
46 changed files with 84 additions and 84 deletions

View File

@@ -0,0 +1,17 @@
using KfChatDotNetBot.Models.DbModels;
using Microsoft.EntityFrameworkCore;
namespace KfChatDotNetBot;
public class ApplicationDbContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder builder)
{
builder.UseSqlite("Data Source=db.sqlite");
}
public DbSet<UserDbModel> Users { get; set; }
public DbSet<JuicerDbModel> Juicers { get; set; }
public DbSet<SettingDbModel> Settings { get; set; }
public DbSet<HowlggBetsDbModel> HowlggBets { get; set; }
}

638
KfChatDotNetBot/ChatBot.cs Normal file
View File

@@ -0,0 +1,638 @@
using KfChatDotNetBot.Models;
using KfChatDotNetBot.Models.DbModels;
using KfChatDotNetBot.Services;
using KfChatDotNetBot.Settings;
using KfChatDotNetWsClient;
using KfChatDotNetWsClient.Models;
using KfChatDotNetWsClient.Models.Events;
using KfChatDotNetWsClient.Models.Json;
using KickWsClient.Models;
using NLog;
using Websocket.Client;
namespace KfChatDotNetBot;
public class ChatBot
{
internal readonly ChatClient KfClient;
private readonly KickWsClient.KickWsClient _kickClient;
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
private readonly bool _pingEnabled = true;
internal bool GambaSeshPresent;
private string _xfSessionToken = null!;
// Oh no it's an ever expanding list that may never get cleaned up!
// BUY MORE RAM
private readonly List<int> _seenMsgIds = [];
// Suppresses the command handler on initial start, so it doesn't pick up things already handled on restart
private bool _initialStartCooldown = true;
private readonly CancellationToken _cancellationToken = new();
private Twitch _twitch;
private Shuffle _shuffle;
private DiscordService _discord;
private TwitchChat _twitchChat;
private string? _lastDiscordStatus;
internal bool IsBmjLive = false;
private bool _isBmjLiveSynced = false;
private DateTime _lastKfEvent = DateTime.Now;
private BotCommands _botCommands;
private string _bmjTwitchUsername;
private Howlgg _howlgg;
private bool _kickDisabled = true;
private bool _twitchDisabled = false;
private Task _websocketWatchdog;
private Jackpot _jackpot;
public ChatBot()
{
_logger.Info("Bot starting!");
var settings = Helpers.GetMultipleValues([
BuiltIn.Keys.KiwiFarmsWsEndpoint, BuiltIn.Keys.KiwiFarmsDomain, BuiltIn.Keys.PusherEndpoint,
BuiltIn.Keys.Proxy, BuiltIn.Keys.PusherReconnectTimeout, BuiltIn.Keys.PusherChannels,
BuiltIn.Keys.TwitchBossmanJackId, BuiltIn.Keys.DiscordToken, BuiltIn.Keys.KiwiFarmsWsReconnectTimeout,
BuiltIn.Keys.KiwiFarmsToken, BuiltIn.Keys.KickEnabled
]).Result;
_xfSessionToken = settings[BuiltIn.Keys.KiwiFarmsToken].Value ?? "unset";
if (_xfSessionToken == "unset")
{
RefreshXfToken().Wait(_cancellationToken);
}
KfClient = new ChatClient(new ChatClientConfigModel
{
WsUri = new Uri(settings[BuiltIn.Keys.KiwiFarmsWsEndpoint].Value ?? throw new InvalidOperationException($"{BuiltIn.Keys.KiwiFarmsWsEndpoint} cannot be null")),
XfSessionToken = _xfSessionToken,
CookieDomain = settings[BuiltIn.Keys.KiwiFarmsDomain].Value ?? throw new InvalidOperationException($"{BuiltIn.Keys.KiwiFarmsDomain} cannot be null"),
Proxy = settings[BuiltIn.Keys.Proxy].Value,
ReconnectTimeout = Convert.ToInt32(settings[BuiltIn.Keys.KiwiFarmsWsReconnectTimeout].Value)
});
_kickClient = new KickWsClient.KickWsClient(settings[BuiltIn.Keys.PusherEndpoint].Value!,
settings[BuiltIn.Keys.Proxy].Value, Convert.ToInt32(settings[BuiltIn.Keys.PusherReconnectTimeout].Value));
_logger.Debug("Creating bot command instance");
_botCommands = new BotCommands(this, _cancellationToken);
KfClient.OnMessages += OnKfChatMessage;
KfClient.OnUsersParted += OnUsersParted;
KfClient.OnUsersJoined += OnUsersJoined;
KfClient.OnWsDisconnection += OnKfWsDisconnected;
KfClient.OnWsReconnect += OnKfWsReconnected;
KfClient.OnFailedToJoinRoom += OnFailedToJoinRoom;
_kickClient.OnStreamerIsLive += OnStreamerIsLive;
_kickClient.OnChatMessage += OnKickChatMessage;
_kickClient.OnWsReconnect += OnPusherWsReconnected;
_kickClient.OnPusherSubscriptionSucceeded += OnPusherSubscriptionSucceeded;
_kickClient.OnStopStreamBroadcast += OnStopStreamBroadcast;
KfClient.StartWsClient().Wait(_cancellationToken);
if (settings[BuiltIn.Keys.KickEnabled].ToBoolean())
{
_kickClient.StartWsClient().Wait(_cancellationToken);
var pusherChannels = settings[BuiltIn.Keys.PusherChannels].Value ?? "";
foreach (var channel in pusherChannels.Split(','))
{
_kickClient.SendPusherSubscribe(channel);
}
_kickDisabled = false;
}
_logger.Debug("Creating ping thread and starting it");
var pingThread = new Thread(PingThread);
pingThread.Start();
if (settings[BuiltIn.Keys.TwitchBossmanJackId].Value != null)
{
_logger.Debug("Creating Twitch live stream notification client");
BuildTwitch();
}
else
{
_twitchDisabled = true;
_logger.Debug($"Ignoring Twitch client as {BuiltIn.Keys.TwitchBossmanJackId} is not defined");
}
BuildShuffle();
BuildDiscord();
BuildTwitchChat();
BuildHowlgg();
_logger.Info("Starting websocket watchdog");
_websocketWatchdog = WebsocketWatchdog();
_logger.Debug("Blocking the main thread");
var exitEvent = new ManualResetEvent(false);
exitEvent.WaitOne();
}
private async Task WebsocketWatchdog()
{
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(10));
while (await timer.WaitForNextTickAsync(_cancellationToken))
{
if (_initialStartCooldown) continue;
try
{
if (!_shuffle.IsConnected())
{
_logger.Error("Shuffle died, recreating it");
_shuffle.Dispose();
_shuffle = null!;
BuildShuffle();
}
if (!_discord.IsConnected())
{
_logger.Error("Discord died, recreating it");
_discord.Dispose();
_discord = null!;
BuildDiscord();
}
if (!_twitchDisabled && !_twitch.IsConnected())
{
_logger.Error("Twitch died, recreating it");
_twitch.Dispose();
_twitch = null!;
BuildTwitch();
}
if (!_twitchChat.IsConnected())
{
_logger.Error("Twitch chat died, recreating it");
_twitchChat.Dispose();
_twitchChat = null!;
BuildTwitchChat();
}
if (!_howlgg.IsConnected())
{
_logger.Error("Howl.gg died, recreating it");
_howlgg.Dispose();
_howlgg = null!;
BuildHowlgg();
}
if (!_jackpot.IsConnected())
{
_logger.Error("Jackpot died, recreating it");
_jackpot.Dispose();
_jackpot = null!;
BuildJackpot();
}
}
catch (Exception e)
{
_logger.Error("Watchdog shit itself while trying to do something, exception follows");
_logger.Error(e);
}
}
}
private void BuildJackpot()
{
var proxy = Helpers.GetValue(BuiltIn.Keys.Proxy).Result.Value;
_jackpot = new Jackpot(proxy, _cancellationToken);
_jackpot.OnJackpotBet += OnJackpotBet;
_jackpot.StartWsClient().Wait(_cancellationToken);
}
private void OnJackpotBet(object sender, JackpotWsBetPayloadModel bet)
{
var settings = Helpers
.GetMultipleValues([
BuiltIn.Keys.JackpotBmjUsername, BuiltIn.Keys.TwitchBossmanJackUsername,
BuiltIn.Keys.KiwiFarmsGreenColor, BuiltIn.Keys.KiwiFarmsRedColor
]).Result;
_logger.Trace("Jackpot bet has arrived");
if (bet.User != settings[BuiltIn.Keys.JackpotBmjUsername].Value)
{
return;
}
_logger.Info("ALERT BMJ IS BETTING (on Jackpot)");
if (IsBmjLive)
{
_logger.Info("Ignoring as BMJ is live");
return;
}
// Only check once because the bot should be tracking the Twitch stream
// This is just in case he's already live while the bot starts
// He was schizo betting on Dice, so I want to avoid a lot of API requests to Twitch in case they rate limit
if (!_isBmjLiveSynced)
{
IsBmjLive = _twitch.IsStreamLive(settings[BuiltIn.Keys.TwitchBossmanJackUsername].Value!).Result;
_isBmjLiveSynced = true;
}
if (IsBmjLive)
{
_logger.Info("Double checked and he is really online");
return;
}
var payoutColor = settings[BuiltIn.Keys.KiwiFarmsGreenColor].Value;
if (bet.Payout < bet.Wager) payoutColor = settings[BuiltIn.Keys.KiwiFarmsRedColor].Value;
// There will be a check for live status but ignoring that while we deal with an emergency dice situation
SendChatMessage($"🚨🚨 JACKPOT BETTING 🚨🚨 {bet.User} just bet {bet.Wager} {bet.Currency} which paid out [color={payoutColor}]{bet.Payout} {bet.Currency}[/color] ({bet.Multiplier}x) on {bet.GameName} 💰💰", false);
}
public void BuildTwitch()
{
var settings = Helpers.GetMultipleValues([BuiltIn.Keys.TwitchBossmanJackId, BuiltIn.Keys.Proxy]).Result;
_twitch = new Twitch([Convert.ToInt32(settings[BuiltIn.Keys.TwitchBossmanJackId].Value)], settings[BuiltIn.Keys.Proxy].Value, _cancellationToken);
_twitch.OnStreamStateUpdated += OnTwitchStreamStateUpdated;
_twitch.StartWsClient().Wait(_cancellationToken);
}
private void BuildHowlgg()
{
var proxy = Helpers.GetValue(BuiltIn.Keys.Proxy).Result.Value;
_howlgg = new Howlgg(proxy, _cancellationToken);
_howlgg.OnHowlggBetHistory += OnHowlggBetHistory;
_howlgg.StartWsClient().Wait(_cancellationToken);
}
private void OnHowlggBetHistory(object sender, HowlggBetHistoryResponseModel data)
{
_logger.Debug("Received bet history from Howl.gg");
using var db = new ApplicationDbContext();
foreach (var bet in data.History.Data)
{
// Slot feature buys have an unrealized value that means they show no profit until the feature finishes
// The feed will return the correct profit later hence updating the values
var existingBet = db.HowlggBets.FirstOrDefault(b => b.BetId == bet.Id);
if (existingBet != null)
{
_logger.Trace("Bet already exists in DB");
if (existingBet.Bet == bet.Bet && existingBet.Profit == bet.Profit) continue;
_logger.Debug("Updating fields");
existingBet.Bet = bet.Bet;
existingBet.Profit = bet.Profit;
db.SaveChanges();
continue;
}
db.HowlggBets.Add(new HowlggBetsDbModel
{
UserId = data.User.Id,
BetId = bet.Id,
GameId = bet.GameId,
Bet = bet.Bet,
Profit = bet.Profit,
Date = bet.Date,
Game = bet.Game
});
_logger.Info("Added bet to DB");
}
db.SaveChanges();
}
private void BuildShuffle()
{
_logger.Debug("Building Shuffle");
_shuffle = new Shuffle(Helpers.GetValue(BuiltIn.Keys.Proxy).Result.Value, _cancellationToken);
_shuffle.OnLatestBetUpdated += ShuffleOnLatestBetUpdated;
_shuffle.StartWsClient().Wait(_cancellationToken);
}
private void BuildDiscord()
{
var settings = Helpers.GetMultipleValues([BuiltIn.Keys.DiscordToken, BuiltIn.Keys.Proxy]).Result;
_logger.Debug("Building Discord");
if (settings[BuiltIn.Keys.DiscordToken].Value == null)
{
_logger.Info("Not building Discord as the token is not configured");
return;
}
_discord = new DiscordService(settings[BuiltIn.Keys.DiscordToken].Value!, settings[BuiltIn.Keys.Proxy].Value, _cancellationToken);
_discord.OnInvalidCredentials += DiscordOnInvalidCredentials;
_discord.OnMessageReceived += DiscordOnMessageReceived;
_discord.OnPresenceUpdated += DiscordOnPresenceUpdated;
_discord.StartWsClient().Wait(_cancellationToken);
}
private void BuildTwitchChat()
{
var settings = Helpers.GetMultipleValues([BuiltIn.Keys.TwitchBossmanJackUsername, BuiltIn.Keys.Proxy]).Result;
_logger.Debug("Building Twitch Chat");
if (settings[BuiltIn.Keys.TwitchBossmanJackUsername].Value == null)
{
_logger.Info("Not building Twitch Chat client as BMJ's username is not configured");
return;
}
_bmjTwitchUsername = settings[BuiltIn.Keys.TwitchBossmanJackUsername].Value!;
_twitchChat = new TwitchChat($"#{settings[BuiltIn.Keys.TwitchBossmanJackUsername].Value}", settings[BuiltIn.Keys.Proxy].Value, _cancellationToken);
_twitchChat.OnMessageReceived += TwitchChatOnMessageReceived;
_twitchChat.StartWsClient().Wait(_cancellationToken);
}
private void TwitchChatOnMessageReceived(object sender, string nick, string target, string message)
{
if (nick != _bmjTwitchUsername)
{
return;
}
// Not caching this value as it won't harm it to have to look this up in even the worst spergout sesh
var twitchIcon = Helpers.GetValue(BuiltIn.Keys.TwitchIcon).Result.Value;
SendChatMessage($"[img]{twitchIcon}[/img] {nick}: {message}", true);
}
private void DiscordOnPresenceUpdated(object sender, DiscordPresenceUpdateModel presence)
{
var settings = Helpers.GetMultipleValues([BuiltIn.Keys.DiscordBmjId, BuiltIn.Keys.DiscordIcon]).Result;
if (presence.User.Id != settings[BuiltIn.Keys.DiscordBmjId].Value)
{
return;
}
// if (_lastDiscordStatus == presence.Status)
// {
// _logger.Debug("Ignoring status update as it's the same as the last one");
// return;
// }
// _lastDiscordStatus = presence.Status;
var clientStatus = presence.ClientStatus.Keys.Aggregate(string.Empty, (current, device) => current + $"{device} is {presence.ClientStatus[device]}; ");
SendChatMessage($"[img]{settings[BuiltIn.Keys.DiscordIcon].Value}[/img] BossmanJack has updated his Discord presence: {clientStatus}");
}
private void DiscordOnMessageReceived(object sender, DiscordMessageModel message)
{
var settings = Helpers.GetMultipleValues([BuiltIn.Keys.DiscordBmjId, BuiltIn.Keys.DiscordIcon]).Result;
if (message.Author.Id != settings[BuiltIn.Keys.DiscordBmjId].Value)
{
return;
}
var result = $"[img]{settings[BuiltIn.Keys.DiscordIcon].Value}[/img] BossmanJack: {message.Content}";
foreach (var attachment in message.Attachments ?? [])
{
result += $"[br]Attachment: {attachment.GetProperty("filename").GetString()} {attachment.GetProperty("url").GetString()}";
}
SendChatMessage(result);
}
private void DiscordOnInvalidCredentials(object sender, DiscordPacketReadModel packet)
{
_logger.Error("Credentials failed to validate.");
}
private void ShuffleOnLatestBetUpdated(object sender, ShuffleLatestBetModel bet)
{
var settings = Helpers
.GetMultipleValues([
BuiltIn.Keys.ShuffleBmjUsername, BuiltIn.Keys.TwitchBossmanJackUsername,
BuiltIn.Keys.KiwiFarmsGreenColor, BuiltIn.Keys.KiwiFarmsRedColor
]).Result;
_logger.Trace("Shuffle bet has arrived");
if (bet.Username != settings[BuiltIn.Keys.ShuffleBmjUsername].Value)
{
return;
}
_logger.Info("ALERT BMJ IS BETTING");
if (IsBmjLive)
{
_logger.Info("Ignoring as BMJ is live");
return;
}
// Only check once because the bot should be tracking the Twitch stream
// This is just in case he's already live while the bot starts
// He was schizo betting on Dice, so I want to avoid a lot of API requests to Twitch in case they rate limit
if (!_isBmjLiveSynced)
{
IsBmjLive = _twitch.IsStreamLive(settings[BuiltIn.Keys.TwitchBossmanJackUsername].Value!).Result;
_isBmjLiveSynced = true;
}
if (IsBmjLive)
{
_logger.Info("Double checked and he is really online");
return;
}
var payoutColor = settings[BuiltIn.Keys.KiwiFarmsGreenColor].Value;
if (float.Parse(bet.Payout) < float.Parse(bet.Amount)) payoutColor = settings[BuiltIn.Keys.KiwiFarmsRedColor].Value;
// There will be a check for live status but ignoring that while we deal with an emergency dice situation
SendChatMessage($"🚨🚨 Shufflebros! 🚨🚨 {bet.Username} just bet {bet.Amount} {bet.Currency} which paid out [color={payoutColor}]{bet.Payout} {bet.Currency}[/color] ({bet.Multiplier}x) on {bet.GameName} 💰💰", true);
}
private void OnTwitchStreamStateUpdated(object sender, int channelId, bool isLive)
{
_logger.Info($"BossmanJack stream event came in. isLive => {isLive}");
if (isLive)
{
SendChatMessage("BossmanJack just went live on Twitch! https://www.twitch.tv/thebossmanjack\r\n" +
"Ad-free re-stream at https://bossmanjack.tv courtesy of @Kees H");
IsBmjLive = true;
return;
}
SendChatMessage("BossmanJack is no longer live! :lossmanjack:");
IsBmjLive = false;
}
private void OnFailedToJoinRoom(object sender, string message)
{
_logger.Error($"Couldn't join the room. KF returned: {message}");
_logger.Error("This is likely due to the session cookie expiring. Retrieving a new one.");
RefreshXfToken().Wait(_cancellationToken);
KfClient.UpdateToken(_xfSessionToken);
_logger.Info("Retrieved fresh token. Reconnecting.");
KfClient.Disconnect();
KfClient.StartWsClient().Wait(_cancellationToken);
_logger.Info("Client should be reconnecting now");
}
private void PingThread()
{
while (_pingEnabled)
{
Thread.Sleep(TimeSpan.FromSeconds(15));
_logger.Debug("Pinging KF");
KfClient.SendMessage("/ping");
if (!_kickDisabled)
{
_kickClient.SendPusherPing();
}
if (_initialStartCooldown) _initialStartCooldown = false;
var inactivityTime = DateTime.Now - _lastKfEvent;
_logger.Debug($"Last KF event was {inactivityTime:g} ago");
if (inactivityTime.TotalMinutes > 10)
{
_logger.Error("Forcing reconnection as bot is completely dead");
KfClient.Reconnect().Wait(_cancellationToken);
}
_logger.Debug("Polling Bossman's Howl.gg stats");
_howlgg?.GetUserInfo("951905");
}
}
private async Task RefreshXfToken()
{
var settings = Helpers.GetMultipleValues([BuiltIn.Keys.KiwiFarmsDomain,
BuiltIn.Keys.KiwiFarmsUsername, BuiltIn.Keys.KiwiFarmsPassword, BuiltIn.Keys.KiwiFarmsChromiumPath,
BuiltIn.Keys.Proxy]).Result;
var cookie = await KfTokenService.FetchSessionTokenAsync(settings[BuiltIn.Keys.KiwiFarmsDomain].Value!,
settings[BuiltIn.Keys.KiwiFarmsUsername].Value!, settings[BuiltIn.Keys.KiwiFarmsPassword].Value!,
settings[BuiltIn.Keys.KiwiFarmsChromiumPath].Value!, settings[BuiltIn.Keys.Proxy].Value);
_logger.Debug($"FetchSessionTokenAsync returned {cookie}");
_xfSessionToken = cookie;
await Helpers.SetValue(BuiltIn.Keys.KiwiFarmsToken, _xfSessionToken);
}
private void OnStreamerIsLive(object sender, KickModels.StreamerIsLiveEventModel? e)
{
if (e == null) return;
SendChatMessage($"Dirt Devils LFG! @Juhlonduss is live! {e.Livestream.SessionTitle} https://kick.com/dirtdevil-enjoyer", true);
}
private void OnStopStreamBroadcast(object sender, KickModels.StopStreamBroadcastEventModel? e)
{
SendChatMessage("Dirt Devils felted. Stream is over. :lossmanjack:", true);
}
private void OnKfChatMessage(object sender, List<MessageModel> messages, MessagesJsonModel jsonPayload)
{
var settings = Helpers.GetMultipleValues([BuiltIn.Keys.GambaSeshDetectEnabled, BuiltIn.Keys.GambaSeshUserId])
.Result;
_lastKfEvent = DateTime.Now;
_logger.Debug($"Received {messages.Count} message(s)");
foreach (var message in messages)
{
_logger.Info($"KF ({message.MessageDate.ToLocalTime():HH:mm:ss}) <{message.Author.Username}> {message.Message}");
if (settings[BuiltIn.Keys.GambaSeshDetectEnabled].Value == "true" && !_initialStartCooldown && message.Author.Id == Convert.ToInt32(settings[BuiltIn.Keys.GambaSeshUserId].Value) && !GambaSeshPresent)
{
_logger.Info("Received a GambaSesh message after cooldown and while thinking he's not here. Setting the presence flag to avoid spamming chat");
GambaSeshPresent = true;
}
if (!_seenMsgIds.Contains(message.MessageId) && !_initialStartCooldown)
{
_logger.Debug("Passing message to command interface");
_botCommands.ProcessMessage(message);
}
else
{
_logger.Debug($"_seenMsgIds check => {!_seenMsgIds.Contains(message.MessageId)}, _initialStartCooldown => {_initialStartCooldown}");
}
_seenMsgIds.Add(message.MessageId);
}
}
public void SendChatMessage(string message, bool bypassSeshDetect = false)
{
var settings = Helpers
.GetMultipleValues([BuiltIn.Keys.KiwiFarmsSuppressChatMessages, BuiltIn.Keys.GambaSeshDetectEnabled])
.Result;
if (settings[BuiltIn.Keys.KiwiFarmsSuppressChatMessages].Value == "true")
{
_logger.Info("Not sending message as SuppressChatMessages is enabled");
_logger.Info($"Message was: {message}");
return;
}
if (GambaSeshPresent && settings[BuiltIn.Keys.GambaSeshDetectEnabled].Value == "true" && !bypassSeshDetect)
{
_logger.Info($"Not sending message '{message}' as GambaSesh is present");
return;
}
KfClient.SendMessage(message);
}
private void OnKickChatMessage(object sender, KickModels.ChatMessageEventModel? e)
{
if (e == null) return;
_logger.Info($"Kick ({e.CreatedAt.LocalDateTime.ToLocalTime():HH:mm:ss}) <{e.Sender.Username}> {e.Content}");
_logger.Debug($"BB Code Translation: {e.Content.TranslateKickEmotes()}");
if (e.Sender.Slug != "bossmanjack") return;
var kickIcon = Helpers.GetValue(BuiltIn.Keys.KickIcon).Result;
_logger.Debug("Message from BossmanJack");
SendChatMessage($"[img]{kickIcon.Value}[/img] BossmanJack: {e.Content.TranslateKickEmotes()}");
}
private void OnUsersJoined(object sender, List<UserModel> users, UsersJsonModel jsonPayload)
{
var settings = Helpers.GetMultipleValues([BuiltIn.Keys.GambaSeshUserId, BuiltIn.Keys.GambaSeshDetectEnabled])
.Result;
_lastKfEvent = DateTime.Now;
_logger.Debug($"Received {users.Count} user join events");
using var db = new ApplicationDbContext();
foreach (var user in users)
{
if (user.Id == Convert.ToInt32(settings[BuiltIn.Keys.GambaSeshUserId].Value) && settings[BuiltIn.Keys.GambaSeshDetectEnabled].Value == "true")
{
_logger.Info("GambaSesh is now present");
GambaSeshPresent = true;
}
_logger.Info($"{user.Username} joined!");
var userDb = db.Users.FirstOrDefault(u => u.KfId == user.Id);
if (userDb == null)
{
db.Users.Add(new UserDbModel { KfId = user.Id, KfUsername = user.Username });
_logger.Debug("Adding user to DB");
continue;
}
// Detect a username change
if (userDb.KfUsername != user.Username)
{
_logger.Debug("Username has updated, updating DB");
userDb.KfUsername = user.Username;
db.SaveChanges();
}
}
db.SaveChanges();
}
private void OnUsersParted(object sender, List<int> userIds)
{
var settings = Helpers.GetMultipleValues([BuiltIn.Keys.GambaSeshUserId, BuiltIn.Keys.GambaSeshDetectEnabled])
.Result;
_lastKfEvent = DateTime.Now;
if (userIds.Contains(Convert.ToInt32(settings[BuiltIn.Keys.GambaSeshUserId].Value)) && settings[BuiltIn.Keys.GambaSeshDetectEnabled].Value == "true")
{
_logger.Info("GambaSesh is no longer present");
GambaSeshPresent = false;
}
}
private void OnKfWsDisconnected(object sender, DisconnectionInfo disconnectionInfo)
{
_logger.Error($"Sneedchat disconnected due to {disconnectionInfo.Type}");
_logger.Error($"Close Status => {disconnectionInfo.CloseStatus}; Close Status Description => {disconnectionInfo.CloseStatusDescription}");
_logger.Error(disconnectionInfo.Exception);
}
private void OnKfWsReconnected(object sender, ReconnectionInfo reconnectionInfo)
{
var roomId = Convert.ToInt32(Helpers.GetValue(BuiltIn.Keys.KiwiFarmsRoomId).Result.Value);
_logger.Error($"Sneedchat reconnected due to {reconnectionInfo.Type}");
_logger.Info("Resetting GambaSesh presence so it can resync if he crashed while the bot was DC'd");
GambaSeshPresent = false;
_logger.Info($"Rejoining {roomId}");
KfClient.JoinRoom(roomId);
}
private void OnPusherWsReconnected(object sender, ReconnectionInfo reconnectionInfo)
{
_logger.Error($"Pusher reconnected due to {reconnectionInfo.Type}");
var channels = Helpers.GetValue(BuiltIn.Keys.PusherChannels).Result.Value ?? "";
foreach (var channel in channels.Split(','))
{
_logger.Info($"Rejoining {channel}");
_kickClient.SendPusherSubscribe(channel);
}
}
private void OnPusherSubscriptionSucceeded(object sender, PusherModels.BasePusherEventModel? e)
{
_logger.Info($"Pusher indicates subscription to {e?.Channel} was successful");
}
}

View File

@@ -0,0 +1,63 @@
using System.Text.RegularExpressions;
using Humanizer;
using KfChatDotNetBot.Models.DbModels;
using KfChatDotNetBot.Settings;
using KfChatDotNetWsClient.Models.Events;
using Microsoft.EntityFrameworkCore;
namespace KfChatDotNetBot.Commands;
public class HowlggStatsCommand : ICommand
{
public List<Regex> Patterns => [
new Regex(@"^howl stats (?<window>\d+)$")
];
public string HelpText => "Get betting statistics in the given window";
public bool HideFromHelp => false;
public UserRight RequiredRight => UserRight.Guest;
public async Task RunCommand(ChatBot botInstance, MessageModel message, GroupCollection arguments, CancellationToken ctx)
{
var window = Convert.ToInt32(arguments["window"].Value);
var start = DateTimeOffset.UtcNow.AddHours(-window);
var division = (await Helpers.GetValue(BuiltIn.Keys.HowlggDivisionAmount)).ToType<float>();
await using var db = new ApplicationDbContext();
// EF SQLite doesn't support filtering on dates :(
var bets = (await db.HowlggBets.ToListAsync(ctx)).Where(b => b.Date.UtcDateTime > start).ToList();
if (bets.Count == 0)
{
botInstance.SendChatMessage("No bets captured during this window", true);
return;
}
var output = $"Howl.gg stats for the last {window} hours:[br]" +
$"Bets: {bets.Count:N0}; Profit: {bets.Sum(b => b.Profit) / division:C}; Wagered: {bets.Sum(b => b.Bet) / division:C}";
botInstance.SendChatMessage(output, true);
}
}
public class HowlggRecentBetCommand : ICommand
{
public List<Regex> Patterns => [
new Regex(@"^howl recent$")
];
public string HelpText => "Get the most recent 3 bets";
public bool HideFromHelp => false;
public UserRight RequiredRight => UserRight.Guest;
public async Task RunCommand(ChatBot botInstance, MessageModel message, GroupCollection arguments, CancellationToken ctx)
{
var settings = await Helpers.GetMultipleValues([
BuiltIn.Keys.KiwiFarmsGreenColor, BuiltIn.Keys.KiwiFarmsRedColor, BuiltIn.Keys.HowlggDivisionAmount
]);
var division = settings[BuiltIn.Keys.HowlggDivisionAmount].ToType<float>();
await using var db = new ApplicationDbContext();
// EF SQLite doesn't support filtering on dates :(
var bets = (await db.HowlggBets.ToListAsync(ctx)).OrderByDescending(j => j.Date).Take(3).ToList();
var output = "Most recent 3 bets on Howl.gg:";
foreach (var bet in bets)
{
var color = settings[BuiltIn.Keys.KiwiFarmsGreenColor].Value;
if (bet.Profit < 0) color = settings[BuiltIn.Keys.KiwiFarmsRedColor].Value;
output += $"[br]Bet: {bet.Bet / division:C}; Profit: [color={color}]{bet.Profit / division:C}[/color]; Game: {bet.Game.Humanize()}; {(DateTimeOffset.UtcNow - bet.Date).Humanize(precision: 1)} ago";
}
botInstance.SendChatMessage(output, true);
}
}

View File

@@ -0,0 +1,15 @@
using System.Text.RegularExpressions;
using KfChatDotNetBot.Models.DbModels;
using KfChatDotNetWsClient.Models.Events;
namespace KfChatDotNetBot.Commands;
internal interface ICommand
{
List<Regex> Patterns { get; }
string HelpText { get; }
bool HideFromHelp { get; }
UserRight RequiredRight { get; }
Task RunCommand(ChatBot botInstance, MessageModel message, GroupCollection arguments, CancellationToken ctx);
}

View File

@@ -0,0 +1,46 @@
using System.Text.RegularExpressions;
using Humanizer;
using KfChatDotNetBot.Models.DbModels;
using KfChatDotNetBot.Settings;
using KfChatDotNetWsClient.Models.Events;
using Microsoft.EntityFrameworkCore;
namespace KfChatDotNetBot.Commands;
public class JuiceCommand : ICommand
{
public List<Regex> Patterns => [new Regex("^juiceme")];
public string HelpText => "Get juice!";
public bool HideFromHelp => false;
public UserRight RequiredRight => UserRight.Guest;
public async Task RunCommand(ChatBot botInstance, MessageModel message, GroupCollection arguments, CancellationToken ctx)
{
await using var db = new ApplicationDbContext();
var user = await db.Users.FirstOrDefaultAsync(u => u.KfId == message.Author.Id, cancellationToken: ctx);
if (user == null) return;
var juicerSettings = await Helpers.GetMultipleValues([BuiltIn.Keys.JuiceAmount, BuiltIn.Keys.JuiceCooldown]);
var cooldown = juicerSettings[BuiltIn.Keys.JuiceCooldown].ToType<int>();
var amount = juicerSettings[BuiltIn.Keys.JuiceAmount].ToType<int>();
var lastJuicer = (await db.Juicers.Where(j => j.User == user).ToListAsync(ctx)).OrderByDescending(j => j.JuicedAt).Take(1).ToList();
if (lastJuicer.Count == 0)
{
botInstance.SendChatMessage($"!juice {message.Author.Id} {amount}", true);
await db.Juicers.AddAsync(new JuicerDbModel
{ Amount = amount, User = user, JuicedAt = DateTimeOffset.UtcNow }, ctx);
await db.SaveChangesAsync(ctx);
return;
}
var secondsRemaining = lastJuicer[0].JuicedAt.AddSeconds(cooldown) - DateTimeOffset.UtcNow;
if (secondsRemaining.TotalSeconds <= 0)
{
botInstance.SendChatMessage($"!juice {message.Author.Id} {amount}", true);
await db.Juicers.AddAsync(new JuicerDbModel
{ Amount = amount, User = user, JuicedAt = DateTimeOffset.UtcNow }, ctx);
await db.SaveChangesAsync(ctx);
return;
}
botInstance.SendChatMessage($"You gotta wait {secondsRemaining.Humanize(precision: 2)} for another juicer", true);
}
}

View File

@@ -0,0 +1,61 @@
using System.Text.RegularExpressions;
using KfChatDotNetBot.Models.DbModels;
using KfChatDotNetWsClient.Models.Events;
namespace KfChatDotNetBot.Commands;
public class InsanityCommand : ICommand
{
public List<Regex> Patterns => [new Regex("^insanity")];
public string HelpText => "Insanity";
public bool HideFromHelp => false;
public UserRight RequiredRight => UserRight.Guest;
public async Task RunCommand(ChatBot botInstance, MessageModel message, GroupCollection arguments, CancellationToken ctx)
{
// ReSharper disable once StringLiteralTypo
botInstance.SendChatMessage("definition of insanity = doing the same thing over and over and over excecting a different result, and heres my dumbass trying to get rich every day and losing everythign i fucking touch every fucking time FUCK this bullshit FUCK MY LIEFdefinition of insanity = doing the same thing over and over and over excecting a different result, and heres my dumbass trying to get rich every day and losing everythign i fucking touch every fucking time FUCK this bullshit FUCK MY LIEF");
}
}
public class TwistedCommand : ICommand
{
public List<Regex> Patterns => [new Regex("^twisted")];
public string HelpText => "Get it twisted";
public bool HideFromHelp => false;
public UserRight RequiredRight => UserRight.Guest;
public async Task RunCommand(ChatBot botInstance, MessageModel message, GroupCollection arguments, CancellationToken ctx)
{
// ReSharper disable once StringLiteralTypo
botInstance.SendChatMessage("🦍 🗣 GET IT TWISTED 🌪 , GAMBLE ✅ . PLEASE START GAMBLING 👍 . GAMBLING IS AN INVESTMENT 🎰 AND AN INVESTMENT ONLY 👍 . YOU WILL PROFIT 💰 , YOU WILL WIN ❗ . YOU WILL DO ALL OF THAT 💯 , YOU UNDERSTAND ⁉ YOU WILL BECOME A BILLIONAIRE 💵 📈 AND REBUILD YOUR FUCKING LIFE 🤯");
}
}
public class HelpMeCommand : ICommand
{
public List<Regex> Patterns => [new Regex("^helpme")];
public string HelpText => "Somebody please help me";
public bool HideFromHelp => false;
public UserRight RequiredRight => UserRight.Guest;
public async Task RunCommand(ChatBot botInstance, MessageModel message, GroupCollection arguments, CancellationToken ctx)
{
// ReSharper disable once StringLiteralTypo
botInstance.SendChatMessage("[img]https://i.postimg.cc/fTw6tGWZ/ineedmoneydumbfuck.png[/img]", true);
}
}
public class SentCommand : ICommand
{
public List<Regex> Patterns => [new Regex("^sent$")];
public string HelpText => "Sent love";
public bool HideFromHelp => false;
public UserRight RequiredRight => UserRight.Guest;
public async Task RunCommand(ChatBot botInstance, MessageModel message, GroupCollection arguments, CancellationToken ctx)
{
// ReSharper disable once StringLiteralTypo
botInstance.SendChatMessage("[img]https://i.ibb.co/GHq7hb1/4373-g-N5-HEH2-Hkc.png[/img]", true);
}
}

View File

@@ -0,0 +1,20 @@
using System.Text.RegularExpressions;
using KfChatDotNetBot.Models.DbModels;
using KfChatDotNetWsClient.Models.Events;
namespace KfChatDotNetBot.Commands;
public class TimeCommand : ICommand
{
public List<Regex> Patterns => [new Regex("^time")];
public string HelpText => "Get current time in BMT";
public bool HideFromHelp => false;
public UserRight RequiredRight => UserRight.Guest;
public async Task RunCommand(ChatBot botInstance, MessageModel message, GroupCollection arguments, CancellationToken ctx)
{
var bmt = new DateTimeOffset(TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow,
TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")), TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time").BaseUtcOffset);
botInstance.SendChatMessage($"It's currently {bmt:h:mm:ss tt} BMT");
}
}

View File

@@ -0,0 +1,30 @@
using System.Text.RegularExpressions;
using KfChatDotNetBot.Models.DbModels;
using KfChatDotNetWsClient.Models.Events;
using Microsoft.EntityFrameworkCore;
namespace KfChatDotNetBot.Commands;
public class WhoisCommand : ICommand
{
public List<Regex> Patterns => [
new Regex("^whois (?<user>.+)")
];
public string HelpText => "Lookup user IDs by username";
public bool HideFromHelp => false;
public UserRight RequiredRight => UserRight.Guest;
public async Task RunCommand(ChatBot botInstance, MessageModel message, GroupCollection arguments, CancellationToken ctx)
{
await using var db = new ApplicationDbContext();
var query = arguments["user"].Value.TrimStart('@').TrimEnd(',').TrimEnd();
var user = await db.Users.FirstOrDefaultAsync(u => u.KfUsername == query, cancellationToken: ctx);
if (user == null)
{
botInstance.SendChatMessage($"Requested user '{query}' does not exist. (Note this is case-sensitive)", true);
return;
}
botInstance.SendChatMessage($"@{message.Author.Username}, {user.KfUsername}'s ID is {user.KfId}", true);
}
}

View File

@@ -0,0 +1,30 @@
using System.Text.RegularExpressions;
namespace KfChatDotNetBot;
public static class Extensions
{
/// Emotes are encoded like [emote:161238:russW] which translates to -> https://files.kick.com/emotes/161238/fullsize
public static string TranslateKickEmotes(this string s)
{
Regex regex = new Regex(@"\[(.+?):(\d+):(\S+?)\]");
var matches = regex.Matches(s);
if (matches.Count == 0)
{
return s;
}
foreach (Match match in matches)
{
// First group is the whole matched string
// 0 -> [emote:161238:russW]
// 1 -> emote
// 2 -> 161238
// 3 -> russW
var emoteId = match.Groups[2];
s = s.Replace(match.Value, $"[img]https://files.kick.com/emotes/{emoteId}/fullsize[/img]");
}
return s;
}
}

View File

@@ -0,0 +1,40 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Humanizer.Core" Version="2.14.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.7" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.7">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="8.0.7" />
<PackageReference Include="NLog" Version="5.3.2" />
<PackageReference Include="PuppeteerSharp" Version="18.0.5" />
<PackageReference Include="System.Text.Json" Version="8.0.4" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\KfChatDotNetWsClient\KfChatDotNetWsClient.csproj" />
<ProjectReference Include="..\KickWsClient\KickWsClient.csproj" />
</ItemGroup>
<ItemGroup>
<Content Update="NLog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<None Remove="config.json" />
<Content Include="config.json" />
<None Remove="NLog.config" />
<Content Include="NLog.config">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,82 @@
// <auto-generated />
using System;
using KfChatDotNetBot;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace KfChatDotNetBot.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20240714132259_Initial")]
partial class Initial
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "8.0.7");
modelBuilder.Entity("KfChatDotNetKickBot.Models.DbModels.JuicerDbModel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<float>("Amount")
.HasColumnType("REAL");
b.Property<DateTimeOffset>("JuicedAt")
.HasColumnType("TEXT");
b.Property<int>("UserId")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("Juicers");
});
modelBuilder.Entity("KfChatDotNetKickBot.Models.DbModels.UserDbModel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<bool>("Ignored")
.HasColumnType("INTEGER");
b.Property<int>("KfId")
.HasColumnType("INTEGER");
b.Property<string>("KfUsername")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("UserRight")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("KfChatDotNetKickBot.Models.DbModels.JuicerDbModel", b =>
{
b.HasOne("KfChatDotNetKickBot.Models.DbModels.UserDbModel", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,67 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace KfChatDotNetBot.Migrations
{
/// <inheritdoc />
public partial class Initial : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
KfUsername = table.Column<string>(type: "TEXT", nullable: false),
KfId = table.Column<int>(type: "INTEGER", nullable: false),
UserRight = table.Column<int>(type: "INTEGER", nullable: false),
Ignored = table.Column<bool>(type: "INTEGER", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Users", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Juicers",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
UserId = table.Column<int>(type: "INTEGER", nullable: false),
Amount = table.Column<float>(type: "REAL", nullable: false),
JuicedAt = table.Column<DateTimeOffset>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Juicers", x => x.Id);
table.ForeignKey(
name: "FK_Juicers_Users_UserId",
column: x => x.UserId,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Juicers_UserId",
table: "Juicers",
column: "UserId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Juicers");
migrationBuilder.DropTable(
name: "Users");
}
}
}

View File

@@ -0,0 +1,115 @@
// <auto-generated />
using System;
using KfChatDotNetBot;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace KfChatDotNetBot.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20240716193646_Settings")]
partial class Settings
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "8.0.7");
modelBuilder.Entity("KfChatDotNetKickBot.Models.DbModels.JuicerDbModel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<float>("Amount")
.HasColumnType("REAL");
b.Property<DateTimeOffset>("JuicedAt")
.HasColumnType("TEXT");
b.Property<int>("UserId")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("Juicers");
});
modelBuilder.Entity("KfChatDotNetKickBot.Models.DbModels.SettingDbModel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("Default")
.HasColumnType("TEXT");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("TEXT");
b.Property<bool>("IsSecret")
.HasColumnType("INTEGER");
b.Property<string>("Key")
.IsRequired()
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("Regex")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Value")
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("Settings");
});
modelBuilder.Entity("KfChatDotNetKickBot.Models.DbModels.UserDbModel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<bool>("Ignored")
.HasColumnType("INTEGER");
b.Property<int>("KfId")
.HasColumnType("INTEGER");
b.Property<string>("KfUsername")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("UserRight")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("KfChatDotNetKickBot.Models.DbModels.JuicerDbModel", b =>
{
b.HasOne("KfChatDotNetKickBot.Models.DbModels.UserDbModel", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,39 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace KfChatDotNetBot.Migrations
{
/// <inheritdoc />
public partial class Settings : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Settings",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Key = table.Column<string>(type: "TEXT", nullable: false),
Value = table.Column<string>(type: "TEXT", nullable: true),
Regex = table.Column<string>(type: "TEXT", nullable: false),
Description = table.Column<string>(type: "TEXT", nullable: false),
Default = table.Column<string>(type: "TEXT", nullable: true),
IsSecret = table.Column<bool>(type: "INTEGER", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Settings", x => x.Id);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Settings");
}
}
}

View File

@@ -0,0 +1,148 @@
// <auto-generated />
using System;
using KfChatDotNetBot;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace KfChatDotNetBot.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20240717110408_Howlgg")]
partial class Howlgg
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "8.0.7");
modelBuilder.Entity("KfChatDotNetKickBot.Models.DbModels.HowlggBetsDbModel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("Bet")
.HasColumnType("INTEGER");
b.Property<int>("BetId")
.HasColumnType("INTEGER");
b.Property<DateTimeOffset>("Date")
.HasColumnType("TEXT");
b.Property<string>("Game")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long>("GameId")
.HasColumnType("INTEGER");
b.Property<long>("Profit")
.HasColumnType("INTEGER");
b.Property<int>("UserId")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.ToTable("HowlggBets");
});
modelBuilder.Entity("KfChatDotNetKickBot.Models.DbModels.JuicerDbModel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<float>("Amount")
.HasColumnType("REAL");
b.Property<DateTimeOffset>("JuicedAt")
.HasColumnType("TEXT");
b.Property<int>("UserId")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("Juicers");
});
modelBuilder.Entity("KfChatDotNetKickBot.Models.DbModels.SettingDbModel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("Default")
.HasColumnType("TEXT");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("TEXT");
b.Property<bool>("IsSecret")
.HasColumnType("INTEGER");
b.Property<string>("Key")
.IsRequired()
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("Regex")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Value")
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("Settings");
});
modelBuilder.Entity("KfChatDotNetKickBot.Models.DbModels.UserDbModel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<bool>("Ignored")
.HasColumnType("INTEGER");
b.Property<int>("KfId")
.HasColumnType("INTEGER");
b.Property<string>("KfUsername")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("UserRight")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("KfChatDotNetKickBot.Models.DbModels.JuicerDbModel", b =>
{
b.HasOne("KfChatDotNetKickBot.Models.DbModels.UserDbModel", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,41 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace KfChatDotNetBot.Migrations
{
/// <inheritdoc />
public partial class Howlgg : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "HowlggBets",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
UserId = table.Column<int>(type: "INTEGER", nullable: false),
BetId = table.Column<int>(type: "INTEGER", nullable: false),
GameId = table.Column<long>(type: "INTEGER", nullable: false),
Bet = table.Column<long>(type: "INTEGER", nullable: false),
Profit = table.Column<long>(type: "INTEGER", nullable: false),
Date = table.Column<DateTimeOffset>(type: "TEXT", nullable: false),
Game = table.Column<string>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_HowlggBets", x => x.Id);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "HowlggBets");
}
}
}

View File

@@ -0,0 +1,145 @@
// <auto-generated />
using System;
using KfChatDotNetBot;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace KfChatDotNetBot.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
partial class ApplicationDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "8.0.7");
modelBuilder.Entity("KfChatDotNetKickBot.Models.DbModels.HowlggBetsDbModel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("Bet")
.HasColumnType("INTEGER");
b.Property<int>("BetId")
.HasColumnType("INTEGER");
b.Property<DateTimeOffset>("Date")
.HasColumnType("TEXT");
b.Property<string>("Game")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long>("GameId")
.HasColumnType("INTEGER");
b.Property<long>("Profit")
.HasColumnType("INTEGER");
b.Property<int>("UserId")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.ToTable("HowlggBets");
});
modelBuilder.Entity("KfChatDotNetKickBot.Models.DbModels.JuicerDbModel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<float>("Amount")
.HasColumnType("REAL");
b.Property<DateTimeOffset>("JuicedAt")
.HasColumnType("TEXT");
b.Property<int>("UserId")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("Juicers");
});
modelBuilder.Entity("KfChatDotNetKickBot.Models.DbModels.SettingDbModel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("Default")
.HasColumnType("TEXT");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("TEXT");
b.Property<bool>("IsSecret")
.HasColumnType("INTEGER");
b.Property<string>("Key")
.IsRequired()
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("Regex")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Value")
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("Settings");
});
modelBuilder.Entity("KfChatDotNetKickBot.Models.DbModels.UserDbModel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<bool>("Ignored")
.HasColumnType("INTEGER");
b.Property<int>("KfId")
.HasColumnType("INTEGER");
b.Property<string>("KfUsername")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("UserRight")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("KfChatDotNetKickBot.Models.DbModels.JuicerDbModel", b =>
{
b.HasOne("KfChatDotNetKickBot.Models.DbModels.UserDbModel", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,13 @@
namespace KfChatDotNetBot.Models;
public class BuiltInSettingsModel
{
// Model here largely maps to what's in SettingDbModel, the idea is that there's a set of built-in settings that get
// populated when migrating old JSON configs and updated on start if there's a schema change (e.g. regex changed)
public required string Key { get; set; }
public required string Regex { get; set; }
public required string Description { get; set; }
public string? Default { get; set; }
public required bool IsSecret { get; set; }
}

View File

@@ -0,0 +1,30 @@
namespace KfChatDotNetBot.Models;
[Obsolete]
public class ConfigModel
{
public Uri PusherEndpoint { get; set; } =
new("wss://ws-us2.pusher.com/app/eb1d5f283081a78b932c?protocol=7&client=js&version=7.6.0&flash=false");
public Uri KfWsEndpoint { get; set; } = new("wss://kiwifarms.st:9443/chat.ws");
public List<string> PusherChannels { get; set; } = [];
public int KfChatRoomId { get; set; }
// Proxy to use for everything
public string? Proxy { get; set; }
public int KfReconnectTimeout { get; set; } = 30;
public int PusherReconnectTimeout { get; set; } = 30;
public bool EnableGambaSeshDetect { get; set; } = true;
public int GambaSeshUserId { get; set; } = 168162;
public string KickIcon { get; set; } = "https://i.ibb.co/0cqwscx/kick.png";
public string KfDomain { get; set; } = "kiwifarms.st";
public required string KfUsername { get; set; }
public required string KfPassword { get; set; }
public string ChromiumPath { get; set; } = "chromium_install";
public int? BossmanJackTwitchId { get; set; } = null;
public string? BossmanJackTwitchUsername { get; set; } = "thebossmanjack";
// Used for testing
public bool SuppressChatMessages { get; set; } = false;
public string? DiscordToken { get; set; } = null;
public string? DiscordBmjId { get; set; } = "554123642246529046";
}

View File

@@ -0,0 +1,17 @@
namespace KfChatDotNetBot.Models.DbModels;
public class HowlggBetsDbModel
{
public int Id { get; set; }
public required int UserId { get; set; }
// Per-user bet ID, counts up based on total # of bets
public required int BetId { get; set; }
// Global bet ID
public required long GameId { get; set; }
// Cents
public required long Bet { get; set; }
// Cents
public required long Profit { get; set; }
public required DateTimeOffset Date { get; set; }
public required string Game { get; set; }
}

View File

@@ -0,0 +1,9 @@
namespace KfChatDotNetBot.Models.DbModels;
public class JuicerDbModel
{
public int Id { get; set; }
public required UserDbModel User { get; set; }
public float Amount { get; set; }
public DateTimeOffset JuicedAt { get; set; }
}

View File

@@ -0,0 +1,19 @@
using System.ComponentModel.DataAnnotations.Schema;
namespace KfChatDotNetBot.Models.DbModels;
public class SettingDbModel
{
public int Id { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public required string Key { get; set; }
public string? Value { get; set; }
// For validation
public required string Regex { get; set; } = @"\S+";
// Friendly descriptor for the setting, e.g. "BossmanJack's howl.gg ID"
public required string Description { get; set; }
// Default to use when constructing the setting and nothing is supplied
public string? Default { get; set; } = null;
// Prevents the value from being revealed to Sneedchat when queried by an admin
public bool IsSecret { get; set; } = false;
}

View File

@@ -0,0 +1,21 @@
using System.ComponentModel;
namespace KfChatDotNetBot.Models.DbModels;
public class UserDbModel
{
public int Id { get; set; }
public required string KfUsername { get; set; }
public int KfId { get; set; }
public UserRight UserRight { get; set; } = UserRight.Guest;
public bool Ignored { get; set; } = false;
}
public enum UserRight
{
Admin = 1000,
[Description("True and Honest")]
TrueAndHonest = 100,
Guest = 10,
Loser = 0
}

View File

@@ -0,0 +1,50 @@
using System.Text.Json.Serialization;
namespace KfChatDotNetBot.Models;
public class HowlggBetHistoryResponseModel
{
[JsonPropertyName("user")]
public required HowlggUserModel User { get; set; }
[JsonPropertyName("history")]
public required HowlggHistoryModel History { get; set; }
}
public class HowlggUserModel
{
[JsonPropertyName("id")]
public required int Id { get; set; }
[JsonPropertyName("name")]
public required string Name { get; set; }
[JsonPropertyName("createdAt")]
public required DateTimeOffset CreatedAt { get; set; }
[JsonPropertyName("netProfit")]
public long NetProfit { get; set; }
}
public class HowlggHistoryModel
{
[JsonPropertyName("profit")]
public required long Profit { get; set; }
[JsonPropertyName("cumulative")]
public required long Cumulative { get; set; }
[JsonPropertyName("data")]
public required List<HowlggHistoryDataModel> Data { get; set; }
}
public class HowlggHistoryDataModel
{
[JsonPropertyName("id")]
public required int Id { get; set; }
[JsonPropertyName("bet")]
public required long Bet { get; set; }
[JsonPropertyName("date")]
// For some reason it has a +2 offset
public required DateTimeOffset Date { get; set; }
[JsonPropertyName("game")]
public required string Game { get; set; }
[JsonPropertyName("gameId")]
public required long GameId { get; set; }
[JsonPropertyName("profit")]
public required long Profit { get; set; }
}

View File

@@ -0,0 +1,62 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace KfChatDotNetBot.Models;
public class JackpotWsPacketModel
{
[JsonPropertyName("id")]
public required string Id { get; set; }
[JsonPropertyName("type")]
public required string Type { get; set; }
[JsonPropertyName("payload")]
public JsonElement? Payload { get; set; }
}
public class JackpotWsBetPayloadModel
{
[JsonPropertyName("createdAt")]
public required long CreatedAt { get; set; }
[JsonPropertyName("roundId")]
public required string RoundId { get; set; }
[JsonPropertyName("gameName")]
public required string GameName { get; set; }
[JsonPropertyName("gameSlug")]
public required string GameSlug { get; set; }
[JsonPropertyName("currency")]
public required string Currency { get; set; }
[JsonPropertyName("wager")]
public required float Wager { get; set; }
[JsonPropertyName("payout")]
public required float Payout { get; set; }
[JsonPropertyName("multiplier")]
public required float Multiplier { get; set; }
[JsonPropertyName("user")]
public required string User { get; set; }
}
public class JackpotQuickviewModel
{
[JsonPropertyName("createdAt")]
public required long CreatedAt { get; set; }
[JsonPropertyName("userId")]
public required string UserId { get; set; }
[JsonPropertyName("username")]
public required string Username { get; set; }
[JsonPropertyName("isPrivate")]
public bool IsPrivate { get; set; }
[JsonPropertyName("role")]
public required string Role { get; set; }
[JsonPropertyName("rankId")]
public required int RankId { get; set; }
[JsonPropertyName("rank")]
public required string Rank { get; set; }
[JsonPropertyName("rankProgress")]
public required float RankProgress { get; set; }
[JsonPropertyName("wagered")]
public required Dictionary<string, float> Wagered { get; set; }
[JsonPropertyName("bets")]
public required Dictionary<string, int> Bets { get; set; }
[JsonPropertyName("wins")]
public required Dictionary<string, int> Wins { get; set; }
}

View File

@@ -0,0 +1,26 @@
namespace KfChatDotNetBot.Models;
public class PocketWatchModel
{
public required string Network { get; set; }
public required string Address { get; set; }
public required string Label { get; set; }
public required bool BypassGambaSeshPresenceDetection { get; set; }
public required int CheckIntervalSec { get; set; }
// Used internally to detect new transactions
public required DateTime LastChecked { get; set; } = DateTime.Now;
}
public class PocketWatchEventModel
{
public required string TransactionHash { get; set; }
public required DateTimeOffset Time { get; set; }
public required string Currency { get; set; }
public required string Effect { get; set; }
public required string Network { get; set; }
public required string Address { get; set; }
public required long Balance { get; set; }
public required float UsdRate { get; set; }
public required bool IsMempool { get; set; }
public required PocketWatchModel PocketWatch { get; set; }
}

View File

@@ -0,0 +1,58 @@
using System.Text.Json.Serialization;
namespace KfChatDotNetBot.Models;
public class ShuffleLatestBetModel
{
[JsonPropertyName("id")]
public required string Id { get; set; }
[JsonPropertyName("username")]
public string? Username { get; set; }
[JsonPropertyName("vipLevel")]
public required string VipLevel { get; set; }
[JsonPropertyName("currency")]
public required string Currency { get; set; }
[JsonPropertyName("amount")]
public required string Amount { get; set; }
[JsonPropertyName("payout")]
public required string Payout { get; set; }
[JsonPropertyName("multiplier")]
public required string Multiplier { get; set; }
[JsonPropertyName("gameName")]
public required string GameName { get; set; }
[JsonPropertyName("gameCategory")]
public required string GameCategory { get; set; }
[JsonPropertyName("gameSlug")]
public required string GameSlug { get; set; }
}
// {
// "data": {
// "user": {
// "id": "a98f83c3-89b7-4e8d-9e11-7dcf1a89b1ba",
// "username": "TheBossmanJack",
// "vipLevel": "SAPPHIRE_3",
// "createdAt": "2024-06-16T23:17:58.533Z",
// "avatar": 36,
// "avatarBackground": 1,
// "bets": 9450,
// "usdWagered": "3518595.04092444",
// "__typename": "User"
// }
// }
// }
public class ShuffleUserModel
{
[JsonPropertyName("id")]
public required string Id { get; set; }
[JsonPropertyName("username")]
public required string Username { get; set; }
[JsonPropertyName("vipLevel")]
public required string VipLevel { get; set; }
[JsonPropertyName("createdAt")]
public required DateTimeOffset CreatedAt { get; set; }
[JsonPropertyName("bets")]
public required int Bets { get; set; }
[JsonPropertyName("usdWagered")]
public required string UsdWagered { get; set; }
}

View File

@@ -0,0 +1,48 @@
using System.Text.Json.Serialization;
namespace KfChatDotNetBot.Models;
public class ThreeXplEventModel
{
[JsonPropertyName("block")]
public int? Block { get; set; }
[JsonPropertyName("transaction")]
public required string TransactionHash { get; set; }
[JsonPropertyName("sort_key")]
public int? SortKey { get; set; }
[JsonPropertyName("time")]
public DateTimeOffset? Time { get; set; }
[JsonPropertyName("currency")]
public required string Currency { get; set; }
[JsonPropertyName("effect")]
public required string Effect { get; set; }
[JsonPropertyName("failed")]
public bool? Failed { get; set; }
[JsonPropertyName("extra")]
public string? Extra { get; set; }
}
public class ThreeXplCurrencyModel
{
[JsonPropertyName("name")]
public required string Name { get; set; }
[JsonPropertyName("type")]
public string? Type { get; set; }
[JsonPropertyName("symbol")]
public required string Symbol { get; set; }
[JsonPropertyName("decimals")]
public required int Decimals { get; set; }
[JsonPropertyName("description")]
public string? Description { get; set; }
}
public class ThreeXplAddressModel
{
[JsonPropertyName("address")]
public required string Address { get; set; }
[JsonPropertyName("balances")]
public required Dictionary<string, int?> Balances { get; set; }
[JsonPropertyName("events")]
public required Dictionary<string, int?> Events { get; set; }
}

View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
throwExceptions="false"
internalLogLevel="Off" internalLogFile="~/nlog-internal.log">
<targets>
<target xsi:type="ColoredConsole" name="console"/>
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="console" />
</rules>
</nlog>

3483
KfChatDotNetBot/NLog.xsd Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,25 @@
using System.Text;
using KfChatDotNetBot.Settings;
using Microsoft.EntityFrameworkCore;
using NLog;
namespace KfChatDotNetBot
{
public class Program
{
static void Main(string[] args)
{
var logger = LogManager.GetCurrentClassLogger();
logger.Info("Opening up DB to perform a migration (if one is needed)");
using var db = new ApplicationDbContext();
db.Database.Migrate();
logger.Info("Migration done. Syncing bultin settings keys");
BuiltIn.SyncSettingsWithDb().Wait();
logger.Info("Migrating settings from config.json (if needed)");
BuiltIn.MigrateJsonSettingsToDb().Wait();
logger.Info("Handing over to bot now");
Console.OutputEncoding = Encoding.UTF8;
new ChatBot();
}
}
}

View 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);
}
}
}

View 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; }
}

View 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);
}
}

View 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);
}
}

View 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;
}

View 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);
}
}

View 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;
}
}

View 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);
}
}

View 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);
}
}

View File

@@ -0,0 +1,391 @@
using System.Text.Json;
using KfChatDotNetBot.Models;
using KfChatDotNetBot.Models.DbModels;
using NLog;
namespace KfChatDotNetBot.Settings;
public static class BuiltIn
{
// Creates DB options if they don't exist and all fields (except value) if these have changed in code
public static async Task SyncSettingsWithDb()
{
var logger = LogManager.GetCurrentClassLogger();
await using var db = new ApplicationDbContext();
logger.Info($"Syncing {BuiltInSettings.Count} settings with the DB");
foreach (var builtIn in BuiltInSettings)
{
var setting = db.Settings.FirstOrDefault(setting => setting.Key == builtIn.Key);
if (setting == null)
{
logger.Info($"{builtIn.Key} doesn't exist in the DB, creating");
db.Settings.Add(new SettingDbModel
{
Key = builtIn.Key,
Value = builtIn.Default,
Regex = builtIn.Regex,
Description = builtIn.Description,
Default = builtIn.Default,
IsSecret = builtIn.IsSecret
});
continue;
}
logger.Debug($"{builtIn.Key} exists in the DB, now going to ensure its fields are consistent");
setting.Key = builtIn.Key;
setting.Regex = builtIn.Regex;
setting.Description = builtIn.Description;
setting.Default = builtIn.Default;
setting.IsSecret = builtIn.IsSecret;
}
logger.Info("Saving changes to the DB");
await db.SaveChangesAsync();
}
public static async Task MigrateJsonSettingsToDb()
{
var oldConfigPath = "config.json";
var logger = LogManager.GetCurrentClassLogger();
await using var db = new ApplicationDbContext();
logger.Info($"Checking {oldConfigPath} exists");
if (!Path.Exists(oldConfigPath))
{
logger.Info($"{oldConfigPath} does not exist. Migration already performed or was never needed");
return;
}
logger.Info($"Migrating {oldConfigPath}");
#pragma warning disable CS0612 // Type or member is obsolete
var oldConfig = JsonSerializer.Deserialize<ConfigModel>(await File.ReadAllTextAsync(oldConfigPath));
#pragma warning restore CS0612 // Type or member is obsolete
if (oldConfig == null)
{
logger.Error($"Caught a null when deserializing {oldConfigPath}");
return;
}
await Helpers.SetValue(Keys.PusherEndpoint, oldConfig.PusherEndpoint.ToString());
await Helpers.SetValue(Keys.KiwiFarmsWsEndpoint, oldConfig.KfWsEndpoint.ToString());
await Helpers.SetValueAsList(Keys.PusherChannels, oldConfig.PusherChannels);
await Helpers.SetValue(Keys.KiwiFarmsRoomId, oldConfig.KfChatRoomId);
await Helpers.SetValue(Keys.Proxy, oldConfig.Proxy);
await Helpers.SetValue(Keys.KiwiFarmsWsReconnectTimeout, oldConfig.KfReconnectTimeout);
await Helpers.SetValue(Keys.PusherReconnectTimeout, oldConfig.PusherReconnectTimeout);
await Helpers.SetValueAsBoolean(Keys.GambaSeshDetectEnabled, oldConfig.EnableGambaSeshDetect);
await Helpers.SetValue(Keys.GambaSeshUserId, oldConfig.GambaSeshUserId);
await Helpers.SetValue(Keys.KickIcon, oldConfig.KickIcon);
await Helpers.SetValue(Keys.KiwiFarmsDomain, oldConfig.KfDomain);
await Helpers.SetValue(Keys.KiwiFarmsUsername, oldConfig.KfUsername);
await Helpers.SetValue(Keys.KiwiFarmsPassword, oldConfig.KfPassword);
await Helpers.SetValue(Keys.KiwiFarmsChromiumPath, oldConfig.ChromiumPath);
await Helpers.SetValue(Keys.TwitchBossmanJackId, oldConfig.BossmanJackTwitchId);
await Helpers.SetValue(Keys.TwitchBossmanJackUsername, oldConfig.BossmanJackTwitchUsername);
await Helpers.SetValueAsBoolean(Keys.KiwiFarmsSuppressChatMessages, oldConfig.SuppressChatMessages);
await Helpers.SetValue(Keys.DiscordToken, oldConfig.DiscordToken);
await Helpers.SetValue(Keys.DiscordBmjId, oldConfig.DiscordBmjId);
logger.Info($"{oldConfigPath} migration done.");
logger.Info("Renaming files no longer in use");
// Utils.SafelyRenameFile will attempt to rename and swallow any exception (with logging) if it fails
Utils.SafelyRenameFile(oldConfigPath, $"{oldConfigPath}.migrated");
logger.Info("File renamed");
}
public static List<BuiltInSettingsModel> BuiltInSettings =
[
new BuiltInSettingsModel
{
Key = Keys.PusherEndpoint,
Regex = @".+",
Description =
"Pusher WebSocket endpoint URL",
Default = "wss://ws-us2.pusher.com/app/eb1d5f283081a78b932c?protocol=7&client=js&version=7.6.0&flash=false",
IsSecret = false
},
new BuiltInSettingsModel
{
Key = Keys.KiwiFarmsWsEndpoint,
Regex = @".+",
Description =
"Kiwi Farms chat WebSocket endpoint",
Default = "wss://kiwifarms.st:9443/chat.ws",
IsSecret = false
},
new BuiltInSettingsModel
{
Key = Keys.PusherChannels,
Regex = @".+",
Description =
"List of Pusher channels to subscribe to",
Default = null,
IsSecret = false
},
new BuiltInSettingsModel
{
Key = Keys.KiwiFarmsRoomId,
Regex = @"\d+",
Description =
"Kiwi Farms Keno Kasino room ID",
Default = "15",
IsSecret = false
},
new BuiltInSettingsModel
{
Key = Keys.Proxy,
Regex = @".+",
Description =
"Proxy to use for all outgoing requests. Null to disable",
Default = null,
IsSecret = false
},
new BuiltInSettingsModel
{
Key = Keys.KiwiFarmsWsReconnectTimeout,
Regex = @"\d+",
Description =
"Kiwi Farms chat reconnect timeout",
Default = "30",
IsSecret = false
},
new BuiltInSettingsModel
{
Key = Keys.PusherReconnectTimeout,
Regex = @"\d+",
Description =
"Pusher reconnect timeout",
Default = "30",
IsSecret = false
},
new BuiltInSettingsModel
{
Key = Keys.GambaSeshDetectEnabled,
Regex = @"true|false",
Description =
"Whether to enable detection for the presence of GambaSesh",
Default = "true",
IsSecret = false
},
new BuiltInSettingsModel
{
Key = Keys.GambaSeshUserId,
Regex = @"\d+",
Description =
"GambaSesh's uer ID for the purposes of detection",
Default = "168162",
IsSecret = false
},
new BuiltInSettingsModel
{
Key = Keys.KickIcon,
Regex = @".+",
Description =
"Kick Icon to use for relaying chat messages",
Default = "https://i.postimg.cc/Qtw4nCPG/kick16.png",
IsSecret = false
},
new BuiltInSettingsModel
{
Key = Keys.KiwiFarmsDomain,
Regex = @".+",
Description =
"Domain to use when retrieving a session token",
Default = "kiwifarms.st",
IsSecret = false
},
new BuiltInSettingsModel
{
Key = Keys.KiwiFarmsUsername,
Regex = @".+",
Description =
"Username to use when authenticating with Kiwi Farms",
Default = null,
IsSecret = true
},
new BuiltInSettingsModel
{
Key = Keys.KiwiFarmsPassword,
Regex = @".+",
Description =
"Password to use when authenticating with Kiwi Farms",
Default = null,
IsSecret = true
},
new BuiltInSettingsModel
{
Key = Keys.KiwiFarmsChromiumPath,
Regex = @".+",
Description =
"Path to download the Chromium install used for the token grabber",
Default = "chromium_install",
IsSecret = false
},
new BuiltInSettingsModel
{
Key = Keys.TwitchBossmanJackId,
Regex = @"\d+",
Description =
"BossmanJack's Twitch channel ID",
Default = "114122847",
IsSecret = false
},
new BuiltInSettingsModel
{
Key = Keys.TwitchBossmanJackUsername,
Regex = @".+",
Description =
"BossmanJack's Twitch channel username",
Default = "thebossmanjack",
IsSecret = false
},
new BuiltInSettingsModel
{
Key = Keys.KiwiFarmsSuppressChatMessages,
Regex = @"true|false",
Description =
"Enable to prevent messages from actually being sent to chat.",
Default = "false",
IsSecret = false
},
new BuiltInSettingsModel
{
Key = Keys.DiscordToken,
Regex = @".+",
Description =
"Token to use when authenticating with Discord. Set to null to disable.",
Default = null,
IsSecret = true
},
new BuiltInSettingsModel
{
Key = Keys.DiscordBmjId,
Regex = @"\d+",
Description =
"BossmanJack's Discord user ID",
Default = "554123642246529046",
IsSecret = false
},
new BuiltInSettingsModel
{
Key = Keys.TwitchIcon,
Regex = ".+",
Description = "URL for the 16px Twitch icon",
Default = "https://i.postimg.cc/QMFVV2Xk/twitch16.png",
IsSecret = false
},
new BuiltInSettingsModel
{
Key = Keys.DiscordIcon,
Regex = ".+",
Description = "URL for the 16px Discord icon",
Default = "https://i.postimg.cc/cLmQrp89/discord16.png",
IsSecret = false
},
new BuiltInSettingsModel
{
Key = Keys.ShuffleBmjUsername,
Regex = ".+",
Description = "Bossman's Shuffle Username",
Default = "TheBossmanJack",
IsSecret = false
},
new BuiltInSettingsModel
{
Key = Keys.JuiceCooldown,
Regex = @"\d+",
Description = "Cooldown (in seconds) until you can get juiced again",
Default = "3600",
IsSecret = false
},
new BuiltInSettingsModel
{
Key = Keys.JuiceAmount,
Regex = @"\d+",
Description = "Amount of $KKK to juice",
Default = "50",
IsSecret = false
},
new BuiltInSettingsModel
{
Key = Keys.KiwiFarmsToken,
Regex = ".+",
Description = "Last successfully retrieved forum token (will be refreshed automatically if expired)",
Default = null,
IsSecret = true
},
new BuiltInSettingsModel
{
Key = Keys.KickEnabled,
Regex = "true|false",
Description = "Whether to enable Kick functionality (Pusher websocket mainly)",
Default = "true",
IsSecret = false
},
new BuiltInSettingsModel
{
Key = Keys.HowlggDivisionAmount,
Regex = @"\d+",
Description = "How much to divide the Howlgg bets/profit by to get the real value",
Default = "1650",
IsSecret = false
},
new BuiltInSettingsModel()
{
Key = Keys.KiwiFarmsGreenColor,
Regex = ".+",
Description = "Green color used for showing positive values in chat",
Default = "#3dd179",
IsSecret = false
},
new BuiltInSettingsModel()
{
Key = Keys.KiwiFarmsRedColor,
Regex = ".+",
Description = "Red color used for showing negative values in chat",
Default = "#f1323e",
IsSecret = false
},
new BuiltInSettingsModel()
{
Key = Keys.JackpotBmjUsername,
Regex = ".+",
Description = "Bossman's username on Jackpot",
Default = "TheBossmanJack",
IsSecret = false
}
];
public static class Keys
{
public static string PusherEndpoint = "Pusher.Endpoint";
public static string KiwiFarmsWsEndpoint = "KiwiFarms.WsEndpoint";
public static string PusherChannels = "Pusher.Channels";
public static string KiwiFarmsRoomId = "KiwiFarms.RoomId";
public static string Proxy = "Proxy";
public static string KiwiFarmsWsReconnectTimeout = "KiwiFarms.WsReconnectTimeout";
public static string PusherReconnectTimeout = "Pusher.ReconnectTimeout";
public static string GambaSeshDetectEnabled = "GambaSesh.DetectEnabled";
public static string GambaSeshUserId = "GambaSesh.UserId";
public static string KickIcon = "Kick.Icon";
public static string KiwiFarmsDomain = "KiwiFarms.Domain";
public static string KiwiFarmsUsername = "KiwiFarms.Username";
public static string KiwiFarmsPassword = "KiwiFarms.Password";
public static string KiwiFarmsChromiumPath = "KiwiFarms.ChromiumPath";
public static string TwitchBossmanJackId = "Twitch.BossmanJackId";
public static string TwitchBossmanJackUsername = "Twitch.BossmanJackUsername";
public static string KiwiFarmsSuppressChatMessages = "KiwiFarms.SuppressChatMessages";
public static string DiscordToken = "Discord.Token";
public static string DiscordBmjId = "Discord.BmjId";
public static string TwitchIcon = "Twitch.Icon";
public static string DiscordIcon = "Discord.Icon";
public static string ShuffleBmjUsername = "Shuffle.BmjUsername";
public static string JuiceCooldown = "Juice.Cooldown";
public static string JuiceAmount = "Juice.Amount";
public static string KiwiFarmsToken = "KiwiFarms.Token";
public static string KickEnabled = "Kick.Enabled";
public static string HowlggDivisionAmount = "Howlgg.DivisionAmount";
public static string KiwiFarmsGreenColor = "KiwiFarms.GreenColor";
public static string KiwiFarmsRedColor = "KiwiFarms.RedColor";
public static string JackpotBmjUsername = "Jackpot.BmjUsername";
}
}

View File

@@ -0,0 +1,173 @@
using KfChatDotNetBot.Models.DbModels;
using Microsoft.EntityFrameworkCore;
using NLog;
namespace KfChatDotNetBot.Settings;
public static class Helpers
{
public static async Task<SettingValue> GetValue(string key, bool caseInsensitive = false)
{
var logger = LogManager.GetCurrentClassLogger();
await using var db = new ApplicationDbContext();
logger.Trace($"Retrieving value for {key}");
SettingDbModel? setting;
if (caseInsensitive)
{
// String comparison doesn't work on EF core if I recall correctly
#pragma warning disable CA1862
setting = await db.Settings.FirstOrDefaultAsync(s => s.Key.ToLower() == key.ToLower());
#pragma warning restore CA1862
}
else
{
setting = await db.Settings.FirstOrDefaultAsync(s => s.Key == key);
}
if (setting == null)
{
logger.Debug($"{key} does not exist, throwing KeyNotFoundException");
throw new KeyNotFoundException($"{key} does not exist");
}
if (setting.Value == "null")
{
logger.Debug($"{key}'s value is null so returning SettingValue(null)");
return new SettingValue(null, null);
}
logger.Debug($"Returning '{setting.Value}' as {typeof(SettingValue)}");
return new SettingValue(setting.Value, setting);
}
public static async Task<Dictionary<string, SettingValue>> GetMultipleValues(string[] keys, bool caseInsensitive = false)
{
var logger = LogManager.GetCurrentClassLogger();
await using var db = new ApplicationDbContext();
logger.Trace($"Getting values for keys {string.Join(", ", keys)}");
Dictionary<string, SettingValue> values = new Dictionary<string, SettingValue>();
foreach (var key in keys)
{
SettingDbModel? setting;
if (caseInsensitive)
{
// String comparison doesn't work on EF core if I recall correctly
#pragma warning disable CA1862
setting = await db.Settings.FirstOrDefaultAsync(s => s.Key.ToLower() == key.ToLower());
#pragma warning restore CA1862
}
else
{
setting = await db.Settings.FirstOrDefaultAsync(s => s.Key == key);
}
if (setting == null)
{
logger.Debug($"{key} does not exist, throwing KeyNotFoundException()");
throw new KeyNotFoundException();
}
if (setting.Value == "null")
{
logger.Debug($"{key}'s value is null so returning SettingValue(null)");
values.Add(key, new SettingValue(null, null));
continue;
}
values.Add(key, new SettingValue(setting.Value, setting));
}
return values;
}
public static async Task SetValue(string key, object? value)
{
var logger = LogManager.GetCurrentClassLogger();
await using var db = new ApplicationDbContext();
string stringValue;
if (value == null)
{
stringValue = "null";
}
else if (value is string)
{
stringValue = (string)value;
}
else
{
stringValue = (string)Convert.ChangeType(value, TypeCode.String);
}
logger.Debug($"Setting {key} to {stringValue}");
var setting = await db.Settings.FirstOrDefaultAsync(s => s.Key == key);
if (setting == null)
{
logger.Debug($"{key} does not exist, throwing KeyNotFoundException()");
throw new KeyNotFoundException();
}
setting.Value = stringValue;
await db.SaveChangesAsync();
}
public static async Task SetValueAsList<T>(string key, List<T> values, char separator = ',')
{
var logger = LogManager.GetCurrentClassLogger();
await using var db = new ApplicationDbContext();
List<string> stringValues = values.Select(val => (string)Convert.ChangeType(val, TypeCode.String)).ToList();
string joinedValue = string.Join(separator, stringValues);
logger.Debug($"Setting {key} to {joinedValue}");
var setting = await db.Settings.FirstOrDefaultAsync(s => s.Key == key);
if (setting == null)
{
logger.Debug($"{key} does not exist, throwing KeyNotFoundException()");
throw new KeyNotFoundException();
}
setting.Value = joinedValue;
await db.SaveChangesAsync();
}
public static async Task SetValueAsKeyValuePairs<T>(string key, Dictionary<string, T> data, char delimiter = ',',
char separator = '=')
{
var logger = LogManager.GetCurrentClassLogger();
await using var db = new ApplicationDbContext();
logger.Debug($"Building data for {key}");
var value = data.Keys.Aggregate(string.Empty,
(current, dictKey) => current + $"{dictKey}{separator}{data[dictKey]}{delimiter}");
// Remove trailing delimiters that would be leftover as it doesn't account for whether it's the last key
value = value.TrimEnd(delimiter);
logger.Debug($"Setting {key} to {value}");
var setting = await db.Settings.FirstOrDefaultAsync(s => s.Key == key);
if (setting == null)
{
logger.Debug($"{key} does not exist, throwing KeyNotFoundException()");
throw new KeyNotFoundException();
}
setting.Value = value;
await db.SaveChangesAsync();
}
public static async Task SetValueAsBoolean(string key, bool value)
{
var logger = LogManager.GetCurrentClassLogger();
await using var db = new ApplicationDbContext();
logger.Debug($"Setting {key} to {value}");
var setting = await db.Settings.FirstOrDefaultAsync(s => s.Key == key);
if (setting == null)
{
logger.Debug($"{key} does not exist, throwing KeyNotFoundException()");
throw new KeyNotFoundException();
}
setting.Value = value ? "true" : "false";
await db.SaveChangesAsync();
}
}

View File

@@ -0,0 +1,9 @@
using KfChatDotNetBot.Models.DbModels;
namespace KfChatDotNetBot.Settings;
public class SettingValue(string? value, SettingDbModel? dbEntry)
{
public string? Value { get; set; } = value;
public SettingDbModel? DbEntry { get; set; } = dbEntry;
}

View File

@@ -0,0 +1,59 @@
using NLog;
namespace KfChatDotNetBot.Settings;
public static class Utils
{
public static List<string> ToList(this SettingValue settingValue, char separator = ',')
{
if (settingValue.Value == null) return new List<string>();
return settingValue.Value.Split(separator).ToList();
}
public static Dictionary<string, T> ToKeyValuePairs<T>(this SettingValue settingValue, char delimiter = ',',
char separator = '=')
{
if (settingValue.Value == null)
{
return new Dictionary<string, T>();
}
return settingValue.Value.Split(delimiter).ToDictionary(kv => kv.Split(separator)[0],
kv => ValueToType<T>(kv.Split(separator)[1]));
}
public static bool ToBoolean(this SettingValue settingValue)
{
var logger = LogManager.GetCurrentClassLogger();
if (settingValue.Value is null or "null")
{
return default;
}
return settingValue.Value.Equals("true", StringComparison.CurrentCultureIgnoreCase);
}
public static T ValueToType<T>(string value)
{
return (T)Convert.ChangeType(value, typeof(T));
}
public static T ToType<T>(this SettingValue settingValue)
{
return (T)Convert.ChangeType(settingValue.Value, typeof(T));
}
public static void SafelyRenameFile(string oldName, string newName)
{
var logger = LogManager.GetCurrentClassLogger();
logger.Debug($"Renaming {oldName} to {newName}");
try
{
File.Move(oldName, newName);
}
catch (Exception e)
{
logger.Error($"Failed to rename {oldName} to {newName}");
logger.Error(e);
}
}
}

View File

@@ -0,0 +1,6 @@
{
"PusherChannels": ["channel.28448806"],
"Proxy": "socks5://us-lax-wg-socks5-203.relays.mullvad.net:1080",
"KfChatRoomId": 15,
"BossmanJackTwitchId": 114122847
}