Initial commit

This commit is contained in:
barelyprofessional
2024-03-25 20:11:49 +08:00
commit 9f92fc8e27
62 changed files with 17831 additions and 0 deletions

View File

@@ -0,0 +1,36 @@
using Microsoft.Data.Sqlite;
using NLog;
namespace KfChatDotNetKickBot;
public static class Helpers
{
// This ended up being pretty useless as it turns out Firefox doesn't store session cookies in cookies.sqlite
// But I'll leave it here in case it becomes useful one day
public static async Task<string?> GetXfToken(string cookieName, string cookieDomain, string containerPath)
{
var logger = LogManager.GetCurrentClassLogger();
await using var connection = new SqliteConnection($"Data Source={containerPath}");
await connection.OpenAsync();
logger.Debug($"Opened {containerPath}");
var command = connection.CreateCommand();
command.CommandText = "SELECT value FROM moz_cookies WHERE host = $host AND name = $name ORDER BY creationTime DESC LIMIT 1";
command.Parameters.AddWithValue("$host", cookieDomain);
command.Parameters.AddWithValue("$name", cookieName);
logger.Debug("Created command");
logger.Debug(command.CommandText);
await using var reader = await command.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
logger.Debug("Reading first row, which will be immediately returned anyway");
return reader.GetString(0);
}
logger.Error("Fucked up while retrieving cookie. Cookie doesn't exist?");
return null;
}
}

View File

