// Copyright (c) 2026 HexEchoTV (CUB) // Licensed under the MIT License. See LICENSE file in the project root for full license information. // https://github.com/HexEchoTV/Streamerbot-Commands // // DEPENDENCIES: // - ConfigSetup.cs (run it first: it sets the currency and every config_ value read below; // anything it hasn't set falls back to the default shown in the code) // // SETUP: create an action, add a sub-action "Core > C# > Execute C# Code", paste this file, // then add a Command trigger for !race. // Leave the action out of any blocking queue: the starter's run waits for racers // to join, and a blocking queue would hold every !race join until it had finished. // // USAGE: // !race start [bet] start a race; others have config_race_join_seconds (default 30) to join // !race join join for the same entry fee // Computer racers fill the field to 4. A viewer who wins takes entry x config_race_win_mult // (default 4), or the whole pot when more viewers than that race. Every racer then waits // config_race_cooldown_minutes (default 35) before racing again. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Text; public class CPHInline { public bool Execute() { try { LoadCurrency(); string user = Arg("user"); string userId = Arg("userId"); if (string.IsNullOrEmpty(user) || string.IsNullOrEmpty(userId)) { CPH.LogError("Race command: missing 'user' or 'userId' argument"); return false; } int minBet = Cfg("config_race_min_bet", 25); int maxBet = Cfg("config_race_max_bet", 450); int winMult = Cfg("config_race_win_mult", 4); int cooldownMinutes = Cfg("config_race_cooldown_minutes", 35); int joinSeconds = Cfg("config_race_join_seconds", 30); string sub = Arg("input0").ToLowerInvariant(); double wait = CooldownLeft(userId, "race_cooldown", TimeSpan.FromMinutes(cooldownMinutes)); if (sub == "join") { int fee; lock (RaceLock) { if (Racers == null) { CPH.SendMessage($"{user}, no race is starting. Start one with !race start [bet]!"); return false; } if (Racers.Any(r => r.UserId == userId)) { CPH.SendMessage($"{user}, you're already on the start line!"); return false; } fee = Entry; } if (wait > 0) { CPH.SendMessage($"{user}, you're still catching your breath. Race again in {FormatWait(wait)}!"); return false; } int balance = GetBalance(userId); if (balance < fee) { CPH.SendMessage($"{user}, the entry is {Money(fee)} {currencyName}; you have {Money(balance)}."); return false; } lock (RaceLock) { if (Racers == null) { CPH.SendMessage($"{user}, too late, the race has started!"); return false; } SetBalance(userId, balance - fee); Racers.Add(new Racer { UserId = userId, Name = user }); } LogCommand("!race join", user, $"Entry: {Money(fee)}"); CPH.SendMessage($"🏃 {user} joined the race! ({Money(fee)})"); return true; } if (sub != "start") { CPH.SendMessage($"{user}, usage: !race start [bet {minBet}-{maxBet}] or !race join"); return false; } lock (RaceLock) { if (Racers != null) { CPH.SendMessage($"{user}, a race is about to start! Type !race join to get in."); return false; } } if (wait > 0) { CPH.SendMessage($"{user}, you're still catching your breath. Race again in {FormatWait(wait)}!"); return false; } int bal = GetBalance(userId), bet; if (!ReadBet(Arg("input1"), bal, minBet, maxBet, out bet)) { CPH.SendMessage($"{user}, usage: !race start [bet {minBet}-{maxBet}]"); return false; } if (bet < minBet || bet > maxBet) { CPH.SendMessage($"{user}, the entry must be between {Money(minBet)} and {Money(maxBet)}!"); return false; } if (bal < bet) { CPH.SendMessage($"{user}, you only have {Money(bal)} {currencyName}! You need {Money(bet)}."); return false; } lock (RaceLock) { if (Racers != null) { CPH.SendMessage($"{user}, a race is about to start! Type !race join to get in."); return false; } SetBalance(userId, bal - bet); Racers = new List { new Racer { UserId = userId, Name = user } }; Entry = bet; } LogCommand("!race start", user, $"Entry: {Money(bet)}"); CPH.SendMessage($"🏁 {user} started a race! Entry: {Money(bet)} | Type !race join ({joinSeconds}s)"); CPH.Wait(joinSeconds * 1000); List field; lock (RaceLock) { field = Racers; Racers = null; } int humans = field.Count; string[] bots = { "Speedy", "Turbo", "Zippy", "Dash" }; for (int i = 0; field.Count < 4; i++) field.Add(new Racer { Name = bots[i] }); string[] animals = { "🐢", "🐇", "🐎", "🐆", "🦊", "🐕", "🐿️", "🦘" }; for (int i = 0; i < field.Count; i++) field[i].Icon = animals[i % animals.Length]; Racer winner = field[Roll(field.Count)]; foreach (Racer r in field) if (r.UserId != null) StartCooldown(r.UserId, "race_cooldown"); string line = string.Join(" ", field.Select(r => r.Icon + r.Name + "...")).Trim(); if (winner.UserId != null) { int prize = bet * Math.Max(winMult, humans); int balance = AddToBalance(winner.UserId, prize); LogSuccess("Race Won", $"**Winner:** {winner.Name}\n**Racers:** {humans} viewers, {field.Count - humans} computer\n**Prize:** {Money(prize)}"); CPH.SendMessage($"🏁 RACE! {line} {winner.Icon}{winner.Name} wins {Money(prize)}! | Balance: {Money(balance)}"); } else { LogInfo("Race Lost", $"**Winner:** {winner.Name} (computer)\n**Racers:** {humans} viewers\n**Entry each:** {Money(bet)}"); CPH.SendMessage($"🏁 RACE! {line} {winner.Icon}{winner.Name} wins! Better luck next time."); } return true; } catch (Exception ex) { LogError("Race Command Exception", $"**Error:** {ex.Message}\n**Stack Trace:** {ex.StackTrace}"); CPH.SendMessage("⚠️ An error occurred during race"); CPH.LogError($"Race error: {ex.Message}"); return false; } } private class Racer { public string UserId; public string Name; public string Icon; } // The race being joined. Static so "!race join" (a separate run of this action) // adds to the race the starter's run is waiting on. private static List Racers; private static int Entry; private static readonly object RaceLock = new object(); // ═══════════════════════════════════════════════════════════ // SHARED HELPERS // ═══════════════════════════════════════════════════════════ // One Random for every run of this action, behind a lock: Streamer.bot can run // the same action for several viewers at once, and Random is not thread-safe. private static readonly Random Rng = new Random(); private static readonly object RngLock = new object(); private static int Roll(int maxExclusive) { lock (RngLock) return Rng.Next(maxExclusive); } private static int Roll(int min, int maxInclusive) { lock (RngLock) return Rng.Next(min, maxInclusive + 1); } private static double RollDouble() { lock (RngLock) return Rng.NextDouble(); } private string currencyName; private string currencyKey; private void LoadCurrency() { currencyName = CPH.GetGlobalVar("config_currency_name", true); if (string.IsNullOrEmpty(currencyName)) currencyName = "Cub Coins"; currencyKey = CPH.GetGlobalVar("config_currency_key", true); if (string.IsNullOrEmpty(currencyKey)) currencyKey = "cubcoins"; } // A config value, or the default if ConfigSetup hasn't set it (unset reads as 0). private int Cfg(string key, int fallback) { int value = CPH.GetGlobalVar(key, true); return value == 0 ? fallback : value; } private int GetBalance(string userId) { return CPH.GetTwitchUserVarById(userId, currencyKey, true); } private void SetBalance(string userId, int amount) { CPH.SetTwitchUserVarById(userId, currencyKey, amount, true); } private int AddToBalance(string userId, int amount) { int balance = GetBalance(userId) + amount; SetBalance(userId, balance); return balance; } // Seconds left on a cooldown (0 when ready). Times are saved as UTC and read // back as UTC; a plain DateTime.Parse turns them into local time, which made // cooldowns hours too long east of UTC and too short west of it. private double CooldownLeft(string userId, string key, TimeSpan length) { string last = CPH.GetTwitchUserVarById(userId, key, true); if (string.IsNullOrEmpty(last)) return 0; DateTime when; if (!DateTime.TryParse(last, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out when)) return 0; double left = (when.ToUniversalTime() + length - DateTime.UtcNow).TotalSeconds; return left > 0 ? left : 0; } private void StartCooldown(string userId, string key) { CPH.SetTwitchUserVarById(userId, key, DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture), true); } private static string FormatWait(double seconds) { TimeSpan t = TimeSpan.FromSeconds(Math.Ceiling(seconds)); if (t.TotalHours >= 1) return $"{(int)t.TotalHours}h {t.Minutes}m"; if (t.TotalMinutes >= 1) return $"{t.Minutes}m {t.Seconds}s"; return $"{t.Seconds}s"; } // $1,500 on every PC (the PC's own culture would write $1.500 in some countries). private static string Money(int amount) { return "$" + amount.ToString("N0", CultureInfo.InvariantCulture); } private string Arg(string name) { string value; return CPH.TryGetArg(name, out value) && value != null ? value.Trim() : ""; } // A bet from chat: a number, or "all" (as much as you have, up to the max bet). private bool ReadBet(string text, int balance, int min, int max, out int bet) { bet = 0; if (string.IsNullOrEmpty(text)) return false; text = text.Trim().TrimStart('$').Replace(",", ""); if (text.Equals("all", StringComparison.OrdinalIgnoreCase) || text.Equals("max", StringComparison.OrdinalIgnoreCase)) { bet = Math.Min(balance, max); return true; } return int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out bet); } // Everything a single-player bet game checks before playing: the bet, the // cooldown and the balance. On success the bet has been taken. private bool TakeBet(string command, string prefix, string betText, int minBet, int maxBet, int cooldownSeconds, string usage, string user, string userId, out int bet) { bet = 0; double wait = CooldownLeft(userId, prefix + "_last_played", TimeSpan.FromSeconds(cooldownSeconds)); if (wait > 0) { CPH.SendMessage($"{user}, {command} cooldown! Wait {FormatWait(wait)} before playing again."); return false; } int balance = GetBalance(userId); if (!ReadBet(betText, balance, minBet, maxBet, out bet)) { CPH.SendMessage($"{user}, usage: {usage} (bet {minBet}-{maxBet} or \"all\")"); return false; } if (bet < minBet || bet > maxBet) { CPH.SendMessage($"{user}, bet must be between {Money(minBet)} and {Money(maxBet)} {currencyName}!"); return false; } if (balance < bet) { LogWarning($"{command} Insufficient Funds", $"**User:** {user}\n**Bet:** {Money(bet)}\n**Balance:** {Money(balance)}"); CPH.SendMessage($"{user}, you only have {Money(balance)} {currencyName}! You need {Money(bet)}."); return false; } SetBalance(userId, balance - bet); StartCooldown(userId, prefix + "_last_played"); return true; } // ═══════════════════════════════════════════════════════════ // DISCORD LOGGING METHODS // ═══════════════════════════════════════════════════════════ private const int COLOR_INFO = 3447003; // Blue private const int COLOR_SUCCESS = 5763719; // Green private const int COLOR_WARNING = 16705372; // Orange private const int COLOR_ERROR = 15548997; // Red private const int COLOR_COMMAND = 10181046; // Purple private void LogInfo(string title, string message) { SendToDiscord(title, message, COLOR_INFO, "INFO"); } private void LogSuccess(string title, string message) { SendToDiscord(title, message, COLOR_SUCCESS, "SUCCESS"); } private void LogWarning(string title, string message) { SendToDiscord(title, message, COLOR_WARNING, "WARNING"); } private void LogError(string title, string message) { SendToDiscord(title, message, COLOR_ERROR, "ERROR"); } private void LogCommand(string commandName, string user, string details = "") { string message = $"**User:** {user}"; if (!string.IsNullOrEmpty(details)) message += $"\n**Details:** {details}"; SendToDiscord($"Command: {commandName}", message, COLOR_COMMAND, "COMMAND"); } private void SendToDiscord(string title, string description, int color, string footer) { try { bool loggingEnabled = CPH.GetGlobalVar("discordLoggingEnabled", true); if (!loggingEnabled) return; string webhookUrl = CPH.GetGlobalVar("discordLogWebhook", true); if (string.IsNullOrEmpty(webhookUrl)) { CPH.LogWarn("Discord webhook not configured. Run ConfigSetup.cs first."); return; } StringBuilder json = new StringBuilder(); json.Append("{\"embeds\":[{"); json.Append($"\"title\":\"{EscapeJson(title)}\","); json.Append($"\"description\":\"{EscapeJson(description)}\","); json.Append($"\"color\":{color},"); json.Append($"\"timestamp\":\"{DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture)}\","); json.Append($"\"footer\":{{\"text\":\"{EscapeJson(footer)} | HexEchoTV Logging System\"}}"); json.Append("}]}"); using (WebClient client = new WebClient()) { client.Encoding = Encoding.UTF8; client.Headers.Add("Content-Type", "application/json"); client.UploadString(webhookUrl, "POST", json.ToString()); } } catch (Exception ex) { CPH.LogError($"DiscordLogger error: {ex.Message}"); } } private string EscapeJson(string str) { if (string.IsNullOrEmpty(str)) return ""; return str.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\n", "\\n").Replace("\r", "\\r").Replace("\t", "\\t"); } }