// 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 !heist. // Leave the action out of any blocking queue: the leader's run waits for the crew // to join, and a blocking queue would hold every !heist join until it had finished. // // USAGE: // !heist [bet] plan a heist; others have config_heist_join_seconds (default 30) to join // !heist join join the heist being planned (same stake as the leader) // Success chance: config_heist_success_rate % (default 30) + 5 for each extra crew member (max 85). // Success pays each member stake x config_heist_win_mult (default 4); a failed heist loses the stakes. // Every member then waits config_heist_cooldown_hours (default 3) before the next heist. 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("Heist command: missing 'user' or 'userId' argument"); return false; } int minBet = Cfg("config_heist_min_bet", 50); int maxBet = Cfg("config_heist_max_bet", 1000); int successRate = Cfg("config_heist_success_rate", 30); int winMult = Cfg("config_heist_win_mult", 4); int cooldownHours = Cfg("config_heist_cooldown_hours", 3); int joinSeconds = Cfg("config_heist_join_seconds", 30); string input = Arg("input0").ToLowerInvariant(); double wait = CooldownLeft(userId, "heist_cooldown", TimeSpan.FromHours(cooldownHours)); if (input == "join") { int stake; lock (CrewLock) { if (Crew == null) { CPH.SendMessage($"{user}, no heist is being planned. Start one with !heist [bet]!"); return false; } if (Crew.Any(m => m.UserId == userId)) { CPH.SendMessage($"{user}, you're already in the crew!"); return false; } stake = Stake; } if (wait > 0) { CPH.SendMessage($"{user}, you're laying low after the last heist. Wait {FormatWait(wait)}!"); return false; } int balance = GetBalance(userId); if (balance < stake) { CPH.SendMessage($"{user}, joining costs {Money(stake)} {currencyName}; you have {Money(balance)}."); return false; } lock (CrewLock) { if (Crew == null) { CPH.SendMessage($"{user}, too late, the crew has left!"); return false; } SetBalance(userId, balance - stake); Crew.Add(new Member { UserId = userId, Name = user }); } LogCommand("!heist join", user, $"Stake: {Money(stake)}"); CPH.SendMessage($"🕶️ {user} joined the heist crew! ({Money(stake)})"); return true; } lock (CrewLock) { if (Crew != null) { CPH.SendMessage($"{user}, a heist is already being planned! Type !heist join to get in."); return false; } } if (wait > 0) { CPH.SendMessage($"{user}, you're laying low after the last heist. Wait {FormatWait(wait)}!"); return false; } int bal = GetBalance(userId), bet; if (!ReadBet(input, bal, minBet, maxBet, out bet)) { CPH.SendMessage($"{user}, usage: !heist [bet {minBet}-{maxBet}] or !heist join"); return false; } if (bet < minBet || bet > maxBet) { CPH.SendMessage($"{user}, a heist stake 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 (CrewLock) { if (Crew != null) { CPH.SendMessage($"{user}, a heist is already being planned! Type !heist join to get in."); return false; } SetBalance(userId, bal - bet); Crew = new List { new Member { UserId = userId, Name = user } }; Stake = bet; } LogCommand("!heist", user, $"Stake: {Money(bet)}"); CPH.SendMessage($"🕶️ {user} is planning a bank heist! Stake: {Money(bet)} | Others can !heist join ({joinSeconds}s)"); CPH.Wait(joinSeconds * 1000); List crew; lock (CrewLock) { crew = Crew; Crew = null; } int chance = Math.Min(85, successRate + 5 * (crew.Count - 1)); string names = string.Join(", ", crew.Select(m => m.Name)); foreach (Member m in crew) StartCooldown(m.UserId, "heist_cooldown"); if (Roll(100) < chance) { int payout = bet * winMult; foreach (Member m in crew) AddToBalance(m.UserId, payout); LogSuccess("Heist Success", $"**Crew:** {names}\n**Stake each:** {Money(bet)}\n**Chance:** {chance}%\n**Payout each:** {Money(payout)}"); string who = crew.Count == 1 ? $"{user} escaped" : $"The crew ({names}) escaped"; CPH.SendMessage($"🕶️ HEIST SUCCESSFUL! {who} with {Money(payout)} each! 💰"); } else { LogWarning("Heist Failed", $"**Crew:** {names}\n**Stake each:** {Money(bet)}\n**Chance:** {chance}%"); string who = crew.Count == 1 ? $"{user} was caught" : $"The crew ({names}) got caught"; CPH.SendMessage($"🚨 HEIST FAILED! {who}! Lost {Money(bet)} each."); } return true; } catch (Exception ex) { LogError("Heist Command Exception", $"**Error:** {ex.Message}\n**Stack Trace:** {ex.StackTrace}"); CPH.SendMessage("⚠️ An error occurred during heist"); CPH.LogError($"Heist error: {ex.Message}"); return false; } } private class Member { public string UserId; public string Name; } // The crew being planned. Static so "!heist join" (a separate run of this // action) adds to the heist the leader's run is waiting on. private static List Crew; private static int Stake; private static readonly object CrewLock = 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"); } }