@@ -0,0 +1,32 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Data.Sqlite" Version="8.0.3" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="NLog" Version="5.2.8" />
<PackageReference Include="Spectre.Console" Version="0.48.0" />
</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">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,164 @@
using KfChatDotNetWsClient;
using KfChatDotNetWsClient.Models;
using KfChatDotNetWsClient.Models.Events;
using KfChatDotNetWsClient.Models.Json;
using KickWsClient.Models;
using Newtonsoft.Json;
using NLog;
using Spectre.Console;
using Websocket.Client;
namespace KfChatDotNetKickBot;
public class KickBot
{
private ChatClient _kfClient;
private KickWsClient.KickWsClient _kickClient;
private Logger _logger = LogManager.GetCurrentClassLogger();
private Models.ConfigModel _config;
private Thread _pingThread;
private bool _pingEnabled = true;
public KickBot()
{
_logger.Info("Bot starting!");
const string configPath = "config.json";
if (!Path.Exists(configPath))
{
_logger.Error($"{configPath} is missing! Exiting");
Environment.Exit(1);
}
_config = JsonConvert.DeserializeObject<Models.ConfigModel>(File.ReadAllText(configPath)) ??
throw new InvalidOperationException();
_kfClient = new ChatClient(new ChatClientConfigModel
{
WsUri = _config.KfWsEndpoint,
XfSessionToken = GetXfToken(),
CookieDomain = _config.KfWsEndpoint.Host,
Proxy = _config.KfProxy,
ReconnectTimeout = _config.KfReconnectTimeout
});
_kickClient = new KickWsClient.KickWsClient(_config.PusherEndpoint.ToString(),
_config.PusherProxy, _config.PusherReconnectTimeout);
_kfClient.OnMessages += OnKfChatMessage;
_kfClient.OnUsersParted += OnUsersParted;
_kfClient.OnUsersJoined += OnUsersJoined;
_kfClient.OnWsDisconnection += OnKfWsDisconnected;
_kfClient.OnWsReconnect += OnKfWsReconnected;
_kickClient.OnStreamerIsLive += OnStreamerIsLive;
_kickClient.OnChatMessage += OnKickChatMessage;
_kickClient.OnWsReconnect += OnPusherWsReconnected;
_kickClient.OnPusherSubscriptionSucceeded += OnPusherSubscriptionSucceeded;
_kfClient.StartWsClient().Wait();
_kfClient.JoinRoom(_config.KfChatRoomId);
_kickClient.StartWsClient().Wait();
foreach (var channel in _config.PusherChannels)
{
_kickClient.SendPusherSubscribe(channel);
}
_pingThread = new Thread(PingThread);
_pingThread.Start();
while (true)
{
var input = AnsiConsole.Prompt(new TextPrompt<string>("Enter Message:"));
_kfClient.SendMessage(input);
}
}
private void PingThread()
{
while (_pingEnabled)
{
Thread.Sleep(TimeSpan.FromSeconds(15));
_logger.Debug("Pinging KF and Pusher");
_kfClient.SendMessage("/ping");
_kickClient.SendPusherPing();
}
}
private string GetXfToken()
{
//return Helpers.GetXfToken("xf_session", _config.KfWsEndpoint.Host, _config.FirefoxCookieContainer).Result ??
// throw new InvalidOperationException();
return _config.XfTokenValue;
}
private void OnStreamerIsLive(object sender, KickModels.StreamerIsLiveEventModel? e)
{
}
private void OnKfChatMessage(object sender, List<MessageModel> messages, MessagesJsonModel jsonPayload)
{
_logger.Debug($"Received {messages.Count} message(s)");
foreach (var message in messages)
{
AnsiConsole.MarkupLine($"[yellow]KF[/] <{message.Author.Username}> {message.Message.EscapeMarkup()} ({message.MessageDate.LocalDateTime.ToShortTimeString()})");
}
}
private void OnKickChatMessage(object sender, KickModels.ChatMessageEventModel? e)
{
if (e == null) return;
AnsiConsole.MarkupLine($"[green]Kick[/] <{e.Sender.Username}> {e.Content.EscapeMarkup()} ({e.CreatedAt.LocalDateTime.ToShortTimeString()})");
}
private void OnUsersJoined(object sender, List<UserModel> users, UsersJsonModel jsonPayload)
{
_logger.Debug($"Received {users.Count} user join events");
foreach (var user in users)
{
AnsiConsole.MarkupLine($"[green]{user.Username.EscapeMarkup()} joined![/]");
}
}
private void OnUsersParted(object sender, List<int> userIds)
{
_logger.Debug($"Received {userIds.Count} user part events");
foreach (var id in userIds)
{
AnsiConsole.MarkupLine($"[red]{id} left the chat...[/]");
}
}
private void OnKfWsDisconnected(object sender, DisconnectionInfo disconnectionInfo)
{
AnsiConsole.MarkupLine($"[red]Sneedchat disconnected due to {disconnectionInfo.Type}[/]");
AnsiConsole.MarkupLine("[yellow]Grabbing fresh token from browser[/]");
var token = GetXfToken();
AnsiConsole.MarkupLine($"[green]Obtained token = {token.EscapeMarkup()}[/]");
_kfClient.UpdateToken(token);
}
private void OnKfWsReconnected(object sender, ReconnectionInfo reconnectionInfo)
{
AnsiConsole.MarkupLine($"[red]Sneedchat reconnected due to {reconnectionInfo.Type}[/]");
AnsiConsole.MarkupLine($"[green]Rejoining {_config.KfChatRoomId}[/]");
_kfClient.JoinRoom(_config.KfChatRoomId);
}
private void OnPusherWsReconnected(object sender, ReconnectionInfo reconnectionInfo)
{
AnsiConsole.MarkupLine($"[red]Pusher reconnected due to {reconnectionInfo.Type}[/]");
foreach (var channel in _config.PusherChannels)
{
AnsiConsole.MarkupLine($"[green]Rejoining {channel}[/]");
_kickClient.SendPusherSubscribe(channel);
}
}
private void OnPusherSubscriptionSucceeded(object sender, PusherModels.BasePusherEventModel? e)
{
AnsiConsole.MarkupLine($"[green]Pusher indicates subscription to {e?.Channel.EscapeMarkup()} was successful[/]");
}
}

View File

@@ -0,0 +1,24 @@
namespace KfChatDotNetKickBot;
public class Models
{
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 connecting to Sneedchat
public string? KfProxy { get; set; }
// Proxy to use for the Pusher websocket
// e.g. socks5://blahblah:1080
public string? PusherProxy { get; set; }
public int KfReconnectTimeout { get; set; } = 30;
public int PusherReconnectTimeout { get; set; } = 30;
// Todo: Find a way to extract this from the browser as it's not valid forever
public string? XfTokenValue { 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="Console" name="console"/>
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="console" />
</rules>
</nlog>

3483
KfChatDotNetKickBot/NLog.xsd Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,15 @@
using System.Net;
using System.Text;
using NLog;
namespace KfChatDotNetKickBot
{
public class Program
{
static void Main(string[] args)
{
Console.OutputEncoding = Encoding.UTF8;
new KickBot();
}
}
}

View File

@@ -0,0 +1,6 @@
{
"PusherChannels": ["chatrooms.2507974.v2", "channel.2515504"],
"KfProxy": "socks5://us-lax-wg-socks5-203.relays.mullvad.net:1080",
"KfChatRoomId": 15,
"XfTokenValue": "fill this in with the value from xf_session"
}